openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
23 lines (22 loc) • 34.3 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{s as asFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{a as asOptionalRecord}from"./record-coerce-BTbqdJ3-.mjs";import{r as filterStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{n as sliceUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{r as isIncognitoSessionKey}from"./session-key-DYtwLLn1.mjs";import{N as parseAgentSessionKey,c as normalizeOptionalAgentId,l as resolveAgentIdFromSessionKey,w as isSubagentSessionKey}from"./session-key-BPgKfU2m.mjs";import{n as normalizeAccountId}from"./account-id-3yqrEsRn.mjs";import{r as getBoundLegacyPluginSdkResourceHost}from"./legacy-sdk-resource-host-9HMZFK01.mjs";import{l as resolveConfiguredAcpSubagentTargetIds}from"./agent-roster-4XrgUgPK.mjs";import{l as resolveSessionStorePathCore}from"./paths-CcxgiC3g.mjs";import{x as resolveSessionAgentId}from"./agent-scope-config-CG9CFpGX.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{o as sessionChanges}from"./session-row-changes-21DJT-m_.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{h as onAgentEventForRun}from"./agent-events-Dz03BVGI.mjs";import{m as sessionEntryCommitGuardOptions,s as composeSessionSourceAssertion}from"./session-source-authority-Cun3s-rH.mjs";import{i as requesterCreatorProfileId}from"./requester-origin-C_JipMKu.mjs";import{s as normalizeAssistantPhase}from"./chat-message-content-BwODI7B3.mjs";import{n as isExecutionIdentityCollectionEnabled}from"./audit-config-Dqz9Raz7.mjs";import{h as recordSubagentSpawned}from"./session-state-events-CQlZG6hg.mjs";import{t as enqueueSessionEventForHost}from"./session-event-handoff-DPJ2DWnj.mjs";import{i as buildSessionCreationStamp,n as attributeDelegatedSessionCreator,o as inheritSessionGitContributorProfileIds}from"./session-entry-provenance-DZd--atF.mjs";import{r as hasDeliveryTargetFields}from"./delivery-context.shared-L-4UIv4-.mjs";import{i as resolveSpawnedWorkspaceInheritance}from"./spawned-context-BR4pD9zG.mjs";import{r as resolveChannelAccountEntry}from"./account-lookup-DXbrh7Os.mjs";import{i as readSessionEntryReadOnlyInWorker,l as withSessionEntryReadOnlyInWorker}from"./session-entry-read-runtime-kAgwDw0B.mjs";import{t as deliveryContextFromSession}from"./delivery-context.read-DWpauVKG.mjs";import{o as getGatewayToolCallerIdentity}from"./gateway-caller-context-Dw9IijqV.mjs";import{i as resolveInboundConversationResolution}from"./conversation-resolution-CtbOlmJd.mjs";import{m as isSessionBindingError}from"./current-conversation-bindings.kernel-CjaL8Y5w.mjs";import{a as listSessionBindingsBySessionAsync,t as getSessionBindingService}from"./session-binding-service-TO5btU7E.mjs";import{i as captureSessionEventTargetForHost}from"./session-event-target-xxrhl4__.mjs";import"./session-accessor-CY8UYP4m.mjs";import{s as withPreparedSessionCapabilityRead}from"./subagent-session-store-ClkR5Yv6.mjs";import{d as upsertSessionEntryCore}from"./session-accessor.sqlite-entry-CQTjQD5y.mjs";import"./config-DkZ8y8Gv.mjs";import{h as isSessionVisibilityAllowed}from"./session-sharing-policy-CQ0Zqotl.mjs";import{C as findAcpUnsupportedInheritedToolDeny,D as inheritedToolDenyPatch,E as inheritedToolAllowPatch,S as findAcpUnsupportedInheritedToolAllow,T as formatAcpInheritedToolDenyError,l as resolveSubagentCapabilityStore,t as isSubagentEnvelopeSession,w as formatAcpInheritedToolAllowError}from"./subagent-capabilities-Cq_ZFJj-.mjs";import{n as getSubagentDepthFromSessionStoreInWorker}from"./subagent-depth-BZiMynYG.mjs";import{_ as prepareSubagentSessionListReadCache}from"./subagent-registry-state-6jDCy1Tv.mjs";import{s as getSubagentSessionListRunByChildSessionKey}from"./subagent-registry-read-tETbCW7T.mjs";import{r as resolveGatewaySessionStoreTargetInWorker}from"./session-utils-store-worker-43BDHG7V.mjs";import{n as getGlobalHookRunner}from"./hook-runner-global-DNCi6wD6.mjs";import{c as runWithAgentToolSourceExecutionScope}from"./agent-tool-source-execution-guard-D2z6vTFX.mjs";import{t as acpSessionRowMatchesEntry}from"./session-meta-keys-DL7xDHXx.mjs";import{n as listActiveAcpSessionsForOwner}from"./active-turns-DVMo0kah.mjs";import{r as truncateUtf16WithEllipsis}from"./text-truncate-BxVDOUs6.mjs";import{n as isAcpEnabledByPolicy,r as resolveAcpAgentPolicyError}from"./policy-CIPOPPWo.mjs";import{o as resolveInternalSessionKey,s as resolveMainSessionAlias}from"./sessions-resolution-BEFvpmxf.mjs";import"./sessions-helpers-FFwQ13n5.mjs";import{l as captureAcpSessionReadContext}from"./session-meta-read-hVOPXzGo.mjs";import{t as AGENT_LANE_SUBAGENT}from"./lanes-tRD-rSIg.mjs";import{T as resolveChannelStreamingProgressCommentary}from"./streaming-L5RwfkL2.mjs";import{t as recordSessionCreated}from"./session-created-CttkwWUi.mjs";import{n as resolveEventSessionRoutingPolicy,t as resolveEventSessionKeyForPolicy}from"./event-session-routing-BUjmzHiY.mjs";import{n as waitForSessionParticipantRecording,t as recordSessionParticipantBestEffort}from"./session-participant-recording-CxaUPmMI.mjs";import{n as formatConversationTarget,t as deliveryContextFromConversation}from"./route-projection-ImIQZq_k.mjs";import{n as resolveRequesterOriginForChild,r as resolveSpawnRequesterConversationTarget}from"./spawn-requester-origin-BINbaf_h.mjs";import{t as readParentExecutionIdentity}from"./execution-identity-spawn-context-qCnrk4rz.mjs";import{a as resolveSpawnMode,i as resolveSpawnChannelAccountId,n as prepareSpawnThreadBinding,r as resolveSpawnAdmission,s as reserveChildAdmissionSlot,t as mintSpawnSessionKey}from"./spawn-plan-D3Wy3SHx.mjs";import{n as resolveAcpSpawnRuntimePolicyError,t as resolveAcpSenderSpawnError}from"./acp-spawn-policy-BXR-KaeE.mjs";import{n as resolveTargetAcpAgentId}from"./acp-spawn-target-AwumxLF-.mjs";import{i as readGatewayRunId,n as callSubagentGateway}from"./subagent-spawn-gateway-DJxCRS42.mjs";import{r as withSubagentGatewayExecutionIdentity,t as buildSubagentExecutionSessionSpawnContext}from"./subagent-spawn-execution-identity-Cit7tpZM.mjs";import{a as cleanupFailedAcpSpawn,i as resolveRuntimeCwdForAcpSpawn,n as initializeAcpSpawnRuntime,r as resolveAcpSpawnRuntimeOptions,t as bindPreparedAcpThread}from"./acp-spawn-runtime-Ba3j1dXe.mjs";import{a as runSpawnPipeline,o as summarizeSpawnError,t as resolveConfiguredSubagentRunTimeoutSeconds}from"./subagent-spawn-plan-C4GjtC_l.mjs";import{t as captureSpawnParentLineage}from"./spawn-parent-lineage-BM1dz2Yv.mjs";import{n as resolveAcpProjectionSettings,t as isAcpTagVisible}from"./acp-stream-settings-BKvgFCOC.mjs";import{t as resolveSubagentSpawnOwnership}from"./subagent-spawn-ownership-gOOT55cQ.mjs";import crypto from"node:crypto";
//!src/acp/runtime/session-meta-resume.ts
async function readAcpResumeSessionOwner(e){const{agentId:t,backendId:n,resumeSessionId:r}=e;const i=normalizeOptionalAgentId(e.runtimeAgentId);const{cfg:a,env:o,databasePath:s,assertCurrent:c}=await captureAcpSessionReadContext(e);if(!i)return;const lookup=async e=>{const i=await executeExistingOpenClawStateRead({env:o,path:s},{type:`acpSessions.resume`,agentId:t,backendId:n,resumeSessionId:r,sessionKey:e},{current:true});c();if(!i)return[];return i.rows};const l=await lookup();const u=resolveSessionStorePathCore(a.session?.store,{agentId:t,env:o});for(const n of l){if(normalizeOptionalAgentId(n.agent)!==i)continue;e.onCandidate?.(n.sessionKey);const r=await withSessionEntryReadOnlyInWorker({agentId:t,storePath:u,sessionKey:n.sessionKey,env:o,clone:false},c,async e=>{if(!e.ok)throw e.error;if(!e.value||!acpSessionRowMatchesEntry(n,e.value))return;const[t]=await lookup(n.sessionKey);return t&&acpSessionRowMatchesEntry(t,e.value)&&normalizeOptionalAgentId(t.agent)===i?{sessionKey:n.sessionKey,entry:e.value}:void 0});if(r)return r}}
//!src/acp/runtime/session-meta-resume-authorization.ts
async function withAcpResumeSessionAuthorization(e,t){if(!normalizeOptionalString(e.resumeSessionId))return t();let n=true;const r=/* @__PURE__ */ new Map;const i=sessionChanges.subscribeFacts(e=>{if(`sessionKey`in e&&!e.factsInvalidated&&(e.facts?.kind===`unchanged`||e.facts?.kind===`participants`||e.facts?.kind===`category`))return;if(`all`in e||r.has(e.sessionKey)&&(!e.agentId||r.get(e.sessionKey)?.has(e.agentId)))n=false});const assertCurrent=()=>{e.assertCurrent?.();if(!n)throw new Error(`ACP resume source authority changed; retry from the current session.`)};try{return await t(async()=>{assertCurrent();const t=await validateAcpResumeSessionOwnership({...e,assertCurrent},(e,t)=>{const n=r.get(t)??/* @__PURE__ */ new Set;n.add(e);r.set(t,n)});if(!t.ok)throw new Error(t.error);return assertCurrent})}finally{n=false;i()}}async function validateAcpResumeSessionOwnership(e,t){const n=normalizeOptionalString(e.resumeSessionId);if(!n)return{ok:true};const r=normalizeOptionalString(e.requesterSessionKey);if(!r)return{ok:false,error:`sessions_spawn resumeSessionId requires an active requester session context.`};for(const i of/* @__PURE__ */ new Set([e.ownerAgentId,e.runtimeAgentId])){const a=await readAcpResumeSessionOwner({...e,agentId:i,resumeSessionId:n,onCandidate:e=>t?.(i,e)});e.assertCurrent?.();if(!a)continue;if(a.sessionKey===r||normalizeOptionalString(a.entry.spawnedBy)===r||normalizeOptionalString(a.entry.parentSessionKey)===r)return{ok:true};break}return{ok:false,error:`sessions_spawn resumeSessionId is only allowed for ACP sessions previously recorded for this requester. Omit resumeSessionId to start a fresh ACP session.`}}
//!src/agents/subagents/spawn/acp-spawn-admission.ts
function countUntrackedActiveAcpRunsForOwner(e,t){if(!e?.trim())return 0;const n=listActiveAcpSessionsForOwner(e.trim());return new Set(n.filter(e=>{const n=getSubagentSessionListRunByChildSessionKey(e);return!t?.has(e)&&!(n&&typeof n.execution.endedAt!==`number`)})).size}
//!src/agents/subagents/spawn/acp-spawn-bootstrap-delivery.ts
function toGatewayImageAttachments(e){if(!e||e.length===0)return;return e.map(e=>({type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data}}))}function resolveAcpSpawnBootstrapDeliveryPlan(e){const t=normalizeOptionalString(e.binding?.conversation.conversationId);const n=e.requester.origin?.threadId;const r=n!=null?normalizeOptionalString(String(n)):void 0;const i=t??r;const a=resolveInboundConversationResolution({cfg:e.cfg,channel:e.requester.origin?.channel,accountId:e.requester.origin?.accountId,threadId:r,to:e.requester.origin?.to});const o=resolveSpawnChannelAccountId({cfg:e.cfg,channel:e.requester.origin?.channel,accountId:e.requester.origin?.accountId});const s=Boolean(e.requester.origin?.channel&&e.binding?.conversation.channel===e.requester.origin.channel&&e.binding.conversation.accountId===o&&a?.conversationId&&e.binding.conversation.conversationId===a.conversationId&&e.binding.conversation.parentConversationId===a.parentConversationId);const c=deliveryContextFromConversation(e.binding?.conversation);const l=(s?e.requester.origin?.to:void 0)??c?.to??e.requester.origin?.to??formatConversationTarget({channel:e.requester.origin?.channel,conversationId:i});const u=s?r:c?.threadId??i;const d=Boolean(e.requester.origin?.channel&&l)&&!e.effectiveStreamToParent&&e.spawnMode===`session`;return{useInlineDelivery:d,channel:d?e.requester.origin?.channel:void 0,accountId:d?o:void 0,to:d?l:void 0,threadId:d&&u!=null?normalizeOptionalString(String(u)):void 0}}
//!src/agents/subagents/spawn/acp-spawn-creation.ts
function prepareAcpSpawnCreation(e){const t=captureSpawnParentLineage({parentEntry:e.parentEntry,expectedParentSessionId:e.expectedParentSessionId,senderIsOwner:e.senderIsOwner});const n=composeSessionSourceAssertion([e.assertActive],t=>{t();if(e.parentEntry?.visibility===`draft`&&!isSessionVisibilityAllowed(readRuntimeConfig(),`draft`))throw new Error(`session visibility is disabled: draft. Continue in the existing Draft or ask an administrator to enable Draft creation.`)});n();return{assertCurrent:n,parentPatch:{...t,...e.parentEntry?.visibility===`draft`?{visibility:`draft`}:{}},stamp:buildSessionCreationStamp({via:`spawn`,actor:attributeDelegatedSessionCreator({type:`agent`,id:e.requesterAgentId},e.creatorProfileId),inheritedGitContributorProfileIds:inheritSessionGitContributorProfileIds(e.parentEntry,{config:e.cfg,agentId:e.requesterAgentId,sessionKey:e.requesterSessionKey,requesterProfileId:e.gitContributorProfileId})})}}
//!src/agents/subagents/spawn/acp-spawn-gateway.ts
async function launchAcpChildThroughGateway(e){const t=Date.now();const n=await callSubagentGateway(withSubagentGatewayExecutionIdentity({method:`agent`,assertDispatchCurrent:e.assertDispatchCurrent,params:{message:e.task,sessionKey:e.sessionKey,channel:e.deliveryPlan.channel,to:e.deliveryPlan.to,accountId:e.deliveryPlan.accountId,threadId:e.deliveryPlan.threadId,idempotencyKey:e.childIdem,deliver:e.deliveryPlan.useInlineDelivery,lane:AGENT_LANE_SUBAGENT,acpTurnSource:`manual_spawn`,timeout:e.runTimeoutSeconds,label:e.label||void 0,...e.attachments?{attachments:e.attachments}:{}},timeoutMs:1e4},{sessionSpawnContext:buildSubagentExecutionSessionSpawnContext(e.lineage),parentExecutionIdentityToken:e.parentExecutionIdentityToken}));recordSessionParticipantBestEffort({promptedAt:t,identity:{type:`agent`,id:e.lineage.parentAgentId},agentId:e.lineage.targetAgentId,sessionKey:e.sessionKey,storePath:e.participantStorePath});return n}
//!src/agents/subagents/spawn/acp-spawn-parent-stream.ts
const STREAM_FLUSH_MS=2500;const NO_OUTPUT_NOTICE_MS=6e4;const NO_OUTPUT_POLL_MS=15e3;const MAX_RELAY_LIFETIME_MS=216e5;const STREAM_BUFFER_MAX_CHARS=4e3;const STREAM_SNIPPET_MAX_CHARS=220;const log=createSubsystemLogger(`agents/acp-parent-stream`);function mergeStreamingConfig(e,t){const n=asOptionalRecord(e);const r=asOptionalRecord(t);if(!n||!r)return t??e;const i={...n,...r};const a=asOptionalRecord(n.progress);const o=asOptionalRecord(r.progress);if(a&&o)i.progress={...a,...o};else if(o??a)i.progress=o??a;else delete i.progress;return i}function resolveParentProgressStreamingEntry(e){const t=normalizeOptionalString(e.deliveryContext?.channel);if(!e.cfg||!t)return;const n=e.cfg.channels?.[t];if(!n)return;const r=resolveChannelAccountEntry(n.accounts,normalizeAccountId(e.deliveryContext?.accountId),t,normalizeAccountId);return r?{...n,...r,streaming:mergeStreamingConfig(n.streaming,r.streaming)}:n}function startAcpSpawnParentStreamRelay(e){const{runId:t,parentSessionKey:n,eventRouting:r}=e;const i=truncateUtf16WithEllipsis(e.agentId.replace(/\s+/g,` `).trim(),40)||`ACP child`;const a=`acp-spawn:${t}`;const o=getBoundLegacyPluginSdkResourceHost()?.scheduler.signal;let s=false;const c=resolveChannelStreamingProgressCommentary(resolveParentProgressStreamingEntry({cfg:e.cfg,deliveryContext:e.deliveryContext}),true);const l=resolveAcpProjectionSettings(e.cfg??{});const u=resolveEventSessionKeyForPolicy(n,r);const d=structuredClone(e.deliveryContext);const emit=(n,r)=>{const i=truncateUtf16WithEllipsis(n.trim(),STREAM_BUFFER_MAX_CHARS);if(s||!i)return;try{enqueueSessionEventForHost(i,{agentId:e.requesterAgentId,sessionKey:u,source:`task`,contextKey:r,deliveryContext:d,expectedTarget:e.expectedTarget}).settled.then(e=>{if(e.status!==`completed`)log.warn(`ACP parent relay follow-up failed`,{runId:t,contextKey:r,...e})})}catch(e){log.warn(`ACP parent relay follow-up rejected`,{runId:t,contextKey:r,error:String(e)})}};const emitStartNotice=()=>{emit(`Started ${i} session ${e.childSessionKey}. Streaming progress updates to parent session.`,`${a}:start`)};let f=``;let p;let m;const h=/* @__PURE__ */ new Map;let g=Date.now();let _=false;let v;let y;let b;let x;let S=[];let C;const clearFlushTimer=()=>{clearTimeout(C);C=void 0};const flushPending=()=>{clearFlushTimer();if(!f)return;const e=truncateUtf16WithEllipsis(f.replace(/\s+/g,` `).trim(),STREAM_SNIPPET_MAX_CHARS);f=``;p=void 0;if(!e)return;emit(`${i}: ${e}`,`${a}:progress`)};const scheduleFlush=()=>{if(s||C)return;C=setTimeout(flushPending,STREAM_FLUSH_MS);C.unref()};const appendVisibleProgress=(e,t)=>{if(_){_=false;emit(`${i} resumed output.`,`${a}:resumed`)}g=Date.now();b??=g;if(f&&p&&p!==t)flushPending();p=t;f+=e;if(f.length>STREAM_BUFFER_MAX_CHARS)f=sliceUtf16Safe(f,-4e3);if(f.length>=STREAM_SNIPPET_MAX_CHARS||e.includes(`
`)){flushPending();return}scheduleFlush()};const flushReplaceableAssistantSnapshot=()=>{const e=m;m=void 0;if(!e?.trim())return;appendVisibleProgress(e,`assistant:replaceable`)};const appendItemProgressSnapshot=e=>{const t=h.get(e.itemId)??``;if(e.text===t)return;const n=`item:${e.itemId}`;const r=Boolean(t&&e.text.startsWith(t));if(t&&!r&&p===n&&Boolean(f))f=``;h.set(e.itemId,e.text);const i=r?e.text.slice(t.length):e.text;appendVisibleProgress(i,n)};const buildNoOutputNotice=()=>{const e=Math.round(NO_OUTPUT_NOTICE_MS/1e3);if(!v)return`${i} session started but no prompt submission was observed for ${e}s.`;if(!y){const t=`proxy env: ${S.join(`, `)||`none`}`;return`${i} prompt was submitted but no ACP runtime event arrived for ${e}s (${t}). Check upstream connectivity, auth, or proxy/network access in the gateway child environment.`}if(!b){const t=x?` Last ACP event: ${x}.`:``;return`${i} has ACP runtime activity but no visible assistant output for ${e}s.${t} It may be working, blocked on a tool, or failing before visible output.`}return`${i} has produced no visible output for ${e}s. It may be waiting for interactive input.`};const w=setInterval(()=>{if(s||_||Date.now()-g<NO_OUTPUT_NOTICE_MS)return;_=true;emit(buildNoOutputNotice(),`${a}:stall`)},NO_OUTPUT_POLL_MS);w.unref();const T=setTimeout(()=>{if(s)return;emit(`${i} stream relay timed out after ${Math.round(MAX_RELAY_LIFETIME_MS/1e3)}s without completion.`,`${a}:timeout`);dispose()},MAX_RELAY_LIFETIME_MS);T.unref();const E=onAgentEventForRun(t,e=>{if(s||e.runId!==t)return;if(e.stream===`assistant`){const t=e.data;const n=normalizeAssistantPhase(t.phase);const r=t.text;const i=t.delta;const a=typeof r===`string`?r:typeof i===`string`?i:void 0;if(t.replaceable===true){if(a?.trim()){m=a;g=Date.now()}return}const o=typeof i===`string`?i:a;if(!o||!o.trim())return;if(n===`commentary`&&!c){g=Date.now();return}m=void 0;appendVisibleProgress(o,`assistant:${n??`unknown`}`);return}if(e.stream===`item`){const t=e.data;const n=normalizeOptionalString(t?.itemId);const r=normalizeOptionalString(t?.kind);const i=normalizeOptionalString(t?.progressText);if(r===`preamble`&&i){g=Date.now();if(c&&n)appendItemProgressSnapshot({itemId:n,text:i})}return}if(e.stream===`acp`){const t=e.data;const n=normalizeOptionalString(t?.phase);if(n===`prompt_submitted`){const e=asFiniteNumber(t?.at)??Date.now();v??=e;S=filterStringEntries(t?.proxyEnvKeys).filter(Boolean);g=Date.now();return}if(n===`runtime_event`){const e=normalizeOptionalString(t?.eventType);const n=normalizeOptionalString(t?.text);const r=normalizeOptionalString(t?.tag);y??=Date.now();x=e;if(c&&e===`status`&&n&&isAcpTagVisible(l,r)){appendVisibleProgress(`${n}\n\n`,`acp:status`);return}g=Date.now();return}return}if(e.stream!==`lifecycle`)return;const n=normalizeOptionalString(e.data.phase);if(n!==`end`&&n!==`error`)return;flushReplaceableAssistantSnapshot();flushPending();if(n===`end`){const t=asFiniteNumber(e.data.startedAt);const n=asFiniteNumber(e.data.endedAt);const r=t!=null&&n!=null&&n>=t?n-t:void 0;emit(r!=null?`${i} run completed in ${Math.max(1,Math.round(r/1e3))}s.`:`${i} run completed.`,`${a}:done`)}else{const t=normalizeOptionalString(e.data.error);emit(t?`${i} run failed: ${t}`:`${i} run failed.`,`${a}:error`)}dispose()});const dispose=async()=>{if(s)return;s=true;clearFlushTimer();clearTimeout(T);clearInterval(w);E();o?.removeEventListener(`abort`,onClose)};const onClose=()=>{dispose()};o?.addEventListener(`abort`,onClose,{once:true});return{dispose,notifyStarted:emitStartNotice}}
//!src/agents/subagents/spawn/acp-spawn-requester.ts
async function readAcpSpawnParentDeliveryContext(e){return await withSessionEntryReadOnlyInWorker({sessionKey:e.parentSessionKey,agentId:resolveAgentIdFromSessionKey(e.parentSessionKey,e.requesterAgentId),clone:false},()=>e.assertActive?.(),async e=>{if(!e.ok)throw e.error;return deliveryContextFromSession(e.value)})}function resolveRequesterInternalSessionKey(e){const{alias:t}=resolveMainSessionAlias(e.cfg);const n=normalizeOptionalString(e.requesterSessionKey);return n?resolveInternalSessionKey({key:n,alias:t}):t}async function resolveAcpSpawnRequesterState(e){const t=parseAgentSessionKey(e.parentSessionKey);const n=Boolean(t)&&isSubagentSessionKey(e.parentSessionKey);const r=n&&e.parentSessionKey?(await listSessionBindingsBySessionAsync(e.parentSessionKey)).some(e=>e.targetKind===`subagent`&&e.status!==`ended`):false;e.assertActive?.();const i=resolveSpawnRequesterConversationTarget(e.ctx);const a=i.threadId!=null;const o=Boolean(n&&!r&&!a&&e.parentSessionKey&&e.cfg.session?.scope!==`global`&&hasDeliveryTargetFields(await readAcpSpawnParentDeliveryContext({parentSessionKey:e.parentSessionKey,requesterAgentId:e.requesterAgentId,assertActive:e.assertActive})));e.assertActive?.();return{isSubagentSession:n,hasActiveSubagentBinding:r,hasThreadContext:a,sessionRelayRouteUsable:o,origin:resolveRequesterOriginForChild({cfg:e.cfg,targetAgentId:e.ownerAgentId,requesterAgentId:e.requesterAgentId,requesterChannel:e.ctx.agentChannel,requesterAccountId:e.ctx.agentAccountId,requesterTo:i.to,requesterThreadId:i.threadId,requesterGroupSpace:e.ctx.agentGroupSpace,requesterMemberRoleIds:e.ctx.agentMemberRoleIds})}}function shouldStreamAcpSpawnToParent(e){const t=e.spawnMode===`run`&&!e.requestThreadBinding&&e.requester.isSubagentSession&&!e.requester.hasActiveSubagentBinding&&!e.requester.hasThreadContext&&e.requester.sessionRelayRouteUsable;return e.streamToParentRequested||t}
//!src/agents/subagents/spawn/acp-spawn-result.ts
function buildAcpSpawnError(e,t,n=`error`){return{status:n,errorCode:e,error:t}}function buildAcpSpawnFailureResult(e,t){const{phase:n,error:r,runId:i}=e;const a=n===`initialize`&&isSessionBindingError(r);return{status:`error`,errorCode:a?`thread_binding_invalid`:n===`dispatch`?`dispatch_failed`:`spawn_failed`,error:a?r.message:n===`register`?`Failed to register ACP run: ${summarizeSpawnError(r)}. Cleanup was attempted, but the already-started ACP run may still finish in the background.`:summarizeSpawnError(r),...n!==`initialize`?{childSessionKey:t}:{},...n===`register`&&i?{runId:i}:{}}}
//!src/agents/subagents/spawn/acp-spawn.ts
const ACP_SPAWN_ACCEPTED_NOTE=`initial ACP task queued in isolated session; follow-ups continue in the bound thread.`;const ACP_SPAWN_SESSION_ACCEPTED_NOTE=`thread-bound ACP session stays active after this task; continue in-thread for follow-ups.`;async function spawnAcpDirect(e,t){const n=readRuntimeConfig();const r=requesterCreatorProfileId(getGatewayToolCallerIdentity()?.requesterOrigin);const i=resolveConfiguredSubagentRunTimeoutSeconds({cfg:n,runTimeoutSeconds:e.runTimeoutSeconds});const a=resolveRequesterInternalSessionKey({cfg:n,requesterSessionKey:t.agentSessionKey});if(!isAcpEnabledByPolicy(n))return buildAcpSpawnError(`acp_disabled`,"ACP is disabled by policy (`acp.enabled=false`).",`forbidden`);const o=e.streamTo===`parent`;const s=normalizeOptionalString(t.agentSessionKey);if(o&&!s)return buildAcpSpawnError(`requester_session_required`,`sessions_spawn streamTo="parent" requires an active requester session context.`);const c=e.thread===true;const l=resolveSessionAgentId({config:n,sessionKey:a,agentId:t.requesterAgentIdOverride});const u=await resolveAcpSpawnRuntimePolicyError({cfg:n,requesterAgentId:l,requesterSessionKey:t.agentSessionKey,requesterSandboxed:t.sandboxed,sandbox:e.sandbox});if(u)return buildAcpSpawnError(`runtime_policy`,u,`forbidden`);const d=findAcpUnsupportedInheritedToolDeny(t.inheritedToolDenylist);if(d)return buildAcpSpawnError(`runtime_policy`,formatAcpInheritedToolDenyError(d),`forbidden`);const f=findAcpUnsupportedInheritedToolAllow(t.inheritedToolAllowlist);if(f)return buildAcpSpawnError(`runtime_policy`,formatAcpInheritedToolAllowError(f),`forbidden`);const p=resolveSpawnMode({requestedMode:e.mode,threadRequested:c});if(p===`session`&&!c)return buildAcpSpawnError(`thread_required`,`sessions_spawn(runtime="acp", mode="session") requires thread=true so the ACP session can stay bound to a channel thread. Retry with { mode: "session", thread: true } on a channel that exposes threads (e.g. Discord, Slack, Telegram topics), or use mode="run" for one-shot work.`);const m=resolveTargetAcpAgentId({requestedAgentId:e.agentId,cfg:n});if(!m.ok)return buildAcpSpawnError(e.agentId&&normalizeOptionalAgentId(e.agentId)?`runtime_agent_mismatch`:`target_agent_required`,m.error);const{agentId:h,configAgentId:g,backendId:_}=m;const v=g??l;const y=t.inheritedToolPolicySource===`sender`;const b=t.sessionPermissionPolicy?.root??t.workspaceDir;const x=resolveAcpSenderSpawnError({...t,requesterAgentId:l,targetAgentId:h,cwd:e.cwd});if(x)return buildAcpSpawnError(`runtime_policy`,x,`forbidden`);const S=resolveAcpAgentPolicyError(n,h);if(S)return buildAcpSpawnError(`agent_forbidden`,S.message,`forbidden`);const C=resolveSubagentCapabilityStore(s,{cfg:n});const w=await resolveAcpSpawnRequesterState({cfg:n,parentSessionKey:s,requesterAgentId:l,ownerAgentId:v,ctx:t,assertActive:t.assertActive});t.assertActive?.();const T=resolveSubagentSpawnOwnership({cfg:n,agentSessionKey:t.agentSessionKey,completionOwnerKey:t.completionOwnerKey});const E=await resolveGatewaySessionStoreTargetInWorker({cfg:n,key:T.completionRequesterSessionKey,agentId:t.requesterAgentIdOverride,assertActive:t.assertActive});t.assertActive?.();const D=E.store[E.canonicalKey];const O=D?.sessionId;const k=D?.lifecycleRevision;const A=await withPreparedSessionCapabilityRead(()=>isSubagentEnvelopeSession(a,{cfg:n,store:C}));const j=await getSubagentDepthFromSessionStoreInWorker(a,{cfg:n,agentId:l});await prepareSubagentSessionListReadCache();t.assertActive?.();const resolveAdmission=(r=0,i)=>resolveSpawnAdmission({cfg:n,callerDepth:j,inheritedToolPolicySource:t.inheritedToolPolicySource,enabled:A||y,requesterSessionKey:a,requesterAgentId:l,targetAgentId:h,requestedAgentId:e.agentId,configuredAgentIds:Array.from(resolveConfiguredAcpSubagentTargetIds(n)),additionalActiveChildren:A?countUntrackedActiveAcpRunsForOwner(a,i)+r:0});const M=resolveAdmission();if(!M.ok)return buildAcpSpawnError(`subagent_policy`,M.error,`forbidden`);const N={cfg:n,ownerAgentId:v,runtimeAgentId:h,backendId:_,requesterSessionKey:a,resumeSessionId:e.resumeSessionId,assertCurrent:t.assertActive};const P=await validateAcpResumeSessionOwnership(N);t.assertActive?.();if(!P.ok)return buildAcpSpawnError(`resume_forbidden`,P.error,`forbidden`);const F=resolveAcpSpawnRuntimeOptions({cfg:n,targetAgentId:h,configAgentId:m.configAgentId,model:e.model,thinking:e.thinking,runTimeoutSeconds:i});if(!F.ok)return buildAcpSpawnError(`spawn_failed`,F.error);const I=shouldStreamAcpSpawnToParent({spawnMode:p,requestThreadBinding:c,streamToParentRequested:o,requester:w});const L=mintSpawnSessionKey({targetAgentId:v,backend:`acp`});const R=resolveSpawnedWorkspaceInheritance({config:n,targetAgentId:v,requesterSessionKey:t.agentSessionKey,explicitWorkspaceDir:y?b:e.cwd});let z;try{z=await resolveRuntimeCwdForAcpSpawn({resolvedCwd:R,explicitCwd:y?b:e.cwd})}catch(e){return buildAcpSpawnError(`cwd_resolution_failed`,formatErrorMessage(e))}let B=null;if(c){const e=await prepareSpawnThreadBinding({cfg:n,kind:`acp`,mode:p,bindingService:{...getSessionBindingService(),listBySession:listSessionBindingsBySessionAsync},channel:w.origin?.channel,accountId:w.origin?.accountId,to:w.origin?.to,threadId:w.origin?.threadId,groupId:t.agentGroupId});t.assertActive?.();if(!e.ok)return buildAcpSpawnError(`thread_binding_invalid`,e.error);B=e.binding}let V;let H;const U=crypto.randomUUID();const W=I&&s?await readAcpSpawnParentDeliveryContext({parentSessionKey:s,requesterAgentId:l,assertActive:t.assertActive}):void 0;t.assertActive?.();const G={...process.env};const K=s?resolveEventSessionRoutingPolicy({cfg:n,sessionKey:s}):void 0;const q=I&&s&&K?await captureSessionEventTargetForHost(l,resolveEventSessionKeyForPolicy(s,K)):void 0;const ee=toGatewayImageAttachments(e.attachments);const J=w.origin;const Y={channel:J?.channel,accountId:J?.accountId,to:t.currentMessagingTarget??t.currentChannelId??J?.to,threadId:J?.threadId,channelId:t.currentChannelId,messageId:t.currentMessageId};const te={async initialize(){const i=await resolveGatewaySessionStoreTargetInWorker({cfg:n,key:a,agentId:l,assertActive:t.assertActive});const o=i.readSource?.path??i.storePath;await waitForSessionParticipantRecording({agentId:l,sessionKey:i.canonicalKey,storePath:o});t.assertActive?.();const readParentEntry=()=>readSessionEntryReadOnlyInWorker({agentId:l,sessionKey:i.canonicalKey,storePath:o},()=>t.assertActive?.());const s=isIncognitoSessionKey(a)?void 0:await readParentEntry();const c=prepareAcpSpawnCreation({cfg:n,parentEntry:s,requesterAgentId:l,requesterSessionKey:a,creatorProfileId:r,gitContributorProfileId:t.gitContributorProfileId,expectedParentSessionId:t.expectedParentSessionId,senderIsOwner:t.senderIsOwner,assertActive:t.assertActive});const u=resolveSessionStorePathCore(n.session?.store,{agentId:v});const d=M.childSessionPatch?{spawnDepth:M.childSessionPatch.spawnDepth,...M.childSessionPatch.subagentRole?{subagentRole:M.childSessionPatch.subagentRole}:{},subagentControlScope:M.childSessionPatch.subagentControlScope}:{};t.assertActive?.();V=await upsertSessionEntryCore({storePath:u,sessionKey:L,agentId:v},{...c.stamp,spawnedBy:a,completionOwnerSessionKey:T.completionRequesterSessionKey,parentSessionKey:a,...d,inheritedToolPolicyVersion:1,...t.inheritedToolPolicySource?{inheritedToolPolicySource:t.inheritedToolPolicySource}:{},...inheritedToolAllowPatch(t.inheritedToolAllowlist),...inheritedToolDenyPatch(t.inheritedToolDenylist),...y?{spawnedWorkspaceDir:t.workspaceDir??b,spawnedCwd:z,sessionRoot:b,permissionMode:t.sessionPermissionPolicy?.mode}:{},...e.label?{label:e.label}:{},...c.parentPatch},sessionEntryCommitGuardOptions(c.assertCurrent))??void 0;const f=await withAcpResumeSessionAuthorization(N,r=>runWithAgentToolSourceExecutionScope(t.assertActive,()=>initializeAcpSpawnRuntime({assertActive:t.assertActive,revalidateResume:r,cfg:n,sessionKey:L,ownerAgentId:v,runtimeAgentId:h,runtimeMode:p===`session`?`persistent`:`oneshot`,backendId:_,resumeSessionId:e.resumeSessionId,runtimeOptions:F.runtimeOptions,modelExplicit:F.modelExplicit,thinkingExplicit:F.thinkingExplicit,cwd:z})));H=f.initialized.closeRuntimeOnFailure;t.assertActive?.();return{initializedSession:f,binding:B?await runWithAgentToolSourceExecutionScope(t.assertActive,()=>{t.assertActive?.();return bindPreparedAcpThread({assertActive:t.assertActive,cfg:n,sessionKey:L,targetAgentId:v,label:e.label,preparedBinding:B,initializedRuntime:f})}):null}},async dispatchTurn(r){const o=resolveAcpSpawnBootstrapDeliveryPlan({cfg:n,spawnMode:p,effectiveStreamToParent:I,requester:w,binding:r.binding});r.deliveryPlan=o;if(V)await recordSessionCreated(n,{sessionKey:L,agentId:v,entry:V});await recordSubagentSpawned({childSessionKey:L,childRunId:U,requesterSessionKey:a,agentId:v});const startParentRelay=e=>I&&s&&K&&q?startAcpSpawnParentStreamRelay({runId:e,parentSessionKey:s,requesterAgentId:l,expectedTarget:q,childSessionKey:L,childSessionId:r.initializedSession.sessionId,agentId:h,ownerAgentId:v,env:G,eventRouting:K,deliveryContext:W,cfg:n}):void 0;r.parentRelay=startParentRelay(U);const c=await runWithAgentToolSourceExecutionScope(t.assertActive,()=>launchAcpChildThroughGateway({assertDispatchCurrent:t.assertActive,task:e.task,sessionKey:L,deliveryPlan:o,childIdem:U,runTimeoutSeconds:i,label:e.label,attachments:ee,lineage:{enabled:isExecutionIdentityCollectionEnabled(n),backend:`acp`,parentAgentId:l,requesterRef:a,controllerRef:T.controllerSessionKey,depth:M.childSessionPatch?.spawnDepth??1,maxDepth:M.maxSpawnDepth,targetAgentId:v,sandbox:e.sandbox===`require`?`require`:`inherit`,inheritedToolAllowlist:t.inheritedToolAllowlist,inheritedToolDenylist:t.inheritedToolDenylist},parentExecutionIdentityToken:readParentExecutionIdentity(t),participantStorePath:resolveSessionStorePathCore(n.session?.store,{agentId:v})}));const u=readGatewayRunId(c)??U;if(r.parentRelay&&u!==U){r.parentRelay.dispose();r.parentRelay=startParentRelay(u)}r.parentRelay?.notifyStarted();return{runId:u}},async cleanupOnFailure({state:e}){await e?.parentRelay?.dispose();await cleanupFailedAcpSpawn({cfg:n,sessionKey:L,agentId:v,sessionEntry:V,deleteTranscript:true,closeRuntimeOnFailure:H})}};const{controllerSessionKey:X}=T;t.assertActive?.();const Z=A?reserveChildAdmissionSlot({controllerSessionKey:X,childSessionKey:L,resolveAdmission}):void 0;if(Z&&!Z.ok)return buildAcpSpawnError(`subagent_policy`,Z.error,`forbidden`);t.onSpawnEffectsStart?.();let Q=false;const $=await runSpawnPipeline({adapter:te,assertActive:t.assertActive,admissionReservation:Z,hookRunner:getGlobalHookRunner(),progressOrigin:Y,progressSessionKey:T.completionRequesterSessionKey,buildRegistration:(n,r)=>{Q=!(n.deliveryPlan?.useInlineDelivery===true)&&e.expectsCompletionMessage!==false;return{runId:r,requesterTurnRunId:t.requesterTurnRunId,childSessionKey:L,childAgentId:v,controllerSessionKey:X,sessionEntry:n.initializedSession.sessionEntry,requesterSessionKey:T.completionRequesterSessionKey,completionRequesterSessionId:O,completionRequesterLifecycleRevision:k,requesterOrigin:J,progressOrigin:Y,requesterDisplayKey:T.completionRequesterDisplayKey,task:e.task,taskName:e.taskName,requesterAgentId:l,cleanup:p===`session`?`keep`:e.cleanup===`delete`?`delete`:`keep`,label:e.label,runTimeoutSeconds:i,expectsCompletionMessage:Q,spawnMode:p}}});if(!$.ok)return buildAcpSpawnFailureResult($,L);return{status:`accepted`,childSessionKey:L,runId:$.runId,mode:p,runTimeoutSeconds:i,expectsCompletionMessage:Q,...$.state.deliveryPlan?.useInlineDelivery?{inlineDelivery:true}:{},note:p===`session`?ACP_SPAWN_SESSION_ACCEPTED_NOTE:ACP_SPAWN_ACCEPTED_NOTE}}export{spawnAcpDirect};