UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

161 lines (160 loc) • 7.09 kB
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { l as prepareAssistantTranscriptText } from "./chat-message-content-DNUdbbJ8.mjs"; import { c as hasInterSessionUserProvenance } from "./input-provenance-DupvvURj.mjs"; import { o as isOpenClawDeliveryMirrorAssistantMessage } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs"; import { n as selectVisibleTranscriptEvents } from "./transcript-visible-events-0xtUU8h3.mjs"; import { f as loadTranscriptReadSnapshotSync } from "./session-accessor.sqlite-read-DA1Bsaij.mjs"; import { n as readSessionTranscriptBoundedMessageTailPageFromProjection } from "./session-accessor.sqlite-active-events-read-C1zch5ew.mjs"; import { t as withCurrentProjectionSnapshot } from "./session-accessor.sqlite-active-projection-BlW01ngO.mjs"; import { r as sanitizeModelSpecialTokens } from "./external-content-CGL7l-3s.mjs"; import { t as classifySessionMessageOrigin } from "./session-provenance-DMP2xbqy.mjs"; //#region src/hooks/bundled/session-memory/transcript.ts const SESSION_MEMORY_TOOL_DIRECTIVE_PREFIX = String.raw`(?:(?:\|DSML\|)|(?:\uFF5CDSML\uFF5C))?`; const SESSION_MEMORY_TOOL_DIRECTIVE_KIND = String.raw`(?:tool_calls?|function_calls?|tool_use_error)`; const SESSION_MEMORY_DROP_BLOCK_RE = new RegExp(String.raw`<${SESSION_MEMORY_TOOL_DIRECTIVE_PREFIX}${SESSION_MEMORY_TOOL_DIRECTIVE_KIND}\b[^>]*>` + String.raw`[\s\S]*?(?:<\/${SESSION_MEMORY_TOOL_DIRECTIVE_PREFIX}${SESSION_MEMORY_TOOL_DIRECTIVE_KIND}>|$)`, "gi"); const SESSION_MEMORY_ROLE_DIRECTIVE_BLOCK_RE = /<(system|assistant|user)\b[^>]*>[\s\S]*?<\/\1>/gi; const SESSION_MEMORY_ROLE_DIRECTIVE_TAG_RE = /<\/?(?:system|assistant|user)\b[^>]*>/gi; const SESSION_MEMORY_JSON_LINE_SEPARATOR_RE = /[\u0085\u2028\u2029]/gu; function quoteSessionMemoryText(e) { return JSON.stringify(e).replace(SESSION_MEMORY_JSON_LINE_SEPARATOR_RE, (e) => `\\u${e.charCodeAt(0).toString(16).padStart(4, "0")}`); } function sanitizeSessionMemoryTranscriptText(e) { return sanitizeModelSpecialTokens(e).replace(SESSION_MEMORY_DROP_BLOCK_RE, "").replace(SESSION_MEMORY_ROLE_DIRECTIVE_BLOCK_RE, "").replace(SESSION_MEMORY_ROLE_DIRECTIVE_TAG_RE, "").trim() || null; } function extractTextMessageContent(e) { if (typeof e === "string") return e; if (!Array.isArray(e)) return; const t = e.flatMap((e) => { if (!e || typeof e !== "object") return []; const t = e; return t.type === "text" && typeof t.text === "string" ? [t.text] : []; }); return t.length > 0 ? t.join("\n") : void 0; } function renderSessionMemoryRecords(e) { const t = []; let n; let r = "untrusted"; for (const i of e) { if (!i || typeof i !== "object") continue; const e = i; if (e.type !== "message" || !e.message) continue; const a = e.message.role; if (a !== "user" && a !== "assistant" || !("content" in e.message)) continue; if (a === "user") r = classifySessionMessageOrigin(e.message, r); const o = classifySessionMessageOrigin(e.message, r); if (a === "user" && hasInterSessionUserProvenance(e.message)) continue; if (e.message.display === false) continue; const s = prepareAssistantTranscriptText(e.message, extractTextMessageContent(e.message.content)); const c = s ? sanitizeSessionMemoryTranscriptText(s) : null; if (!c) continue; if (a === "user") n = void 0; if (c.startsWith("/")) continue; if (isOpenClawDeliveryMirrorAssistantMessage(e.message) && c === n) continue; t.push({ line: `${a}: ${quoteSessionMemoryText(c)}`, originClass: o }); if (a === "assistant") n = c; } return t; } /** Counts transcript events that remain after session-memory filtering and deduplication. */ function countSessionMemoryMessages(e) { return renderSessionMemoryRecords(e).length; } function getRecentSessionProjectionFromEvents(e, t = 15) { const n = Number.isFinite(t) ? Math.max(0, Math.floor(t)) : 0; if (n === 0) return null; const r = renderSessionMemoryRecords(e).slice(-n); if (r.length === 0) return null; return { content: r.map((e) => e.line).join("\n"), originClass: r.some((e) => e.originClass === "untrusted" || e.originClass === "system") ? "untrusted" : "agent" }; } //#endregion //#region src/hooks/bundled/session-memory/capture.worker.ts const SESSION_MEMORY_CAPTURE_MAX_BYTES = 8388608; const SESSION_MEMORY_CAPTURE_PAGE_MESSAGES = 256; const SESSION_MEMORY_CAPTURE_MAX_SCANNED_MESSAGES = 4096; function relinkCapturedActiveMessageEvents(e) { let t = null; return e.map((e, n) => { if (!isRecord(e) || e.type !== "message") return e; const r = typeof e.id === "string" ? e.id : `session-memory-${n + 1}`; const i = { ...e, id: r, parentId: t }; t = r; return i; }); } function captureRecentSessionMemoryEvents(e, t) { const n = []; let r = 0; let i = 0; let a = Number.POSITIVE_INFINITY; while (i < a && i < SESSION_MEMORY_CAPTURE_MAX_SCANNED_MESSAGES && r < SESSION_MEMORY_CAPTURE_MAX_BYTES && countSessionMemoryMessages(selectVisibleTranscriptEvents(relinkCapturedActiveMessageEvents(n))) < t) { const t = readSessionTranscriptBoundedMessageTailPageFromProjection(e, { maxBytes: SESSION_MEMORY_CAPTURE_MAX_BYTES - r, maxMessages: Math.min(SESSION_MEMORY_CAPTURE_PAGE_MESSAGES, SESSION_MEMORY_CAPTURE_MAX_SCANNED_MESSAGES - i), offset: i }); a = t.totalMessages; if (t.scannedMessages === 0) break; n.unshift(...t.events.map(({ event: e }) => e)); r += t.serializedBytes; i += t.scannedMessages; } return relinkCapturedActiveMessageEvents(n); } function selectCurrentMemoryWindow(e) { const t = selectVisibleTranscriptEvents(e); const n = t.findLastIndex((e) => isRecord(e) && e.type === "reset"); const r = t[n]; if (!isRecord(r)) return t; const i = typeof r.firstKeptEntryId === "string" ? t.findIndex((e) => isRecord(e) && e.id === r.firstKeptEntryId) : -1; return [...(i >= 0 && i < n ? t.slice(i, n) : []).filter((e) => isRecord(e) && e.type === "message" && isRecord(e.message) && (e.message.role === "user" || e.message.role === "assistant")), ...t.slice(n + 1)]; } function captureAuthoritativeMemoryEvents(e, t) { const n = selectCurrentMemoryWindow(loadTranscriptReadSnapshotSync(e, { readOnly: true, resolvedScope: t }).events).filter((e) => isRecord(e) && e.type === "message").slice(-4096); const r = []; let i = 0; for (const e of n.toReversed()) { const t = Buffer.byteLength(JSON.stringify(e)) + 1; if (i + t <= SESSION_MEMORY_CAPTURE_MAX_BYTES) { r.unshift(e); i += t; } } return relinkCapturedActiveMessageEvents(r); } /** The retained history reader owns SQL; only the bounded excerpt leaves its snapshot. */ function readSessionMemoryCapture({ scope: e, resolvedScope: t, messageCount: n }) { let r; try { r = withCurrentProjectionSnapshot(e, (e) => captureRecentSessionMemoryEvents(e, n), { readOnly: true, resolvedScope: t }); } catch { r = captureAuthoritativeMemoryEvents(e, t); } const i = getRecentSessionProjectionFromEvents(r, n); return i ? { status: "available", ...i } : { status: "available", content: null, originClass: "agent" }; } //#endregion export { readSessionMemoryCapture };