UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

752 lines (751 loc) • 27.8 kB
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { n as estimateStringChars, t as CHARS_PER_TOKEN_ESTIMATE } from "./cjk-chars-CgnWl5qA.mjs"; import { n as sliceUtf16Safe, r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { p as hasRuntimeContextMarker } from "./types-iq-cNLsd.mjs"; import { a as collectToolPairingMessageFact, m as createToolCallOccurrenceQueue, p as classifyToolPairingFacts } from "./tool-result-pairing-gfPySfH_.mjs"; import { u as isRuntimeContextCarrier } from "./messages-MSizso-z.mjs"; import { a as projectSessionEntryMessage } from "./session-BC1-SoD4.mjs"; import "./src-DFw9QOgs.mjs"; import { r as copyString } from "./truncate-DCXARhAL.mjs"; //#region packages/agent-core/src/harness/compaction/conversation-serialization.ts const ENTRY_SEPARATOR = "\n\n"; /** * Upper bound for the conversation text of one summary request, in CJK-weighted * characters (about 40k tokens). Summary latency and cost follow this bound, not * the session size, so a 1M-token window compacts as fast as a 128k one. */ const MAX_SUMMARY_INPUT_CHARS = 16e4; const MAX_SAMPLED_ENTRY_CHARS = 6e3; const MIN_TRIMMED_ENTRY_CHARS = 200; const TRIMMED_ENTRY_HEAD_SHARE = .7; const ELISION_MARKER_RESERVE_CHARS = 64; const SUMMARY_INPUT_TAIL_SHARE = .5; const SUMMARY_INPUT_USER_SHARE = .25; const SUMMARY_INPUT_HEAD_SHARE = .1; const SUMMARY_INPUT_MIDDLE_SLICES = 8; const MAX_USER_ENTRY_CHARS = 2e3; const MIN_USER_ENTRY_CHARS = 400; const OMISSION_MARKER_CHARS = 40; /** * Keep both ends of `text` within `maxChars` CJK-weighted characters: the start * usually states the request and the end its latest instruction or result. * Weighted length is at least the UTF-16 length, so each binary search is * bounded by the weight budget, not by the size of the text. */ function elideMiddleWithinWeight(e, t) { const n = t - 64; if (n < MIN_TRIMMED_ENTRY_CHARS) return; const r = Math.floor(n * TRIMMED_ENTRY_HEAD_SHARE); let i = 0; let a = Math.min(e.length, r); while (i < a) { const t = Math.ceil((i + a) / 2); if (estimateStringChars(truncateUtf16Safe(e, t)) <= r) i = t; else a = t - 1; } const o = truncateUtf16Safe(e, i); const s = n - estimateStringChars(o); i = Math.max(o.length, e.length - s); a = e.length; while (i < a) { const t = Math.floor((i + a) / 2); if (estimateStringChars(sliceUtf16Safe(e, t)) <= s) a = t; else i = t + 1; } const c = sliceUtf16Safe(e, i); return `${o}\n\n[... ${e.length - o.length - c.length} characters omitted ...]\n\n${c}`; } /** * Render descriptors for one summary request within `maxChars` CJK-weighted * characters. Small inputs are unchanged. Larger inputs keep, in this order: * the newest entries verbatim (half the budget); older user messages, which * carry the asks, decisions and corrections (a quarter, newest first, each up * to 2,000 characters); the oldest entries (a tenth); and eight evenly spaced * runs of what remains. Older tool results keep 500 characters of their head * and tail instead of 2,000. Sampled entries are trimmed to 6,000 characters, every * gap is marked with its entry count, and each tool result names its call, * because sampling can separate the two. The transcript itself is not changed. * Only candidate text is read synchronously, inside the source reader's lifetime; * descriptors and the bounded selection never retain unselected source payloads. */ function renderConversationEntriesWithinBudget(e, t, n) { const r = 2; if (e.reduce((e, t) => e + t.fullChars, 0) + r * Math.max(0, e.length - 1) <= t) return { text: e.map((e) => copyString(n(e, "full"))).join("\n\n"), omittedEntries: 0, trimmedEntries: 0 }; let i = false; let a = e.length; const weight = (t) => (i && t < a ? e[t]?.shortChars : e[t]?.labeledChars) ?? 0; const o = /* @__PURE__ */ new Map(); let s = 0; let c = OMISSION_MARKER_CHARS; const take = (l, u, d = u) => { if (o.has(l)) return true; const f = e[l]; if (!f) return false; const p = l > 0 && !o.has(l - 1); const m = l < e.length - 1 && !o.has(l + 1); const h = (p && m ? 1 : !p && !m ? -1 : 0) * OMISSION_MARKER_CHARS; const g = Math.min(u - h, d + r); let _ = weight(l) + r; if (_ > g && g - r - 64 < MIN_TRIMMED_ENTRY_CHARS) return false; if (_ <= g && c + _ + h > t) return false; const v = n(f, i && l < a ? "short" : "labeled"); let y = v; if (_ > g) { const e = elideMiddleWithinWeight(v, g - r); if (e === void 0) return false; y = e; _ = estimateStringChars(e) + r; } if (c + _ + h > t) return false; if (y !== v) s += 1; o.set(l, copyString(y)); c += _ + h; return true; }; const l = Math.floor(t * SUMMARY_INPUT_TAIL_SHARE); for (let t = e.length - 1; t >= 0; t -= 1) { const n = l - c; if (!(weight(t) + r <= n) && a !== e.length || !take(t, n)) break; a = t; } i = true; const u = []; for (let t = 0; t < a; t++) if (e[t]?.user) u.push(t); if (u.length > 0) { const e = Math.floor(t * SUMMARY_INPUT_USER_SHARE); const n = c + e; const i = Math.min(MAX_USER_ENTRY_CHARS, Math.max(MIN_USER_ENTRY_CHARS, Math.floor(e / u.length - OMISSION_MARKER_CHARS))); const a = u.reduce((e, t) => e + Math.min(weight(t) + r, i + r) + OMISSION_MARKER_CHARS, 0); const o = Math.max(1, a / e); for (let e = u.length - 1; e >= 0; e -= o) { const t = u[Math.round(e)]; if (t === void 0 || !take(t, n - c, i)) break; } } let d = 0; const f = c + Math.floor(t * SUMMARY_INPUT_HEAD_SHARE); while (d < a && take(d, f - c, MAX_SAMPLED_ENTRY_CHARS)) d += 1; const p = a - d; if (p > 0) { const e = Math.floor((t - c) / SUMMARY_INPUT_MIDDLE_SLICES); let n = d; for (let t = 0; t < SUMMARY_INPUT_MIDDLE_SLICES; t += 1) { let r = Math.max(n, d + Math.floor(t * p / SUMMARY_INPUT_MIDDLE_SLICES)); const i = c + e; while (r < a && take(r, i - c, MAX_SAMPLED_ENTRY_CHARS)) r += 1; n = r; } } const m = []; let h = 0; let g = 0; for (let t = 0; t <= e.length; t += 1) { const n = o.get(t); if (n === void 0 && t < e.length) { g += 1; continue; } if (g > 0) { m.push(`[... ${g} ${g === 1 ? "entry" : "entries"} omitted ...]`); h += g; g = 0; } if (n !== void 0) m.push(n); } return { text: m.join("\n\n"), omittedEntries: h, trimmedEntries: s }; } //#endregion //#region packages/agent-core/src/harness/compaction/utils.ts const SAMPLED_TOOL_RESULT_MAX_CHARS = 500; function normalizeFileToolName(e) { const t = e.toLowerCase(); const n = t.indexOf("__", t.startsWith("mcp__") ? 5 : 0); return n < 0 ? t : t.slice(n + 2); } function addFilePaths(e, t) { for (const n of Array.isArray(t) ? t : []) if (typeof n === "string") e.add(n); } /** Create an empty file-operation accumulator. */ function createFileOps() { return { read: /* @__PURE__ */ new Set(), written: /* @__PURE__ */ new Set(), edited: /* @__PURE__ */ new Set() }; } /** Restore file metadata recorded by an earlier compaction or branch summary. */ function mergeSummaryFileOperations(e, t) { addFilePaths(e.read, t.readFiles); addFilePaths(e.edited, t.modifiedFiles); } /** Exact file identities survive a row; message text and tool arguments do not. */ function collectFileOperationMessageFact(e) { const t = { read: /* @__PURE__ */ new Set(), written: /* @__PURE__ */ new Set(), edited: /* @__PURE__ */ new Set() }; if (e.role === "toolResult") { if (normalizeFileToolName(e.toolName) === "apply_patch") for (const n of [e, ...Array.isArray(e.content) ? e.content : []]) { const e = asOptionalRecord(asOptionalRecord(asOptionalRecord(n)?.details)?.summary); addFilePaths(t.written, e?.added); addFilePaths(t.edited, e?.modified); } } else if (e.role === "assistant") for (const n of e.content) { if (n.type !== "toolCall") continue; const e = asOptionalRecord(n.arguments); const r = [ e?.path, e?.file_path, e?.filePath ].find((e) => typeof e === "string"); if (r === void 0) continue; const i = normalizeFileToolName(n.name); if (i === "read") t.read.add(r); else if (i === "write") t.written.add(r); else if (i === "edit") t.edited.add(r); } return { read: [...t.read], written: [...t.written], edited: [...t.edited] }; } function extractFileOpsFromFacts(e, t) { for (const n of e) { addFilePaths(t.read, n.read); addFilePaths(t.written, n.written); addFilePaths(t.edited, n.edited); } } function extractFileOpsFromMessage(e, t) { extractFileOpsFromFacts([collectFileOperationMessageFact(e)], t); } function extractFileOpsFromMessages(e, t) { for (const n of e) extractFileOpsFromMessage(n, t); } /** Compute sorted read-only and modified file lists from accumulated operations. */ function computeFileLists(e) { const t = /* @__PURE__ */ new Set([...e.edited, ...e.written]); return { readFiles: [...e.read].filter((e) => !t.has(e)).toSorted(), modifiedFiles: [...t].toSorted() }; } const MAX_FILE_OPS_LIST_CHARS = 900; function formatBoundedFileList(e, t, n) { if (t.length === 0 || n <= 0) return ""; const r = `<${e}>\n`; const i = `\n</${e}>`; const a = []; let o = r.length + i.length; for (let e = 0; e < t.length; e++) { const r = `${t[e]}\n`; const i = t.length - e - 1; const s = i > 0 ? `...and ${i} more\n` : ""; if (o + r.length + s.length > n) { const r = `...and ${t.length - e} more\n`; if (o + r.length <= n) a.push(r); break; } a.push(r); o += r.length; } return a.length > 0 ? `${r}${a.join("").trimEnd()}${i}` : ""; } /** Format file lists as bounded summary metadata tags. */ function formatFileOperations(e, t) { const n = [formatBoundedFileList("read-files", e, MAX_FILE_OPS_LIST_CHARS), formatBoundedFileList("modified-files", t, MAX_FILE_OPS_LIST_CHARS)].filter(Boolean); return n.length > 0 ? `\n\n${n.join("\n\n")}` : ""; } /** Extract visible summary text without normalizing valid model output. */ function extractSummaryText(e) { const t = e.content.filter((e) => e.type === "text").map((e) => e.text).join("\n"); return t.trim() ? t : void 0; } const TOOL_RESULT_MAX_CHARS = 2e3; const IMPORTANT_TOOL_RESULT_TAIL = /(error|exception|failed|fatal|traceback|panic|stack trace|errno|exit code)/i; function stringifyCompactionValue(e) { try { return JSON.stringify(e) ?? "undefined"; } catch { return "[unserializable]"; } } function truncateForSummary(e, t) { if (e.length <= t) return e; const n = Math.min(Math.floor(t * .3), 600); const r = sliceUtf16Safe(e, -t); const i = [...r.matchAll(new RegExp(IMPORTANT_TOOL_RESULT_TAIL.source, "gi"))]; const a = i.findLast((e) => /^(error|exception|fatal|panic|errno)$/i.test(e[0])) ?? i.at(-1); if (a) { const i = truncateUtf16Safe(e, t - n); const o = sliceUtf16Safe(e, Math.max(0, i.length - 32), t); if (!IMPORTANT_TOOL_RESULT_TAIL.test(o)) { const t = e.length - r.length + (a.index ?? 0); const o = Math.min(t, e.length - n); if (o >= i.length) { const t = sliceUtf16Safe(e, o, o + n); return `${i}\n\n[... ${e.length - i.length - t.length} ${o + t.length < e.length ? "middle/trailing" : "more"} characters truncated]\n\n${t}`; } } } const o = t - n - 64; const s = truncateUtf16Safe(e, t); const c = IMPORTANT_TOOL_RESULT_TAIL.test(s) ? "" : sliceUtf16Safe(e, -n); const l = c ? truncateUtf16Safe(s, o) : s; return `${l}\n\n[... ${e.length - l.length - c.length} more characters truncated]${c ? `\n\n${c}` : ""}`; } /** Project summary content once so rendering and token accounting share omission facts. */ function getCompactionContent(e) { const t = /* @__PURE__ */ new Set(); return { text: typeof e === "string" ? e : e.map((e) => { let n = ""; if ((e.type === "text" || e.type === "toolResult" || e.type === "tool_result") && e.text) n = e.text; else if ((e.type === "toolResult" || e.type === "tool_result") && typeof e.content === "string") n = e.content; if (e.type !== "text" && !n) t.add(e.type === "image" ? "[image data omitted from summary input]" : "[non-text data omitted from summary input]"); return n; }).filter(Boolean).join("\n"), omissionText: [...t].join("\n") }; } const MAX_OMISSION_MESSAGES = 8; const OMISSION_OVERFLOW = "[More image/non-text data omitted from summary input]"; /** * Return exactly the persisted-sender text which is projected into a user * conversation label. Keep this shared with token accounting: adding a label * to the prompt without charging it can make bounded compaction overflow. */ function formatPersistedSenderSuffix(e) { if (e.role !== "user") return ""; const t = asOptionalRecord(Reflect.get(e, "__openclaw")); if (!t) return ""; const normalize = (e) => { if (typeof e !== "string") return; return e.replaceAll("\0", "").trim() || void 0; }; const n = { id: normalize(t.senderId), name: normalize(t.senderName), username: normalize(t.senderUsername) }; return n.id ? ` sender=${JSON.stringify(n)}` : ""; } function compactionUserRole(e) { if (hasRuntimeContextMarker(e)) return "Runtime context"; if (Reflect.get(e, "synthetic") === true) return "Synthetic input"; if (Reflect.get(e, "operatorMessage") !== void 0) return "Operator input"; if (asOptionalRecord(Reflect.get(e, "__openclaw"))?.beforeAgentRunBlocked !== void 0) return "Internal system input"; const t = Reflect.get(e, "provenance"); if (t === void 0) return "User"; const n = asOptionalRecord(t); switch (n?.kind) { case "external_user": return "User"; case "realtime_voice": return n.sourceChannel === "talk" ? "User" : "Unknown-origin input"; case "inter_session": return "Inter-session input"; case "internal_system": return "Internal system input"; default: return "Unknown-origin input"; } } /** Compaction request attribution only; admitted internal inputs still start runtime turns. */ function isCompactionUserRequest(e) { return e.role === "user" && compactionUserRole(e) === "User"; } /** Callers retain their text projection; request attribution has one owner. */ function findLatestCompactionUserMessage(e, t) { return e.findLast((e) => e.role === "user" && isCompactionUserRequest(e) && Boolean(t(e).trim())); } const CREDENTIAL_PATTERNS = [ /\b(?:sk|pk|rk|ghp|gho|ghu|ghs|github_pat|xox[abprs]|glpat|AKIA|AIza)[-_A-Za-z0-9]{16,}/g, /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{5,}/g, /\b(?:api[_-]?key|token|secret|password|passwd|authorization|bearer)\b\s*[:=]\s*["']?[^\s"']{8,}/gi, /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g ]; /** * Text quoted verbatim into compaction artifacts. Summaries are persisted and replayed * on every later request, so credential shapes are redacted here, before any caller * clips an excerpt that could leave a fragment. The transcript itself stays raw. */ function extractCompactionMessageText(e) { const t = Reflect.get(e, "content"); const n = typeof t === "string" ? t.trim() : Array.isArray(t) ? t.flatMap((e) => { const t = e && typeof e === "object" ? Reflect.get(e, "text") : void 0; return typeof t === "string" && t.trim() ? [t.trim()] : []; }).join("\n") : ""; return CREDENTIAL_PATTERNS.reduce((e, t) => e.replace(t, "[redacted]"), n); } /** Legacy producers cannot search past an independent input for a pending ask. */ function extractCurrentCompactionUserRequest(e, t) { const n = e.findLast((e) => e.role === "user"); return n && isCompactionUserRequest(n) ? t(n) : null; } /** Shared by summary input, preserved excerpts, and their token accounting. */ function formatCompactionUserLabel(e) { return `${compactionUserRole(e)}${formatPersistedSenderSuffix(e)}`; } function removeGeneratedCompactionSection(e, t) { if (!e) return e; if (e.startsWith(t)) return e.slice(t.length); const n = `\n\n${t}`; const r = e.indexOf(n); return r < 0 ? e : `${e.slice(0, r)}\n\n${e.slice(r + n.length)}`; } /** Authoritative request owners clear stale model-written asks without rewriting other sections. */ function clearCompactionPendingAskSection(e) { const t = /^## Pending user asks[ \t]*$/mu.exec(e); if (!t) return e; const n = t.index + t[0].length; const r = e.slice(n + 1); const i = /^##[ \t]+\S.*$/mu.exec(r); return `${e.slice(0, n)}\nNone.${i ? `\n${r.slice(i.index)}` : ""}`; } /** Serialize LLM messages to plain text for summarization prompts. */ function serializeConversation(e) { return collectConversationEntries(e).map(({ text: e }) => e.full).join("\n\n"); } const MAX_CALL_LABEL_ARGUMENT_CHARS = 120; const MAX_CALL_LABEL_CHARS = 300; function formatCallLabel(e, t) { const n = `${e}(${t.map(([e, t]) => `${e}=${t.length > MAX_CALL_LABEL_ARGUMENT_CHARS ? `${truncateUtf16Safe(t, MAX_CALL_LABEL_ARGUMENT_CHARS)}...` : t}`).join(", ")})`; return copyString(n.length > MAX_CALL_LABEL_CHARS ? `${truncateUtf16Safe(n, MAX_CALL_LABEL_CHARS)}...)` : n); } function omissionPhase(e) { return e < MAX_OMISSION_MESSAGES ? 0 : e === MAX_OMISSION_MESSAGES ? 1 : 2; } /** Project one actual source row, sharing exactly the same text rules on collection and reads. */ function projectConversationMessage(e, t, n) { const r = []; const add = (e, t = e, n = t, i = false, a) => { r.push({ full: e, labeled: t, short: n, user: i, toolResult: a }); }; if (hasRuntimeContextMarker(e)) return r; if (e.role === "user" || e.role === "toolResult") { const { text: n, omissionText: r } = getCompactionContent(e.content); const i = omissionPhase(t.omissionMessages); if (r) t.omissionMessages += 1; if (r && i === 1) add(OMISSION_OVERFLOW); const a = i === 0 ? r : ""; const project = (t) => [a, e.role === "toolResult" ? truncateForSummary(n, t) : n].filter(Boolean).join("\n"); const o = project(TOOL_RESULT_MAX_CHARS); if (o) { if (e.role === "toolResult") { const n = t.callLabel ?? `${e.toolName}(...)`; add(`[Tool result]: ${o}`, `[Tool result of ${n}]: ${o}`, `[Tool result of ${n}]: ${project(SAMPLED_TOOL_RESULT_MAX_CHARS)}`, false, true); } else { const t = `[${formatCompactionUserLabel(e)}]: ${o}`; add(t, t, t, isCompactionUserRequest(e)); } } } else if (e.role === "assistant") { const t = []; const r = []; for (const i of e.content) if (i.type === "text") t.push(i.text); else if (i.type === "toolCall") { const e = Object.entries(i.arguments).map(([e, t]) => [e, stringifyCompactionValue(t)]); const t = e.map(([e, t]) => `${e}=${t}`).join(", "); r.push(`${i.name}(${t})`); n?.(i.id, formatCallLabel(i.name, e)); } if (t.length > 0) add(`[Assistant]: ${t.join("\n")}`); if (r.length > 0) add(`[Assistant tool calls]: ${r.join("; ")}`); } return r; } /** Carry occurrence and omission state across rows, never source messages or full text. */ function createConversationSequenceState() { const e = createToolCallOccurrenceQueue(); let t = 0; return { begin(n, r) { if (n === "assistant") e.clear(); return { omissionMessages: t, callLabel: n === "toolResult" && r !== void 0 ? e.claim(r) : void 0 }; }, finish(e) { t = e.omissionMessages; }, add: e.add }; } function createConversationProjector() { const e = createConversationSequenceState(); return (t) => { if (hasRuntimeContextMarker(t)) return { parts: [], omissionMessages: 0, callLabel: void 0 }; const n = e.begin(t.role, t.role === "toolResult" ? t.toolCallId : void 0); const r = n.omissionMessages; const i = projectConversationMessage(t, n, e.add); e.finish(n); return { parts: i, omissionMessages: r, callLabel: n.callLabel }; }; } function describeConversationParts(e, t, n) { return e.map((e, r) => { const i = estimateStringChars(e.full); const a = e.labeled === e.full ? i : estimateStringChars(e.labeled); return { descriptor: { source: t, partIndex: r, fullChars: i, labeledChars: a, shortChars: e.short === e.labeled ? a : estimateStringChars(e.short), fullLength: e.full.length, labeledLength: e.labeled.length, shortLength: e.short.length, user: e.user === true, toolResult: e.toolResult, ...n }, text: e }; }); } /** * Collect one sequence in a single row-at-a-time pass. Retain only `descriptor` * for a lazy source; `text` is transient and lets array callers avoid reserialization. * A fresh collector defines a fresh summary sequence, including omission and call state. */ function createConversationEntryCollector() { const e = createConversationProjector(); return (t, n) => { const { parts: r, omissionMessages: i, callLabel: a } = e(t); return describeConversationParts(r, n, { omissionMessages: i, callLabel: a }); }; } function collectConversationEntries(e) { const t = createConversationEntryCollector(); const n = []; for (const [r, i] of e.entries()) n.push(...t(i, r)); return n; } /** Array callers use the same descriptor-driven selection kernel as lazy transcript readers. */ function serializeConversationWithinBudget(e, t) { const n = collectConversationEntries(e).map(({ descriptor: e, text: t }) => Object.assign(e, { text: t })); return renderConversationEntriesWithinBudget(n, t, (e, t) => e.text[t]); } //#endregion //#region packages/agent-core/src/harness/compaction/compaction-cut-point.ts function getMessageFromEntryForCompaction(e) { if (e.type === "compaction") return; return projectSessionEntryMessage(e); } const IMAGE_BLOCK_TOKENS = 2e3; const IMAGE_BLOCK_CHARS = IMAGE_BLOCK_TOKENS * 4; function countCompactionContentChars(e) { const { text: t, omissionText: n } = getCompactionContent(e); const r = typeof e === "string" ? 0 : e.filter((e) => e.type === "image").length; return countCompactionContentCharsFromParts(estimateStringChars(t), r, n); } function countCompactionContentCharsFromParts(e, t, n) { const r = n ? n.length + 17 : 0; return e + t * IMAGE_BLOCK_CHARS + r; } /** Unrounded contribution; callers merging turns must round only after merging. */ function estimateCompactionChars(e) { if ("excludeFromContext" in e && e.excludeFromContext === true) return 0; let t = 0; switch (e.role) { case "assistant": for (const n of e.content) if (n.type === "text") t += estimateStringChars(n.text); else if (n.type === "thinking") t += estimateStringChars(n.thinking); else if (n.type === "toolCall") t += estimateStringChars(n.name) + estimateStringChars(stringifyCompactionValue(n.arguments)); break; case "user": t = countCompactionContentChars(e.content); t += estimateStringChars(formatCompactionUserLabel(e)) - 4; break; case "custom": case "toolResult": t = countCompactionContentChars(e.content); break; case "bashExecution": t = estimateStringChars(e.command) + estimateStringChars(e.output); break; case "branchSummary": case "compactionSummary": t = estimateStringChars(e.summary); } return t; } /** Estimate token count for one message using a conservative character heuristic. */ function estimateTokens(e) { return Math.ceil(estimateCompactionChars(e) / 4); } function isCutPointMessage(e) { return e.role === "assistant" || isTurnStartMessage(e); } function isTurnStartMessage(e) { const t = e.role; return t === "custom" ? !isRuntimeContextCarrier(e) : t === "user" || t === "bashExecution" || t === "branchSummary" || t === "compactionSummary"; } function isTurnStartEntry(e) { const t = getMessageFromEntryForCompaction(e); return t ? isTurnStartMessage(t) : false; } /** Find the user-visible message that starts the turn containing an entry. */ function findTurnStartIndex(e, t, n) { return findPreviousTurnStart(t, n, (t) => { const n = e[t]; return n ? isTurnStartEntry(n) : false; }); } function findPreviousTurnStart(e, t, n) { for (let r = e; r >= t; r--) if (n(r)) return r; return -1; } function collectCompactionCutEntryFact(e, t = getMessageFromEntryForCompaction(e)) { return { id: e.id, type: e.type, hasMessage: t !== void 0, isCutPoint: t ? isCutPointMessage(t) : false, isTurnStart: t ? isTurnStartMessage(t) : false, pairing: t ? collectToolPairingMessageFact(t) : void 0 }; } function createToolPairCutResolver(e, t) { const n = []; const entryIndexAt = (e) => { const n = t[e]; if (n === void 0) throw new Error("Tool pairing references a message outside the compaction entries"); return n; }; for (const t of classifyToolPairingFacts(e)) { const e = entryIndexAt(t.startIndex); let r = e; for (const e of t.occurrences) if (e.result) r = Math.max(r, entryIndexAt(e.result.index)); if (r === e) continue; const i = n.at(-1); if (i && e <= i.end) i.end = Math.max(i.end, r); else n.push({ start: e, end: r }); } return (e) => { let t = 0; let r = n.length; while (t < r) { const i = Math.floor((t + r) / 2); const a = n[i]; if (!a) throw new Error("Compaction tool range is missing from the selected search interval"); if (a.start < e) t = i + 1; else r = i; } const i = n[t - 1]; return i && e <= i.end ? i.start : e; }; } /** Find the compaction cut point that keeps approximately the requested recent-token budget. */ function findCutPoint(e, t, n, r, i) { const a = []; for (let r = t; r < n; r++) { const t = e[r]; if (t) a[r] = collectCompactionCutEntryFact(t); } return findCutPointFromFacts(a, t, n, r, i, (t) => { const n = e[t]; const r = n ? getMessageFromEntryForCompaction(n) : void 0; return r ? i?.budget?.estimateTokens(r) ?? estimateTokens(r) : 0; }); } /** Array and reader views share the same cut, pairing, pending-input and retention policy. */ function findCutPointFromFacts(e, t, n, r, i, a) { const o = i?.budget; let s; let c = n - 1; const l = []; const u = []; for (let r = t; r < n; r++) { const t = e[r]; if (t && i?.requestBoundary?.preserve && t.id === i.requestBoundary.entryId) c = r; if (t?.isCutPoint) s = r; const n = t?.pairing; if (n?.role === "toolResult" || n?.role === "assistant" && n.calls.length > 0) { l.push(n); u.push(r); } } if (s === void 0) return { firstKeptEntryIndex: t, turnStartIndex: -1, isSplitTurn: false }; const d = createToolPairCutResolver(l, u); s = d(s); c = d(c); let f = 0; for (let i = n - 1; i >= t; i--) { const t = e[i]; if (!t?.hasMessage) continue; if (t.isCutPoint) s = d(i); f += a(i); if (f >= r) break; } s = Math.min(s, c); if (o) { let t = 0; let r = n; let i = o.maxTokens; for (let l = n - 1; l >= s; l--) { const s = e[l]; t += s?.hasMessage ? a(l) : 0; if (t > i) break; if (l <= c && s?.isCutPoint && d(l) === l) { if (r === n) i = Math.max(t, o.maxTokens - o.reserveTokens); r = l; } } if (r === n) return { firstKeptEntryIndex: n, turnStartIndex: -1, isSplitTurn: false }; s = r; } while (s > t) { const t = e[s - 1]; if (!t) break; if (t.type === "compaction" || t.type === "reset") break; if (t.type === "message" || t.hasMessage) break; s--; } const p = e[s]; if (!p) throw new Error("compaction cut point does not reference a session entry"); const m = p.isTurnStart; const h = m ? -1 : findPreviousTurnStart(s, t, (t) => e[t]?.isTurnStart === true); return { firstKeptEntryIndex: s, turnStartIndex: h, isSplitTurn: !m && h !== -1 }; } //#endregion export { mergeSummaryFileOperations as _, getMessageFromEntryForCompaction as a, serializeConversationWithinBudget as b, createFileOps as c, extractFileOpsFromMessage as d, extractFileOpsFromMessages as f, formatFileOperations as g, formatCompactionUserLabel as h, findTurnStartIndex as i, extractCompactionMessageText as l, findLatestCompactionUserMessage as m, estimateTokens as n, clearCompactionPendingAskSection as o, extractSummaryText as p, findCutPoint as r, computeFileLists as s, IMAGE_BLOCK_TOKENS as t, extractCurrentCompactionUserRequest as u, removeGeneratedCompactionSection as v, MAX_SUMMARY_INPUT_CHARS as x, serializeConversation as y };