UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

476 lines (475 loc) • 17 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { a as throwIfSettledRejected } from "./error-graph-internal-DdjdM90N.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { t as settlesWithin } from "./settle-within-Bj8A0Tzk.mjs"; import { o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { C as isSubagentSessionKey, y as isAcpSessionKey } from "./session-key-CqAyZeVk.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { X as captureSessionTarget, c as getAttachedBackend, st as SESSION_CONTROLLER_DRAIN_TIMEOUT_MS } from "./session-controller.state-BApgK0mV.mjs"; import { a as normalizeStoreSessionKey } from "./store-entry-BTUJi0xl.mjs"; import "./session-accessor-CizTbDQj.mjs"; import { g as captureSessionControllerSourceStopAcknowledgment } from "./session-controller.lifecycle-C_Z3sybN.mjs"; import { r as markSessionAbortTarget, s as resolveSessionAbortTarget } from "./session-accessor.entry-mutation-IJ4DYZ4a.mjs"; import "./sessions-D5Vvu3AE.mjs"; import { l as readChannelContextGatewayContextResolver } from "./admission-evidence-q4_t-NFq.mjs"; import { r as logVerbose } from "./globals-CgepmiqE.mjs"; import { a as captureSessionControllerStopCandidates, i as captureSessionControllerStop, r as stopSession } from "./session-controller.stop-BqKrTY7V.mjs"; import { a as resolveCommandAuthorizationAsync } from "./command-auth-CC1Z19Eh.mjs"; import { o as resolveInternalSessionKey, s as resolveMainSessionAlias } from "./sessions-resolution-B1MUJxVg.mjs"; import "./sessions-helpers-BN0PfnY4.mjs"; import { t as resolveEffectiveResetTargetSessionKey } from "./acp-reset-target-BGHYzzmp.mjs"; import { s as resolveSessionConversationBindingContext } from "./session-conversation-binding-B2fKRrgu.mjs"; import { l as retireSessionMcpRuntime, r as captureSessionMcpRuntimeRetirement } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs"; import { a as shouldPersistAbortCutoff, i as resolveAbortCutoffFromContext } from "./abort-cutoff-DFd683Fe.mjs"; import { r as setAbortMemory } from "./abort-primitives-Bk9blQey.mjs"; import { n as captureExecRequestCancellation } from "./bash-process-control-aLfvOIsE.mjs"; import { t as killAllControlledSubagentRuns } from "./subagent-control-kill-CFJ2AiHG.mjs"; import { r as captureExecRequestSubagentSelection } from "./subagent-control-scope-ir7nv0U5.mjs"; import "./subagent-control-BD7ro9Sk.mjs"; //#region src/auto-reply/reply/abort-retirements.ts async function completeAbortRetirements(e, t) { const [n] = await Promise.allSettled([e()]); const [r] = await Promise.allSettled([(async () => { const e = Promise.allSettled(t); if (!await settlesWithin(e, 15e3)) throw new Error("Cancellation was requested, but cleanup is still pending. Check the turn status before retrying Stop."); throwIfSettledRejected(await e, "Cancellation cleanup failed"); })()]); if (r.status === "rejected" && n.status === "rejected" && r.reason !== n.reason) throw new AggregateError([n.reason, r.reason], "Cancellation cleanup failed"); if (r.status === "rejected") throw r.reason; if (n.status === "rejected") throw n.reason; return n.value; } //#endregion //#region src/auto-reply/reply/abort-operation.ts function matchesStopCandidate(e, t) { if (!e.aliases.has(t.key)) return false; if (e.storeScope && e.storeScope !== t.storePath) return false; return !e.agentId || !t.agentId || normalizeAgentId(e.agentId) === normalizeAgentId(t.agentId); } /** Physical identity and runtime references are captured together, before channel I/O. */ function captureChannelSessionStop(e) { const t = normalizeOptionalString(e.key); const n = t ? captureSessionControllerStopCandidates({ resolveGatewayContext: e.resolveGatewayContext }).filter((n) => matchesStopCandidate(n, { key: t, storePath: e.storePath, agentId: e.agentId })) : []; return captureChannelStopResources(captureSessionControllerStop({ targets: t ? [captureSessionTarget({ storeScope: e.storePath, sessionKey: t, incarnation: e.sessionId, agentId: e.agentId })] : [], inputs: n.flatMap((e) => e.capture.inputs), operations: n.flatMap((e) => e.capture.operations), resolveGatewayContext: e.resolveGatewayContext }), e.sessionId, { sessionKey: t, sessionId: e.sessionId, agentId: e.agentId }); } function captureChannelStopResources(e, t, n) { const r = e.activeInputs[0]?.claim?.operation?.sessionId ?? e.operations[0]?.sessionId ?? t; const i = /* @__PURE__ */ new Map(); for (const t of e.operations) i.set(t, [...t.captureOwnedSessionIds()]); for (const n of e.activeInputs) { const e = n.source?.run.sessionId ?? t; i.set(n, n.claim?.operation ? [...n.claim.operation.captureOwnedSessionIds()] : e ? [e] : []); } const a = e.activeInputs.length > 0 || e.operations.length > 0 ? void 0 : captureSessionMcpRuntimeRetirement({ sessionId: t, sessionKey: n?.sessionKey }); const o = [...e.operations, ...e.activeInputs.flatMap((e) => e.claim?.operation ?? [])]; const s = [...n ? [captureExecRequestCancellation({ ...n, sessionId: n.sessionId ?? r })] : [], ...o.map((e) => captureExecRequestCancellation({ sessionKey: e.key, sessionId: e.sessionId, agentId: e.agentId }))]; return { controller: e, sessionId: r, mcpSessionIds: i, idleMcpRetirements: a ? [a] : [], commands: s, requestRunIds: /* @__PURE__ */ new Set([ ...s.flatMap((e) => e.requestRunIds), ...o.flatMap((e) => getAttachedBackend(e)?.runId ?? []), ...e.effects.flatMap((e) => e.run?.runId ?? []) ]) }; } function combineChannelStopCaptures(e) { return { controller: captureSessionControllerStop({ inputs: e.flatMap((e) => [...e.controller.inputs]), operations: e.flatMap((e) => [...e.controller.operations]), effects: e.flatMap((e) => [...e.controller.effects]), pendingCaptures: e.map((e) => e.controller) }), mcpSessionIds: new Map(e.flatMap((e) => [...e.mcpSessionIds])), idleMcpRetirements: e.flatMap((e) => e.idleMcpRetirements.filter((t) => t.sessionId === e.sessionId)), commands: e.flatMap((e) => e.commands), requestRunIds: new Set(e.flatMap((e) => [...e.requestRunIds])) }; } /** Scope adapter only: cancellation and acceptance belong to the captured Stop kernel. */ function abortSessionRunTargetWithOutcome(e) { let t; const resolveCapture = () => t ??= typeof e.capture === "function" ? e.capture() : e.capture; const n = /* @__PURE__ */ new Set(); const trackRetirement = (t, r) => { if (n.has(t)) return; e.assertCurrent?.(); n.add(t); const i = r(); i.catch(() => {}); e.retirements.push(i); }; const retire = (e) => { for (const t of e) trackRetirement(t, async () => { if (!await retireSessionMcpRuntime({ sessionId: t, reason: "session-stop", preserveActiveLeases: true })) throw new Error("Session MCP runtime retirement failed."); }); }; return stopSession({ source: "channel-user", capture: () => resolveCapture().controller, assertCurrent: e.assertCurrent, hookContext: e.hookContext, messageIdentity: e.messageIdentity, recordAbortTarget: e.recordAbortTarget, stopChildren: e.stopChildren, externalParent: { stop: () => { let t = false; for (const n of resolveCapture().commands) { e.assertCurrent?.(); t = n.cancel() || t; } return t ? "aborted" : "unchanged"; }, get settled() { const t = Promise.all(resolveCapture().commands.map((e) => e.settle())).then(() => void 0); e.retirements.push(t); return t; } }, afterQueued: () => { const t = resolveCapture(); for (const n of t.idleMcpRetirements) trackRetirement(n.sessionId, () => n.retire(() => e.assertCurrent?.())); }, onCancelled: (t) => { const n = resolveCapture(); if (!n.mcpSessionIds.has(t) && "mailbox" in t) e.retirements.push(captureSessionControllerSourceStopAcknowledgment(t)); retire(n.mcpSessionIds.get(t) ?? []); } }); } async function stopSubagentsForRequester(e) { const t = normalizeOptionalString(e.requesterSessionKey); if (!t) { e.assertCurrent?.(); await e.beforeKill?.(() => {}); return { stopped: 0, failed: 0 }; } const { alias: n } = resolveMainSessionAlias(e.cfg); const r = resolveInternalSessionKey({ key: t, alias: n }); const i = resolveSessionAgentId({ config: e.cfg, sessionKey: r, fallbackAgentId: e.requesterAgentId }); const a = { controllerSessionKey: r, controllerAgentId: i, callerSessionKey: r, callerIsSubagent: isSubagentSessionKey(r), controlScope: "children" }; const o = captureExecRequestCancellation({ sessionKey: r, agentId: i }); const s = { cfg: e.cfg, controller: a, owners: o.owners, acceptsRequest: e.acceptsRequest }; const sessionOrigin = (e) => e ? { target: { ...e, sessionKey: r, agentId: i }, acceptsRequest: () => true } : void 0; const c = e.prepareRequesterSession; let l = captureExecRequestSubagentSelection({ ...s, sessionOrigin: sessionOrigin(e.requesterSession), candidateOrigin: c ? { target: { sessionKey: r, agentId: i }, acceptsRequest: () => true } : void 0 }); const u = { runs: l.runs, ownsRoot: (e) => l.ownsRoot(e), selectPublishedRoot: c || l.selectPublishedRoot ? (e) => l.selectPublishedRoot?.(e) === true : void 0, get sessionGeneration() { return l.sessionGeneration; }, prepare: c ? async () => { l = captureExecRequestSubagentSelection({ ...s, sessionOrigin: sessionOrigin(await c()) }); } : void 0 }; const d = await killAllControlledSubagentRuns({ cfg: e.cfg, controller: a, runs: u.runs, requestSelection: u, assertCurrent: e.assertCurrent, suppressTaskDelivery: true, beforeKill: e.beforeKill }); if (d.status === "error") logVerbose(`abort: failed to stop subagents for ${r}: ${d.error}`); return { stopped: d.killed, failed: d.status === "error" ? d.failed : 0, ...d.execAborted ? { execAborted: true } : {} }; } async function executeFastAbortRequest(e, t) { const { ctx: n, cfg: r } = e; const { commandSessionKey: i, targetKey: a, resolveTargetAgentId: o } = t; const s = o(); const c = readChannelContextGatewayContextResolver(n) ?? getPluginRuntimeGatewayRequestScope()?.resolveGatewayContext; const assertCurrent = () => { if (e.isCommandTargetCurrent?.sessionSource) { e.isCommandTargetCurrent.sessionSource(); return; } if (e.isCommandTargetCurrent?.() === false) throw new Error("The selected session changed before it could be stopped."); }; if (a) { const t = resolveSessionStorePathCore(r.session?.store, { agentId: s }); const o = normalizeStoreSessionKey(a); const captureTarget = (e) => { const t = e === o ? s : resolveSessionAgentId({ config: r, sessionKey: e, fallbackAgentId: n.AgentId }); return captureChannelSessionStop({ key: e, agentId: t, resolveGatewayContext: c, storePath: resolveSessionStorePathCore(r.session?.store, { agentId: t }) }); }; const l = captureTarget(o); const u = i && i !== o ? captureTarget(i) : void 0; const d = captureSessionControllerStopCandidates({ resolveGatewayContext: c }).map((e) => ({ aliases: e.aliases, agentId: e.agentId, storeScope: e.storeScope, channel: captureChannelStopResources(e.capture) })); const f = resolveSessionAbortTarget({ agentId: s, sessionKey: a, storePath: t }).catch((e) => { logVerbose(`abort: failed to resolve abort metadata for ${a}: ${formatErrorMessage(e)}`); return null; }); const p = { target: null }; const m = []; let h = l; let g = false; const _ = {}; const v = shouldPersistAbortCutoff({ commandSessionKey: i, targetSessionKey: o }) ? resolveAbortCutoffFromContext(n) : void 0; const y = createDeferredCore(); y.promise.catch(() => {}); const { children: b, executionOutcome: x } = await completeAbortRetirements(async () => { try { const c = await stopSubagentsForRequester({ cfg: r, requesterSessionKey: a, requesterAgentId: s, prepareRequesterSession: async () => { p.target = await f; if (l.controller.activeInputs.length === 0 && l.controller.operations.length === 0) l.sessionId = p.target?.sessionId; return p.target?.sessionId ? { storePath: t, sessionId: p.target.sessionId, lifecycleRevision: p.target.entry.lifecycleRevision ?? null } : void 0; }, acceptsRequest: (e) => !p.target || e.sessionId === p.target.sessionId, assertCurrent, beforeKill: async (c) => { g = (await resolveCommandAuthorizationAsync({ ctx: n, cfg: r, commandAuthorized: n.CommandAuthorized })).isAuthorizedSender; if (!g) return false; const f = i ? resolveSessionConversationBindingContext(r, n) : void 0; const b = i && f ? await resolveEffectiveResetTargetSessionKey({ cfg: r, ...f, activeSessionKey: i, skipConfiguredFallbackWhenActiveSessionNonAcp: false, fallbackToActiveAcpWhenUnbound: false }) : void 0; const x = [l]; const S = !isAcpSessionKey(o) ? b : void 0; if (S && S !== o) { const e = resolveSessionAgentId({ config: r, sessionKey: S }); const t = resolveSessionStorePathCore(r.session?.store, { agentId: e }); x.push(...d.filter((n) => matchesStopCandidate(n, { key: S, storePath: t, agentId: e })).map((e) => e.channel)); } if (u && b && (b === o || b === S)) x.push(u); h = combineChannelStopCaptures(x); const C = e.isCommandTargetCurrent?.(); if ((typeof C === "boolean" || C === void 0 ? C : await C) === false) throw new Error("The selected session changed before it could be stopped."); c(); const w = createDeferredCore(); _.execution = abortSessionRunTargetWithOutcome({ capture: h, assertCurrent, retirements: m, stopChildren: async (e) => { try { w.resolve(await e()); } catch (e) { w.reject(e); throw e; } return await y.promise; }, hookContext: { sessionKey: o, sessionEntry: p.target?.entry, sessionId: l.sessionId ?? p.target?.sessionId, commandSource: n.Surface ?? n.Provider ?? n.OriginatingChannel, senderId: n.SenderId }, messageIdentity: v, recordAbortTarget: async ({ recordCutoff: n }) => { const r = p.target?.entry.activeWriterRunId; if (l.sessionId && l.sessionId !== p.target?.sessionId || r && !l.requestRunIds.has(r)) { logVerbose(`abort: skipped metadata for a replacement writer on ${a}`); return; } try { const r = await markSessionAbortTarget({ isCurrent: e.isCommandTargetCurrent, expectedTarget: p.target?.entry ?? null, scope: { agentId: s, sessionKey: a, storePath: t }, resolveAbortCutoff: n ? () => v : void 0 }); if (r?.persisted === false) logVerbose(`abort: failed to persist abort metadata for ${a}: ${r.persistenceError ?? "unknown error"}`); } catch (e) { logVerbose(`abort: failed to persist abort metadata for ${a}: ${formatErrorMessage(e)}`); } } }); return await w.promise; } }); y.resolve(c); return { children: c, executionOutcome: await _.execution?.completed }; } catch (e) { y.reject(e); throw e; } }, m); if (!g || !x) return { handled: false, aborted: false }; const S = x.aborted || b.execAborted === true; const C = x.alreadyFinalizing && !S ? "finalizing" : void 0; return { handled: true, aborted: S, ...C ? { rejectionReason: C } : {}, ...x.localModelMayStillBeFinishing ? { localModelMayStillBeFinishing: true } : {}, stoppedSubagents: b.stopped, failedSubagents: b.failed }; } const l = await resolveCommandAuthorizationAsync({ ctx: n, cfg: r, commandAuthorized: n.CommandAuthorized }); if (!l.isAuthorizedSender) return { handled: false, aborted: false }; const u = l.from ?? l.to; const d = n.SessionKey ?? u; if (u) { assertCurrent(); setAbortMemory(u, true); } const { stopped: f, failed: p, execAborted: m } = await stopSubagentsForRequester({ cfg: r, requesterSessionKey: d, assertCurrent }); return { handled: true, aborted: m === true, stoppedSubagents: f, failedSubagents: p }; } //#endregion export { completeAbortRetirements as a, stopSubagentsForRequester as i, captureChannelSessionStop as n, executeFastAbortRequest as r, abortSessionRunTargetWithOutcome as t };