UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

6 lines (5 loc) • 10.8 kB
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty,u as normalizeOptionalStringifiedId}from"./string-coerce-CpTFcSwY.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as sliceUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{d as sleepWithAbort}from"./src-De06gkOi.mjs";import{l as resolveAgentIdFromSessionKey,w as isSubagentSessionKey,x as isCronSessionKey}from"./session-key-BPgKfU2m.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{r as emitDiagnosticEvent}from"./diagnostic-events-BYBrlAdF.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{r as remainingMonotonicMs,t as monotonicDeadlineAfter}from"./monotonic-time-DjtFTu2s.mjs";import{n as normalizeMessageChannel}from"./message-channel-core-D_hPOadj.mjs";import{n as isGatewayMessageChannel}from"./message-channel-normalize-hDAO6_JQ.mjs";import"./message-channel-514k57tV.mjs";import{i as readSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{a as readCapturedSessionActorEntry,t as captureSessionActorStorageOwner}from"./session-actor-storage-binding-Bq_IHhu0.mjs";import{n as renderUserFacingText}from"./user-facing-text-ZTl9Tw-Y.mjs";import{O as formatExecDeniedReasonMessage,j as parseExecApprovalResultText}from"./user-copy-B1CccoqG.mjs";import{t as callGatewayTool}from"./gateway-Bf9f0Pcc.mjs";import{n as getGatewayLifecycleRuntime}from"./server-lifecycle-runtime-context-DYFWrmlO.mjs";import{t as resolveExternalBestEffortDeliveryTarget}from"./best-effort-delivery-LTdpuRik.mjs";import{t as sendMessage}from"./message-C5aDUZ_P.mjs";import{n as buildExecApprovalContinuationFallbackPrompt}from"./bash-tools.exec-approval-output-KQknzBii.mjs";import{i as isExecApprovalFollowupSessionRebound,o as registerExecApprovalFollowupRuntimeHandoff,t as buildExecApprovalFollowupIdempotencyKey}from"./bash-tools.exec-approval-followup-state-tzO4P1ay.mjs"; //!src/agents/bash-tools.exec-approval-followup.ts const log=createSubsystemLogger(`agents/exec-approval-followup`);const DIRECT_FOLLOWUP_MAX_UTF16_UNITS=4e3;const DIRECT_FOLLOWUP_TRUNCATION_MARKER=`[... earlier command output omitted ...]`;const DIRECT_FOLLOWUP_COMPLETION_RETENTION={idPrefix:`exec-approval-followup:`,maxAgeMs:864e5,maxEntries:2e3};const AGENT_FOLLOWUP_WAIT_TIMEOUT_MS=6e4;const AGENT_FOLLOWUP_WAIT_RETRY_DELAY_MS=1e3;const AGENT_FOLLOWUP_OBSERVATION_TIMEOUT_MS=36e4;async function callExecApprovalFollowupGateway(e,t,n){const r=getGatewayLifecycleRuntime();if(r)return e===`agent`?await r.dispatchAgent(n,t):await r.waitForAgent(n,t);return await callGatewayTool(e,{timeoutMs:t},n)}function buildExecDeniedFollowupPrompt(e){return[`An async command did not run.`,`Do not run the command again.`,`There is no new command output.`,`Do not mention, summarize, or reuse output from any earlier run in this session.`,``,`Exact completion details:`,e.trim(),``,`Reply to the user in a helpful way.`,`Explain that the command did not run and why.`,`Do not claim there is new command output.`].join(` `)}function formatUnknownError(e){if(e instanceof Error)return e.message;if(typeof e===`string`)return e;try{return JSON.stringify(e)}catch{return`unknown error`}}function shouldSuppressExecDeniedFollowup(e){return isSubagentSessionKey(e)||isCronSessionKey(e)}async function isExecApprovalFollowupDirectDeliveryStale(e){const t=normalizeOptionalString(e.sessionKey);const n=normalizeOptionalString(e.expectedSessionId);if(!t||!n)return false;try{if(e.source){const r=e.source;const i=readCapturedSessionActorEntry(r,t);return!i||i.sessionId!==n||i.lifecycleRevision!==e.expectedLifecycleRevision}const r=resolveSessionStorePathCore(normalizeOptionalString(e.sessionStore),{agentId:e.agentId??resolveAgentIdFromSessionKey(t)});const i=normalizeOptionalString((await readSessionEntryReadOnlyInWorker({agentId:e.agentId,storePath:r,sessionKey:t,clone:false}))?.sessionId);return isExecApprovalFollowupSessionRebound({expectedSessionId:n,resolvedSessionId:i})}catch(n){if(e.source){log.debug(`exec approval followup source retired for ${t}; suppressing delivery`);return true}log.debug(`exec approval followup session-rebind check skipped for ${t}; delivering: ${formatUnknownError(n)}`);return false}}function formatDirectExecApprovalFollowupText(e,t={}){if(e.kind===`other`&&!e.raw)return null;if(e.kind===`denied`)return t.allowDenied?formatExecDeniedReasonMessage(e.metadata):null;const n=e.kind===`finished`?normalizeLowercaseStringOrEmpty(e.metadata):``;const r=renderUserFacingText(e.kind===`finished`||e.kind===`completed`?e.body:e.raw,{errorContext:!n.includes(`code 0`)}).trim();if(e.kind===`finished`)return r||(n.includes(`code 0`)?`Background command finished.`:n.includes(`signal`)?`Background command stopped unexpectedly.`:`Background command finished with an error.`);return r||(e.kind===`completed`?`Background command finished.`:null)}function readGatewayString(e,t){return isRecord(e)?normalizeOptionalString(e[t]):void 0}function buildFollowupWaitError(e){const t=typeof e.error===`string`&&e.error.trim()?`: ${e.error.trim()}`:e.status?`: ${e.status}`:``;return/* @__PURE__ */ new Error(`exec approval followup session resume failed${t}`)}function hasTerminalFollowupEvidence(e){if(!isRecord(e))return false;return typeof e.endedAt===`number`||typeof e.error===`string`||typeof e.stopReason===`string`||e.livenessState===`terminal`}async function waitForAgentFollowupRun(e){const t=monotonicDeadlineAfter(AGENT_FOLLOWUP_OBSERVATION_TIMEOUT_MS);let n=0;let r=0;for(;;){const i=remainingMonotonicMs(t);if(i<=0)return{status:`observation_ended`,reason:`deadline`,transportErrors:r};const a=Math.max(1,Math.ceil(Math.min(e.timeoutMs,i)));let o;try{o=await callExecApprovalFollowupGateway(`agent.wait`,a+2e3,{runId:e.runId,timeoutMs:a})}catch{n+=1;r+=1;const e=Math.min(AGENT_FOLLOWUP_WAIT_RETRY_DELAY_MS,remainingMonotonicMs(t));if(e<=0)return{status:`observation_ended`,reason:`deadline`,transportErrors:r};if(n>1)await sleepWithAbort(e,void 0,{ref:false});continue}n=0;const s=readGatewayString(o,`status`);if(s===`ok`)return{status:`completed`};if(hasTerminalFollowupEvidence(o))throw buildFollowupWaitError({status:s,error:o.error})}}async function sendExecApprovalFollowup(e){const t=e.sessionKey?.trim();const n=t?captureSessionActorStorageOwner({agentId:e.agentId,sessionKey:t},{assertCurrent(){},authorize(){}}):void 0;const r=n&&t?readCapturedSessionActorEntry(n,t)?.lifecycleRevision:void 0;const i=parseExecApprovalResultText(e.resultText);if(!i.raw)return false;const a=e.resultText;const o=i.kind===`denied`;let s=e.internalRuntimeHandoffId;let c=e.idempotencyKey;if(!o&&t&&e.direct!==true&&!s){const n=registerExecApprovalFollowupRuntimeHandoff({approvalId:e.approvalId,sessionKey:t,resultText:a});s=n?.handoffId;c=n?.idempotencyKey}const l=resolveExternalBestEffortDeliveryTarget({channel:e.turnSourceChannel,to:e.turnSourceTo,accountId:e.turnSourceAccountId,threadId:e.turnSourceThreadId});const u=normalizeMessageChannel(e.turnSourceChannel);const d=u&&isGatewayMessageChannel(u)?u:void 0;let f=null;if(o&&(!t||shouldSuppressExecDeniedFollowup(t)))return false;if(t&&e.direct!==true)try{const n=d??e.turnSourceChannel;const r={...e.agentId?{agentId:e.agentId}:{},sessionKey:t,message:o?buildExecDeniedFollowupPrompt(a):buildExecApprovalContinuationFallbackPrompt(a,i),inputProvenance:{kind:`inter_session`,sourceSessionKey:t,sourceTool:`exec_approval_followup`},deliver:l.deliver,...l.deliver?{bestEffortDeliver:true}:{},channel:l.deliver?l.channel:n,to:l.deliver?l.to:e.turnSourceTo,accountId:l.deliver?l.accountId:e.turnSourceAccountId,threadId:l.deliver?l.threadId:normalizeOptionalStringifiedId(e.turnSourceThreadId),idempotencyKey:c??buildExecApprovalFollowupIdempotencyKey({approvalId:e.approvalId}),...e.expectedSessionId?{execApprovalFollowupExpectedSessionId:e.expectedSessionId}:{},...s?{internalRuntimeHandoffId:s}:{}};const u=await callExecApprovalFollowupGateway(`agent`,6e4,r);const f=readGatewayString(u,`status`);if(f===`ok`)return true;if(f===`accepted`||f===`in_flight`||f===`pending`){const t=readGatewayString(u,`runId`)??normalizeOptionalString(r.idempotencyKey);if(!t)throw buildFollowupWaitError({status:`missing-run-id`});const n=await waitForAgentFollowupRun({runId:t,timeoutMs:AGENT_FOLLOWUP_WAIT_TIMEOUT_MS});if(n.status===`observation_ended`){emitDiagnosticEvent({type:`log.record`,level:`WARN`,message:`Exec approval followup observation ended`,loggerName:`agents/exec-approval-followup`,attributes:{approvalId:e.approvalId,runId:t,reason:n.reason,transportErrors:n.transportErrors,deliveryOwner:`accepted_agent_run`}});log.warn(`Stopped observing accepted exec approval followup ${e.approvalId} after its bounded wait window; run ${t} remains the sole delivery owner`)}return true}throw buildFollowupWaitError({status:f,error:u.error})}catch(e){f=e}if(await isExecApprovalFollowupDirectDeliveryStale({agentId:e.agentId,sessionKey:t,expectedSessionId:e.expectedSessionId,sessionStore:e.sessionStore,source:n,expectedLifecycleRevision:r})){emitDiagnosticEvent({type:`exec.approval.followup_suppressed`,approvalId:e.approvalId,reason:`session_rebound`,phase:`direct_delivery`});log.info(o?`Dropping stale denied exec approval followup ${e.approvalId}: session ${t??``} was rebound before the approval resolved`:`Dropping stale exec approval followup ${e.approvalId} direct fallback: session ${t??``} was rebound before the approval resolved`);return false}const p=formatDirectExecApprovalFollowupText(i,{allowDenied:o||f!==null});if(l.deliver&&p){const t=!o&&f&&(i.kind!==`finished`||!normalizeLowercaseStringOrEmpty(i.metadata).includes(`code 0`))?`Automatic session resume failed, so sending the status directly. `:``;const n=DIRECT_FOLLOWUP_MAX_UTF16_UNITS-t.length-40-1;const r=`${t}${p}`.length<=DIRECT_FOLLOWUP_MAX_UTF16_UNITS?`${t}${p}`:`${t}${DIRECT_FOLLOWUP_TRUNCATION_MARKER}\n${sliceUtf16Safe(p,Math.max(0,p.length-Math.max(1,n)))}`;const a=`exec-approval-followup:${e.approvalId}`;const s=await sendMessage({channel:l.channel,to:l.to??``,accountId:l.accountId,threadId:l.threadId,content:r,agentId:e.agentId,gatewayOwnedDelivery:true,idempotencyKey:a,deliveryIntentId:a,reusePendingDeliveryIntent:true,completionRetention:DIRECT_FOLLOWUP_COMPLETION_RETENTION});if(s.deliveryStatus===`suppressed`)throw new Error(s.suppressionReason===`adapter_returned_no_identity`?`exec approval followup delivery could not be confirmed: adapter returned no identity`:`exec approval followup delivery was suppressed: ${s.suppressionReason??`unknown reason`}`);return true}if(f)throw new Error(`Session followup failed: ${formatUnknownError(f)}`);if(o)return false;throw new Error(`Session key or deliverable origin route is required`)}export{sendExecApprovalFollowup};