UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

520 lines (519 loc) • 19.6 kB
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as isIncognitoSessionKey } from "./session-key-DW1jcHbM.mjs"; import { Et as _enum, Fn as object, Jn as string } from "./schemas-Cy6abvsu.mjs"; import { s as resolveSessionTranscriptActiveLeafEntryId } from "./transcript-tree-CyUZzlQ1.mjs"; import { r as augmentChatHistoryWithCanvasBlocks } from "./chat-display-projection.canvas-XAAIxHM8.mjs"; import { r as jsonUtf8Bytes } from "./json-utf8-bytes-DNwtq2cu.mjs"; import { n as createTranscriptDisplaySource } from "./transcript-display-position-nYZ0UpDE.mjs"; import { c as readLegacyCompactionMetrics } from "./session-accessor.sqlite-references-sJ03Zh3Z.mjs"; import { r as getCliSessionBinding } from "./cli-session-binding-BEOgFSDg.mjs"; import { t as captureSessionActorTranscriptRead } from "./session-actor-transcript-read-CHpAgP2z.mjs"; import { t as resolveCurrentUserProfileDisplay } from "./current-user-profile-display-BvqB5fqy.mjs"; import { c as projectChatDisplayMessagesWithState, t as createChatHistoryRecoveryProjection } from "./chat-display-projection.core-ApUvO4fQ.mjs"; import { h as mapChatDisplayMessages, r as dropPreSessionStartAnnouncePairs, s as isProjectedHistoryTurnBoundaryMessage, u as projectForwardedMessages } from "./chat-display-projection.history-BZNUjEB3.mjs"; import { i as composeTranscriptDisplay } from "./transcript-image-artifacts-CcmdOg97.mjs"; import { a as readChatHistoryAnchorPage, c as readChatHistoryPaginationKey, l as readChatHistoryRecoveryContext, o as readChatHistoryMessageId, r as dropChatHistoryOverreadContextMessage, s as readChatHistoryMessageSeq, t as createSessionActorTranscriptReader, u as readIncrementalChatHistoryTail } from "./session-transcript-memory-reader-_afqDL9S.mjs"; import { _ as session_transcript_readers_exports } from "./session-transcript-readers-D1WqgwbF.mjs"; import { n as resolveClaudeCliProjectsDir } from "./claude-cli-project-dir-DwJdMUca.mjs"; import { a as createChatHistoryActivityProjection, l as replaceOversizedChatHistoryMessages, o as createChatHistoryByteCounter, r as buildOversizedHistoryPlaceholder, t as CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES } from "./chat-history-budget-DoE23WjR.mjs"; import { t as prepareForwardedMessageCronJobNameResolver } from "./chat-display-projection.cron-2V2VZ-K7.mjs"; import { n as projectChatHistoryWithReplies, t as attachChatHistoryReplyMessages } from "./chat-history-reply-messages-DT8sCO_d.mjs"; import { constants, deflateRawSync } from "node:zlib"; //#region src/gateway/chat-history-page-cursor.ts const PREFIX = "history-page:"; const MAX_CURSOR_CHARS = 4096; const cursorSchema = object({ sessionId: string().min(1).max(1024), source: string().min(1).max(128), messageId: string().min(1).max(1024), direction: _enum(["older", "newer"]) }); function encodeChatHistoryPageCursor(e) { if (!cursorSchema.safeParse(e).success) return; const t = PREFIX + Buffer.from(JSON.stringify(e)).toString("base64url"); return t.length <= MAX_CURSOR_CHARS ? t : void 0; } /** Undefined is a delta cursor; null is a malformed page cursor. Neither grants access. */ function decodeChatHistoryPageCursor(e) { if (!e?.startsWith(PREFIX)) return; if (e.length > MAX_CURSOR_CHARS) return null; try { const t = cursorSchema.safeParse(JSON.parse(Buffer.from(e.slice(13), "base64url").toString("utf8"))); return t.success ? t.data : null; } catch { return null; } } function resolveChatHistorySelectorError({ offset: e, messageId: t, cursor: n, sessionId: r }, i, a) { if (i === null) return "invalid history page cursor"; if (e !== void 0 && t !== void 0) return "offset and messageId cannot be used together"; if (n !== void 0 && (e !== void 0 || t !== void 0)) return "cursor cannot be used with offset or messageId"; if (r !== void 0 && t === void 0) return "sessionId requires messageId"; if (i && a && i.sessionId !== a) return "history page cursor does not belong to retained transcript"; } function resolveChatHistoryPageCursors(e, t, n) { if (!e) return {}; const r = readChatHistoryMessageId(t[0]); const i = t.length > 0 && r !== readChatHistoryMessageId(n[0]); const a = i ? r : e.oldestMessageId ?? r; const o = readChatHistoryMessageId(t.at(-1)) ?? e.newestMessageId; const cursor = (t, n) => encodeChatHistoryPageCursor({ sessionId: e.sessionId, source: e.source, messageId: t, direction: n }); return { ...a && (e.hasOlder || i) ? { olderCursor: cursor(a, "older") } : {}, ...o && (e.hasNewer || t.length > 0 && o !== readChatHistoryMessageId(n.at(-1))) ? { newerCursor: cursor(o, "newer") } : {} }; } //#endregion //#region src/gateway/chat-history-response-page.ts function readPageMessageSequence(e, t) { if (typeof t === "function") return t(e); return t?.[readChatHistoryPaginationKey(e) ?? ""] ?? readChatHistoryMessageSeq(e); } /** Preserve token metrics saved by pre-removal builds; new markers own their metrics. */ function enrichChatHistoryCompactionMarkers(e, t, n = readLegacyCompactionMetrics(t)) { if (n.length === 0) return e; const r = new Map(n.map((e) => [e.entryId, e])); return mapChatDisplayMessages(e, (e) => { const t = asOptionalRecord(e); const n = asOptionalRecord(t?.["__openclaw"]); if (n?.kind !== "compaction" || typeof n.id !== "string") return e; const i = r.get(n.id); if (!i) return e; const a = i.tokensBefore; const o = i.tokensAfter; if (a === void 0 && o === void 0) return e; return { ...t, __openclaw: { ...n, ...a !== void 0 ? { tokensBefore: a } : {}, ...o !== void 0 ? { tokensAfter: o } : {} } }; }); } function resolveChatHistoryMessageGroup(e, t, n, r) { const sequence = (e) => readPageMessageSequence(e, r); const i = sequence(e[t]); let a = t; let o = t + 1; let s = n(e[t]); if (i === void 0) return { start: a, end: o, cost: s }; while (a > 0 && sequence(e[a - 1]) === i) { a -= 1; s += n(e[a]); } while (o < e.length && sequence(e[o]) === i) { s += n(e[o]); o += 1; } return { start: a, end: o, cost: s }; } function prepareChatHistoryResponsePage(e, { entry: t, compactionMetrics: n, maxHistoryBytes: r, responseHistoryBytes: i = r, messageId: a }, o = e.pagination?.messageSequences ?? e.anchor?.messageSequences, s = jsonUtf8Bytes) { const c = enrichChatHistoryCompactionMarkers(e.messages, t, n); const l = createChatHistoryActivityProjection(c, e.activity); const u = createChatHistoryByteCounter(l, s); const d = i - (1 + u.framingBytes(c)); const messageCost = (e) => u.messageBytes(e) + 1; let f; for (let e = 0; e < c.length;) { const t = resolveChatHistoryMessageGroup(c, e, messageCost, o); if (t.cost > d) { f ??= c.slice(0, t.start); f.push(buildOversizedHistoryPlaceholder(c.slice(t.start, t.end).find((e) => readChatHistoryMessageId(e) === a) ?? c[t.end - 1])); } else if (f) for (let e = t.start; e < t.end; e++) f.push(c[e]); e = t.end; } const p = replaceOversizedChatHistoryMessages({ byteCounter: u, messages: f ?? c, maxSingleMessageBytes: Math.min(CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES, d - 1) }); const m = p.messages; function capChatHistoryTail() { let e = m.length; let t = 0; while (e > 0) { const n = resolveChatHistoryMessageGroup(m, e - 1, messageCost, o); if (t + n.cost > d) break; e = n.start; t += n.cost; } return e > 0 ? m.slice(e) : m; } function capChatHistoryAroundMessage(e) { const t = m.findIndex((t) => readChatHistoryMessageId(t) === e); if (t === -1) return []; const groupAt = (e) => resolveChatHistoryMessageGroup(m, e, messageCost, o); const n = groupAt(t); if (!(n.cost <= d)) return [m[t]]; let { start: r, end: i, cost: a } = n; const grow = (e) => { const t = groupAt(e); if (!(a + t.cost <= d)) return false; r = Math.min(r, t.start); i = Math.max(i, t.end); a += t.cost; return true; }; let s = r > 0; let c = i < m.length; while (s || c) { s &&= grow(r - 1) && r > 0; c &&= grow(i) && i < m.length; } return m.slice(r, i); } const h = a ? capChatHistoryAroundMessage(e.anchor?.direction ? readChatHistoryMessageId(e.anchor.direction === "newer" ? p.messages[0] : p.messages.at(-1)) ?? a : a) : capChatHistoryTail(); const g = e.pagination; let _; if (g !== void 0) { let e; for (const t of h) { e = readPageMessageSequence(t, g.messageSequences); if (e !== void 0) break; } _ = e === void 0 ? g.offset + g.rawPageMessages : Math.max(g.offset + 1, g.totalMessages - e + 1); } const v = resolveChatHistoryPageCursors(e.anchor, h, c); const y = g !== void 0 && _ !== void 0 ? _ < g.totalMessages && (!e.anchor || e.anchor.hasOlder || h.length < m.length) : void 0; const b = new Set(h); const x = c.reduce((e, t) => e + (b.has(t) ? 0 : 1), 0); return { messages: composeTranscriptDisplay(h), ...h.some((e) => l.has(e)) ? { activity: h.flatMap((e) => l.get(e) ?? []) } : {}, messagesBytes: u.messagesBytes(h), ...x > 0 ? { omission: { omittedCount: x, normalizedBytes: u.messagesBytes(c), ...h.length < p.messages.length ? { byteLimited: true } : {} } } : {}, responseHistoryBytes: i, ...v, ...y ? { nextOffset: _ } : {}, ...y !== void 0 ? { hasMore: y } : {}, ...g !== void 0 ? { totalMessages: g.totalMessages } : {} }; } function encodeChatHistoryResponsePage(e, t) { if (!t.encodeResponse) return e; const n = /* @__PURE__ */ new Map(); const serialize = (e) => { if (!n.has(e)) n.set(e, JSON.stringify(e)); return n.get(e); }; const r = prepareChatHistoryResponsePage(e, t, void 0, (e) => { try { return Buffer.byteLength(serialize(e) ?? String(e), "utf8"); } catch { return Buffer.byteLength(String(e), "utf8"); } }); const i = new TextEncoder(); const encodeArray = (e) => { const t = e.map((e) => serialize(e) ?? "null"); const n = new Uint8Array(2 + Math.max(0, t.length - 1) + t.reduce((e, t) => e + Buffer.byteLength(t), 0)); n[0] = 91; let r = 1; for (const [e, a] of t.entries()) { if (e > 0) n[r++] = 44; r += i.encodeInto(a, n.subarray(r)).written; } n[r] = 93; return n; }; const a = encodeArray(r.messages); const o = r.activity ? encodeArray(r.activity) : void 0; return { ...e, messages: [], activity: void 0, pagination: void 0, anchor: void 0, encodedMessagesDeflate: t.deflateResponse && a.byteLength >= 4096 ? new Uint8Array(deflateRawSync(a, { level: 1, finishFlush: constants.Z_SYNC_FLUSH })) : void 0, encodedResponse: { ...r, messages: a, activity: o } }; } //#endregion //#region src/gateway/chat-history-page-kernel.ts function resolveChatHistoryActiveLeafEntryId(e) { if (e.transcriptSource !== "active") return null; if (Object.hasOwn(e, "activeLeafEntryId")) return e.activeLeafEntryId ?? null; return resolveSessionTranscriptActiveLeafEntryId(e.transcriptEvents ?? []) ?? null; } /** Assemble one page from admitted readers; host imports and profile discovery stay outside. */ async function readChatHistoryPageKernel(e, t) { const { entry: n, sessionId: r, storePath: i, sessionAgentId: a, canonicalKey: o, max: s, maxHistoryBytes: c, effectiveMaxChars: l, offset: u, messageId: d, pageCursor: f } = e; if (!r || !i) { if (d) return { messages: [] }; return { ...(u ?? 0) === 0 ? { activeLeafEntryId: null } : {}, messages: [], ...u !== void 0 ? { responseOffset: u } : {}, pagination: { offset: u ?? 0, totalMessages: 0, rawPageMessages: 0 } }; } const p = { agentId: a, sessionEntry: n, sessionId: r, sessionKey: o, storePath: i }; const attachReplyMessages = (n) => attachChatHistoryReplyMessages(augmentChatHistoryWithCanvasBlocks(n), e, t); const m = t.readMessageSequence ?? readChatHistoryMessageSeq; if (d) { const i = f?.direction; const a = await readChatHistoryAnchorPage(t.readers, p, { messageId: d, maxMessages: s + (i === "older" ? 2 : i === "newer" ? 1 : 0), direction: i, allowResetArchiveFallback: true, readOnly: t.readOnly }); const o = a.displaySource ? createTranscriptDisplaySource([a.displaySource]) : void 0; if (f && (!a.found || a.windowReset || o !== f.source)) return { messages: [], windowReset: true }; if (!a.found) return { messages: [] }; let u = a.messages; let h = a.hasOverreadContext ? u[0] : void 0; if (i) { const e = u.findIndex((e) => readChatHistoryMessageId(e) === d); if (e < 0) return { messages: [], windowReset: true }; const t = m(u[e]); let n = e; let r = e + 1; if (t !== void 0) { while (n > 0 && m(u[n - 1]) === t) n -= 1; while (r < u.length && m(u[r]) === t) r += 1; } if (i === "newer") { h = u[r - 1]; u = u.slice(r - 1); } else { u = u.slice(0, n); const e = m(u[0]); if (t !== void 0 && e !== void 0 && t - e > s) { h = u[0]; u = [h, ...u.filter((t) => m(t) !== e)]; } } } const g = dropChatHistoryOverreadContextMessage(dropPreSessionStartAnnouncePairs(u, typeof n?.sessionStartedAt === "number" ? n.sessionStartedAt : void 0), h); const project = (n) => projectChatDisplayMessagesWithState(n, { includePluginSteering: e.includePluginSteering, subagentCoordination: t.readers.subagentCoordination, includeCommentaryFallbacks: true, maxChars: l, toolResultMaxChars: e.toolResultMaxChars, resolveCronJobName: t.resolveCronJobName, ...t.deferProfileDisplay ? {} : { resolveCurrentUserProfileDisplay: t.resolveCurrentUserProfileDisplay }, turnBoundaryPending: isProjectedHistoryTurnBoundaryMessage(h) }); const _ = project(g); let v = _.messages; const y = m(g.at(-1)); if ((i === "older" || a.offset > 0) && y !== void 0 && _.assistantErrorPending) { const e = await readChatHistoryRecoveryContext({ messages: g, createRecovery: (e) => { const n = createChatHistoryRecoveryProjection({ maxChars: l, subagentCoordination: t.readers.subagentCoordination }); n.append(e); return n; }, readScope: p, readers: t.readers, displaySource: a.displaySource, maxBytes: c, readOnly: t.readOnly, sessionStartedAt: n?.sessionStartedAt }); if (e.length > 0) v = project([...g, ...e]).messages.filter((e) => (m(e) ?? Infinity) <= y); } const b = dropChatHistoryOverreadContextMessage(u, h); const x = m(b[0]); return { messages: await attachReplyMessages(v), ..._.activity.length ? { activity: _.activity } : {}, ...o ? { anchor: { sessionId: r, source: o, direction: i, hasOlder: i === "newer" || x !== void 0 && x > 1, hasNewer: i === "older" || a.offset > 0, oldestMessageId: readChatHistoryMessageId(b[0]), newestMessageId: readChatHistoryMessageId(b.at(-1)) } } : {} }; } const h = await readIncrementalChatHistoryTail({ entry: n, readScope: p, effectiveMaxChars: l, max: s, toolResultMaxChars: e.toolResultMaxChars, includePluginSteering: e.includePluginSteering, maxBytes: c, isPageFull: (n) => prepareChatHistoryResponsePage(n, e, t.readMessageSequence).omission?.byteLimited === true, offset: u, ...t }); const { readPage: g } = h; const _ = h.windowReset ? 0 : u; const v = _ !== void 0; const y = !v || _ === 0; const b = y ? resolveChatHistoryActiveLeafEntryId(g) : null; const x = g.displaySource ? createTranscriptDisplaySource([g.displaySource]) : void 0; return { ...h.windowReset ? { windowReset: true } : {}, ...y ? { activeLeafEntryId: b } : {}, ...y && g.transcriptSource === "active" && g.deltaCursor && !h.projection.assistantErrorPending ? { deltaCursor: g.deltaCursor } : {}, messages: await attachReplyMessages(h.projected), ...h.projection.activity.length ? { activity: h.projection.activity } : {}, ...v ? { responseOffset: _ } : {}, ...x ? { anchor: { sessionId: r, source: x, hasOlder: h.hasOlder, hasNewer: (_ ?? 0) > 0, oldestMessageId: h.oldestMessageId, newestMessageId: h.newestMessageId } } : {}, pagination: { offset: _ ?? 0, totalMessages: g.totalMessages, rawPageMessages: h.rawPageMessages } }; } //#endregion //#region src/gateway/server-methods/chat-history-pages.ts function prepareChatHistoryParams(e) { return getCliSessionBinding(e.entry, "claude-cli")?.sessionId ? { ...e, cliHistoryProjectsDir: resolveClaudeCliProjectsDir() } : e; } function chatHistoryScope(e) { return { agentId: e.sessionAgentId, sessionId: e.sessionId ?? "", sessionKey: e.canonicalKey, storePath: e.storePath, sessionEntry: e.entry }; } async function readChatHistoryMessageById(e) { const t = chatHistoryScope(e); const n = captureSessionActorTranscriptRead(t); const r = n ? structuredClone(e) : e; const i = getCliSessionBinding(r.entry, "claude-cli"); if (n && i?.sessionId) { const { readProcessHeldCliHistoryMessage: e } = await import("./cli-session-history.process-held-yoFUCqIt.mjs"); const t = await e(prepareChatHistoryParams(r), n); n.assertCurrent(); return t; } if (n || !i?.sessionId || !e.storePath || e.entry?.incognito || isIncognitoSessionKey(e.canonicalKey)) { const e = await (n ? createSessionActorTranscriptReader(n) : session_transcript_readers_exports).readSessionMessageByIdAsync(t, r.messageId, { allowResetArchiveFallback: true, historyVisibility: { sessionStartedAt: r.entry?.sessionStartedAt } }); n?.assertCurrent(); return e; } const a = prepareChatHistoryParams(e); const { readSessionHistoryPageInWorker: o } = await import("./session-history-worker-runtime-D8lOqPp3.mjs"); return o({ kind: "rpc-message", params: { ...a, storePath: e.storePath } }); } async function readChatHistoryPage(e, t) { t?.throwIfAborted(); const n = chatHistoryScope(e); const r = captureSessionActorTranscriptRead(n, t); const i = getCliSessionBinding(e.entry, "claude-cli"); const a = prepareChatHistoryParams(r ? structuredClone(e) : e); if (r) { const e = Boolean(i?.sessionId && !a.ignoreCliSessionImports); let n; if (e) { const { readProcessHeldCliHistory: e } = await import("./cli-session-history.process-held-yoFUCqIt.mjs"); n = await e(a, t, r); } else n = await readChatHistoryPageKernel(a, { readers: createSessionActorTranscriptReader(r), readOnly: true, resolveCurrentUserProfileDisplay, resolveCronJobName: () => void 0 }); const o = { ...n, messages: await refreshForwardedLabels(n.messages) }; t?.throwIfAborted(); r.assertCurrent(); return e ? o : encodeChatHistoryResponsePage(o, a); } if (!a.sessionId || !a.storePath || a.entry?.incognito || isIncognitoSessionKey(a.canonicalKey)) { const e = await readChatHistoryPageKernel(a, { readers: session_transcript_readers_exports, resolveCurrentUserProfileDisplay, resolveCronJobName: () => void 0 }); return { ...e, messages: await refreshForwardedLabels(e.messages) }; } const { readSessionHistoryPageInWorker: o } = await import("./session-history-worker-runtime-D8lOqPp3.mjs"); return o({ kind: "rpc", params: { ...a, compactionMetrics: readLegacyCompactionMetrics(a.entry), sessionId: a.sessionId, storePath: a.storePath } }, t); } async function refreshForwardedLabels(e) { return projectChatHistoryWithReplies(e.filter((e) => asOptionalRecord(e) !== void 0), async (e) => projectForwardedMessages(e, await prepareForwardedMessageCronJobNameResolver(e))); } //#endregion export { decodeChatHistoryPageCursor as a, prepareChatHistoryResponsePage as i, readChatHistoryPage as n, resolveChatHistorySelectorError as o, enrichChatHistoryCompactionMarkers as r, readChatHistoryMessageById as t };