UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

984 lines (983 loc) • 36.7 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as isPromiseLike } from "./promise-like-aMoWEh5w.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import { m as scopeLegacySessionKeyToAgent } from "./session-key-CqAyZeVk.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { d as resolveAgentVerboseDefault, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs"; import { c as measureDiagnosticsTimelineSpanSync, s as measureDiagnosticsTimelineSpan } from "./diagnostics-timeline-CSwiG24r.mjs"; import { i as sha256StableValue } from "./node-crypto-B6yuTjmm.mjs"; import { n as GATEWAY_CLIENT_IDS } from "./client-info-Cm1BcrMm.mjs"; import { bs as validateChatStartupParams, ps as validateChatHistoryParams } from "./src-BX8OAe1J.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { S as findModelCatalogEntry } from "./model-selection-shared-9Kz63Hhm.mjs"; import { _t as getSessionControllerEntryForOperation, t as activeSessionOperations } 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 { m as resolveOperatorRolePolicy } from "./operator-role-policy-DhcqVpmG.mjs"; import { T as resolveEffectiveChatHistoryMaxChars } from "./chat-display-projection.canvas-XAAIxHM8.mjs"; import { i as jsonUtf8BytesOrInfinity } from "./json-utf8-bytes-DNwtq2cu.mjs"; import { o as isOpenClawDeliveryMirrorAssistantMessage } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs"; import { q as readSessionPendingInputReceiptsInWorker } from "./session-accessor-CizTbDQj.mjs"; import { n as projectTranscriptEntryMessage } from "./session-transcript-entry-message-BrwStPpF.mjs"; import { D as captureSessionStoreScopeMatcher, E as captureRpcSourceScopeMatcher, T as captureGatewayScopeMatcher } from "./session-controller.lifecycle-C_Z3sybN.mjs"; import { r as resolveRequestedSessionAgentId, s as tryResolveSessionCompatibilityOwnerAgentId } from "./session-request-agent-tfwWH53J.mjs"; import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs"; import { t as captureSessionActorTranscriptRead } from "./session-actor-transcript-read-CHpAgP2z.mjs"; import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs"; import { t as SessionMutationFactsUnavailableError } from "./session-sharing-incognito-DCw8veq-.mjs"; import { d as isGatewayAdmin, u as hiddenSessionNotFound, y as resolveSessionVisibility } from "./session-sharing-policy-3TAaxC-R.mjs"; import { t as prepareSessionMutationFacts } from "./session-sharing-preparation-vuYznHON.mjs"; import { a as getRpcSourceIdentity, c as getRpcSourceStartedAt, r as getRpcSourceForGateway, v as listRpcSourceEntries, w as resolveRpcSourceSessionProgressState } from "./session-controller.rpc-sources-CTFbRW2t.mjs"; import { n as chatRunBelongsToSelectedAgent } from "./chat-run-owner-2pVCqGmw.mjs"; import { c as getSubagentSessionListReadSnapshotIdentity, f as prepareOptionalSubagentSessionListReadCache } from "./subagent-registry-state-CMZQXOjY.mjs"; import { o as prepareProjectedSessionSharing } from "./session-sharing-read-BqjuH16A.mjs"; import "./session-sharing-BIP3raq1.mjs"; import { n as SerializedJsonArray } from "./serialized-json-Ji3ULdJD.mjs"; import { a as prepareSessionFastModePresentation, i as projectOperatorModelRead } from "./operator-model-presentation-BAAXja2o.mjs"; import { n as resolveConfiguredThinkingDefaultCore } from "./model-thinking-default-DTaWSs8g.mjs"; import { r as resolveSessionModelRef } from "./session-model-ref-Cha0Enxi.mjs"; import { i as resolveGatewayModelThinkingProfile, t as getSessionDefaults } from "./session-utils-model-BFA7PxHy.mjs"; import { L as buildGatewaySessionRow, s as withReadySessionRows } from "./session-row-prepared-read-B4U_T7SO.mjs"; import { t as buildGatewaySessionSnapshot } from "./session-event-payload-CM3quPDs.mjs"; import { t as resolveCurrentUserProfileDisplay } from "./current-user-profile-display-BvqB5fqy.mjs"; import { r as readPreparedGatewayModelMetadata } from "./server-model-catalog-view-Do3gDG1F.mjs"; import { t as readAcpSessionMetaForEntries } from "./session-meta-readonly-B5S0IsZ_.mjs"; import "./model-catalog-ZbVopayG.mjs"; import { t as prepareProjectedSessionPresentation } from "./session-row-presentation-CvvGm3no.mjs"; import { i as resolveVisibleActiveSessionRunState } from "./session-active-runs-ENHF8ERS.mjs"; import { r as registerDeflatedSegment } from "./ws-compression-BlKVWwRd.mjs"; import { n as defineValidatedGatewayHandler, t as assertValidParams } from "./validation-DwNk6A-B.mjs"; import { n as createCurrentUserProfileMessageProjector } from "./chat-display-projection.core-ApUvO4fQ.mjs"; import { n as projectAgentHistoryActivity } from "./agent-activity-events-BvMnPRzr.mjs"; import { a as isAssistantTtsSupplementMessage } from "./chat-display-projection.history-BZNUjEB3.mjs"; import { i as composeTranscriptDisplay } from "./transcript-image-artifacts-CcmdOg97.mjs"; import { f as createPreparedSessionHistorySubagentProjection, p as isAppendOnlySessionHistoryDelta, t as createSessionActorTranscriptReader } from "./session-transcript-memory-reader-_afqDL9S.mjs"; import { g as resolveActiveEmbeddedRunOwnerForOperation } from "./runs-C1RO1Y6L.mjs"; import { t as resolveGatewayModelSelectionPolicy } from "./session-model-selection-policy-DLMXookV.mjs"; import "./session-utils-CavYkLyd.mjs"; import "./chat-display-projection-lHBiRfmJ.mjs"; import { t as readSessionHistoryPageInWorker } from "./session-history-worker-runtime-CRJi5EUs.mjs"; import { i as resolveClaudeCliBindingSessionId } from "./cli-session-history.claude-CcMY4HgJ.mjs"; import { a as withChatStartupDiagnostics } from "./chat-server-timing-Cp4A59kY.mjs"; import { a as createChatHistoryActivityProjection, c as getMaxChatHistoryMessagesBytes, i as chatHistoryActivityBytes, n as boundInFlightRunSnapshotForChatHistory, s as createChatHistoryDeltaByteCounter, u as reportOmittedChatHistory } from "./chat-history-budget-DoE23WjR.mjs"; import { a as decodeChatHistoryPageCursor, i as prepareChatHistoryResponsePage, n as readChatHistoryPage, o as resolveChatHistorySelectorError } from "./chat-history-pages-DJbqhqAa.mjs"; import { t as prepareForwardedMessageCronJobNameResolver } from "./chat-display-projection.cron-2V2VZ-K7.mjs"; import { n as withPreparedSessionResolve } from "./sessions-resolve-CJ_EcgrH.mjs"; import { r as readChatPendingInputs, t as captureQueuedChatInputRunIds } from "./chat-pending-inputs-Dxwqhxeq.mjs"; import { t as resolveSessionHistoryUnavailableMessage } from "./session-history-error-E8Y6aJos.mjs"; import { t as projectSessionMessagePayload } from "./session-transcript-message-BaYF68by.mjs"; import { t as handleChatMetadataRequest } from "./chat-metadata-handler-CPaDSq6_.mjs"; //#region src/gateway/chat-inflight-snapshot.ts function projectInFlightRunSnapshot(e) { const t = e.chatRunState.runs.get(e.runId); const n = e.chatRunState.resolveBuffer(e.runId); const r = t?.planSnapshot; const i = t?.progressSnapshot?.events; return { runId: e.runId, text: n.suppress ? "" : n.text, ...e.startedAtMs === void 0 ? {} : { startedAt: e.startedAtMs }, ...e.sessionAbortable ? { sessionAbortable: true } : {}, ...r ? { plan: r } : {}, ...i?.length ? { events: i } : {} }; } //#endregion //#region src/gateway/chat-inflight-snapshot.runtime.ts /** Restore the newest visible run for this Gateway's physical session store. */ function resolveInFlightRunSnapshot(e) { const t = captureRpcSourceScopeMatcher(e); const matchesKey = (t, n) => { const r = getRpcSourceIdentity(t); if (r.sessionKey !== n) return false; if (n !== "global") return true; const i = normalizeOptionalLowercaseString(e.agentId) ?? normalizeOptionalLowercaseString(e.defaultAgentId); if (!i) return false; return (normalizeOptionalLowercaseString(r.agentId) ?? normalizeOptionalLowercaseString(e.defaultAgentId)) === i; }; let n; for (const [r, i] of listRpcSourceEntries()) { if (!t(i) || !resolveRpcSourceSessionProgressState(i) || i.adapter.controlUiVisible === false || i.input.abortSignal.aborted || i.adapter.kind === "agent" || !matchesKey(i, e.requestedSessionKey) && !matchesKey(i, e.canonicalSessionKey)) continue; const a = getRpcSourceStartedAt(i); if (n === void 0 || (a ?? 0) > (n.startedAtMs ?? 0) || (a ?? 0) === (n.startedAtMs ?? 0) && r > n.runId) n = { runId: r, startedAtMs: a }; } if (n === void 0) return; return projectInFlightRunSnapshot({ chatRunState: e.chatRunState, runId: n.runId, startedAtMs: n.startedAtMs }); } //#endregion //#region src/gateway/server-methods/chat-history-delta.ts const CHAT_HISTORY_DELTA_MAX_EVENTS = 200; const CHAT_HISTORY_DELTA_MAX_BYTES = 1e6; function chatHistoryDeltaLimits(e) { return { cursor: e.cursor, maxBytes: Math.min(e.maxBytes ?? Infinity, CHAT_HISTORY_DELTA_MAX_BYTES), maxEvents: CHAT_HISTORY_DELTA_MAX_EVENTS }; } async function readChatHistoryDelta(e, t) { t?.throwIfAborted(); const n = captureSessionActorTranscriptRead(e.scope, t); if (n) { if (n.missing) return { kind: "reset" }; const r = await n.read("session.history.delta", { options: chatHistoryDeltaLimits(e) }); const i = createSessionActorTranscriptReader(n); if (r.kind === "page") await i.prepareVisibility(r.events.flatMap((e) => e.messageSeq === void 0 ? [] : [projectTranscriptEntryMessage(e.event, e.messageSeq, e.displayPosition)])); const a = await projectChatHistoryDelta(e, r, i.subagentCoordination); t?.throwIfAborted(); n.assertCurrent(); return a; } if (e.incognito || isIncognitoSessionKey(e.sessionKey)) return { kind: "reset" }; const r = { ...e.scope, sessionEntry: e.scope.sessionEntry ? { sessionId: e.scope.sessionEntry.sessionId } : void 0 }; const { readSessionHistoryPageInWorker: i } = await import("./session-history-worker-runtime-D8lOqPp3.mjs"); const a = await i({ kind: "delta", params: { target: r, limits: chatHistoryDeltaLimits(e) } }, t); return projectChatHistoryDelta(e, a.delta, createPreparedSessionHistorySubagentProjection(a.subagentCoordination, a.assertCurrent)); } async function projectChatHistoryDelta(e, t, n) { const r = Math.min(e.maxBytes ?? Infinity, CHAT_HISTORY_DELTA_MAX_BYTES); n.assertCurrent?.(); if (!isAppendOnlySessionHistoryDelta(t)) return { kind: "reset" }; const i = await prepareForwardedMessageCronJobNameResolver(t.events.flatMap((e) => e.messageSeq === void 0 ? [] : [projectTranscriptEntryMessage(e.event, e.messageSeq, e.displayPosition)])); n.assertCurrent?.(); let a = { assistantErrorPending: false, turnBoundaryPending: false }; const o = createCurrentUserProfileMessageProjector(resolveCurrentUserProfileDisplay); const s = []; const c = []; let l = 2; const u = t.events.length > 1 ? createChatHistoryDeltaByteCounter(e.sessionSnapshot) : void 0; for (const d of t.events) { if (d.messageSeq === void 0) continue; const t = projectTranscriptEntryMessage(d.event, d.messageSeq, d.displayPosition); if (!t) continue; if (isOpenClawDeliveryMirrorAssistantMessage(t) && asOptionalRecord(asOptionalRecord(t)?.openclawDeliveryMirror)?.kind === "channel-final") return { kind: "reset" }; if (isAssistantTtsSupplementMessage(t)) return { kind: "reset" }; const f = asOptionalRecord(d.event)?.id; const p = projectSessionMessagePayload({ agentId: e.agentId, historyDelta: true, includePluginSteering: e.includePluginSteering, maxChars: e.maxChars, toolResultMaxChars: e.toolResultMaxChars, message: t, ...typeof f === "string" && f ? { messageId: f } : {}, messageSeq: d.messageSeq, transcriptPosition: d.displayPosition, projectionState: a, projectCurrentUserProfile: o, subagentCoordination: n, resolveCronJobName: i, sessionKey: e.sessionKey, sessionSnapshot: e.sessionSnapshot }); if (p.requiresHistoryReset) return { kind: "reset" }; a = p.projectionState; if (a.assistantErrorPending) return { kind: "reset" }; if (p.payload) { l += (u ? u(p.payload) : jsonUtf8BytesOrInfinity(p.payload)) + (s.length > 0 ? 1 : 0); if (l > r) return { kind: "reset" }; s.push(p.payload); if (typeof f === "string") c.push({ messageId: f, message: t }); } } n.assertCurrent?.(); const d = [...createChatHistoryActivityProjection(s.map((e) => e.message), projectAgentHistoryActivity(c)).values()]; const f = chatHistoryActivityBytes(d); if (l + f > r) return { kind: "reset" }; return { activeLeafEntryId: t.activeLeafEntryId, deltaCursor: t.cursor, kind: "delta", activity: d, messages: composeTranscriptDisplay(s, (e) => e.message), messagesBytes: l, activityBytes: f }; } //#endregion //#region src/gateway/server-methods/chat-history-recovery.ts function resolveEmbeddedAgentRunRecoverySnapshot(e) { const t = captureSessionStoreScopeMatcher(e); const n = captureGatewayScopeMatcher(e.resolveGatewayContext); const r = Array.from(activeSessionOperations()).filter((r) => { const i = getSessionControllerEntryForOperation(r); const a = i.target; return a !== void 0 && i.attachment?.projectSessionActive !== false && t(a.storeScope, r.agentId) && n(r) && !r.result && (e.sessionId === void 0 || r.sessionId === e.sessionId) && (i.aliases.has(e.requestedSessionKey) || i.aliases.has(e.canonicalSessionKey)) && chatRunBelongsToSelectedAgent({ agentId: r.agentId, sessionKey: r.key, selectedAgentId: e.agentId ?? a.agentId ?? e.defaultAgentId, defaultAgentId: e.defaultAgentId }); }); const i = r.length === 1 ? r[0] : void 0; const a = i && getSessionControllerEntryForOperation(i).target; if (!i || !a) return; const o = resolveActiveEmbeddedRunOwnerForOperation(i); if (!o) return; const s = e.chatRunState.registry.peek(o.runId); const c = s && getRpcSourceForGateway(s.clientRunId, e.resolveGatewayContext, a); const l = s && c?.input.claim?.operation === i && (s.sessionKey === e.requestedSessionKey || s.sessionKey === e.canonicalSessionKey) && chatRunBelongsToSelectedAgent({ agentId: s.agentId, sessionKey: s.sessionKey, selectedAgentId: e.agentId, defaultAgentId: e.defaultAgentId }) ? s.clientRunId : o.runId; return projectInFlightRunSnapshot({ chatRunState: e.chatRunState, runId: l, startedAtMs: o.startedAtMs, sessionAbortable: true }); } function respondChatHistoryUnavailable(e, t, n) { t(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, n, { details: { method: e }, retryable: true, retryAfterMs: 250 })); } //#endregion //#region src/gateway/server-methods/chat-history-session-read.ts /** Select and revalidate history metadata through its prepared row and sharing owners. */ async function prepareChatHistorySessionRead({ context: e, client: t, respond: n, signal: r, sessionMutationAuthorization: i, method: a, sessionKey: o, agentIdOverride: s, requestedSessionId: c, retainedSessionId: l }) { const unavailable = (e) => respondChatHistoryUnavailable(a, n, e); const u = getSessionRowProjection(e); if (!u) { unavailable("session rows are initializing; reload the conversation"); return; } const queries = (e) => { const t = resolveRequestedSessionAgentId(e, o, s, "read"); if (!t.ok) return []; const { canonicalKey: n, agentId: r } = resolveSessionStoreIdentity({ cfg: e, sessionKey: o, agentId: t.agentId }); return [{ key: n, agentId: r }]; }; const selectSession = (e) => { const t = e.state.cfg; const r = resolveRequestedSessionAgentId(t, o, s, "read"); if (!r.ok) { n(false, void 0, r.error); return; } const i = resolveSessionStoreIdentity({ cfg: t, sessionKey: o, agentId: r.agentId }); const a = e.describe({ key: i.canonicalKey, agentId: i.agentId }); const c = a ? { agentId: a.agentId, canonicalKey: a.key } : i; const u = a?.storeTarget.storePath ?? resolveSessionStorePathCore(t.session?.store, { agentId: c.agentId }); return { cfg: t, ...c, record: a, entry: a?.storedEntry ?? a?.entry, storePath: u, sourcePath: l && a && !isIncognitoSessionKey(a.key) ? e.readSource(a)?.path : u, storeKeys: [c.canonicalKey], store: {} }; }; const authorizeSharingFacts = (e, r) => { i?.assertCurrent(); if (e.entry ? !r.canReadTarget({ ...e, entry: e.entry, storeKey: e.canonicalKey, storeKeys: [e.canonicalKey] }) : c && !l && !isGatewayAdmin(t)) { n(false, void 0, hiddenSessionNotFound(e.canonicalKey)); return; } return r; }; const authorizeSharing = (e, n) => authorizeSharingFacts(e, prepareProjectedSessionPresentation(n, t).sharing); const d = await measureDiagnosticsTimelineSpan(`gateway.${a}.session_entry`, () => withReadySessionRows(u, queries, (e) => { const t = selectSession(e); return t && authorizeSharing(t, e) ? t : void 0; }), { config: e.getRuntimeConfig(), phase: a }); r?.throwIfAborted(); if (!d) return; const { agentId: f, storePath: p, canonicalKey: m, entry: h } = d; const readTranscriptOwner = async () => { if (!c) return true; const e = await readSessionHistoryPageInWorker({ kind: "transcript-binding", params: { target: { agentId: f, sessionId: c, storePath: p } } }, r); if (!e) return false; const t = e.sessionKey; return (t === "global" || t === "unknown" ? t : scopeLegacySessionKeyToAgent({ sessionKey: t, agentId: f })) === m; }; if (c && !await readTranscriptOwner()) { if (l) unavailable("retained transcript is no longer available"); else n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "sessionId does not belong to sessionKey")); return; } let g; try { if (!d.entry && !isIncognitoSessionKey(o)) { g = await prepareSessionMutationFacts({ cfg: d.cfg, sessionKey: o, agentId: d.agentId, allowMissing: true }); r?.throwIfAborted(); } const readCurrentSharing = (e) => { const t = selectSession(e); if (!t) return; if (g) { let r; try { r = g.readCurrent(e.state.cfg).target?.entry; } catch (e) { if (!(e instanceof SessionMutationFactsUnavailableError)) throw e; unavailable(e.message); return; } if (r) { if (authorizeSharing({ ...t, entry: r }, e)) { if (t.entry) unavailable("session changed while reading history; reload the conversation"); else n(false, void 0, hiddenSessionNotFound(t.canonicalKey)); } return; } } const r = t.entry; if (h && (!r || t.agentId !== f || t.canonicalKey !== m || t.storePath !== p || !l && (!e.describe({ key: m, agentId: f, storePath: p }, d.record) || r.sessionId !== h.sessionId || r.lifecycleRevision !== h.lifecycleRevision || h.sessionStartedAt !== void 0 && r.sessionStartedAt !== h.sessionStartedAt))) { unavailable("session changed while reading history; reload the conversation"); return; } const i = authorizeSharing(t, e); if (!i) return; return r ? { visibility: resolveSessionVisibility(r), sharingRole: i.roleForTarget({ ...t, entry: r, storeKey: t.canonicalKey }) } : {}; }; if (g && !await withReadySessionRows(u, queries, readCurrentSharing)) { g.release(); return; } r?.throwIfAborted(); return { selectedSession: d, entry: h, queries, readCurrentSharing, readTranscriptOwner, rowProjection: u, async publishRetainedTranscript(n) { for (let i = 0; i < 2; i += 1) { let a; try { const i = await prepareSessionMutationFacts({ cfg: e.getRuntimeConfig(), sessionKey: m, agentId: f, allowMissing: true }); a = i.release; if (!await n.verify()) { unavailable("retained transcript changed while reading history"); return; } r?.throwIfAborted(); const o = e.getRuntimeConfig(); const s = i.readCurrent(o); const c = s.target; if (h && !c || c && (c.agentId !== f || c.canonicalKey !== m || s.sourcePath !== d.sourcePath) || n.requireCurrentSession && c?.entry.sessionId !== l) { unavailable("retained session changed while reading history"); return; } const g = authorizeSharingFacts({ entry: c?.entry, canonicalKey: m, agentId: f, storePath: p }, prepareProjectedSessionSharing({ cfg: u.getPolicyConfig(), client: t ?? null, isMember: (e, t) => Boolean(c && e.agentId === c.agentId && e.canonicalKey === c.canonicalKey && e.storePath === c.storePath && s.membership.has(t)) })); if (!g) return; const _ = c ? resolveSessionVisibility(c.entry) : void 0; const v = c ? g.roleForTarget(c) : void 0; if (_ !== n.sharing.visibility || v !== n.sharing.sharingRole) { unavailable("session access changed while reading history"); return; } const y = n.publish(); if (isPromiseLike(y)) { Promise.resolve(y).catch(() => {}); throw new Error("Retained history publication must remain synchronous"); } return; } catch (e) { if (!(e instanceof SessionMutationFactsUnavailableError) || i === 1) throw e; } finally { a?.(); } } }, release: () => g?.release() }; } catch (e) { g?.release(); if (e instanceof SessionMutationFactsUnavailableError) { unavailable(e.message); return; } throw e; } } //#endregion //#region src/gateway/server-methods/chat-history-handler.ts /** Internal callers carry schema-validated fields and their resolved session target. */ async function handleChatHistoryRequest({ params: e, respond: t, client: n, context: r, method: i, signal: a, sessionMutationAuthorization: o, retainedTranscript: s, acceptsSerializedJson: c, acceptsDeflatedSegments: l, req: u }) { const { sessionKey: d, limit: f, offset: p, cursor: m, knownState: h, messageId: g, sessionId: _, maxChars: v, toolResultMaxChars: y, maxBytes: b, pendingBefore: x, inputRunIds: S } = e; const C = decodeChatHistoryPageCursor(m); const w = n?.connect.client?.id === GATEWAY_CLIENT_IDS.CONTROL_UI; const T = C?.messageId ?? g; const E = C ? void 0 : m; const D = s?.sessionId; const O = D ?? C?.sessionId ?? _; const k = resolveChatHistorySelectorError(e, C, D); if (k) { t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, k)); return; } if (!getSubagentSessionListReadSnapshotIdentity()) await prepareOptionalSubagentSessionListReadCache(); a?.throwIfAborted(); const A = await prepareChatHistorySessionRead({ context: r, sessionMutationAuthorization: o, client: n, respond: t, signal: a, method: i, sessionKey: d, agentIdOverride: normalizeOptionalString(e.agentId), requestedSessionId: O, retainedSessionId: D }); if (!A) return; const respondReadError = (e) => { const n = resolveSessionHistoryUnavailableMessage(e); if (n === void 0) throw e; respondChatHistoryUnavailable(i, t, n); }; try { const { selectedSession: e, entry: o, queries: m, readCurrentSharing: g, readTranscriptOwner: _, rowProjection: D } = A; const { cfg: k, agentId: j, storePath: M, canonicalKey: N } = e; const readStartupProjection = () => measureDiagnosticsTimelineSpan(`gateway.${i}.startup_projection`, async () => { try { return await r.readChatStartupProjection?.({ agentId: j, sessionKey: N, sessionEntry: o, readPolicy: i === "chat.history" ? "ready" : "current" }); } catch (e) { r.logGateway.debug(`${i} continuing without prepared startup projection: ${formatErrorMessage(e)}`); return; } }, { config: k, phase: i, attributes: { agentId: j } }); const ee = o?.authProfileOverride?.trim() ? readStartupProjection() : void 0; const P = O ?? o?.sessionId; const F = { storePath: M, physicalPaths: D.physicalPaths, resolveGatewayContext: r.resolveGatewayContext }; const I = P ? captureQueuedChatInputRunIds({ ...F, sessionKey: N, sessionId: P, agentId: j }) : void 0; const L = O && O !== o?.sessionId ? void 0 : o; const te = resolveSessionModelRef(k, o, j, { allowPluginNormalization: false }); const R = f ?? 200; const z = Math.min(b ?? Infinity, getMaxChatHistoryMessagesBytes()); const B = Math.min(b ?? 524288, z); const V = resolveEffectiveChatHistoryMaxChars(v); const H = P && P === o?.sessionId ? await measureDiagnosticsTimelineSpan(`gateway.${i}.pending_inputs`, () => readChatPendingInputs({ agentId: j, sessionKey: N, sessionId: P, storePath: M }, { before: x, limit: R, maxChars: V, queuedRunIds: I, cronStorePath: r.cronStorePath })) : { items: [], total: 0 }; const U = S ? !T && P && P === o?.sessionId ? (await readSessionPendingInputReceiptsInWorker({ agentId: j, sessionKey: N, sessionId: P, storePath: M }, { runIds: S })).map((e) => e.state === "pending" && !e.cancelled && I?.has(e.runId) ? { runId: e.runId, state: e.state, queued: true } : e) : [] : void 0; const W = U?.flatMap((e) => e.state === "consumed" ? [{ runId: e.runId, consumedByEventId: e.consumedByEventId }] : []); let G; const K = c && i === u.method; const ne = K && l && !resolveOperatorRolePolicy(n, r.getCommittedRuntimeConfig?.() ?? k)?.modelPolicy; try { G = E !== void 0 ? { messages: [] } : await measureDiagnosticsTimelineSpan(`gateway.${i}.history_page`, () => readChatHistoryPage({ encodeResponse: K, deflateResponse: ne, includePluginSteering: w, entry: L, provider: te.provider, sessionId: P, storePath: M, sessionAgentId: j, canonicalKey: N, max: R, maxHistoryBytes: z, responseHistoryBytes: B, effectiveMaxChars: V, toolResultMaxChars: y, offset: p, messageId: T, ...C ? { pageCursor: C } : {} }, a), { config: k, phase: i, attributes: { limit: R, hasMessageId: Boolean(T), hasOffset: p !== void 0 } }); } catch (e) { respondReadError(e); return; } if (G.encodedResponse && G.encodedMessagesDeflate) registerDeflatedSegment(G.encodedResponse.messages, G.encodedMessagesDeflate); const { messages: re, messagesBytes: ie, responseHistoryBytes: q, omission: J, ...ae } = G.encodedResponse ? { ...G.encodedResponse, messages: new SerializedJsonArray(G.encodedResponse.messages), activity: G.encodedResponse.activity ? new SerializedJsonArray(G.encodedResponse.activity) : void 0 } : prepareChatHistoryResponsePage(G, { entry: L, maxHistoryBytes: z, responseHistoryBytes: B, messageId: T }); if (J) reportOmittedChatHistory({ ...J, maxHistoryBytes: q, logDebug: (e) => r.logGateway.debug(e) }); const Y = tryResolveSessionCompatibilityOwnerAgentId(k, d); const X = await (ee ?? readStartupProjection()); const Z = i === "chat.startup" ? X?.metadata : void 0; const { sessionModelCatalog: Q, defaultModelCatalog: $ } = X ?? {}; const oe = { context: r, client: n, agentId: j, catalog: $ }; const presentHistory = (e) => { const t = projectOperatorModelRead(oe, e); if (h === void 0) return t; const n = { commands: Z ? X?.commandsRevision : void 0, pendingInputs: sha256StableValue(t.pendingInputs).digest, sessionInfo: t.sessionInfo ? sha256StableValue({ ...t.sessionInfo, snapshotAt: void 0 }).digest : void 0 }; return { ...t, stateRevision: n, ...n.commands && h.commands === n.commands ? { metadata: { ...t.metadata, commands: void 0 } } : {}, ...E !== void 0 && h?.pendingInputs === n.pendingInputs ? { pendingInputs: void 0 } : {}, ...E !== void 0 && h?.sessionInfo === n.sessionInfo ? { sessionInfo: void 0, sessionInfoSnapshotAt: t.sessionInfo?.snapshotAt } : {} }; }; const [se] = o ? [] : await readAcpSessionMetaForEntries({ cfg: k, entries: [{ agentId: j, sessionKey: N, entry: void 0 }] }); const presentRead = (c) => { const l = { ...F, physicalPaths: c.physicalPaths }; const u = g(c); if (!u) return; const f = measureDiagnosticsTimelineSpanSync(`gateway.${i}.session_info`, () => prepareProjectedSessionPresentation(c, n).snapshot({ key: N, agentId: j, storePath: M }).row ?? (o ? void 0 : buildGatewaySessionRow({ ...e, key: N, preparedAcpMeta: se ?? null, preparedRuntimeOwnership: null, modelCatalog: Q, rowContext: D.state.rowContext })), { config: k, phase: i }); if (!o && f) { const e = prepareSessionFastModePresentation(n); f.fastMode = e(f.fastMode); f.effectiveFastMode = e(f.effectiveFastMode); } if (o && !f) { respondChatHistoryUnavailable(i, t, "session changed while reading history; reload the conversation"); return; } const p = resolveVisibleActiveSessionRunState({ ...l, requestedKey: d, canonicalKey: N, sessionId: P, ...j ? { agentId: j } : {}, defaultAgentId: Y, includeTerminalPersistence: true }); if (f) { Object.assign(f, u); f.hasActiveRun = p.active; if (p.runIds !== void 0) f.activeRunIds = p.runIds; if (p.active) f.status = p.status ?? "running"; } const h = resolveEmbeddedAgentRunRecoverySnapshot({ ...l, chatRunState: r.chatRunState, requestedSessionKey: d, canonicalSessionKey: N, sessionId: P, agentId: j, defaultAgentId: Y }); if (f && Object.hasOwn(G, "activeLeafEntryId")) f.activeLeafEntryId = G.activeLeafEntryId ?? null; const v = E === void 0 ? { ...getSessionDefaults(k, $, { agentId: j, allowPluginNormalization: false, metadataSnapshot: readPreparedGatewayModelMetadata(k), providerPolicySource: "active" }), modelSelectionTarget: resolveGatewayModelSelectionPolicy({ callerScopes: n?.connect?.scopes ?? [], cfg: k }).target } : void 0; for (const [e, t] of [[f, Q], [v, $]]) { if (!e) continue; const { modelProvider: n, model: r } = e; if (typeof (t && n && r ? findModelCatalogEntry(t, { provider: n, modelId: r }) : void 0)?.reasoning === "boolean" && n && r) { Object.assign(e, resolveGatewayModelThinkingProfile({ cfg: k, agentId: j, provider: n, model: r, modelCatalog: t, agentRuntime: e.agentRuntime?.id, sessionKey: e === f ? N : void 0, providerPolicySource: "active" })); e.thinkingOptions = e.thinkingLevels?.map(({ label: e }) => e); continue; } delete e.thinkingLevels; delete e.thinkingOptions; e.thinkingDefault = resolveAgentConfig(k, j)?.thinkingDefault ?? (n && r ? resolveConfiguredThinkingDefaultCore({ cfg: k, provider: n, model: r }) : k.agents?.defaults?.thinkingDefault); } const b = f?.thinkingLevel ?? f?.thinkingDefault ?? v?.thinkingDefault; const x = o?.verboseLevel ?? resolveAgentVerboseDefault(k, j); if (f) f.verboseLevel = x; const S = resolveInFlightRunSnapshot({ ...l, chatRunState: r.chatRunState, requestedSessionKey: d, canonicalSessionKey: N, agentId: j, defaultAgentId: Y }) ?? h; if (E !== void 0) return async () => { if (!f || !P || !M || resolveClaudeCliBindingSessionId(o)) { t(true, { kind: "reset" }); return; } const e = buildGatewaySessionSnapshot({ sessionRow: f, agentId: j, activeRunState: p }); let n; try { n = await readChatHistoryDelta({ maxChars: V, toolResultMaxChars: y, includePluginSteering: w, agentId: j, cursor: E, maxBytes: B, scope: { agentId: j, sessionEntry: o, sessionId: P, sessionKey: N, storePath: M }, sessionKey: N, sessionSnapshot: e, incognito: o?.incognito }, a); } catch (e) { respondReadError(e); return; } return withReadySessionRows(D, m, (e) => { const r = g(e); if (!r) return; if (r.visibility !== u.visibility || r.sharingRole !== u.sharingRole) { respondChatHistoryUnavailable(i, t, "session changed while reading history; reload the conversation"); return; } if (n.kind === "reset") { t(true, n); return; } f.activeLeafEntryId = n.activeLeafEntryId; const a = boundInFlightRunSnapshotForChatHistory({ snapshot: S, messages: n.messages, getMessagesBytes: () => n.messagesBytes, maxBytes: B - n.activityBytes }); const o = { kind: "delta", messages: n.messages, ...n.activity.length > 0 ? { activity: n.activity } : {}, deltaCursor: n.deltaCursor, pendingInputs: H, ...U ? { inputReceipts: U, inputConsumptions: W } : {}, sessionInfo: f, ...a ? { inFlightRun: a } : {}, ...Z ? { metadata: Z } : {} }; t(true, presentHistory(o)); }); }; const C = boundInFlightRunSnapshotForChatHistory({ snapshot: S, messages: [], getMessagesBytes: () => ie, maxBytes: q }); const T = { sessionKey: d, sessionId: P, messages: re, ...ae, pendingInputs: H, ...U ? { inputReceipts: U, inputConsumptions: W } : {}, ...G.deltaCursor ? { deltaCursor: G.deltaCursor } : {}, ...G.windowReset ? { windowReset: true } : {}, ...G.responseOffset !== void 0 ? { offset: G.responseOffset } : {}, defaults: v, sessionInfo: f, thinkingLevel: b, fastMode: prepareSessionFastModePresentation(n)(o?.fastMode), toolOverrides: o?.toolOverrides && structuredClone(o.toolOverrides), verboseLevel: x, ...C ? { inFlightRun: C } : {}, ...Z ? { metadata: Z } : {} }; if (s) return () => A.publishRetainedTranscript({ verify: async () => await _() && (await s.verifyRetainedState?.() ?? true), requireCurrentSession: s.requireCurrentSession === true, sharing: u, publish: () => t(true, presentHistory(T)) }); t(true, presentHistory(T)); }; await (await measureDiagnosticsTimelineSpan(`gateway.${i}.projection_final`, () => withReadySessionRows(D, m, presentRead)))?.(); } finally { A.release(); } } const chatHistoryHandlers = { "chat.history": defineValidatedGatewayHandler("chat.history", validateChatHistoryParams, (e) => handleChatHistoryRequest({ ...e, method: "chat.history" })), "chat.startup": withChatStartupDiagnostics(async (e) => { if (!assertValidParams(e.params, validateChatStartupParams, "chat.startup", e.respond)) return; if ("sessionKey" in e.params) { await handleChatHistoryRequest({ ...e, params: e.params, method: "chat.startup" }); return; } const t = e.client?.connId?.trim(); if (t) { e.context.subscribeSessionEvents(t); if (!e.context.getSessionEventSubscriberConnIds().has(t)) { e.respond(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "connection closed before chat startup")); return; } } const { shortId: n, slugHint: r, agentId: i, limit: a, maxBytes: o, toolResultMaxChars: s } = e.params; const c = getSessionRowProjection(e.context); if (!c) { respondChatHistoryUnavailable("chat.startup", e.respond, "session rows are initializing; reload the conversation"); return; } const l = await withPreparedSessionResolve({ projection: c, client: e.client, p: { shortId: n, slugHint: r, agentId: i, allowMissing: true }, isCurrent: () => getSessionRowProjection(e.context) === c }, (t) => { e.sessionMutationAuthorization?.assertCurrent(); if (!t.ok) { e.respond(false, void 0, t.error); return; } if ("missing" in t || "ambiguous" in t) { e.respond(true, { resolution: { ok: false, ..."ambiguous" in t ? { candidates: t.candidates } : {} } }); return; } return t; }); if (!l) return; await handleChatHistoryRequest({ ...e, params: { sessionKey: l.key, agentId: l.agentId, limit: a, maxBytes: o, toolResultMaxChars: s }, method: "chat.startup", respond: (t, n, r, i) => e.respond(t, t ? { ...asOptionalRecord(n), resolution: l } : n, r, i) }); }), "chat.metadata": handleChatMetadataRequest }; //#endregion export { handleChatHistoryRequest as n, prepareChatHistorySessionRead as r, chatHistoryHandlers as t };