openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
191 lines (190 loc) • 6.79 kB
JavaScript
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as readToolErrorFlag, i as isToolResultContentType, n as isToolCallContentType } from "./tool-content-DG-uYHoo.mjs";
import { i as jsonUtf8BytesOrInfinity, r as jsonUtf8Bytes } from "./json-utf8-bytes-DNwtq2cu.mjs";
import { t as logLargePayload } from "./diagnostic-payload-KWldAlR0.mjs";
import { h as mapChatDisplayMessages } from "./chat-display-projection.history-BZNUjEB3.mjs";
import { a as readTranscriptDisplayPosition } from "./transcript-image-artifacts-CcmdOg97.mjs";
import { o as readChatHistoryMessageId } from "./session-transcript-memory-reader-_afqDL9S.mjs";
//#region src/gateway/chat-history-budget.ts
const DEFAULT_MAX_CHAT_HISTORY_MESSAGES_BYTES = 6291456;
const getMaxChatHistoryMessagesBytes = () => DEFAULT_MAX_CHAT_HISTORY_MESSAGES_BYTES;
const CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES = 131072;
const CHAT_HISTORY_OVERSIZED_PLACEHOLDER = "[chat.history omitted: message too large]";
const CHAT_HISTORY_UNAVAILABLE_SENTINEL = "[chat.history unavailable: transcript too large to display; the full history is preserved on disk]";
let chatHistoryOmittedEmitCount = 0;
function createChatHistoryActivityProjection(e, t = []) {
const n = new Map(t.map((e) => [e.messageId, e]));
const r = /* @__PURE__ */ new Map();
for (const t of e) {
const e = readChatHistoryMessageId(t);
const i = e ? n.get(e) : void 0;
const a = asOptionalRecord(t);
if (i && a && (isToolResultContentType(a.role) || a.role === "tool" || a.role === "function" || Array.isArray(a.content) && a.content.some((e) => {
const t = asOptionalRecord(e)?.type;
return isToolCallContentType(t) || isToolResultContentType(t);
}))) r.set(t, i);
}
return r;
}
function createChatHistoryByteCounter(e, t = jsonUtf8Bytes) {
const n = /* @__PURE__ */ new Map();
const messageBytes = (r) => {
const i = n.get(r);
if (i !== void 0) return i;
const a = e?.get(r);
const o = t(r) + (a ? t(a) + 1 : 0);
n.set(r, o);
return o;
};
return {
messageBytes,
framingBytes: (t) => t.some((t) => e?.has(t)) ? 13 : 0,
messagesBytes: (t) => (t.some((t) => e?.has(t)) ? 15 : 2) + t.reduce((e, t) => e + messageBytes(t), 0) + Math.max(0, t.length - 1)
};
}
function chatHistoryActivityBytes(e) {
return e.length > 0 ? jsonUtf8Bytes({ activity: e }) - 1 : 0;
}
/** Delta envelopes share one prepared plain-data snapshot throughout their synchronous projection. */
function createChatHistoryDeltaByteCounter(e) {
let t;
return (n) => {
t ??= {
bytes: jsonUtf8BytesOrInfinity(e),
keys: new Set(Object.keys(e))
};
const r = {};
for (const e in n) if (!t.keys.has(e) && Object.hasOwn(n, e)) r[e] = n[e];
const i = jsonUtf8BytesOrInfinity(r);
return t.bytes + i - 2 + (t.bytes > 2 && i > 2 ? 1 : 0);
};
}
function buildChatHistoryUnavailableSentinel() {
return {
role: "assistant",
timestamp: Date.now(),
content: [{
type: "text",
text: CHAT_HISTORY_UNAVAILABLE_SENTINEL
}]
};
}
function buildOversizedHistoryPlaceholder(e) {
const t = asOptionalRecord(e) ?? {};
const n = typeof t.role === "string" ? t.role : "assistant";
const r = typeof t.timestamp === "number" ? t.timestamp : Date.now();
const i = asOptionalRecord(t["__openclaw"]) ?? {};
const a = Object.fromEntries([
"toolCallId",
"tool_call_id",
"toolUseId",
"tool_use_id",
"toolName",
"tool_name",
"name"
].filter((e) => typeof t[e] === "string").map((e) => [e, t[e]]));
const o = readToolErrorFlag(t);
const s = typeof i.id === "string" ? i.id : void 0;
const c = typeof i.seq === "number" ? i.seq : void 0;
const l = typeof i.idempotencyKey === "string" ? i.idempotencyKey : void 0;
const u = i.turnBoundary === true;
const d = readTranscriptDisplayPosition(i.transcriptPosition);
const f = asOptionalRecord(i.transport);
return {
role: n,
timestamp: r,
content: [{
type: "text",
text: CHAT_HISTORY_OVERSIZED_PLACEHOLDER
}],
...a,
...o !== void 0 ? { isError: o } : {},
__openclaw: {
...i.toolOutput ? { toolOutput: i.toolOutput } : {},
...s ? { id: s } : {},
...typeof i.runId === "string" ? { runId: i.runId } : {},
...c !== void 0 ? { seq: c } : {},
...l ? { idempotencyKey: l } : {},
...u ? { turnBoundary: true } : {},
...d ? { transcriptPosition: d } : {},
...f ? { transport: f } : {},
truncated: true,
reason: "oversized"
}
};
}
function replaceOversizedChatHistoryMessages(e) {
const { messages: t, maxSingleMessageBytes: n } = e;
const r = e.byteCounter ?? createChatHistoryByteCounter();
let i = 0;
return {
messages: mapChatDisplayMessages(t, (e) => {
if (r.messageBytes(e) <= n) return e;
i += 1;
const t = buildOversizedHistoryPlaceholder(e);
return r.messageBytes(t) <= n ? t : buildChatHistoryUnavailableSentinel();
}),
replacedCount: i
};
}
function reportOmittedChatHistory(e) {
const { omittedCount: t, normalizedBytes: n, maxHistoryBytes: r, logDebug: i } = e;
if (t === 0) return 0;
chatHistoryOmittedEmitCount += t;
logLargePayload({
surface: "gateway.chat.history",
action: "truncated",
bytes: n,
limitBytes: r,
count: t,
reason: "chat_history_budget"
});
i(`chat.history omitted oversized payloads count=${t} total=${chatHistoryOmittedEmitCount}`);
return t;
}
function boundInFlightRunSnapshotForChatHistory(e) {
if (!e.snapshot) return;
const t = e.getMessagesBytes?.() ?? jsonUtf8Bytes(e.messages);
if (t + jsonUtf8Bytes(e.snapshot) <= e.maxBytes) return e.snapshot;
let n = {
runId: e.snapshot.runId,
text: "",
...e.snapshot.sessionAbortable ? { sessionAbortable: true } : {},
...e.snapshot.events ? { events: [] } : {},
...e.snapshot.plan ? { plan: { steps: [] } } : {}
};
const retainIfWithinBudget = (r) => {
if (!(t + jsonUtf8Bytes(r) <= e.maxBytes)) return false;
n = r;
return true;
};
if (e.snapshot.startedAt !== void 0) retainIfWithinBudget({
...n,
startedAt: e.snapshot.startedAt
});
if (e.snapshot.events) {
const t = e.snapshot.events;
let r = 0;
let i = t.length;
let a = 0;
while (r < i) {
if (retainIfWithinBudget({
...n,
events: t.slice(a)
})) i = a;
else r = a + 1;
a = Math.floor((r + i) / 2);
}
}
if (e.snapshot.plan) retainIfWithinBudget({
...n,
plan: e.snapshot.plan
});
if (e.snapshot.text) retainIfWithinBudget({
...n,
text: e.snapshot.text
});
return n;
}
//#endregion
export { createChatHistoryActivityProjection as a, getMaxChatHistoryMessagesBytes as c, chatHistoryActivityBytes as i, replaceOversizedChatHistoryMessages as l, boundInFlightRunSnapshotForChatHistory as n, createChatHistoryByteCounter as o, buildOversizedHistoryPlaceholder as r, createChatHistoryDeltaByteCounter as s, CHAT_HISTORY_MAX_SINGLE_MESSAGE_BYTES as t, reportOmittedChatHistory as u };