UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

818 lines (817 loc) • 30.6 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import "./session-key-CqAyZeVk.mjs"; import { d as getAgentEventLifecycleGeneration, f as isAgentEventLifecycleGenerationCurrent, t as assertAgentRunLifecycleGenerationCurrent } from "./agent-events-BdfWYmot.mjs"; import { o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs"; import { t as assertAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs"; import "./method-scopes-Dpyb0Ck-.mjs"; import { X as captureSessionTarget, _t as getSessionControllerEntryForOperation, c as getAttachedBackend, vt as getSessionControllerSourceIdentity } from "./session-controller.state-BApgK0mV.mjs"; import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs"; import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs"; import { E as captureRpcSourceScopeMatcher, T as captureGatewayScopeMatcher, V as isCurrentSessionControllerTurnInput, et as inputMatchesSessionId } from "./session-controller.lifecycle-C_Z3sybN.mjs"; import { o as resolveSessionStoreKey } from "./session-store-key-CEwU3noi.mjs"; import { i as resolveAuthenticatedPersonalGatewayProfileId } from "./gateway-personal-caller-_qqOw6oy.mjs"; import { a as getRpcSourceIdentity, g as isRpcSourceRegistered, h as isRpcSourceQueued, o as getRpcSourceLifecycleGeneration, r as getRpcSourceForGateway, s as getRpcSourceProjectSessionActive, v as listRpcSourceEntries, y as listRpcSourceEntriesForSession } from "./session-controller.rpc-sources-CTFbRW2t.mjs"; import { r as resolveChatRunOwnerAgentId, t as chatRunBelongsToAgent } from "./chat-run-owner-2pVCqGmw.mjs"; import { s as isSubagentRunQueued } from "./subagent-run-liveness-D7qiCtn0.mjs"; import { a as getCurrentSubagentRunOwner, v as subagentRuns } from "./subagent-registry-memory-lc6LBIFb.mjs"; import { i as getLatestLiveSubagentRunByChildSessionKey } from "./subagent-registry-read-DHkmVSx2.mjs"; import { i as captureSessionControllerStop, r as stopSession } from "./session-controller.stop-BqKrTY7V.mjs"; import { r as emitSessionsChanged } from "./session-change-event-DFgDuXAu.mjs"; import { n as createChatAbortMarker } from "./server-chat-state-hXRKEuCM.mjs"; import { t as errorShapeFromError } from "./error-shape-BcwiXcnc.mjs"; import { a as readGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs"; import { n as captureExecRequestCancellation } from "./bash-process-control-aLfvOIsE.mjs"; import { R as SUBAGENT_KILL_TASK_ERROR } from "./subagent-registry-DXsif7FR.mjs"; import "./session-utils-CavYkLyd.mjs"; import { t as persistGatewaySessionLifecycleEvent } from "./session-lifecycle-state-YOgSt9Rr.mjs"; import { r as killSubagentRunAdmin } from "./subagent-control-kill-CFJ2AiHG.mjs"; import { i as ensureSubagentControllerOwnsRun } from "./subagent-control-scope-ir7nv0U5.mjs"; import { l as waitForChatAbortTerminalPersistence, s as waitForChatAbortAcknowledgment } from "./chat-abort-lifecycle-internal-ChM03p20.mjs"; import { i as setGatewayDedupeEntry } from "./agent-job-mP_hfXWa.mjs"; import { a as persistAbortedPartials } from "./chat-transcript-persistence-CsYeaysF.mjs"; import { i as deferAbortedPartialPersistence, l as withQueuedCollectorWarning, n as abortedPartialPersistenceError, r as captureAbortedPartial, s as settleChatAbortPersistence } from "./chat-aborted-partial-DMRg9ZMt.mjs"; import { r as createChatAbortSignalReason, t as abortChatRunById } from "./chat-abort-DHc0iNFP.mjs"; import { n as createChatAbortOps, t as captureWorkerInferenceForSession } from "./chat-abort-ops-BGjSJRNq.mjs"; import { n as pendingChatSendDedupeKey, t as PENDING_CHAT_SEND_DEDUPE_PREFIX } from "./server-shared-BUcqD38M.mjs"; import { t as abortControlledSubagents } from "./chat-abort-descendants-2IwJM3Ms.mjs"; //#region src/gateway/server-methods/chat-abort-authorization.ts function captureSessionAbortRequestOrigin(e, t) { const n = e.session?.ok ? e.session.value : void 0; return n?.entry && (e.requiredSessionId === void 0 || n.entry.sessionId === e.requiredSessionId) && (e.sessionId === void 0 || n.entry.sessionId === e.sessionId) ? { target: { agentId: n.agentId, storePath: n.storePath, sessionKey: n.canonicalKey, sessionId: n.entry.sessionId, lifecycleRevision: n.entry.lifecycleRevision ?? null }, acceptsRequest: t } : void 0; } function buildAbortedChatSendPayload(e) { return { runId: e.runId, status: "timeout", summary: "aborted", ...e.stopReason ? { stopReason: e.stopReason } : {}, endedAt: e.endedAt }; } function resolveChatAbortRequester(e, t, n) { const r = Array.isArray(e?.connect?.scopes) ? e.connect.scopes : []; const i = (e?.internal?.syntheticClient ? e.internal.agentToolCaller : void 0)?.assertCurrent; const a = t?.admittedTarget; const o = i && t && a ? composeSessionSourceAssertion([i, t.assertCurrent]) : void 0; o?.(); const s = resolveAuthenticatedPersonalGatewayProfileId(e); const c = s && a && t && n ? { profileId: s, target: a, assertCurrent: composeSessionSourceAssertion([n, t.assertCurrent], (t) => { t(); if (resolveAuthenticatedPersonalGatewayProfileId(e) !== s) throw new Error("Gateway requester identity changed"); }) } : void 0; c?.assertCurrent(); return { connId: normalizeOptionalString(e?.connId), deviceId: normalizeOptionalString(e?.connect?.device?.id), isAdmin: r.includes(ADMIN_SCOPE), ...c ? { personalAuthority: c } : {}, ...o && a ? { sessionAuthority: { target: a, assertCurrent: o } } : {} }; } /** Both Stop RPCs capture the same requester identity, current guard and session scope. */ function captureChatAbortAuthority(e) { const { client: t, sessionMutationAuthorization: n } = e; const r = readGatewayRequestMutationAuthority(e); const i = resolveChatAbortRequester(t, n, r.assertCurrent); return { requester: i, narrow: r.sessionScope === "operator.sessions.write" || i.sessionAuthority !== void 0, assertRequesterCurrent: r.assertCurrent }; } /** Keep cancellation identity and initiating-person evidence on the same captured source. */ function getChatRunAbortAuthority(e) { return { ...getRpcSourceIdentity(e), requester: e.adapter.requester, initiatingPersonalOperator: e.adapter.initiatingPersonalOperator }; } function canRequesterAbortChatRun(e, t, n = {}) { if (t.sessionAuthority) { t.sessionAuthority.assertCurrent(); const { target: n } = t.sessionAuthority; return e.sessionKey === n.sessionKey && e.sessionId === n.sessionId && resolveChatRunOwnerAgentId(e) === n.agentId; } if (t.isAdmin) return true; const r = t.personalAuthority; const i = e.initiatingPersonalOperator; if (r && i) { assertAdmittedRunOperatorAuthority(i); r.assertCurrent(); if (i.profileId === r.profileId && e.sessionKey === r.target.sessionKey && e.sessionId === r.target.sessionId && resolveChatRunOwnerAgentId(e) === r.target.agentId) return true; } const a = normalizeOptionalString(e.requester?.deviceId); const o = normalizeOptionalString(e.requester?.connectionId); return Boolean(!n.requireOwnerMatch && !a && !o || a && t.deviceId && a === t.deviceId || o && t.connId && o === t.connId); } /** Bind explicit physical targets and scoped callers before cancellation selects work. */ function resolveChatAbortSessionRestriction(e) { const { requestedSessionId: t, admittedTarget: n, narrow: r } = e; if (t && !e.runId) return { ok: false, message: "sessionId requires an exact runId" }; if (e.discardPendingInput && !e.runId) return { ok: false, message: "discardPendingInput requires an exact runId" }; if (e.discardPendingInput && isIncognitoSessionKey(e.sessionKey)) return { ok: false, message: "Removing accepted queued input is unavailable in incognito sessions. Use Stop to cancel it." }; if (r && (!n?.sessionId.trim() || n.sessionKey !== e.sessionKey || n.agentId !== e.agentId)) return { ok: false, message: "session target is unavailable" }; if (r && t && t !== n?.sessionId) return { ok: false, message: "session incarnation changed" }; return { ok: true, requiredSessionId: t ?? (r ? n?.sessionId : void 0) }; } /** Returns the protocol-facing rejection for one exact run target, if any. */ function resolveChatAbortTargetRejection(e) { const { target: t } = e; const n = t.sessionKey === e.requestedSessionKey || t.sessionKey === e.canonicalSessionKey; if (e.discardPendingInput && !n) return "discarded input runId does not match sessionKey"; if (e.requiredSessionId !== void 0 && t.sessionId !== e.requiredSessionId) return "runId does not match session incarnation"; if (!n && (e.requiredSessionId !== void 0 || e.narrow || !canRequesterAbortChatRun(t, e.requester, { requireOwnerMatch: true }))) return "runId does not match sessionKey"; if (!chatRunBelongsToAgent({ agentId: t.agentId, sessionKey: t.sessionKey, defaultAgentId: e.defaultAgentId }, e.requestedAgentId)) return "runId does not match agentId"; return canRequesterAbortChatRun(t, e.requester) ? void 0 : "unauthorized"; } function readPreRegisteredRun(e) { if (!e.key.startsWith("pending-chat:") || !e.entry?.ok) return; const t = e.entry.payload; if (t?.status !== "accepted") return; if (t.controlUiVisible === false) return; const n = (typeof t.runId === "string" ? t.runId : void 0) ?? e.key.slice("pending-chat:".length); const r = normalizeOptionalString(t.sessionKey); if (!n || !r) return; return { runId: n, sessionKey: r, payload: t }; } function writePreRegisteredChatAbort(e) { const t = pendingChatSendDedupeKey(e.runId); const n = e.context.dedupe.get(t); const r = normalizeOptionalString((n?.payload)?.attemptId); if (n && e.attemptId && r !== e.attemptId) return false; const i = Date.now(); const a = buildAbortedChatSendPayload({ runId: e.runId, stopReason: e.stopReason, endedAt: i }); e.context.chatRunState.getOrCreate(e.runId).abortMarker = createChatAbortMarker(i); const o = n ? n.requestIdentity : e.requestIdentity; e.context.dedupe.delete(t); setGatewayDedupeEntry({ dedupe: e.context.dedupe, key: `chat:${e.runId}`, entry: { ts: i, ok: true, payload: a, ...o ? { requestIdentity: o } : {} } }); return true; } function selectAuthorizedRpcSourceRuns(e, t) { const n = /* @__PURE__ */ new Map(); const r = /* @__PURE__ */ new Set(); const i = { hasUnauthorizedRuns: false, hasUnauthorizedProtectedRuns: false, hasProtectedRuns: false }; for (const { runId: a, entry: o } of e) { const { adapter: e } = o; const s = getRpcSourceIdentity(o); const c = canRequesterAbortChatRun(getChatRunAbortAuthority(o), t.requester); r.add(a); if (t.includeProtectedRuns !== true && (e.controlUiVisible === false || t.preserveSideRuns && e.turnKind === "btw")) { i.hasProtectedRuns = true; i.hasUnauthorizedProtectedRuns ||= !c; } else if (c) n.set(a, { runId: a, ...s, entry: o }); else i.hasUnauthorizedRuns = true; } return { authorizedRuns: [...n.values()], matchedRunIds: [...r], ...i }; } function resolveAuthorizedRunsForSessionKeys(e) { return selectAuthorizedRpcSourceRuns(listRpcSourceEntriesForSession(e).filter(({ entry: t }) => e.matchesScope(t) && !isRpcSourceQueued(t)), e); } function resolveAuthorizedQueuedTurnsForSession(e) { const { authorizedRuns: t, ...n } = selectAuthorizedRpcSourceRuns(listRpcSourceEntriesForSession({ queuedOnly: true, sessionKeys: e.sessionKeys, sessionIds: [e.sessionId], requiredSessionId: e.requiredSessionId, agentId: e.agentId, defaultAgentId: e.defaultAgentId }).filter(({ entry: t }) => e.matchesScope(t)), e); return { authorized: t, ...n }; } /** Competing active, pending, or queued Gateway owner for an exact session. */ function hasGatewaySessionAbortOwner(e) { return listRpcSourceEntriesForSession({ storeScope: e.storePath, resolveGatewayContext: e.context.resolveGatewayContext, sessionKeys: e.sessionKeys, sessionIds: [e.sessionId], agentId: e.agentId, defaultAgentId: e.defaultAgentId }).some(({ entry: e }) => !isCurrentSessionControllerTurnInput(e.input)); } //#endregion //#region src/gateway/server-methods/session-abort-persistence.ts /** Capture the session writer and lifecycle generation before cancellation can yield. */ function createSessionAbortPersistence(e) { return async (t, n) => { await persistGatewaySessionLifecycleEvent({ sessionKey: e.sessionKey, agentId: e.agentId, assertCommitAllowed: () => { e.assertCurrent?.(); assertAgentRunLifecycleGenerationCurrent(e.lifecycleGeneration); }, expectedWriter: { ...n ? { requireYielded: n } : {}, runId: t.runId, sessionId: t.sessionId, lifecycleRevision: e.lifecycleRevision }, event: { runId: t.runId, sessionId: t.sessionId, lifecycleGeneration: e.lifecycleGeneration, ts: Date.now(), data: { phase: "end", status: "cancelled", aborted: true, stopReason: e.stopReason ?? "rpc", startedAt: t.startedAtMs ?? e.startedAt, endedAt: Date.now() } } }); }; } //#endregion //#region src/gateway/server-methods/chat-abort-session-plan.ts /** Resolve once at the cancellation boundary; persist captured partials only after Stop. */ function prepareChatSessionAbort(e, t, n) { const r = [e.sessionKey, ...e.sessionKeyAliases ?? []]; const i = e.session?.ok ? e.session.value : void 0; const a = e.context.resolveGatewayContext; const o = captureGatewayScopeMatcher(a); const s = new Set(listRpcSourceEntriesForSession({ sessionKeys: r, sessionIds: [e.sessionId], requiredSessionId: e.requiredSessionId, agentId: e.agentId, defaultAgentId: e.defaultAgentId }).flatMap(({ entry: e }) => o(e.input) && e.input.target ? [e.input.target.storeScope] : [])); const c = e.controllerTargets?.[0]?.storeScope ?? i?.storePath ?? (s.size === 1 ? s.values().next().value : void 0); const l = c ? captureRpcSourceScopeMatcher({ storePath: c, resolveGatewayContext: a }) : () => false; const acceptsRequest = (t) => canRequesterAbortChatRun({ ...t, requester: { connectionId: t.ownerConnId, deviceId: t.ownerDeviceId } }, e.requester) && (e.includeProtectedRuns === true || t.controlUiVisible !== false && !(e.preserveSideRuns && t.turnKind === "btw")); const u = captureExecRequestCancellation({ sessionKey: e.sessionKey, sessionId: e.requiredSessionId ?? e.sessionId, agentId: e.agentId }, acceptsRequest); const d = captureSessionAbortRequestOrigin(e, acceptsRequest); const includesSource = (t) => e.stopSource !== "mutation" || !isCurrentSessionControllerTurnInput(t); const f = { sessionKeys: r, matchesScope: (e) => l(e) && includesSource(e.input), requiredSessionId: e.requiredSessionId, agentId: e.agentId, defaultAgentId: e.defaultAgentId, requester: e.requester, preserveSideRuns: e.preserveSideRuns, includeProtectedRuns: e.includeProtectedRuns }; const p = resolveAuthorizedQueuedTurnsForSession({ ...f, sessionId: e.sessionId }); const { authorizedRuns: m, matchedRunIds: h, hasUnauthorizedRuns: g, hasUnauthorizedProtectedRuns: _, hasProtectedRuns: v } = resolveAuthorizedRunsForSessionKeys({ ...f, sessionIds: [e.sessionId] }); const y = m.length > 0 || p.authorized.length > 0; const b = Boolean(e.cascadeDescendants); const x = Boolean((!y || b) && t?.runIds.length); const S = x && h.some((e) => t?.runIds.includes(e)); const C = g || p.hasUnauthorizedRuns || x && !S && !e.requester.isAdmin; const w = v || p.hasProtectedRuns; const T = _ || p.hasUnauthorizedProtectedRuns; const E = b && T; const D = !C && !w; const O = !b || !w; const k = []; const A = [...p.authorized, ...m]; const j = new Map(A.map((e) => [e.entry.input, e])); const M = e.controllerTargets ?? (c ? [captureSessionTarget({ storeScope: c, sessionKey: e.sessionKey, aliases: e.sessionKeyAliases, agentId: e.agentId, incarnation: e.requiredSessionId })] : []); const N = captureSessionControllerStop({ targets: M, resolveGatewayContext: a }); const P = captureSessionControllerStop({ pendingCaptures: [N], inputs: N.inputs.filter((e) => e.target?.storeScope === c && o(e) && includesSource(e)), operations: N.operations.filter((t) => getSessionControllerEntryForOperation(t).target?.storeScope === c && o(t) && (e.requiredSessionId === void 0 || r.includes(t.key))), effects: D ? N.effects.filter((t) => t.run !== void 0 && acceptsRequest(t.run) && (e.requiredSessionId === void 0 || t.run.sessionKey !== void 0 && r.includes(t.run.sessionKey))) : [] }); const F = captureSessionControllerStop({ pendingCaptures: D ? [P] : [], inputs: [...j.keys(), ...P?.inputs ?? []], operations: P?.operations, effects: P.effects }); const I = []; const L = createSessionAbortPersistence({ sessionKey: e.sessionKey, agentId: e.agentId, lifecycleRevision: i?.entry?.lifecycleRevision, lifecycleGeneration: getAgentEventLifecycleGeneration(), startedAt: i?.entry?.startedAt, stopReason: e.stopReason, assertCurrent: e.assertCurrent }); const R = /* @__PURE__ */ new Map(); for (const e of [...F.activeInputs, ...F.operations]) { const t = "instance" in e ? e.claim?.operation : e; if (!t || A.some(({ entry: e }) => e.input.claim?.operation === t)) continue; const n = getAttachedBackend(t)?.runId; if (n) R.set(e, { runId: n, sessionId: t.sessionId, startedAtMs: t.startedAtMs }); } let z; let B; const V = { aborted: false, runIds: [], unauthorized: false }; const recordRun = (e) => { V.aborted = true; if (!V.runIds.includes(e)) V.runIds.push(e); }; const cancelWorker = () => { z = t?.cancel({ assertCurrent: e.assertCurrent, onCancelled: recordRun }); z?.catch(() => void 0); }; const abortAuthorizedRuns = () => { e.assertCurrent?.(); const n = new Map(listRpcSourceEntries().map(([, e]) => [e.input, e])); e.onControllerTargets?.([...A]); if (!y) { if (C || E) { V.unauthorized = true; return V; } } const onCancelled = (e) => { const t = "instance" in e ? j.get(e) : void 0; const n = R.get(e); if (t) recordRun(t.runId); else if (n) { recordRun(n.runId); const e = L(n); I.push(e); e.catch(() => void 0); } else V.aborted = true; }; const cancelInput = (t, i, a) => { const o = j.get(t); if (!o) { if (!P.inputs.includes(t) && !(a && D)) return false; e.assertCurrent?.(); if (!inputMatchesSessionId(t, e.requiredSessionId) || e.requiredSessionId !== void 0 && !r.includes(getSessionControllerSourceIdentity(t).sessionKey)) return false; const o = n.get(t); const s = o ? o.adapter : t.sourceAdapter; if (o && !isRpcSourceRegistered(o) || e.includeProtectedRuns !== true && (s?.controlUiVisible === false || e.preserveSideRuns && s?.turnKind === "btw") || !canRequesterAbortChatRun({ ...getSessionControllerSourceIdentity(t), requester: s?.requester, initiatingPersonalOperator: o?.adapter.initiatingPersonalOperator }, e.requester)) return false; return i(); } const { runId: s, sessionKey: c, sessionId: l, agentId: u, entry: d } = o; const f = getRpcSourceIdentity(d); if (!isRpcSourceRegistered(d) || f.sessionKey !== c || f.sessionId !== l || f.agentId !== u) return false; return abortChatRunById(e.ops, { runId: s, sessionKey: c, expectedEntry: d, cancel: i, assertCurrent: e.assertCurrent, stopReason: e.stopReason, onAbortPrepared: () => { if (!m.some((e) => e.entry === d)) return; const t = e.context.chatRunState.resolveBuffer(s, { final: true }).text; if (!t?.trim()) return; const n = captureAbortedPartial({ runId: s, sessionKey: f.sessionKey, sessionId: f.sessionId, agentId: f.agentId ?? e.agentId, text: t, abortOrigin: e.abortOrigin, resolveTerminalProducer: d.adapter.resolveTerminalProducer, session: e.session }); k.push(n); return deferAbortedPartialPersistence(n, e.context); }, onAbortCommitted: () => recordRun(s) }).aborted; }; const afterParent = () => { if (!V.unauthorized && !V.error) { e.assertCurrent?.(); if (e.requester.isAdmin && O && t?.runIds.length) cancelWorker(); if (u.cancel()) V.aborted = true; } }; const i = [ "channel-user", "client-session", "client-run" ].includes(e.stopSource); if (!e.hookContext && i) throw new Error(`Stop source ${e.stopSource} requires command hook context`); const a = { capture: F, assertCurrent: e.assertCurrent, reason: createChatAbortSignalReason(e.stopReason), hookContext: e.hookContext, onCancelled, onEffectCancelled: (e) => { recordRun(e.run.runId); const t = L(e.run); I.push(t); t.catch(() => void 0); }, cancelInput, cancelOperation: (t, n) => { if (!D || e.requiredSessionId !== void 0 && (t.sessionId !== e.requiredSessionId || !r.includes(t.key))) return false; e.assertCurrent?.(); return n(); }, afterParent }; B = e.stopSource === "mutation" ? stopSession({ ...a, source: e.stopSource, mutation: { cancelQueued: true, stopChildren: false } }) : stopSession({ ...a, source: e.stopSource }); return V; }; const H = h.some((e) => e !== n) || p.matchedRunIds.some((e) => e !== n) || F.effects.some((e) => e.run?.runId !== n) || x && (!n || !t?.runIds.includes(n)); return { canCascade: D && !E, hasOtherWork: H, acceptsRequest, commands: u, sessionOrigin: d, result: V, abort: abortAuthorizedRuns, async finish() { let t; try { await B?.completed; } catch (e) { t = e; } const n = new Set(V.runIds); const [r, i, a, o] = await waitForChatAbortAcknowledgment(Promise.allSettled([ z, V.aborted && k.length > 0 ? persistAbortedPartials({ context: e.context, snapshots: k.filter((e) => n.has(e.runId)) }) : void 0, Promise.all([...I, ...A.filter(({ runId: e }) => n.has(e)).map(({ entry: e }) => waitForChatAbortTerminalPersistence(e))]), u.settle() ])); const s = /* @__PURE__ */ new Set(); if (t !== void 0) s.add(t); for (const e of [ r, i, a, o ]) if (e.status === "rejected") s.add(e.reason); if (e.session && !e.session.ok) s.add(e.session.error); const c = i.status === "fulfilled" ? i.value : void 0; if (s.size > 0) { const e = [...s]; throw abortedPartialPersistenceError(e.length === 1 ? e[0] : new AggregateError(e, "Chat cancellation persistence failed"), c); } return c; } }; } //#endregion //#region src/gateway/server-methods/chat-abort-runtime.ts function getQueuedCollectorCancellationRunId(e) { return e.found && e.killed && e.targetState?.state === "terminal" && e.targetState.task.status === "cancelled" && e.targetState.task.error === "Subagent run killed." ? e.runId : void 0; } /** Stops registry-owned work that has no active executor to reach through ordinary abort. */ function abortDormantSubagentSession(e, t) { let n = e; const r = getLatestLiveSubagentRunByChildSessionKey(n.sessionKey, void 0, n.agentId); if (!r || !isSubagentRunQueued(r) && r.pauseReason !== "sessions_yield" || n.runId && r.runId !== n.runId) return; const i = n.session?.ok ? n.session.value.cfg : n.context.getRuntimeConfig() ?? {}; const a = r.requesterTurnRunId; const o = a ? getRpcSourceForGateway(a, n.context.resolveGatewayContext) : void 0; const s = o && (r.requesterStorePath === void 0 || o.input.target?.storeScope === r.requesterStorePath) ? o : void 0; const c = r.controllerSessionKey?.trim() || r.requesterSessionKey; const l = { controllerSessionKey: c, controllerAgentId: resolveChatRunOwnerAgentId({ sessionKey: c, defaultAgentId: r.requesterAgentId }) }; const assertCurrent = () => { n.assertCurrent?.(); const e = getCurrentSubagentRunOwner(subagentRuns, r); if (!e || e.execution.status === "queued" && !isSubagentRunQueued(e)) throw new Error("Dormant subagent obligation changed; retry Stop."); const t = ensureSubagentControllerOwnsRun({ cfg: i, controller: l, entry: e }); if (t) throw new Error(t); if (n.requester.isAdmin) return; const o = s && getRpcSourceIdentity(s); const u = s && getRpcSourceLifecycleGeneration(s); if (!a || !s || !o || !isRpcSourceRegistered(s) || s.input.phase === "consumed" || s.input.retirementRequested || s.input.custody.cancellationRetired || s.input.abortSignal.aborted || !u || !isAgentEventLifecycleGenerationCurrent(u) || getRpcSourceProjectSessionActive(s) === false || resolveSessionStoreKey({ cfg: i, sessionKey: o.sessionKey, storeAgentId: l.controllerAgentId }) !== c || resolveChatRunOwnerAgentId(o) !== l.controllerAgentId || !canRequesterAbortChatRun(getChatRunAbortAuthority(s), n.requester, { requireOwnerMatch: true })) throw new Error("Unauthorized dormant subagent Stop; use its active parent requester connection or an administrator."); }; return (async () => { let e; let a; let o = { ok: false, error: errorShape(ErrorCodes.UNAVAILABLE, "Dormant subagent cancellation was not published; retry Stop.") }; let s; const publishSnapshot = (t) => { if (a !== void 0 || e && (e.result.unauthorized || !e.canCascade) || getQueuedCollectorCancellationRunId(t) === void 0) return; emitSessionsChanged(n.context, { sessionKey: n.sessionKey, agentId: n.agentId, reason: "abort" }); }; try { assertCurrent(); let s = t === void 0; let c; await killSubagentRunAdmin({ cfg: i, sessionKey: n.sessionKey, agentId: n.agentId, expectedRunId: r.runId, expectedGeneration: r.generation, expectedOwnerKey: r.requesterSessionKey, onResult: (t) => { publishSnapshot(t); if (a) { o = { ok: false, error: a }; return; } if (e?.result.unauthorized) { o = { ok: false, error: errorShape(ErrorCodes.INVALID_REQUEST, "unauthorized") }; return; } if (t.found && t.error) { o = { ok: false, error: errorShape(ErrorCodes.UNAVAILABLE, t.error) }; return; } if (e && !e.canCascade) { o = { ok: false, error: errorShape(ErrorCodes.UNAVAILABLE, "Dormant subagent was not stopped; other session work was preserved. Wait for it to finish or cancel it through its owner, then retry.") }; return; } const n = getQueuedCollectorCancellationRunId(t); o = { ok: true, value: { aborted: n !== void 0 || e?.result.aborted === true, runIds: uniqueStrings([...n ? [n] : [], ...e?.result.runIds ?? []]) } }; } }, { assertCurrent, requiredSessionId: n.requiredSessionId, prepareRead: () => { if (s || !t) return; return c ??= t().then((e) => { n = { ...n, session: e, sessionId: e.ok ? e.value.entry?.sessionId : n.sessionId }; s = true; }); }, onSnapshot: publishSnapshot, beforeSessionKill: async () => { assertCurrent(); e = prepareChatSessionAbort({ ...n, ops: createChatAbortOps(n.context), cascadeDescendants: true, includeProtectedRuns: n.runId ? true : n.includeProtectedRuns }, captureWorkerInferenceForSession({ context: n.context, sessionId: n.sessionId }), r.runId); if (n.runId && e.hasOtherWork) { a = errorShape(ErrorCodes.UNAVAILABLE, "Other work is active in this child session; use a full-session Stop."); return false; } e.abort(); return e.canCascade; } }); } catch (e) { s = { error: e }; o = { ok: false, error: errorShapeFromError(ErrorCodes.INVALID_REQUEST, e) }; } if (e) try { const t = await e.finish(); if (t) o = withQueuedCollectorWarning(o, t); } catch (e) { if (o.ok) throw e; throw new AggregateError([s?.error ?? o.error, e], "Dormant subagent cancellation and persistence failed", { cause: e }); } return o; })(); } async function abortChatRunsForSessionKeyWithPartials(e, t) { let n = e; if (n.cascadeDescendants) { const e = abortDormantSubagentSession(n, t); if (e) { const t = await e; return t.ok ? { ...t.value, unauthorized: false } : { aborted: false, runIds: [], unauthorized: false, error: t.error }; } } let r = prepareChatSessionAbort(n, captureWorkerInferenceForSession(n)); let i = r.result; const a = t ? async () => { const e = await t(); n = { ...n, session: e, sessionId: e.ok ? e.value.entry?.sessionId : n.sessionId }; r = prepareChatSessionAbort(n, captureWorkerInferenceForSession(n)); i = r.result; return { execCancellation: r.commands, sessionOrigin: r.sessionOrigin }; } : void 0; let o; let s; try { if (n.cascadeDescendants && r.canCascade) o = await abortControlledSubagents({ cfg: n.session?.ok ? n.session.value.cfg : n.context.getRuntimeConfig(), sessionKey: n.sessionKey, agentId: n.agentId, sessionId: n.sessionId, yieldedRequesterRunId: n.yieldedRequesterRunId, lifecycleRevision: n.session?.ok ? n.session.value.entry?.lifecycleRevision : void 0, execCancellation: r.commands, sessionOrigin: r.sessionOrigin, prepareSelection: a ? { acceptsRequest: r.acceptsRequest, prepare: a } : void 0, assertCurrent: n.assertCurrent, beforeKill: async () => { r.abort(); return r.canCascade; } }); else { if (a) await a(); r.abort(); } if (!i.unauthorized && !i.error) { n.assertCurrent?.(); n.onCancellationStarted?.(); } } catch (e) { s = { error: e }; } const c = await settleChatAbortPersistence(() => r.finish(), s); return { ...i, aborted: i.aborted || Boolean(o?.killed || o?.continuationRetired || o?.execAborted), descendants: o, ...c ? { warning: c } : {} }; } //#endregion export { canRequesterAbortChatRun as a, hasGatewaySessionAbortOwner as c, resolveChatAbortSessionRestriction as d, resolveChatAbortTargetRejection as f, buildAbortedChatSendPayload as i, readPreRegisteredRun as l, abortDormantSubagentSession as n, captureChatAbortAuthority as o, writePreRegisteredChatAbort as p, createSessionAbortPersistence as r, getChatRunAbortAuthority as s, abortChatRunsForSessionKeyWithPartials as t, resolveChatAbortRequester as u };