openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
630 lines (629 loc) • 20.7 kB
JavaScript
import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord, i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs";
import { o as isSqliteLockError } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { u as normalizeContextUsage } from "./usage-CHLnzpJG.mjs";
import { n as estimateBase64DecodedBytes } from "./base64-CnKpkbff.mjs";
import { a as isAssistantTextContentBlockType, c as parseAssistantTextSignature, d as readTerminalSourceReplyDeliveryMirror, o as isSilentAssistantTranscriptMessage, p as resolveAssistantMessagePhase, u as readAssistantTextBlocksForPhase } from "./chat-message-content-DNUdbbJ8.mjs";
import { A as truncateChatHistoryText, D as stripAssistantMediaDirectivesForDisplay, E as shouldPreserveAssistantControlReplyText, O as stripPrivateToolCallContextForDisplay, c as messageHasToolResultShape, k as takeAssistantManagedMediaUrlsForDisplay, l as projectToolResultDetails, o as isToolHistoryBlockType, p as DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, s as isToolResultHistoryBlockType, w as isProjectedForwardedMessage, y as hasTranscriptMediaFacts } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import { r as parseInboundMediaUri } from "./inbound-media-uri-DpK4_BLW.mjs";
import { i as prepareAgentRunReplyText } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import { t as buildInboundMediaUriFromPath } from "./inbound-media-path-C6oH727p.mjs";
import { t as findNativeToolMarkerTextBlocks } from "./native-tool-marker-B7dSiPNn.mjs";
import { o as projectWorkspaceConflictDetails } from "./workspace-conflicts-D4n5w5tE.mjs";
//#region src/shared/chat-envelope.ts
const ENVELOPE_PREFIX = /^\[([^\]]+)\]\s*/;
const ENVELOPE_CHANNELS = [
"WebChat",
"WhatsApp",
"Telegram",
"Signal",
"Slack",
"Discord",
"Google Chat",
"iMessage",
"Teams",
"Matrix",
"Zalo",
"Zalo Personal"
];
function looksLikeEnvelopeHeader(e) {
if (/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z\b/.test(e)) return true;
if (/\d{4}-\d{2}-\d{2} \d{2}:\d{2}\b/.test(e)) return true;
return ENVELOPE_CHANNELS.some((t) => e.startsWith(`${t} `));
}
/** Removes recognized channel/timestamp prefixes while preserving user-authored bracket text. */
function stripEnvelope(e) {
const t = e.match(ENVELOPE_PREFIX);
if (!t) return e;
if (!looksLikeEnvelopeHeader(t[1] ?? "")) return e;
return e.slice(t[0].length);
}
//#endregion
//#region src/sessions/session-run-error-presentation.ts
const STATE_CONTENTION_SUMMARY = "Your request was interrupted while the server was busy. Check its status before trying again.";
const STATE_CONTENTION_DIAGNOSTIC = "SQLite transaction admission remained busy. Execution may have occurred; check the recorded outcome before resending.";
/** Presentation is not replay authority. Only the direct typed failure is classified. */
function resolveStateContentionPresentation(e) {
return isSqliteLockError(e) ? {
errorKind: "state_contention",
errorMessage: `${STATE_CONTENTION_SUMMARY}\n\n${STATE_CONTENTION_DIAGNOSTIC}`
} : void 0;
}
//#endregion
//#region src/gateway/chat-display-projection.commentary.ts
function projectAssistantCommentaryFallbacks(e, t) {
const n = asOptionalRecord(e);
if (!n || n.role !== "assistant" || isSilentAssistantTranscriptMessage(n) || !Array.isArray(n.content) || n.stopReason === "error" || typeof n.errorMessage === "string") return {
fallbacks: [],
message: e
};
const r = asOptionalRecord(n["__openclaw"]);
const i = new Set(readAssistantTextBlocksForPhase(n, "commentary"));
const a = typeof r?.id === "string" ? r.id.trim() : typeof n.id === "string" ? n.id.trim() : void 0;
const o = [];
const s = /* @__PURE__ */ new Set();
let c = false;
let l;
for (const e of n.content) {
const t = asOptionalRecord(e);
if (!t) continue;
if (!isAssistantTextContentBlockType(t.type)) {
if (l && [
"image",
"audio",
"video",
"attachment",
"attachment_error"
].includes(String(t.type))) {
l.content.push(t);
l.sourceBlocks.push(e);
}
continue;
}
const n = parseAssistantTextSignature(t);
const r = typeof t.text === "string" ? t.text : "";
const s = n?.id?.trim();
const c = s || a;
if (!i.has(e) || !c) {
l = void 0;
continue;
}
if (l?.itemId !== c) {
l = {
itemId: c,
providerKeyed: Boolean(s),
content: [],
text: [],
sourceBlocks: []
};
o.push(l);
}
l.providerKeyed ||= Boolean(s);
if (n?.phase !== "commentary") l.sourceBlocks.push(e);
if (r.trim()) {
l.content.push({
type: "text",
text: r
});
l.text.push(r);
}
}
const u = o.flatMap(({ itemId: e, providerKeyed: i, content: a, text: o, sourceBlocks: l }) => {
const u = a.some((e) => e.type !== "text");
if (a.length === 0 || !i && !u) return [];
for (const e of l) {
s.add(e);
c ||= isAssistantTextContentBlockType(asOptionalRecord(e)?.type);
}
const d = truncateChatHistoryText(o.join("\n"), t);
const f = d.truncated ? {
...r,
truncated: true,
reason: typeof r?.reason === "string" ? r.reason : "display-cap"
} : r ? { ...r } : void 0;
return [{
role: "assistant",
content: a,
...typeof n.timestamp === "number" ? { timestamp: n.timestamp } : {},
openclawStreamFallback: {
replacementText: d.text,
source: "segment",
itemId: e
},
...f ? { __openclaw: f } : {}
}];
});
if (s.size === 0) return {
fallbacks: u,
message: e
};
const d = n.content.filter((e) => !s.has(e));
const f = {
...n,
content: d
};
if (c && d.some((e) => isToolHistoryBlockType(asOptionalRecord(e)?.type))) {
f.content = d.filter((e) => !i.has(e));
delete f.phase;
}
return {
fallbacks: u,
message: f
};
}
//#endregion
//#region src/gateway/chat-display-projection.sanitize.ts
const MEDIA_PRIVATE_FIELDS = [
"data",
"blob",
"path",
"file",
"filePath",
"localPath"
];
const MEDIA_REFERENCE_FIELDS = [
"url",
"openUrl",
"image_url",
"audio_url",
"video_url"
];
const MEDIA_FACT_PRIVATE_FIELDS = ["workspaceDir", ...MEDIA_PRIVATE_FIELDS.filter((e) => e !== "path")];
function projectChatHistoryMediaReference(e) {
if (typeof e !== "string") return;
const t = e.trim();
if (/^\/(?:api\/chat\/media\/outgoing|media|__openclaw__)\//u.test(t)) return t.split(/[?#]/u, 1)[0];
try {
if (/^media:/iu.test(t)) return parseInboundMediaUri(t)?.normalizedSource;
const e = new URL(t);
if (e.protocol !== "http:" && e.protocol !== "https:") return;
e.username = e.password = e.search = e.hash = "";
return e.toString();
} catch {
return;
}
}
function projectChatHistoryMediaBlock(e, t = false) {
if (!t && (typeof e.type !== "string" || !/^(?:image|audio|video)$/u.test(e.type))) return false;
const n = e;
const r = typeof n.data === "string" || typeof n.blob === "string";
const i = t ? void 0 : asOptionalRecord(n.source);
const a = i ? { ...i } : void 0;
const o = [n, ...a ? [a] : []];
if (a) n.source = a;
const s = t ? MEDIA_FACT_PRIVATE_FIELDS : MEDIA_PRIVATE_FIELDS;
const c = t ? ["path", "url"] : MEDIA_REFERENCE_FIELDS;
const l = !i && (!t || typeof n.source !== "string" || /^(?:[a-z][a-z0-9+.-]*:|~?[\\/])|[\\/]/iu.test(n.source));
let u;
for (const e of o) {
let r = false;
const i = typeof e.data === "string" ? e.data : e.blob;
if (u === void 0 && typeof i === "string") u = i;
for (const t of s) {
if (!Object.hasOwn(e, t)) continue;
delete e[t];
r = true;
}
const a = e === n && l ? [...c, "source"] : c;
for (const n of a) {
if (!Object.hasOwn(e, n)) continue;
const i = (t ? buildInboundMediaUriFromPath(String(e[n])) : void 0) ?? projectChatHistoryMediaReference(e[n]);
e[n] = i;
if (i === void 0) {
delete e[n];
r = true;
}
}
if (!t && r) {
if (e === n || n.type !== "image") e.omitted = true;
if (e === n || n.type !== "audio") n.omitted = true;
}
}
if (!t && u !== void 0) (n.type === "audio" && !r && a ? a : n).bytes = estimateBase64DecodedBytes(u);
return true;
}
function projectChatHistoryAttachmentBlock(e) {
const t = e.type === "attachment" ? asOptionalRecord(e.attachment) : void 0;
if (!t) return false;
const n = { ...t };
for (const e of MEDIA_PRIVATE_FIELDS) delete n[e];
n.url = projectChatHistoryMediaReference(n.url);
if (!n.url) delete n.url;
e.attachment = n;
return true;
}
function projectChatHistoryMediaFacts(e) {
return Array.isArray(e) ? e.map((e) => {
const t = { ...asOptionalRecord(e) };
projectChatHistoryMediaBlock(t, true);
return t;
}) : void 0;
}
function sanitizeChatHistoryContentBlock(e, t) {
if (!e || typeof e !== "object") return {
block: e,
changed: false,
truncated: false
};
const n = { ...e };
if (n.type === "plugin_view") return {
block: {
type: "text",
text: ""
},
changed: true,
truncated: false
};
let r = stripPrivateToolCallContextForDisplay(n);
let i = false;
const a = t?.preserveExactToolPayload === true || isToolHistoryBlockType(n.type);
const o = t?.maxChars ?? 8e3;
const s = t?.preserveExactToolPayload || isToolResultHistoryBlockType(n.type) ? t?.toolResultMaxChars : void 0;
if (isToolResultHistoryBlockType(n.type) && "details" in n) {
const e = projectToolResultDetails(n.details, o, n);
if (e.details) n.details = e.details;
else delete n.details;
r = true;
i ||= e.truncated;
}
if (a && Array.isArray(n.content)) {
if (typeof n.text === "string") {
const e = n.content.flatMap((e) => {
const t = asOptionalRecord(e)?.text;
return typeof t === "string" ? [t] : [];
}).join("\n");
if (n.text === e) {
delete n.text;
r = true;
}
}
const e = n.content.map((e) => sanitizeChatHistoryContentBlock(e, {
preserveExactToolPayload: true,
maxChars: o,
toolResultMaxChars: s
}));
if (e.some((e) => e.changed)) {
n.content = e.map((e) => e.block);
r = true;
}
i ||= e.some((e) => e.truncated);
}
for (const e of [
"text",
"content",
"partialJson",
"arguments",
"thinking"
]) {
if (typeof n[e] !== "string" || a && (e === "partialJson" || e === "arguments")) continue;
const t = truncateChatHistoryText(n[e], o, a && (e === "text" || e === "content"), e === "text" || e === "content" ? s : void 0);
n[e] = t.text;
r ||= t.truncated;
i ||= t.truncated;
}
for (const e of ["thinkingSignature", "openclawReasoningReplay"]) if (e in n) {
delete n[e];
r = true;
}
const c = projectChatHistoryMediaBlock(n);
const l = projectChatHistoryAttachmentBlock(n);
r ||= c || l;
return {
block: r ? n : e,
changed: r,
truncated: i
};
}
function sanitizeAssistantPhasedContentBlocks(e) {
if (!e.some((e) => {
const t = asOptionalObjectRecord(e);
return t && isAssistantTextContentBlockType(t.type) && parseAssistantTextSignature(t)?.phase;
})) return e;
const t = e.filter((e) => {
const t = asOptionalObjectRecord(e);
return !t || !isAssistantTextContentBlockType(t.type) || parseAssistantTextSignature(t)?.phase === "final_answer";
});
return t.length === e.length ? e : t;
}
function projectAssistantMixedToolContent(e, t) {
if (!e.some((e) => isToolHistoryBlockType(asOptionalObjectRecord(e)?.type))) return null;
let n = false;
const r = [];
for (const i of e) {
const e = asOptionalObjectRecord(i);
if (!e) continue;
if (!isAssistantTextContentBlockType(e.type)) {
r.push(i);
continue;
}
if (parseAssistantTextSignature(e)?.phase === "commentary") continue;
if (typeof e.text !== "string" || !e.text.trim()) continue;
const a = truncateChatHistoryText(e.text, t);
if (a.text.trim()) {
r.push({
type: "text",
text: a.text
});
n = true;
}
}
return n ? r : null;
}
const COST_FIELDS = [
"input",
"output",
"cacheRead",
"cacheWrite",
"total"
];
const USAGE_FIELDS = [
"input",
"output",
"total",
"totalTokens",
"inputTokens",
"outputTokens",
"promptTokens",
"completionTokens",
"cacheRead",
"cacheWrite",
"cache_read_input_tokens",
"cache_creation_input_tokens",
"input_tokens",
"output_tokens",
"prompt_tokens",
"completion_tokens",
"total_tokens"
];
function sanitizeNumericMetadata(e, t) {
const n = asOptionalObjectRecord(e);
if (!n) return;
const r = {};
for (const e of t) {
const t = asFiniteNumber(n[e]);
if (t !== void 0) r[e] = t;
}
if (t === USAGE_FIELDS) {
const e = asOptionalObjectRecord(n.usageReport)?.state;
if (e === "available" || e === "unavailable") r.usageReport = { state: e };
const t = sanitizeNumericMetadata(n.cost, COST_FIELDS);
if (t) r.cost = t;
const i = normalizeContextUsage(n.contextUsage);
if (i) r.contextUsage = i;
}
return Object.keys(r).length > 0 ? r : void 0;
}
/** Prepares raw stored text before display transforms, retaining its visible disposition. */
function prepareAssistantHistoryMessage(e) {
const t = asOptionalObjectRecord(e);
if (t?.role !== "assistant" || t.display === true || t.display === false || readTerminalSourceReplyDeliveryMirror(t) || isProjectedForwardedMessage(t)) return e;
const n = typeof t.text === "string" ? "text" : "content";
const r = t[n];
if (typeof r !== "string" && !Array.isArray(t.content)) return e;
const i = readAssistantTextBlocksForPhase(t, "final_answer");
const a = i.length ? i : readAssistantTextBlocksForPhase(t);
const o = typeof r === "string" ? r : a.map((e) => e.text).join("");
const s = prepareAgentRunReplyText(o);
if (s === void 0 || s === o) return e;
if (typeof r === "string") return {
...t,
[n]: s,
display: true
};
let c = o.endsWith(s) ? o.length - s.length : 0;
let l = s.length;
const u = /* @__PURE__ */ new Map();
for (const e of a) {
const t = Math.min(c, e.text.length);
c -= t;
const n = e.text.slice(t, t + l);
l -= n.length;
if (n !== e.text) u.set(e, {
...e,
text: n
});
}
return {
...t,
content: Array.isArray(t.content) ? t.content.map((e) => u.get(e) ?? e) : t.content,
display: true
};
}
function sanitizeChatHistoryMessage(e, t = DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, n) {
if (!e || typeof e !== "object") return {
message: e,
changed: false
};
const r = prepareAssistantHistoryMessage(e);
const i = { ...r };
let a = r !== e;
const o = findNativeToolMarkerTextBlocks(e);
if (o.size && Array.isArray(i.content)) {
i.content = i.content.map((e, t) => o.has(t) ? {
...asOptionalRecord(e),
text: ""
} : e);
a = true;
}
let s = false;
if ("providerReplay" in i || "openclawResponsesInputReplay" in i) {
delete i.providerReplay;
delete i.openclawResponsesInputReplay;
a = true;
}
const c = asOptionalRecord(i["__openclaw"]);
if (c && ("upstreamUserText" in c || "modelPromptProjection" in c || "sessionSendDelivery" in c || "requesterOrigin" in c || "chatInputRecovery" in c || "media" in c)) {
const e = { ...c };
delete e.upstreamUserText;
delete e.modelPromptProjection;
delete e.sessionSendDelivery;
delete e.requesterOrigin;
delete e.chatInputRecovery;
if ("media" in e) {
e.media = projectChatHistoryMediaFacts(e.media);
if (e.media === void 0) delete e.media;
}
if (Object.keys(e).length > 0) i["__openclaw"] = e;
else delete i["__openclaw"];
a = true;
}
const l = typeof i.role === "string" ? i.role.toLowerCase() : "";
const u = takeAssistantManagedMediaUrlsForDisplay(i, l);
a ||= u.changed;
const d = l === "toolresult" || l === "tool_result" || l === "tool" || l === "function" || typeof i.toolName === "string" || typeof i.tool_name === "string" || typeof i.toolCallId === "string" || typeof i.tool_call_id === "string";
const f = d && messageHasToolResultShape(i) ? n : void 0;
if ("details" in i) {
const e = projectWorkspaceConflictDetails(i);
const n = !e && messageHasToolResultShape(i) ? projectToolResultDetails(i.details, t, i) : void 0;
const r = i.role === "custom" && i.customType === "run-failed-before-reply" && asOptionalRecord(i.details)?.errorKind === "state_contention" ? {
errorKind: "state_contention",
diagnostic: STATE_CONTENTION_DIAGNOSTIC
} : void 0;
const o = i.role === "custom" && i.customType === "session-model-change" ? asOptionalRecord(i.details) : void 0;
const c = typeof o?.from === "string" && typeof o.to === "string" ? {
from: o.from,
to: o.to
} : void 0;
const l = e ?? n?.details ?? r ?? c;
if (l) i.details = l;
else delete i.details;
a = true;
s ||= n?.truncated === true;
}
for (const e of ["usage", "cost"]) {
if (!(e in i)) continue;
const t = i.role === "assistant" ? sanitizeNumericMetadata(i[e], e === "usage" ? USAGE_FIELDS : COST_FIELDS) : void 0;
if (t) i[e] = t;
else delete i[e];
a = true;
}
const p = l === "assistant" && !shouldPreserveAssistantControlReplyText(i);
const projectText = (e) => {
const n = truncateChatHistoryText(e, t, d, f);
const r = p ? stripAssistantMediaDirectivesForDisplay(n.text, u.urls) : n.text;
a ||= r !== n.text;
a ||= n.truncated;
s ||= n.truncated;
return r;
};
if (typeof i.content === "string") i.content = projectText(i.content);
else if (Array.isArray(i.content)) {
const e = i.content;
const r = asOptionalRecord(i.openclawStreamFallback)?.source === "segment";
let o = t;
let c;
for (let i = 0; i < e.length; i++) {
const a = r ? asOptionalRecord(e[i]) : void 0;
const l = a && isAssistantTextContentBlockType(a.type) && typeof a.text === "string" ? a.text : void 0;
if (l !== void 0 && o <= 0) {
c ??= e.slice();
c[i] = void 0;
s ||= l.length > 0;
continue;
}
const f = sanitizeChatHistoryContentBlock(e[i], {
preserveExactToolPayload: d,
maxChars: l === void 0 ? t : o,
toolResultMaxChars: n
});
if (l !== void 0) o -= l.length + 1;
const m = p ? asOptionalRecord(f.block) : void 0;
if (m && isAssistantTextContentBlockType(m.type) && typeof m.text === "string") {
const e = stripAssistantMediaDirectivesForDisplay(m.text, u.urls);
if (e !== m.text) {
f.block = {
...m,
text: e
};
f.changed = true;
}
}
if (f.changed) {
c ??= e.slice();
c[i] = f.block;
}
s ||= f.truncated;
}
if (c) {
i.content = r ? c.filter((e) => e !== void 0) : c;
a = true;
}
if (i.role === "assistant" && Array.isArray(i.content)) {
const e = projectAssistantMixedToolContent(i.content, t);
if (e) {
i.content = e;
if (i.phase === "commentary") delete i.phase;
a = true;
} else {
const e = sanitizeAssistantPhasedContentBlocks(i.content);
if (e !== i.content) {
i.content = e;
a = true;
}
}
}
}
if (typeof i.text === "string") i.text = projectText(i.text);
if (s) {
const e = asOptionalRecord(i["__openclaw"]);
i["__openclaw"] = {
...e,
truncated: true,
reason: typeof e?.reason === "string" ? e.reason : "display-cap"
};
a = true;
}
return {
message: a ? i : e,
changed: a
};
}
function hasAssistantMixedToolVisibleText(e) {
const t = asOptionalObjectRecord(e)?.content;
if (!Array.isArray(t)) return false;
let n = false;
let r = false;
for (const e of t) {
const t = asOptionalObjectRecord(e);
if (!t) continue;
n ||= isToolHistoryBlockType(t.type);
if (isAssistantTextContentBlockType(t.type) && typeof t.text === "string" && t.text.trim()) r = true;
}
return n && r;
}
function shouldDropAssistantHistoryMessage(e) {
const t = asOptionalObjectRecord(e);
if (t?.role !== "assistant") return false;
if (t.display === false) return true;
if (t.display === true || readTerminalSourceReplyDeliveryMirror(t)) return false;
if (isProjectedForwardedMessage(t)) return false;
return resolveAssistantMessagePhase(e) === "commentary" ? !hasAssistantMixedToolVisibleText(e) : isSilentAssistantTranscriptMessage(e);
}
function sanitizeChatHistoryMessages(e, t = DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, n) {
let r = false;
const i = [];
for (const a of e) {
let e = a;
if (n?.includeCommentaryFallbacks === true) {
const o = projectAssistantCommentaryFallbacks(e, t);
e = o.message;
r ||= e !== a;
for (const e of o.fallbacks) {
r = true;
if (!hasTranscriptMediaFacts(asOptionalRecord(e) ?? {}) && shouldDropAssistantHistoryMessage(e)) continue;
const a = sanitizeChatHistoryMessage(e, t, n?.toolResultMaxChars);
i.push(a.message);
}
}
if (shouldDropAssistantHistoryMessage(e)) {
r = true;
continue;
}
const o = sanitizeChatHistoryMessage(e, t, n?.toolResultMaxChars);
r ||= o.changed;
i.push(o.message);
}
return r ? i : e;
}
//#endregion
export { shouldDropAssistantHistoryMessage as a, stripEnvelope as c, sanitizeChatHistoryMessages as i, sanitizeChatHistoryContentBlock as n, STATE_CONTENTION_SUMMARY as o, sanitizeChatHistoryMessage as r, resolveStateContentionPresentation as s, prepareAssistantHistoryMessage as t };