openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 13.8 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{r as truncateUtf16Safe}from"./utf16-slice-DA3Mllbx.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{o as getPluginRuntimeGatewayRequestScope}from"./gateway-request-scope-7deHmsb_.mjs";import{i as listAgentIds}from"./agent-roster-4XrgUgPK.mjs";import{t as normalizeAnyChannelId}from"./registry-normalize-BP0gv89S.mjs";import{o as closeAdmittedRunDelegatedAuthority}from"./admitted-run-context-xwC9VVgE.mjs";import{t as getChannelPlugin}from"./registry-CpNh6QcT.mjs";import{Z as captureSessionTarget}from"./session-controller.state-BIDbpLPn.mjs";import{i as resolveSpawnedWorkspaceInheritance}from"./spawned-context-BR4pD9zG.mjs";import{i as runSessionMutation}from"./session-controller.lifecycle-M3NLAkoz.mjs";import"./plugins-DxOycUNJ.mjs";import{n as resolveChannelDefaultBindingPlacement}from"./conversation-resolution-CtbOlmJd.mjs";import{r as normalizeConversationRef}from"./session-binding-normalization-BSEcrsb5.mjs";import{T as expectedCurrentSessionBinding,t as getSessionBindingService}from"./session-binding-service-TO5btU7E.mjs";import"./session-accessor-CY8UYP4m.mjs";import{c as updateSessionEntry}from"./session-accessor.entry-mutation-CQIwywNM.mjs";import{c as readChannelContextAdmissionEvidence,l as readChannelContextGatewayContextResolver}from"./admission-evidence-DZ21Kx6F.mjs";import{r as getGatewayLocalUserIngress}from"./local-user-ingress-DFjUgRft.mjs";import{i as captureSessionControllerStop,r as stopSession}from"./session-controller.stop-DE-wTVTx.mjs";import{i as resolveAcpThreadSessionDetailLines,n as resolveAcpSessionCwd}from"./session-identifiers-C_PL7ld9.mjs";import{n as resolveSessionStorePathForAcp}from"./session-meta-store-BnKQZPZp.mjs";import{u as resolveAcpSessionResolutionError}from"./manager.utils-DZOq1tXE.mjs";import{a as resolveAcpDispatchPolicyMessage,i as resolveAcpDispatchPolicyError,n as isAcpEnabledByPolicy,r as resolveAcpAgentPolicyError}from"./policy-CIPOPPWo.mjs";import{n as getAcpSessionManager}from"./manager-CpIPv3ym.mjs";import"./session-meta-skdU9pJ4.mjs";import{t as prepareChannelRunAdmission}from"./channel-run-admission-F9U5Spwo.mjs";import{n as commandReply}from"./command-gates-BMLoLImo.mjs";import{i as resolveThreadBindingThreadName,r as resolveThreadBindingIntroText}from"./thread-bindings-messages-50jodfcd.mjs";import{a as resolveThreadBindingIdleTimeoutMsForChannel,c as resolveThreadBindingSpawnPolicy,n as formatThreadBindingSpawnDisabledError,s as resolveThreadBindingMaxAgeMsForChannel,t as formatThreadBindingDisabledError}from"./thread-bindings-policy-ClGZhBcc.mjs";import{n as resolveAcpSpawnRuntimePolicyError}from"./acp-spawn-policy-BXR-KaeE.mjs";import{a as cleanupFailedAcpSpawn,i as resolveRuntimeCwdForAcpSpawn}from"./acp-spawn-runtime-Ba3j1dXe.mjs";import{i as stopSubagentsForRequester}from"./abort-operation-Bi0IyNPR.mjs";import{t as formatAbortReplyText}from"./abort-DNpgJJJR.mjs";import{r as resolveAcpCommandBindingContext,t as resolveAcpTargetSessionKey}from"./targets-q0eTYMpe.mjs";import{_ as parseSpawnInput,b as resolveCommandRequestId,f as acpCommandErrorReply,v as parseSteerInput,x as withAcpCommandErrorBoundary}from"./shared-BGKM9NK1.mjs";import{randomUUID}from"node:crypto";
//!src/auto-reply/reply/commands-acp/bindings.ts
async function resolveBoundReplyPayload(e){const t=normalizeAnyChannelId(e.binding.conversation.channel);if(!t)return;const n=getChannelPlugin(t)?.conversationBindings?.buildBoundReplyPayload;if(!n)return;return await n({operation:`acp-spawn`,placement:e.placement,conversation:e.binding.conversation})??void 0}async function bindSpawnedAcpSession(e){const{commandParams:t}=e;const n=e.mode===`conversation`;const r=resolveAcpCommandBindingContext(t);const{channel:i,accountId:a,conversationId:o,threadId:s}=r;if(!i)return{ok:false,error:`ACP ${n?`current-conversation`:`thread`} binding requires a channel context.`};const c=resolveThreadBindingSpawnPolicy({cfg:t.cfg,channel:i,accountId:a,kind:`acp`});if(!c.enabled)return{ok:false,error:formatThreadBindingDisabledError({...c,kind:`acp`})};if(!n&&!c.spawnEnabled)return{ok:false,error:formatThreadBindingSpawnDisabledError({...c,kind:`acp`})};const l=getSessionBindingService();const u=l.getCapabilities({channel:c.channel,accountId:c.accountId});const d=n?`Conversation`:`Thread`;if(!u.adapterAvailable||!u.bindSupported)return{ok:false,error:`${d} bindings are unavailable for ${i}.`};const f=n?`current`:resolveChannelDefaultBindingPlacement(i)??`current`;if(e.mode===`thread-here`){if(!(f===`child`?s:o))return{ok:false,error:`--thread here requires running /acp spawn inside an active ${i} thread/conversation.`}}const p=n||s?`current`:f;if(!u.placements.includes(p))return{ok:false,error:`${d} bindings do not support ${p} placement for ${i}.`};if(!o)return{ok:false,error:n?`--bind here requires running /acp spawn inside an active ${i} conversation.`:`Could not resolve a ${i} conversation for ACP thread spawn.`};const m=normalizeOptionalString(t.command.senderId)??``;const h=normalizeConversationRef({channel:c.channel,accountId:c.accountId,conversationId:o,parentConversationId:r.parentConversationId});const g=p===`child`||s&&o===s?`thread`:`conversation`;let _;if(p===`current`){_=await l.resolveByConversationAsync(h);const e=normalizeOptionalString(_?.metadata?.boundBy)??``;if(_&&e&&e!==`system`&&m&&m!==e)return{ok:false,error:`Only ${e} can rebind this ${g}.`}}try{t.command.assertOwnerCurrent?.();const n=e.label||e.agentId;const r={cfg:t.cfg,channel:c.channel,accountId:c.accountId};const i={[expectedCurrentSessionBinding]:_,targetSessionKey:e.sessionKey,targetKind:`session`,conversation:h,placement:p,assertCurrent:t.command.assertOwnerCurrent,metadata:{threadName:resolveThreadBindingThreadName({agentId:e.agentId,label:n}),agentId:e.agentId,label:n,boundBy:m||`unknown`,introText:resolveThreadBindingIntroText({agentId:e.agentId,label:n,idleTimeoutMs:resolveThreadBindingIdleTimeoutMsForChannel(r),maxAgeMs:resolveThreadBindingMaxAgeMsForChannel(r),sessionCwd:resolveAcpSessionCwd(e.sessionMeta),sessionDetails:resolveAcpThreadSessionDetailLines(e.sessionMeta)})}};return{ok:true,bound:{binding:await l.bind(i),placement:p,labelNoun:g}}}catch(e){return{ok:false,error:formatErrorMessage(e)||(n?`Failed to bind the current ${i} conversation to the new ACP session.`:`Failed to bind a ${i} thread/conversation to the new ACP session.`)}}}
//!src/auto-reply/reply/commands-acp/lifecycle.ts
async function persistSpawnedSessionLabel(e){const t=normalizeOptionalString(e.label);if(!t)return;const n=Date.now();const{storePath:r,agentId:i}=resolveSessionStorePathForAcp({cfg:e.commandParams.cfg,sessionKey:e.sessionKey,agentId:e.agentId});e.commandParams.command.assertOwnerCurrent?.();if(e.commandParams.sessionStore&&e.commandParams.storePath===r){const r=e.commandParams.sessionStore[e.sessionKey];if(r)e.commandParams.sessionStore[e.sessionKey]={...r,label:t,updatedAt:n}}await updateSessionEntry({storePath:r,agentId:i,sessionKey:e.sessionKey},()=>{e.commandParams.command.assertOwnerCurrent?.();return{label:t,updatedAt:n}})}async function handleAcpSpawnAction(e,t){if(!isAcpEnabledByPolicy(e.cfg))return commandReply("ACP is disabled by policy (`acp.enabled=false`).");const n=parseSpawnInput(e,t);if(!n.ok)return commandReply(`⚠️ ${n.error}`);const r=n.value;const i=await resolveAcpSpawnRuntimePolicyError({cfg:e.cfg,requesterAgentId:e.agentId,requesterSessionKey:e.sessionKey});if(i)return commandReply(`⚠️ ${i}`);const a=resolveAcpAgentPolicyError(e.cfg,r.agentId);if(a)return acpCommandErrorReply(a,`ACP target agent is not allowed by policy.`,`ACP_SESSION_INIT_FAILED`);const o=getAcpSessionManager();const s=listAgentIds(e.cfg).includes(r.agentId)?r.agentId:e.agentId;const c=`agent:${s}:acp:${randomUUID()}`;const l=resolveSpawnedWorkspaceInheritance({config:e.cfg,targetAgentId:s,requesterSessionKey:e.sessionKey,explicitWorkspaceDir:r.cwd});let u;try{u=await resolveRuntimeCwdForAcpSpawn({resolvedCwd:l,explicitCwd:r.cwd})}catch(e){return acpCommandErrorReply(e,`Could not resolve ACP session workspace.`,`ACP_SESSION_INIT_FAILED`)}let d;try{d=await o.initializeSession({assertActive:e.command.assertOwnerCurrent,cfg:e.cfg,sessionKey:c,agentId:s,agent:r.agentId,mode:r.mode,cwd:u})}catch(e){return acpCommandErrorReply(e,`Could not initialize ACP session runtime.`,`ACP_SESSION_INIT_FAILED`)}const{sessionEntry:f,closeRuntimeOnFailure:p,meta:m}=d;const h=d.handle.backend||m.backend;const cleanupSpawn=()=>cleanupFailedAcpSpawn({cfg:e.cfg,sessionKey:c,agentId:s,sessionEntry:f,deleteTranscript:false,closeRuntimeOnFailure:p});let g;if(r.bind!==`off`||r.thread!==`off`){const t=await bindSpawnedAcpSession({commandParams:e,sessionKey:c,agentId:s,label:r.label??r.agentId,mode:r.bind!==`off`?`conversation`:r.thread===`here`?`thread-here`:`thread-auto`,sessionMeta:m});if(!t.ok){await cleanupSpawn();return commandReply(`⚠️ ${t.error}`)}g=t.bound}try{await persistSpawnedSessionLabel({commandParams:e,sessionKey:c,agentId:s,label:r.label})}catch(e){await cleanupSpawn();const t=formatErrorMessage(e);return commandReply(`⚠️ ACP spawn failed: ${t}`)}const _=[`✅ Spawned ACP session ${c} (${r.mode}, backend ${h}).`];if(g){const{binding:e,placement:t,labelNoun:n}=g;const r=e.conversation.conversationId.trim();if(t===`current`)_.push(`Bound this ${n} to ${c}.`);else _.push(`Created ${n} ${r} and bound it to ${c}.`);const i=await resolveBoundReplyPayload({binding:e,placement:t});if(i)return commandReply({text:_.join(` `),...i})}else _.push(`Session is unbound (use /acp spawn ... --bind here to create a session bound to this conversation).`);const v=resolveAcpDispatchPolicyMessage(e.cfg);if(v)_.push(`ℹ️ ${v}`);return commandReply(_.join(` `))}async function withResolvedAcpSessionTarget(e){const t=getAcpSessionManager();const n=await resolveAcpTargetSessionKey({commandParams:e.commandParams,token:e.token});if(!n.ok)return commandReply(`⚠️ ${n.error}`);const r=await t.resolveSessionAsync({cfg:e.commandParams.cfg,...n,assertCurrent:e.commandParams.command.assertOwnerCurrent});e.commandParams.command.assertOwnerCurrent?.();const i=resolveAcpSessionResolutionError(r);if(i)return acpCommandErrorReply(i,i.message,`ACP_SESSION_INIT_FAILED`);return await e.run({acpManager:t,...n})}async function handleAcpCancelAction(e,t){return await withResolvedAcpSessionTarget({commandParams:e,token:normalizeOptionalString(t.join(` `)),run:async({acpManager:t,sessionKey:n,agentId:r})=>await withAcpCommandErrorBoundary({run:async()=>{const i=e.command.assertOwnerCurrent;const{storePath:a}=resolveSessionStorePathForAcp({cfg:e.cfg,sessionKey:n,agentId:r});const o=captureSessionTarget({storeScope:a,sessionKey:n,agentId:r});return await runSessionMutation({target:o,policy:`allow-live`,assertCurrent:i,run:async()=>{const a=await stopSession({source:`client-session`,capture:captureSessionControllerStop({targets:[o],resolveGatewayContext:readChannelContextGatewayContextResolver(e.rootCtx??e.ctx)??getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext}),assertCurrent:i,hookContext:{sessionKey:n,commandSource:e.command.surface,senderId:e.command.senderId},stopChildren:t=>stopSubagentsForRequester({cfg:e.cfg,requesterSessionKey:n,requesterAgentId:r,assertCurrent:i,beforeKill:async e=>{e();return await t()}})}).completed;if(a.alreadyFinalizing&&!a.aborted)return commandReply(formatAbortReplyText(a.childrenStopped,`finalizing`));if(!a.aborted&&a.queuedCancelled===0)await t.cancelSession({assertActive:i,cfg:e.cfg,sessionKey:n,agentId:r,reason:`manual-cancel`});return commandReply(`✅ Cancel requested for ACP session ${n}.`)}})},fallbackMessage:`ACP cancel failed before completion.`})})}async function handleAcpSteerAction(e,t,n){const r=resolveAcpDispatchPolicyError(e.cfg);if(r)return acpCommandErrorReply(r,r.message,`ACP_DISPATCH_DISABLED`);const i=parseSteerInput(n);if(!i.ok)return commandReply(`⚠️ ${i.error}`);return await withResolvedAcpSessionTarget({commandParams:e,token:i.value.sessionToken,run:async({sessionKey:t,agentId:n})=>withAcpCommandErrorBoundary({run:async()=>{const r=`${resolveCommandRequestId(e)}:steer`;const a=getAcpSessionManager();let o=``;const s=await prepareChannelRunAdmission({assertSourceCurrent:e.command.assertOwnerCurrent,cfg:e.cfg,runId:r,agentId:n,ingressKind:`acp`,boundary:`acp.command.steer`,evidence:readChannelContextAdmissionEvidence(e.rootCtx??e.ctx),gatewayLocalUserIngress:getGatewayLocalUserIngress(e.rootCtx??e.ctx)}).admit(`acp`);try{await a.runTurn({admittedRunContext:s,cfg:e.cfg,sessionKey:t,agentId:n,provenance:`agent`,text:i.value.instruction,mode:`steer`,requestId:r,onEvent:e=>{if(e.type!==`text_delta`||e.stream&&e.stream!==`output`)return;if(e.text){o+=e.text;if(o.length>800)o=`${truncateUtf16Safe(o,800)}…`}}})}finally{closeAdmittedRunDelegatedAuthority(s)}const c=o.trim();return commandReply(`✅ ACP steer sent to ${t}.${c?`\n${c}`:``}`)},fallbackMessage:`ACP steer failed before completion.`})})}async function handleAcpCloseAction(e,t){return await withResolvedAcpSessionTarget({commandParams:e,token:normalizeOptionalString(t.join(` `)),run:async({acpManager:t,sessionKey:n,agentId:r})=>{let i;try{const a=await t.closeSession({assertActive:e.command.assertOwnerCurrent,cfg:e.cfg,sessionKey:n,agentId:r,reason:`manual-close`,allowBackendUnavailable:true,clearMeta:true});i=a.runtimeNotice?` (${a.runtimeNotice})`:``}catch(e){return acpCommandErrorReply(e,`ACP close failed before completion.`)}const a=await getSessionBindingService().unbind({targetSessionKey:n,reason:`manual`});return commandReply(`✅ Closed ACP session ${n}${i}. Removed ${a.length} binding${a.length===1?``:`s`}.`)}})}export{handleAcpCancelAction,handleAcpCloseAction,handleAcpSpawnAction,handleAcpSteerAction};