UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

474 lines (473 loc) • 16.8 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { fs as validateChatAbortParams } from "./src-BX8OAe1J.mjs"; import { a as createAgentRunDirectAbortError } from "./run-termination-0Ig0-bk6.mjs"; import { 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 { s as resolveStateContentionPresentation } from "./chat-display-projection.sanitize-DYNE5Y5I.mjs"; import { E as captureRpcSourceScopeMatcher, T as captureGatewayScopeMatcher, v as holdSessionControllerSourceWithdrawal } from "./session-controller.lifecycle-C_Z3sybN.mjs"; import { r as resolveRequestedSessionAgentId, s as tryResolveSessionCompatibilityOwnerAgentId } from "./session-request-agent-tfwWH53J.mjs"; import { o as resolveSessionStoreKey } from "./session-store-key-CEwU3noi.mjs"; import { a as getRpcSourceIdentity, g as isRpcSourceRegistered, h as isRpcSourceQueued, r as getRpcSourceForGateway, t as getReservedRpcSourceInput, v as listRpcSourceEntries } from "./session-controller.rpc-sources-CTFbRW2t.mjs"; import "./session-controller.mailbox-BcK8UF_b.mjs"; import { i as captureSessionControllerStop, r as stopSession, t as cancelCapturedSessionControllerSource } from "./session-controller.stop-BqKrTY7V.mjs"; import { r as emitSessionsChanged } from "./session-change-event-DFgDuXAu.mjs"; import { t as respondError } from "./response-C7fEiIN1.mjs"; import { t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { n as captureExecRequestCancellation } from "./bash-process-control-aLfvOIsE.mjs"; import "./session-utils-CavYkLyd.mjs"; import { l as waitForChatAbortTerminalPersistence, s as waitForChatAbortAcknowledgment } from "./chat-abort-lifecycle-internal-ChM03p20.mjs"; import { a as persistAbortedPartials } from "./chat-transcript-persistence-CsYeaysF.mjs"; import { a as prepareChatAbortSessionSnapshot, c as withAbortedPartialPersistenceWarning, i as deferAbortedPartialPersistence, n as abortedPartialPersistenceError, r as captureAbortedPartial } from "./chat-aborted-partial-DMRg9ZMt.mjs"; import { i as getWorkerInferenceSessionControl } from "./inference-control-internal-B6MF-IIL.mjs"; import { n as createChatAbortOps, t as captureWorkerInferenceForSession } from "./chat-abort-ops-BGjSJRNq.mjs"; import { n as formatStopRequest } from "./control-plane-audit-Deey8Q_Y.mjs"; import { a as canRequesterAbortChatRun, d as resolveChatAbortSessionRestriction, f as resolveChatAbortTargetRejection, o as captureChatAbortAuthority, s as getChatRunAbortAuthority, t as abortChatRunsForSessionKeyWithPartials } from "./chat-abort-runtime-Dwe_1h4x.mjs"; import { n as descendantAbortError, t as abortControlledSubagents } from "./chat-abort-descendants-2IwJM3Ms.mjs"; import { n as stopExactClientRun, t as captureSourceAssertion } from "./chat-abort-exact-run-Blz_jq-B.mjs"; import { t as discardSessionPendingInput } from "./session-pending-input-withdrawal-xz1ui5pv.mjs"; //#region src/gateway/server-methods/chat-abort-handler.ts async function handleChatAbortRequestWithLifecycle(e, t = {}) { const { params: n, respond: r, context: i, sessionMutationAuthorization: a } = e; const { requester: o, assertRequesterCurrent: s, narrow: c } = captureChatAbortAuthority(e); const assertCurrent = () => { s(); a?.assertCurrent(); o.sessionAuthority?.assertCurrent(); o.personalAuthority?.assertCurrent(); }; if (!assertValidParams(n, validateChatAbortParams, "chat.abort", r)) return; const { sessionKey: l, sessionId: u, runId: d, preserveSideRuns: f, discardPendingInput: p } = n; const m = normalizeOptionalString(n.agentId); const h = i.getRuntimeConfig(); const g = parseAgentSessionKey(l); const _ = tryResolveSessionCompatibilityOwnerAgentId(h, l); const v = !g ? resolveRequestedSessionAgentId(h, l, m) : void 0; if (v && !v.ok) { r(false, void 0, v.error); return; } const y = g ? m ?? normalizeAgentId(g.agentId) : v?.agentId; if (!y) { respondError(r, ErrorCodes.INVALID_REQUEST, l.trim().toLowerCase() === "global" ? "agentId is required for global chat.abort when no compatibility owner exists" : "agentId is required for unscoped chat.abort when no compatibility owner exists"); return; } if (m && g && normalizeAgentId(g.agentId) !== normalizeAgentId(m)) { respondError(r, ErrorCodes.INVALID_REQUEST, `agentId "${m}" does not match session key "${l}"`); return; } const b = resolveSessionStoreKey({ cfg: h, sessionKey: l, storeAgentId: y }); const x = resolveChatAbortSessionRestriction({ requestedSessionId: u, runId: d, discardPendingInput: p, narrow: c, admittedTarget: a?.admittedTarget, sessionKey: b, agentId: normalizeAgentId(y) }); if (!x.ok) { respondError(r, ErrorCodes.INVALID_REQUEST, x.message); return; } const { requiredSessionId: S } = x; const C = createChatAbortOps(i); const prepareAbortSession = (e = b, t = y) => prepareChatAbortSessionSnapshot({ excludeInternalEffects: true, cfg: h, key: e, agentId: t }); const w = t.hookContext ?? { sessionKey: b, sessionId: S, commandSource: "gateway:chat.abort", senderId: o.deviceId ?? o.connId }; if (!d) { const e = await abortChatRunsForSessionKeyWithPartials({ context: i, ops: C, sessionKey: b, sessionKeyAliases: b === l ? void 0 : [l], agentId: y, sessionId: S, requiredSessionId: S, defaultAgentId: _, abortOrigin: "rpc", stopReason: "rpc", stopSource: "client-session", hookContext: w, requester: o, assertCurrent, preserveSideRuns: f, cascadeDescendants: t.cascadeDescendants, yieldedRequesterRunId: t.yieldedRequesterRunId }, prepareAbortSession); if (e.unauthorized) { respondError(r, ErrorCodes.INVALID_REQUEST, "unauthorized"); return; } if (e.descendants?.killed || e.descendants?.continuationRetired) t.onDescendantsCancelled?.(e.descendants); const n = e.error ?? descendantAbortError(e.descendants, "Session"); if (n) { r(false, void 0, withAbortedPartialPersistenceWarning(n, e.warning)); return; } r(true, { ok: true, aborted: e.aborted, runIds: e.runIds, ...e.warning ? { warning: e.warning } : {} }); return; } const T = i.resolveGatewayContext; const E = captureGatewayScopeMatcher(T); const D = listRpcSourceEntries().filter(([e, t]) => e === d && E(t.input)); const O = getReservedRpcSourceInput(d, { resolveGatewayContext: T }); if (!p && O && !O.target && O.sourceAdapter?.preparation) { const e = O.sourceAdapter; const t = e.preparation?.agentId; const n = S !== void 0 ? "runId does not match session incarnation" : t && normalizeAgentId(t) !== normalizeAgentId(y) ? "runId does not match agentId" : !canRequesterAbortChatRun({ requester: e.requester }, o, { requireOwnerMatch: true }) ? "unauthorized" : void 0; if (n) { respondError(r, ErrorCodes.INVALID_REQUEST, n); return; } const i = cancelCapturedSessionControllerSource(captureSessionControllerStop({ inputs: [O] }), { assertCurrent, reason: createAgentRunDirectAbortError() }); const a = i.failures[0]; if (a) throw a.error; const s = i.abortedInputs.includes(O); r(true, { ok: true, aborted: s, runIds: s ? [d] : [] }); return; } const k = captureExecRequestCancellation({ runId: d, sessionKey: b, sessionId: S, agentId: y }); const A = await prepareAbortSession(); const j = A.ok ? A.value.entry : void 0; if (u) { if (!A.ok) throw A.error; if (j?.sessionId !== u) { respondError(r, ErrorCodes.INVALID_REQUEST, "session incarnation changed"); return; } } const M = new Set([...D.map(([, e]) => e.input), O].flatMap((e) => e?.target ? [e.target.storeScope] : [])); const N = A.ok ? A.value.storePath : M.size === 1 ? M.values().next().value : void 0; const P = N ? captureRpcSourceScopeMatcher({ storePath: N, resolveGatewayContext: T }) : () => false; const stopWithoutCapturedRun = (e, t) => stopSession({ source: "client-run", capture: captureSessionControllerStop({}), assertCurrent, reason: e, hookContext: w, afterParent: t }).completed; const authorizeRunTarget = (e) => { const t = resolveChatAbortTargetRejection({ target: e, requester: o, requestedSessionKey: l, canonicalSessionKey: b, requestedAgentId: normalizeAgentId(y), defaultAgentId: _, requiredSessionId: S, discardPendingInput: p, narrow: c }); if (t) respondError(r, ErrorCodes.INVALID_REQUEST, t); return t === void 0; }; const F = D.flatMap(([, e]) => P(e) ? [e] : []); const I = F.length === 1 ? F[0] : void 0; const L = !I && O && N && O.target?.storeScope === N ? O : void 0; const R = I ? getRpcSourceIdentity(I) : L ? getSessionControllerSourceIdentity(L) : void 0; const z = getWorkerInferenceSessionControl(i.workerEnvironmentService)?.resolveSessionTargetForRunId(d); if (z && S !== void 0 && !authorizeRunTarget(z)) return; const B = captureWorkerInferenceForSession({ context: i, sessionId: R?.sessionId ?? z?.sessionId ?? j?.sessionId, runId: d }); let V = false; if (p) { if (I && !authorizeRunTarget(getChatRunAbortAuthority(I))) return; if (!I || !isRpcSourceQueued(I) || I.input.phase === "injecting" || I.input.claim || I.input.retirementRequested) { r(true, { ok: true, aborted: false, runIds: [] }); return; } const e = getRpcSourceIdentity(I); const t = I.input.target; const n = { ...e, agentId: e.agentId ?? y }; const a = holdSessionControllerSourceWithdrawal(I.input); try { if (!A.ok) throw A.error; V = await discardSessionPendingInput({ ...n, storePath: A.value.storePath }, d, () => { assertCurrent(); const n = getRpcSourceIdentity(I); if (!isRpcSourceRegistered(I) || !isRpcSourceQueued(I) || !t || I.input.target !== t || n.sessionKey !== e.sessionKey || n.sessionId !== e.sessionId || n.agentId !== e.agentId) throw new Error("Run changed before input removal; refresh and retry."); }); if (V) { I.adapter.abortStopReason = "rpc"; V = a.commit("rpc"); if (V) emitSessionsChanged(i, { ...n, reason: "agent.input.settled" }, { accessChanged: false }); } } finally { a(); } r(true, { ok: true, aborted: V, runIds: V ? [d] : [] }); return; } const H = /* @__PURE__ */ new Set(); let U; const cancelWorker = () => { if (!o.isAdmin || !B?.runIds.length) return; assertCurrent(); const e = B.cancel({ assertCurrent, onCancelled: (e) => { H.add(e); t.onExactRunAborted?.(e); } }); U = e; e.catch(() => void 0); }; const respondWithWorkerRuns = async (e, t, n = false) => { await U; const i = /* @__PURE__ */ new Set([...e, ...H]); if (!A.ok) throw A.error; r(true, { ok: true, aborted: i.size > 0 || n, runIds: [...i], ...t ? { warning: t } : {} }); }; if (!I) { if (L && R) { if (!authorizeRunTarget({ ...R, requester: L.sourceAdapter?.requester })) return; const e = captureSourceAssertion(L, assertCurrent); const t = R.sessionKey === l || R.sessionKey === b ? A : await prepareAbortSession(R.sessionKey, R.agentId ?? y); const n = t.ok ? t.value.entry : void 0; let i = false; let a; await stopSession({ source: "client-run", capture: captureSessionControllerStop({ inputs: [L] }), assertCurrent: e, reason: createAgentRunDirectAbortError(), hookContext: { ...w, sessionKey: R.sessionKey, sessionId: R.sessionId }, afterParent: cancelWorker, onCancelled: (e) => { if (e === L) i = true; }, stopChildren: async (t) => { await t(); a = await abortControlledSubagents({ cfg: h, sessionKey: R.sessionKey, agentId: R.agentId, requesterTurnRunId: d, sessionId: R.sessionId, lifecycleRevision: n?.sessionId === R.sessionId ? n.lifecycleRevision : void 0, assertCurrent: e }); return { stopped: a?.killed ?? 0, failed: a?.status === "error" ? a.failed : 0 }; } }).completed; const o = descendantAbortError(a, "Parent run"); if (o) { r(false, void 0, o); return; } await respondWithWorkerRuns(i ? [d] : []); return; } if (k.owners.length > 0) { for (const e of k.owners) { const { identity: t } = e; const n = { ...t, requester: { connectionId: t.ownerConnId, deviceId: t.ownerDeviceId } }; if (!t.sessionKey || !t.sessionId || !canRequesterAbortChatRun(n, o, { requireOwnerMatch: true })) { respondError(r, ErrorCodes.INVALID_REQUEST, "unauthorized"); return; } if (!authorizeRunTarget(n)) return; } const e = await abortControlledSubagents({ cfg: h, sessionKey: b, agentId: y, sessionId: j?.sessionId, requesterTurnRunId: d, lifecycleRevision: j?.lifecycleRevision, execCancellation: k, assertCurrent, beforeKill: async () => { assertCurrent(); if (getRpcSourceForGateway(d, T)) throw new Error("Run changed before cancellation; retry Stop."); await stopWithoutCapturedRun("rpc", cancelWorker); return true; } }); const t = descendantAbortError(e, "Parent run"); if (t) { r(false, void 0, t); return; } await respondWithWorkerRuns([], void 0, e?.execAborted); return; } if (!B?.runIds.length) { if (!A.ok) throw A.error; await stopWithoutCapturedRun(); r(true, { ok: true, aborted: false, runIds: [] }); return; } if (!o.isAdmin) { respondError(r, ErrorCodes.INVALID_REQUEST, "unauthorized"); return; } cancelWorker(); await stopWithoutCapturedRun("rpc"); await respondWithWorkerRuns([]); return; } if (!authorizeRunTarget(getChatRunAbortAuthority(I))) return; const { sessionKey: W, sessionId: G, agentId: K } = getRpcSourceIdentity(I); assertCurrent(); const ee = captureSourceAssertion(I.input, assertCurrent); const q = W === l || W === b ? A : await prepareAbortSession(W, K ?? y); let J; const { aborted: Y, descendants: te, failure: X } = await stopExactClientRun({ ops: C, cfg: h, runId: d, active: I, lifecycleRevision: q.ok && q.value.entry?.sessionId === G ? q.value.entry.lifecycleRevision : void 0, assertCurrent: ee, hookContext: w, afterParent: cancelWorker, onAborted: () => t.onExactRunAborted?.(d), onAbortPrepared: () => { const e = i.chatRunState.resolveBuffer(d, { final: true }).text; if (I.adapter.controlUiVisible === false || !e?.trim()) return; J = captureAbortedPartial({ runId: d, sessionKey: W, sessionId: G, agentId: K ?? y, text: e, abortOrigin: "rpc", resolveTerminalProducer: I.adapter.resolveTerminalProducer, session: q }); return deferAbortedPartialPersistence(J, i); } }); const Z = descendantAbortError(te, "Parent run"); let Q; const $ = X ? [X.error] : []; if (Y) try { const e = J ? persistAbortedPartials({ context: i, snapshots: [J] }).then((e) => { Q = e; return e; }) : void 0; await waitForChatAbortAcknowledgment(Promise.all([e, waitForChatAbortTerminalPersistence(I)].map((e) => Promise.resolve(e).catch((e) => $.push(e))))); } catch (e) { $.push(e); } if ($.length) { if (Z) { r(false, void 0, withAbortedPartialPersistenceWarning({ ...Z, message: [Z.message, ...$.map(formatErrorMessage)].join(" ") }, Q)); return; } throw abortedPartialPersistenceError($.length === 1 ? $[0] : new AggregateError($, "Chat cancellation and persistence failed"), Q); } if (!A.ok) throw abortedPartialPersistenceError(A.error, Q); if (Z) { r(false, void 0, withAbortedPartialPersistenceWarning(Z, Q)); return; } try { await respondWithWorkerRuns(Y ? [d] : [], Q); } catch (e) { throw abortedPartialPersistenceError(e, Q); } } async function handleChatAbortRequest(e) { if (validateChatAbortParams(e.params)) e.context.logGateway.info(formatStopRequest("chat.abort", e.client, e.params)); try { await handleChatAbortRequestWithLifecycle(e); } catch (t) { const n = resolveStateContentionPresentation(t); if (!n) throw t; e.respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "The server is busy. Check this turn's status before trying Stop again.\n\nSQLite transaction admission remained busy. Stopping may already have taken effect.", { details: { errorKind: n.errorKind } })); } } //#endregion export { handleChatAbortRequestWithLifecycle as n, handleChatAbortRequest as t };