openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 11.5 kB
JavaScript
import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{n as waitForAbortSignal}from"./abort-signal-BKkRe6pu.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as dedupeByKey}from"./dedupe-by-key-Bdyq9B5M.mjs";import{i as GATEWAY_CLIENT_NAMES,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{a as isApprovalMethod}from"./method-scopes-Dalbwzsv.mjs";import"./message-channel-514k57tV.mjs";import{f as readConnectErrorDetailCode}from"./connect-error-details-CJ6aH8Ny.mjs";import{t as startGatewayClientWhenEventLoopReady}from"./readiness-BGDb6KrA.mjs";import{n as isGatewayNativeApprovalMethod}from"./approval-gateway-runtime-methods-B8iDzFlG.mjs";import{t as getGatewayNativeApprovalRuntime}from"./approval-gateway-runtime-context-BrssdAQd.mjs";import{t as buildChannelApprovalNativeTargetKey}from"./approval-native-target-key-ovU_whEm.mjs";import{n as createApprovalNativeRouteReporter}from"./approval-native-route-coordinator-BC2LJRkc.mjs";import{h as normalizeApprovalRequest,t as classifyApprovalRequestChannelRouteAsync}from"./approval-request-account-binding-DFLDpifZ.mjs";import{t as createOperatorApprovalsGatewayClient}from"./operator-approvals-client-bf8xUgR4.mjs";import{t as createPendingApprovalRegistry}from"./pending-approval-registry-D-gvH4VV.mjs";
//!src/infra/approval-native-delivery.ts
async function resolveChannelNativeApprovalDeliveryPlan(e){const t=e.adapter;const n={targets:[],originTarget:null,notifyOriginWhenDmOnly:false};if(!t)return n;const deliveryContext=()=>({cfg:e.cfg,accountId:e.accountId,approvalKind:e.approvalKind,request:e.request});const r=await t.describeDeliveryCapabilities(deliveryContext());if(!r.enabled)return n;const i=r.supportsOriginSurface&&t.resolveOriginTarget?await t.resolveOriginTarget(deliveryContext())??null:null;const a=r.supportsApproverDmSurface&&t.resolveApproverDmTargets?await t.resolveApproverDmTargets(deliveryContext()):[];const o=[];const s=r.preferredSurface===`origin`||r.preferredSurface===`both`;const c=r.preferredSurface===`approver-dm`||r.preferredSurface===`both`;if(s&&i)o.push({surface:`origin`,target:i,reason:`preferred`});if(c||!i)for(const e of a)o.push({surface:`approver-dm`,target:e,reason:c?`preferred`:`fallback`});return{targets:dedupeByKey(o,e=>buildChannelApprovalNativeTargetKey(e.target)),originTarget:i,notifyOriginWhenDmOnly:r.preferredSurface===`approver-dm`&&r.notifyOriginWhenDmOnly===true&&i!==null}}
//!src/infra/exec-approval-channel-runtime.ts
var ExecApprovalChannelRuntimeTerminalStartError=class extends Error{constructor(e,t){super(`native approval gateway client paused reconnect after startup auth failure (${e.detailCode??`unknown`}): gateway closed (${e.code}): ${e.reason}`,t===void 0?void 0:{cause:t});this.name=`ExecApprovalChannelRuntimeTerminalStartError`;this.detailCode=e.detailCode}};function isExecApprovalChannelRuntimeTerminalStartError(e){return e instanceof ExecApprovalChannelRuntimeTerminalStartError}const APPROVAL_EVENT_PREFIXES=[[`exec`,`exec`],[`plugin`,`plugin`],[`system-agent`,`openclaw`]];function readGatewayConnectErrorDetailCode(e){if(!e||typeof e!==`object`)return null;return readConnectErrorDetailCode(e.details)}function createExecApprovalChannelRuntime(e){const t=createSubsystemLogger(e.label);const n=e.nowMs??Date.now;const r=new Set(e.eventKinds??[`exec`]);const i=getGatewayNativeApprovalRuntime();const a=createPendingApprovalRegistry();let o=null;let s;let c=null;let l=false;let u=false;let d=null;let f=null;let p=null;const spawn=(e,n)=>{n.catch(n=>{const r=formatErrorMessage(n);t.error(`${e}: ${r}`)})};const stopClientIfInactive=e=>{if(u)return false;o=null;e.stop();return true};const finalizeExpiredEntry=async n=>{t.debug(`expired ${n.id}`);await e.finalizeExpired?.(n.value)};const handleExpired=async e=>{const t=a.remove(e);if(!t)return;await finalizeExpiredEntry(t)};const handleRequested=async(r,i)=>{if(i?.ignoreIfInactive&&!u)return;const o=normalizeApprovalRequest(r);if(a.has(o.id)){t.debug(`ignored duplicate request ${o.id}`);return}const s=a.begin(o.id,{request:o,entries:[]});let c;try{const n=i?.alreadyAccepted===true?true:e.shouldHandle(o);if(!(typeof n===`boolean`?n:await n)||i?.ignoreIfInactive&&!u||!a.isCurrent(s)||s.queued){a.remove(o.id,s);return}t.debug(`received request ${o.id}`);c=await e.deliverRequested(o)}catch(e){a.remove(o.id,s);throw e}if(!c.length){a.remove(o.id,s);return}await a.completeDelivery(s,{request:o,entries:c});const l=Math.max(0,o.expiresAtMs-n());a.scheduleExpiry(s,l,e=>{spawn(`error handling approval expiration`,finalizeExpiredEntry(e))})};const handleResolved=async n=>{if(`terminalStatus`in n&&n.terminalStatus===`expired`){await handleExpired(n.id);return}const r=a.settle(n.id,async r=>{t.debug(`resolved ${n.id} with ${n.decision}`);await e.finalizeResolved({request:r.value.request,resolved:n,entries:r.value.entries})});if(r.status===`taken`)await r.terminal(r.entry)};const handleGatewayEvent=e=>{if(APPROVAL_EVENT_PREFIXES.some(([t,n])=>e.event===`${n}.approval.requested`&&r.has(t))){spawn(`error handling approval request`,handleRequested(e.payload,{ignoreIfInactive:true}));return}if(APPROVAL_EVENT_PREFIXES.some(([t,n])=>e.event===`${n}.approval.resolved`&&r.has(t)))spawn(`error handling approval resolved`,handleResolved(e.payload))};const replayPendingApprovals=async(e,t)=>{try{for(const n of APPROVAL_EVENT_PREFIXES.flatMap(([e,t])=>r.has(e)?[`${t}.approval.list`]:[])){if(t&&stopClientIfInactive(t))return;const r=await e.request(n,{});if(t&&stopClientIfInactive(t))return;for(const e of r){if(t&&stopClientIfInactive(t))return;await handleRequested(e,{ignoreIfInactive:true})}}}catch(e){if(!u)return;throw e}};const startPendingApprovalReplay=(e,n)=>{const r=replayPendingApprovals(e,n).catch(e=>{const n=formatErrorMessage(e);t.error(`error replaying pending approvals: ${n}`)}).finally(()=>{if(p===r)p=null});p=r};return{async start(){if(l)return;if(d){await d;return}u=true;const n=new AbortController;f=n;d=(async()=>{if(!await e.isConfigured()){t.debug(`disabled`);return}if(!u)return;if(i){await e.beforeGatewayClientStart?.();s=i;c=s.subscribe({eventKinds:r,shouldHandle:t=>{if(!u)return false;const n=e.shouldHandle(t);return typeof n===`boolean`?n&&u:n.then(e=>e&&u)},onRequested:e=>{spawn(`error handling approval request`,handleRequested(e,{ignoreIfInactive:true,alreadyAccepted:true}))},onResolved:e=>{spawn(`error handling approval resolved`,handleResolved(e))}});if(!u){c();c=null;s=void 0;return}l=true;startPendingApprovalReplay({request:s.request});return}const a=createDeferredCore();let d=null;const f=await createOperatorApprovalsGatewayClient({config:e.cfg,gatewayUrl:e.gatewayUrl,clientDisplayName:e.clientDisplayName,onEvent:handleGatewayEvent,onHelloOk:()=>{t.debug(`connected to gateway`);a.resolve()},onConnectError:e=>{t.error(`connect error: ${e.message}`);d=e;if(readGatewayConnectErrorDetailCode(e))return;a.reject(e)},onReconnectPaused:e=>{a.reject(new ExecApprovalChannelRuntimeTerminalStartError(e,d))},onClose:(e,n)=>{t.debug(`gateway closed: ${e} ${n}`);a.reject(d??/* @__PURE__ */ new Error(`gateway closed: ${e} ${n}`))}});if(!u){f.stop();return}await e.beforeGatewayClientStart?.();o=f;try{const e=await startGatewayClientWhenEventLoopReady(f,{clientOptions:{},signal:n.signal});if(!e.ready){if(stopClientIfInactive(f))return;throw new Error(e.aborted?`gateway approval runtime start aborted before readiness`:`gateway readiness unavailable before exec approval runtime start`)}await waitForAbortSignal(n.signal,a.promise);if(stopClientIfInactive(f))return;l=true;startPendingApprovalReplay(f,f)}catch(e){o=null;l=false;f.stop();throw e}})().finally(()=>{d=null;f=null});await d},async stop(){u=false;f?.abort();if(d)await d.catch(()=>{});const n=l||o!==null||p!==null;l=false;c?.();c=null;s=void 0;o?.stop();o=null;await p?.catch(()=>{});a.clear();await e.onStopped?.();if(n)t.debug(`stopped`)},handleRequested,handleResolved,handleExpired,async request(t,n){if(!isApprovalMethod(t))throw new Error(`${e.label}: operator approvals runtime cannot dispatch ${t}; use a write-capable gateway client`);if(s){if(!isGatewayNativeApprovalMethod(t))throw new Error(`${e.label}: Gateway-owned approval runtime cannot dispatch ${t}`);return await s.request(t,n,{clientDisplayName:e.clientDisplayName})}if(!o)throw new Error(`${e.label}: gateway client not connected`);return await o.request(t,n)}}}
//!src/infra/approval-native-runtime.ts
function createChannelNativeApprovalRuntime(e){return createChannelNativeApprovalRuntimeAsync(e)}function createChannelNativeApprovalRuntimeAsync(e){const t=e.nowMs??Date.now;const n=new Set(e.eventKinds??[`exec`]);const r=getGatewayNativeApprovalRuntime();const i=(r?.routeCoordinator.createReporter??createApprovalNativeRouteReporter)({handledKinds:n,channel:e.channel,channelLabel:e.channelLabel,accountId:e.accountId,shouldHandle:t=>e.shouldHandle(t),classifyRoute:t=>classifyApprovalRequestChannelRouteAsync({cfg:e.getRequestConfig?.(t)??e.cfg,request:t,channel:e.channel??``}),requestGateway:async(t,n)=>{if(r){if(t!==`send`)throw new Error(`native approval route cannot dispatch ${t}`);return await r.requestRoute(t,n)}const{callGatewayLeastPrivilege:i}=await import(`./call-CggG9h6i.mjs`);return await i({config:e.cfg,...e.gatewayUrl?{url:e.gatewayUrl}:{},method:t,params:n,clientName:GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT,mode:GATEWAY_CLIENT_MODES.BACKEND})}});const finalize=e=>async t=>{try{await e(t)}finally{i.completeRequest(t.request.id)}};const a=createExecApprovalChannelRuntime({label:e.label,clientDisplayName:e.clientDisplayName,cfg:e.cfg,gatewayUrl:e.gatewayUrl,eventKinds:e.eventKinds,isConfigured:e.isConfigured,shouldHandle:async t=>{const n=e.resolveApprovalKind?.(t)??t.approvalKind;const r=await i.selectRequest({approvalKind:n,request:t});if(r.kind===`selected`)return true;i.reportSkipped({approvalKind:n,request:t,reason:r.kind===`selector-error`?`ineligible`:r.kind});if(r.kind===`selector-error`)throw r.error;return false},finalizeResolved:finalize(t=>e.finalizeResolved(t)),finalizeExpired:e.finalizeExpired?finalize(t=>e.finalizeExpired?.(t)):void 0,onStopped:e.onStopped,beforeGatewayClientStart:()=>{i.start()},nowMs:t,deliverRequested:async n=>{const r=e.resolveApprovalKind?.(n)??n.approvalKind;let a={targets:[],originTarget:null,notifyOriginWhenDmOnly:false};let o=[];try{const i=await e.buildPendingContent({request:n,approvalKind:r,nowMs:t()});const s=await resolveChannelNativeApprovalDeliveryPlan({cfg:e.getRequestConfig?.(n)??e.cfg,accountId:e.accountId,approvalKind:r,request:n,adapter:e.nativeAdapter});const c=/* @__PURE__ */ new Set;const l=[];const u=[];for(const t of s.targets){const a={plannedTarget:t,request:n,approvalKind:r,pendingContent:i};try{const n=await e.prepareTarget({...a});if(!n)continue;if(c.has(n.dedupeKey)){e.onDuplicateSkipped?.({...a,preparedTarget:n});continue}const r=await e.deliverTarget({...a,preparedTarget:n.target});if(!r)continue;c.add(n.dedupeKey);l.push(r);u.push(t);e.onDelivered?.({...a,preparedTarget:n,entry:r})}catch(t){e.onDeliveryError?.({...a,error:t})}}a=s;o=u;return l}finally{await i.reportDelivery({approvalKind:r,request:n,deliveryPlan:a,deliveredTargets:o})}}});return{...a,async start(){try{await a.start()}catch(e){await i.stop();throw e}},async stop(){await a.stop();await i.stop()}}}export{createChannelNativeApprovalRuntimeAsync as n,isExecApprovalChannelRuntimeTerminalStartError as r,createChannelNativeApprovalRuntime as t};