UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines • 15.8 kB
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{o as getAsyncWorkSignal,t as AsyncWorkScope}from"./async-work-scope-DBcxYU4O.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{a as runWithCapturedWorkerContext}from"./openclaw-state-worker-store-7se2aIrr.mjs";import{O as runWithRetainedGatewayRootWork,a as captureGatewayRootWorkAdmissionContinuationScope}from"./gateway-work-admission-CnMW3_qr.mjs";import{c as getOperatorApprovalResolutionKey}from"./operator-approval-store.rows-BbhJTsaZ.mjs";import{i as getOperatorApprovalDetailed,o as isOperatorApprovalStoreOutcomeUnknown}from"./operator-approval-store-3mVTaQpm.mjs"; //!src/gateway/exec-approval-recovery.ts function captureExecApprovalMutationPersistence(e){const{databaseOptions:t,runtimeEpoch:n}=e;const r=captureOpenClawStateWorkerContext({...t,path:t?.database?.path??t?.path});return{runtimeEpoch:n,databaseOptions:{path:r.admission.databasePath,env:r.environment},workerContext:r}}function runWithExecApprovalMutationPersistence(e,t){assertExecApprovalMutationPersistenceCurrent(e);const n=expectDefined(e.workerContext,`Approval mutation worker context`);return runWithCapturedWorkerContext(n,t)}function assertExecApprovalMutationPersistenceCurrent(e){const t=expectDefined(e.workerContext,`Approval mutation worker context`);t.admission.assertCurrent();t.maintenanceScope?.assertAdmission()}function assertUncertainExecApprovalPersistenceCurrent(e,t){try{assertExecApprovalMutationPersistenceCurrent(t)}catch(t){throw new AggregateError([e,t],`Approval verdict remains uncertain after readback`,{cause:t})}}async function readUncertainExecApprovalVerdict(e,t,n,r){if(!isOperatorApprovalStoreOutcomeUnknown(e))return;if(!t)return null;const{id:i,createdAtMs:a}=t;const{runtimeEpoch:o,databaseOptions:s}=r;assertUncertainExecApprovalPersistenceCurrent(e,r);const c=expectDefined(r.workerContext,`Approval mutation worker context`);try{const t=await runWithCapturedWorkerContext(c,()=>getOperatorApprovalDetailed({id:i,nowMs:a,databaseOptions:s,guard:{family:`worker`,assertCurrent:()=>{c.admission.assertCurrent();c.maintenanceScope?.assertOwnerCurrent()}}}));assertUncertainExecApprovalPersistenceCurrent(e,r);return t.outcome===`found`&&t.record.id===i&&t.record.kind===n&&t.record.runtimeEpoch===o&&t.record.createdAtMs===a?t.record:null}catch(t){throw new AggregateError([e,t],`Approval verdict remains uncertain after readback`,{cause:t})}} //!src/gateway/exec-approval-results.ts function prepareExecApprovalStandingGrant(e){let t=e.decision===`allow-always`&&e.record?e.options.resolveStandingGrantMint?.(e.record.request)??void 0:void 0;if(t?.kind===`mcp-tool`&&e.record?.mcpToolApprovalActive?.()!==true)t=void 0;const n=t?{...t,expiresAtMs:e.grantExpiresAtMs!==void 0?e.grantExpiresAtMs:e.options.resolveStandingGrantExpiresAtMs?.(Date.now())??null}:void 0;return{standingGrantSpec:t,standingGrant:n}}function projectRepairedApprovalResolution(e,t){if(e.outcome===`expired`||e.outcome===`not-found`||e.outcome===`corrupt`)return e;if(e.outcome===`denied`&&t===`deny`)return{outcome:`resolved`,record:e.record,...e.liveRecord?{liveRecord:e.liveRecord}:{}};return{outcome:`already-resolved`,retry:e.record.decision===t?`same`:`conflict`,record:e.record,...e.liveRecord?{liveRecord:e.liveRecord}:{}}}function prepareExecApprovalSettlement(e){const{record:t}=e;if(t.kind!==e.expectedKind||t.runtimeEpoch!==e.runtimeEpoch||t.status===`pending`||t.resolvedAtMs===null)return null;const n=t.status===`allowed`||t.status===`denied`&&t.terminalReason!==`no-route`;const r=e.localDecision===void 0?n?t.decision:null:e.localDecision;return{recordId:t.id,decision:r,resolvedAtMs:t.resolvedAtMs,resolvedBy:e.localResolvedBy,resolverKind:t.resolver?.kind??null,status:t.status,terminalReason:t.terminalReason,consumedAtMs:t.consumedAtMs,consumedBy:t.consumedBy,resolutionSource:e.localResolutionSource}} //!src/gateway/exec-approval-lifecycle.ts const EXEC_APPROVAL_RESOLVED_ENTRY_GRACE_MS=15e3;var ApprovalObserverClosedError=class extends Error{constructor(){super(`Gateway approval observer closed`);this.name=`ApprovalObserverClosedError`}};var ExecApprovalLifecycle=class{constructor(e){this.scheduler=e;this.pending=/* @__PURE__ */ new Map;this.retired=false;this.observingClosed=false;this.observers=/* @__PURE__ */ new Set;this.work=new AsyncWorkScope}emitLifecycle(e){try{const{record:t}=e;const n=this.pending.get(t.id);if(this.options.onLifecycle!==void 0&&e.phase===`terminal`&&n)n.terminalPublication={kind:t.kind,runtimeEpoch:t.runtimeEpoch,status:t.status,decision:t.decision,terminalReason:t.terminalReason,resolvedAtMs:t.resolvedAtMs,updatedAtMs:t.updatedAtMs};this.options.onLifecycle?.(e)}catch{}}retainUncertainVerdict(e,t){const n=e?this.pending.get(e.id):void 0;if(n&&n.record===e&&e.resolvedAtMs===void 0){n.uncertainVerdict??=t;if(t.autoReview&&!n.uncertainVerdict.autoReview?.committedResolutionKey)n.uncertainVerdict.autoReview=t.autoReview}}assertPendingPersistenceCurrent(e){e?.uncertainVerdict?.assertCurrent();if(e?.expiryPersistence)assertExecApprovalMutationPersistenceCurrent(e.expiryPersistence)}clearUncommittedVerdict(e){const t=this.pending.get(e.id);if(t?.record===e&&!t.uncertainVerdict?.autoReview?.committedResolutionKey){this.assertPendingPersistenceCurrent(t);delete t.uncertainVerdict}}settleLocalStorageFailure(e){this.settleLocalEntry({recordId:e,decision:`deny`,resolvedAtMs:Date.now(),resolvedBy:`storage-error`,resolverKind:`system`,status:`denied`,terminalReason:`storage-corrupt`,retainForManagerLifetime:true})}settleLocalFromStore(e,t,n=null,r){const i=this.pending.get(e.id);const a=i?.record;const o=i?.uncertainVerdict;let s=`operator`;if(r===void 0&&o?.autoReview&&e.status===`allowed`&&e.decision===`allow-once`){if(o.autoReview.committedResolutionKey===getOperatorApprovalResolutionKey(e))s=`auto-review`;else if(e.resolver?.kind===`runtime`)return false}const c=prepareExecApprovalSettlement({record:e,expectedKind:this.approvalKind,runtimeEpoch:this.runtimeEpoch,localDecision:t,localResolvedBy:n,localResolutionSource:r??s});if(!c)return false;const l=this.settleLocalEntry(c);if(l){this.emitLifecycle({phase:`terminal`,record:e});if(e.status===`expired`&&a)try{this.options.onExpired?.(e,a)}catch(t){this.reportError(t,{approvalId:e.id,operation:`expire`})}}return l}async reconcileDurableTerminal(e){await this.waitForMutations(e.id);this.settleLocalFromStore(e);const t=this.pending.get(e.id)?.terminalPublication;return t!==void 0&&t.kind===e.kind&&t.runtimeEpoch===e.runtimeEpoch&&t.status===e.status&&t.decision===e.decision&&t.terminalReason===e.terminalReason&&t.resolvedAtMs===e.resolvedAtMs&&t.updatedAtMs===e.updatedAtMs}reportError(e,t){try{this.options.onError?.(e instanceof Error?e:new Error(String(e)),{...t,approvalKind:this.approvalKind})}catch{}}beginClose(){this.observingClosed=true;for(const e of this.observers)e()}retire(){if(this.retired)return;this.retired=true;this.beginClose();for(const[e,t]of this.pending){t.expiryJob?.cancel();t.cleanupJob?.cancel();t.expiryJob=null;t.cleanupJob=null;t.admissionContinuation?.release();t.admissionContinuation=null;if(t.record.resolvedAtMs===void 0&&!this.work.hasPendingWork)for(const e of t.handoffs)e.cancel();if(t.handoffRetainCount===0&&!this.work.hasPendingWork)this.pending.delete(e)}}drain(){this.retire();this.draining??=this.work.drain().then(()=>{for(const e of this.pending.values())for(const t of e.handoffs)t.cancel();this.pending.clear()});return this.draining}trackActiveWork(e){this.assertNotRetired();return this.work.track(()=>runWithRetainedGatewayRootWork(e))}trackMutation(e,t){const n=t===void 0?void 0:this.pending.get(t);const r=n?.mutation;const i=this.work.track(()=>runWithRetainedGatewayRootWork(()=>r?r.then(e):e()));if(n){const e=i.then(()=>void 0,()=>void 0);n.mutation=e;e.then(()=>{if(n.mutation===e)n.mutation=void 0})}return i}async waitForMutations(e){let t=false;for(let n=this.pending.get(e)?.mutation;n;n=this.pending.get(e)?.mutation){t=true;await n}return t}canUseRetainedBinding(){return!this.retired||getAsyncWorkSignal()===this.work.signal}assertNotRetired(){if(this.retired)throw new ApprovalObserverClosedError}registerEntry(e){const t=createDeferredCore();const n={record:e,resolve:t.resolve,expiryJob:null,cleanupJob:null,handoffRetainCount:0,handoffReleasedAtMs:null,retainForManagerLifetime:false,promise:t.promise,handoffs:/* @__PURE__ */ new Set,admissionContinuation:captureGatewayRootWorkAdmissionContinuationScope()};this.pending.set(e.id,n);this.scheduleExpiry(n);return t.promise}registerDecisionHandoff(e,t){this.assertNotRetired();const n=expectDefined(this.pending.get(e),`registered approval handoff`);const r=expectDefined(this.retainForHandoff(e),`live approval handoff`);const i=createDeferredCore();const a={start:e=>{if(!n.handoffs.delete(a))return;this.work.track(()=>runWithRetainedGatewayRootWork(async()=>{try{await Promise.resolve();await t(e)}finally{r()}})).then(i.resolve,i.reject)},cancel:()=>{if(n.handoffs.delete(a)){r();i.reject(new ApprovalObserverClosedError)}}};n.handoffs.add(a);if(n.record.resolvedAtMs!==void 0)a.start(n.record.decision??n.record.consumedDecision??null);return{observation:this.observeEntry(n,i.promise),abandon:a.cancel}}observeEntry(e,t){const n=getAsyncWorkSignal();return new Promise((r,i)=>{const finish=e=>{if(!this.observers.delete(onClose))return;n?.removeEventListener(`abort`,onClose);e()};const onClose=()=>{if(e.record.resolvedAtMs===void 0)finish(()=>i(new ApprovalObserverClosedError))};t.then(e=>finish(()=>r(e)),e=>{const t=e instanceof Error?e:new Error(String(e),{cause:e});finish(()=>i(t))});this.observers.add(onClose);n?.addEventListener(`abort`,onClose,{once:true});if(this.observingClosed||n?.aborted)onClose()})}settleLocalEntry(e){const t=this.pending.get(e.recordId);if(!t||t.record.resolvedAtMs!==void 0||!this.canUseRetainedBinding())return false;this.assertPendingPersistenceCurrent(t);delete t.uncertainVerdict;delete t.expiryPersistence;delete t.expiryRefusals;t.expiryJob?.cancel();t.expiryJob=null;t.record.resolvedAtMs=e.resolvedAtMs;if(e.decision===null)delete t.record.decision;else{t.record.decision=e.decision;t.record.resolutionSource=e.resolutionSource??`operator`}t.record.resolvedBy=e.resolvedBy;t.record.resolverKind=e.resolverKind;t.record.status=e.status;t.record.terminalReason=e.terminalReason;t.record.runtimeEpoch=this.runtimeEpoch;t.record.consumedAtMs=e.consumedAtMs??null;t.record.consumedBy=e.consumedBy??null;delete t.record.mcpToolApprovalActive;t.retainForManagerLifetime||=e.retainForManagerLifetime===true;t.admissionContinuation?.release();t.admissionContinuation=null;for(const n of t.handoffs)n.start(e.decision);t.resolve(e.decision);this.scheduleResolvedCleanup(t);return true}scheduleResolvedCleanup(e){if(this.retired||e.cleanupJob||e.record.resolvedAtMs===void 0||e.retainForManagerLifetime||e.handoffRetainCount>0)return;e.cleanupJob=this.scheduler.schedule({id:`approval:${this.runtimeEpoch}:${this.approvalKind}:${e.record.id}:cleanup`,delayMs:EXEC_APPROVAL_RESOLVED_ENTRY_GRACE_MS,run:()=>{e.cleanupJob=null;if(this.pending.get(e.record.id)===e&&e.handoffRetainCount===0)this.pending.delete(e.record.id)}})}resolvedGraceAnchorMs(e,t){if(e.record.resolvedAtMs===void 0)return null;return e.handoffRetainCount>0?t:e.handoffReleasedAtMs??e.record.resolvedAtMs}retainForHandoff(e){const t=this.pending.get(e);if(!t)return null;const n=Date.now();const r=this.resolvedGraceAnchorMs(t,n);if(!t.retainForManagerLifetime&&r!==null&&t.handoffRetainCount===0&&n-r>=15e3){this.pending.delete(e);return null}t.cleanupJob?.cancel();t.cleanupJob=null;t.handoffRetainCount+=1;let i=false;return()=>{if(i)return;i=true;if(this.pending.get(e)!==t)return;t.handoffRetainCount=Math.max(0,t.handoffRetainCount-1);if(t.handoffRetainCount===0&&t.record.resolvedAtMs!==void 0){t.handoffReleasedAtMs=Date.now();this.scheduleResolvedCleanup(t)}}}async getSnapshot(e,t){t?.assertCurrent();const n=this.getLocalSnapshot(e);if(!this.retired&&n&&n.resolvedAtMs===void 0&&n.expiresAtMs<=Date.now())await this.expireDue(e,t);t?.assertCurrent();return this.getLocalSnapshot(e)}getLocalSnapshot(e){const t=this.pending.get(e);if(!t)return null;const n=Date.now();const r=this.resolvedGraceAnchorMs(t,n);if(t.record.terminalReason!==`storage-corrupt`&&r!==null&&n-r>=15e3){this.pending.delete(e);return null}return t.record}getLiveSnapshot(e){const t=this.pending.get(e);if(!t)return null;const n=Date.now();if(t.record.resolvedAtMs===void 0)return t.record.expiresAtMs>n?t.record:null;const r=this.resolvedGraceAnchorMs(t,n);return r!==null&&n-r<15e3?t.record:null}consumeAskFallback(e){const t=this.pending.get(e);if(!t)return false;const n=t.record;if(n.resolvedAtMs===void 0||n.decision!==void 0||n.consumedDecision!==void 0||n.askFallbackConsumed===true||n.status!==`expired`&&n.terminalReason!==`no-route`)return false;n.askFallbackConsumed=true;return true}runPendingContinuation(e,t){const n=this.pending.get(e);if(this.retired||!n?.admissionContinuation||n.record.resolvedAtMs!==void 0||n.record.expiresAtMs<=Date.now())return null;return n.admissionContinuation.run(t)}async listPendingRecords(e){e?.assertCurrent();if(this.retired)return[];const t=Date.now();for(const n of this.pending.values())if(n.record.resolvedAtMs===void 0&&n.record.expiresAtMs<=t){await this.expireDue(n.record.id,e);e?.assertCurrent()}return this.listLocalPendingRecords()}listLocalPendingRecords(){if(this.retired)return[];return Array.from(this.pending.values(),e=>e.record).filter(e=>e.resolvedAtMs===void 0)}async lookupApprovalId(e,t={}){await this.listPendingRecords(t.authority);const n=t.filter;if(!n)return this.lookupLocalApprovalId(e,{includeResolved:t.includeResolved});const r=this.getLocalSnapshot(e)??this.getLocalSnapshot(e.trim());const i=normalizeLowercaseStringOrEmpty(e.trim());const a=r?[r]:Array.from(this.pending.values(),({record:e})=>e).filter(e=>i&&normalizeLowercaseStringOrEmpty(e.id).startsWith(i));const o=await Promise.all(a.map(async e=>(t.includeResolved||e.resolvedAtMs===void 0)&&await n(e)?e:void 0));t.authority?.assertCurrent();return this.lookupLocalApprovalId(e,{includeResolved:t.includeResolved,filter:e=>o.includes(e)})}lookupLocalApprovalId(e,t={}){const n=this.getLocalSnapshot(e);const r=n?e:e.trim();const i=n??(r?this.getLocalSnapshot(r):null);if(i)return(t.includeResolved||i.resolvedAtMs===void 0)&&(t.filter?.(i)??true)?{kind:`exact`,id:r}:{kind:`none`};if(!r)return{kind:`none`};const a=normalizeLowercaseStringOrEmpty(r);const o=new Map(Array.from(this.pending.values(),e=>[e.record.id,e.record]));const s=[];for(const[e,n]of o){if(!normalizeLowercaseStringOrEmpty(e).startsWith(a)||!t.includeResolved&&n.resolvedAtMs!==void 0||t.filter?.(n)===false)continue;s.push(e)}return s.length===1?{kind:`prefix`,id:expectDefined(s[0],`approval prefix match`)}:s.length>1?{kind:`ambiguous`,ids:s}:{kind:`none`}}};function prepareExecApprovalRedemptionWindow(e,t,n){const r=e.resolvedAtMs;if(r===void 0||t===null||n-t>=15e3||e.decision!==`allow-once`||e.consumedDecision)return null;return EXEC_APPROVAL_RESOLVED_ENTRY_GRACE_MS+Math.max(0,t-r)}export{prepareExecApprovalStandingGrant as a,assertUncertainExecApprovalPersistenceCurrent as c,runWithExecApprovalMutationPersistence as d,prepareExecApprovalRedemptionWindow as i,captureExecApprovalMutationPersistence as l,EXEC_APPROVAL_RESOLVED_ENTRY_GRACE_MS as n,projectRepairedApprovalResolution as o,ExecApprovalLifecycle as r,assertExecApprovalMutationPersistenceCurrent as s,ApprovalObserverClosedError as t,readUncertainExecApprovalVerdict as u};