openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
585 lines (584 loc) • 24.7 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord, p as readStringField } from "./record-coerce-CVPuDqcc.mjs";
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs";
import { m as CONTEXT_OVERFLOW_ERROR_MESSAGE, y as formatProviderRefusalText } from "./redact-Mj7pppxC.mjs";
import { t as classifyGatewayStorageFailure } from "./sqlite-error-diagnostics-6_hREUnq.mjs";
import { o as readSessionTranscriptFailureRunId, s as readSessionTranscriptRunId } from "./transcript-events-BHwlF03q.mjs";
import { a as isAssistantTextContentBlockType } from "./chat-message-content-DNUdbbJ8.mjs";
import { n as GATEWAY_ASSISTANT_ERROR_FALLBACK_TEXT } from "./gateway-error-details-B69XiHdh.mjs";
import { _ as hasAssistantDisplayableNonTextContent, b as isAssistantInternalReasoningContentType, h as extractAssistantTextForSilentCheck, p as DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, v as hasAssistantNonTextContent, y as hasTranscriptMediaFacts } from "./chat-display-projection.canvas-XAAIxHM8.mjs";
import { a as shouldDropAssistantHistoryMessage, i as sanitizeChatHistoryMessages, n as sanitizeChatHistoryContentBlock, r as sanitizeChatHistoryMessage, t as prepareAssistantHistoryMessage } from "./chat-display-projection.sanitize-DYNE5Y5I.mjs";
import { n as extractInboundSenderLabel } from "./strip-inbound-meta-BMUpr5S_.mjs";
import { u as stripInternalMetadataForDisplay } from "./agent-run-terminal-reply-DXju8G9G.mjs";
import { a as readNestedToolActivity, r as nestedToolActivityContent } from "./nested-tool-activity-BiEuCyrz.mjs";
import { a as renderAssistantRequestFailureCopy, c as renderRecordedAssistantFailureCopy } from "./assistant-request-failure-copy-CDAkRIru.mjs";
import { l as isTranscriptOnlyOpenClawAssistantMessage, s as isOpenClawMessageToolMirrorAssistantMessage } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs";
import { r as projectChatWorkContextForDisplay } from "./work-context-DF_-9kCa.mjs";
import { l as readTranscriptSenderIdentity } from "./user-turn-transcript.metadata-GFtsH_a_.mjs";
import { t as stripUserEnvelopeForDisplay } from "./user-envelope-display-CY_79-Ey.mjs";
import { n as STREAM_ERROR_FALLBACK_TEXT } from "./replay-turn-classification-B8UrZf_L.mjs";
import { n as projectAgentHistoryActivity } from "./agent-activity-events-BvMnPRzr.mjs";
import { d as projectPluginSteeringMessage, h as mapChatDisplayMessages, i as filterVisibleProjectedHistoryMessages, l as mergeTtsSupplementMessages, m as toProjectedMessages, n as createSubagentCoordinationHistoryProjection, u as projectForwardedMessages } from "./chat-display-projection.history-BZNUjEB3.mjs";
import { n as projectTranscriptImageArtifacts } from "./transcript-image-artifacts-CcmdOg97.mjs";
//#region src/chat/session-catalog-display.ts
const CATALOG_TOOL_RESULT_PREVIEW_MAX_CHARS = 500;
/** Facts retained beside imported text; never native execution or mount authority. */
function catalogDisplayFacts(e) {
return {
type: e.type,
...e.phase !== void 0 ? { phase: e.phase } : {},
...e.activity !== void 0 ? { activity: e.activity } : {},
...e.toolDetails !== void 0 ? { toolDetails: e.toolDetails } : {},
...e.toolName !== void 0 ? { toolName: e.toolName } : {},
...e.toolCallId !== void 0 ? { toolCallId: e.toolCallId } : {},
...e.toolInput !== void 0 ? { toolInput: e.toolInput } : {},
...e.toolInputOmitted ? { toolInputOmitted: true } : {},
...e.isError !== void 0 ? { isError: e.isError } : {},
...e.exitCode !== void 0 ? { exitCode: e.exitCode } : {},
...e.truncated ? { truncated: true } : {},
...!e.text?.trim() ? { emptyText: true } : {}
};
}
function catalogItemTextPrefix(e) {
return e === "reasoning" ? "Thinking\n\n" : e === "toolCall" ? "Tool call\n\n" : e === "toolResult" ? "Tool result\n\n" : e === "other" ? "Other\n\n" : "";
}
function rawText(e, t) {
const n = asOptionalRecord(e);
for (const e of t) {
const t = readStringField(n, e)?.trim();
if (t) return t;
}
}
/** Same bounded presentation for a native catalog page and a preserved copy. */
function projectCatalogItemForDisplay(e) {
const t = e.type === "toolCall" || e.type === "toolResult";
const n = typeof e.toolName === "string" ? e.toolName.trim() : "";
const r = typeof e.toolCallId === "string" ? e.toolCallId.trim() : "";
const bound = (e) => e.length > CATALOG_TOOL_RESULT_PREVIEW_MAX_CHARS ? `${truncateUtf16Safe(e, 499)}…` : e;
const i = e.toolInputOmitted === true ? "[Tool input omitted: size limit]" : e.toolInput === null ? "null" : e.toolInput;
let a = e.text?.trim() ? e.text : e.text === void 0 ? void 0 : "";
if (e.type === "toolResult") {
const t = asOptionalRecord(e.raw)?.result;
a ??= rawText(e.raw, ["aggregatedOutput"]) ?? (t === void 0 ? void 0 : JSON.stringify(t));
} else if (e.type === "toolCall") a ??= rawText(e.raw, [
"command",
"name",
"tool",
"title",
"query"
]);
const o = t && Boolean(a && a.length > CATALOG_TOOL_RESULT_PREVIEW_MAX_CHARS);
if (t && a) a = bound(a);
const s = e.truncated === true || o;
if (!t && s && !a) a = "…";
const c = {
type: "toolCall",
...r ? { id: r } : {},
...n ? { name: n } : {},
...i !== void 0 || a ? { arguments: i !== void 0 ? i : a } : {}
};
let l;
if (e.type === "toolCall") l = [c];
else if (e.type === "toolResult") l = [...i !== void 0 ? [c] : [], {
type: "toolResult",
...n ? { name: n } : {},
...r ? { toolCallId: r } : {},
content: [{
type: "text",
text: a ?? ""
}],
...typeof e.isError === "boolean" ? { isError: e.isError } : { __openclaw: { toolOutput: {
source: "execution",
modelInput: "unverified",
outcome: "unknown"
} } },
...e.toolDetails !== void 0 || typeof e.exitCode === "number" ? { details: {
...asOptionalRecord(e.toolDetails),
...typeof e.exitCode === "number" ? { exitCode: e.exitCode } : {}
} } : {}
}];
else {
if (!a) return null;
l = e.type === "reasoning" ? [{
type: "thinking",
thinking: a
}] : [{
type: "text",
text: a
}];
}
return {
...e.id ? { messageId: e.id } : {},
display: true,
role: e.type === "userMessage" ? "user" : "assistant",
...typeof e.phase === "string" ? { phase: e.phase } : {},
...e.activity !== void 0 ? { activity: [e.activity] } : {},
__openclaw: {
catalogSource: true,
...s ? { catalogTruncated: true } : {}
},
content: l
};
}
const IMPORT_FRAME = /^(?<label>(?:Thinking|Tool call|Tool result|Other)\r?\n\r?\n)?<<<EXTERNAL_UNTRUSTED_CONTENT id="(?<id>[a-f0-9]{16})">>>\r?\nSource: External\r?\n---\r?\n(?<body>[\s\S]*?)\r?\n<<<END_EXTERNAL_UNTRUSTED_CONTENT id="\k<id>">>>$/u;
function unwrapImportFrame(e) {
const t = IMPORT_FRAME.exec(e);
return t?.groups ? (t.groups.label ?? "") + t.groups.body : e;
}
/** View only. Canonical imported text, including its trust frame, is never rewritten. */
function projectPreservedCatalogMessageForDisplay(e) {
const t = asOptionalRecord(e);
const n = asOptionalRecord(t?.["__openclaw"]);
const r = asOptionalRecord(n?.catalogDisplay);
if (!t || !n || !r || typeof r.type !== "string") return [e];
const i = catalogItemTextPrefix(r.type);
const a = typeof t.content === "string" ? t.content : Array.isArray(t.content) ? readStringField(asOptionalRecord(t.content[0]), "text") : void 0;
if (a === void 0 || !a.startsWith(i)) return [e];
const o = a.slice(i.length);
const { catalogDisplay: s, idempotencyKey: c, ...l } = n;
const { idempotencyKey: u, stopReason: d, ...f } = t;
const p = readStringField(n, "id") ?? readStringField(t, "messageId");
const m = projectCatalogItemForDisplay({
...r,
type: r.type,
...p ? { id: p } : {},
text: r.emptyText === true ? "" : unwrapImportFrame(o)
});
return m ? [{
...f,
...m,
__openclaw: {
...l,
...asOptionalRecord(m["__openclaw"])
}
}] : [];
}
//#endregion
//#region src/shared/run-failure-notice.ts
function readRunFailureNotice(e) {
const t = asOptionalRecord(asOptionalRecord(e)?.openclawRunError);
if (typeof t?.runId !== "string" || !t.runId.trim() || typeof t.summary !== "string" || !t.summary.trim()) return;
return {
runId: t.runId,
summary: t.summary
};
}
//#endregion
//#region src/gateway/chat-sanitize.ts
function extractMessageSenderLabel(e) {
if (typeof e.senderLabel === "string" && e.senderLabel.trim()) return e.senderLabel.trim();
if (typeof e.content === "string") return extractInboundSenderLabel(e.content);
if (Array.isArray(e.content)) for (const t of e.content) {
if (!t || typeof t !== "object") continue;
const e = t.text;
if (typeof e !== "string") continue;
const n = extractInboundSenderLabel(e);
if (n) return n;
}
if (typeof e.text === "string") return extractInboundSenderLabel(e.text);
return null;
}
function stripEnvelopeFromContentWithRole(e, t) {
const n = t === "user";
return mapChatDisplayMessages(e, (e) => {
if (!e || typeof e !== "object") return e;
const r = e;
if (!(r.type === "text" || t === "user" && r.type === "input_text" || t === "assistant" && (r.type === "input_text" || r.type === "output_text")) || typeof r.text !== "string") return e;
const i = n ? stripUserEnvelopeForDisplay(r.text) : stripInternalMetadataForDisplay(r.text);
return i === r.text ? e : {
...r,
text: i
};
});
}
/** Strips OpenClaw envelope metadata from one display message without mutating it. */
function stripEnvelopeFromMessage(e) {
if (!e || typeof e !== "object") return e;
const t = projectChatWorkContextForDisplay(e);
const n = t;
const r = typeof n.role === "string" ? normalizeLowercaseStringOrEmpty(n.role) : "";
const i = r === "user";
let a;
const o = i ? extractMessageSenderLabel(n) : null;
if (o && n.senderLabel !== o) a = {
...n,
senderLabel: o
};
const s = typeof n.content === "string" || Array.isArray(n.content) ? "content" : "text";
const c = n[s];
if (typeof c === "string" || s === "content" && Array.isArray(c)) {
const e = Array.isArray(c) ? stripEnvelopeFromContentWithRole(c, r) : i ? stripUserEnvelopeForDisplay(c) : stripInternalMetadataForDisplay(c);
if (e !== c) {
a ??= { ...n };
a[s] = e;
}
}
return a ?? t;
}
/** Strips envelope metadata from a message array, preserving the original array when unchanged. */
function stripEnvelopeFromMessages(e) {
return mapChatDisplayMessages(e, stripEnvelopeFromMessage);
}
//#endregion
//#region src/gateway/chat-display-projection.core.ts
/** Keep profile display reads local to one history page or event projection operation. */
function createCurrentUserProfileMessageProjector(e) {
const t = /* @__PURE__ */ new Map();
return (n) => {
if (n.role !== "user") return n;
const r = asOptionalRecord(n["__openclaw"]);
if (!r) return n;
const i = readTranscriptSenderIdentity(r.senderIdentity);
if (i?.type !== "profile") return n;
const a = i.id;
let o = t.get(a);
if (!o) {
o = e(a);
t.set(a, o);
}
if (o.kind === "unresolved") return n;
if (r.senderProfileAvatarUrl === o.avatarUrl && i.id === o.profileId) return n;
return {
...n,
__openclaw: {
...r,
senderIdentity: {
type: "profile",
id: o.profileId
},
senderProfileAvatarUrl: o.avatarUrl
}
};
};
}
function projectCurrentUserProfileAvatars(e, t) {
if (!t) return e;
return mapChatDisplayMessages(e, createCurrentUserProfileMessageProjector(t));
}
function getAssistantErrorFallbackText(e) {
return formatProviderRefusalText(e) ?? renderAssistantRequestFailureCopy({
storageFailure: classifyGatewayStorageFailure(e),
code: typeof e.errorCode === "string" ? e.errorCode : void 0
}) ?? renderRecordedAssistantFailureCopy(e) ?? "The agent run failed before producing a reply.";
}
function sanitizeAssistantErrorDisplayMessage(e, t = true) {
const { content: n, ...r } = e;
let i = sanitizeChatHistoryMessage(r, Number.MAX_SAFE_INTEGER).message;
if (Array.isArray(n)) {
let e = true;
i.content = n.flatMap((t) => {
const n = sanitizeChatHistoryContentBlock(t, { maxChars: Number.MAX_SAFE_INTEGER }).block;
if (!n || typeof n !== "object" || Array.isArray(n)) return [n];
const r = n;
if (isAssistantInternalReasoningContentType(r.type)) return [];
if (!e || !isAssistantTextContentBlockType(r.type)) return [n];
e = false;
if (typeof r.text !== "string" || !r.text.startsWith("[assistant turn failed before producing content]")) return [n];
const i = r.text.slice(STREAM_ERROR_FALLBACK_TEXT.length);
return i ? [{
...r,
text: i
}] : [];
});
} else i.content = typeof n === "string" && n.startsWith("[assistant turn failed before producing content]") ? n.slice(STREAM_ERROR_FALLBACK_TEXT.length) : n;
if (typeof i.text === "string" && i.text.startsWith("[assistant turn failed before producing content]")) i.text = i.text.slice(STREAM_ERROR_FALLBACK_TEXT.length);
const a = formatProviderRefusalText(e) ?? renderAssistantRequestFailureCopy({ code: typeof e.errorCode === "string" ? e.errorCode : void 0 }) ?? renderRecordedAssistantFailureCopy(e);
if (t && a) {
i = sanitizeChatHistoryMessage(i, Number.MAX_SAFE_INTEGER).message;
if (shouldDropAssistantHistoryMessage(i)) {
i.content = [];
delete i.text;
delete i.phase;
}
const t = Array.isArray(i.content) ? [...i.content] : typeof i.content === "string" ? [{
type: "text",
text: i.content
}] : [];
const prependText = (e) => {
const n = t.some((t) => {
const n = asOptionalRecord(t);
return n && isAssistantTextContentBlockType(n.type) && typeof n.text === "string" && n.text.includes(e);
});
if (!e || n) return;
const r = t.findIndex((e) => {
const t = asOptionalRecord(e);
return t && isAssistantTextContentBlockType(t.type) && typeof t.text === "string";
});
const i = r >= 0 ? asOptionalRecord(t[r]) : void 0;
if (i) t[r] = {
...i,
text: [e, i.text].filter(Boolean).join("\n\n")
};
else t.push({
type: "text",
text: e
});
};
if (typeof i.text === "string") prependText(i.text);
prependText(getAssistantErrorFallbackText(e));
i.content = t;
delete i.text;
}
delete i.diagnostics;
delete i.errorBody;
delete i.errorCode;
delete i.errorMessage;
delete i.errorType;
return i;
}
function isPureStreamErrorFallbackAssistantMessage(e) {
if (e.role !== "assistant" || e.stopReason !== "error") return false;
const t = extractAssistantTextForSilentCheck(e);
return t !== void 0 && t.trim() === "[assistant turn failed before producing content]" && !hasAssistantNonTextContent(e) && !hasTranscriptMediaFacts(e);
}
function hasVisibleAssistantDisplayContent(e, t = Number.MAX_SAFE_INTEGER) {
if (e.role !== "assistant" || e.display === false || isPureStreamErrorFallbackAssistantMessage(e)) return false;
const n = sanitizeChatHistoryMessage(e, t).message;
if (shouldDropAssistantHistoryMessage(e)) return false;
if (hasAssistantDisplayableNonTextContent(n) || hasTranscriptMediaFacts(n)) return true;
return hasVisibleAssistantReplyText(n);
}
function hasVisibleAssistantReplyText(e) {
return [...Array.isArray(e.content) ? e.content.flatMap((e) => {
const t = asOptionalRecord(e);
return isAssistantTextContentBlockType(t?.type) ? [t?.text] : [];
}) : [e.content], e.text].some((e) => {
if (typeof e !== "string") return false;
const t = e.trim();
return t.length > 0 && t !== "[assistant turn failed before producing content]";
});
}
function isCompletedAssistantMessage(e) {
return e.role === "assistant" && (e.stopReason === "stop" || e.stopReason === "length");
}
/** Sanitized reasoning is display material without being a recovery-completing answer. */
function hasAssistantHistoryMaterial(e) {
return hasVisibleAssistantReplyText(e) || hasAssistantDisplayableNonTextContent(e) || hasTranscriptMediaFacts(e) || Array.isArray(e.content) && e.content.some((e) => {
const t = asOptionalRecord(e);
return isAssistantInternalReasoningContentType(t?.type) && [t?.thinking, t?.text].some((e) => typeof e === "string" && e.trim().length > 0);
});
}
function isDiagnosticOnlyAssistantError(e) {
const t = asOptionalRecord(e);
return t?.role === "assistant" && t.display !== false && t.stopReason === "error" && (isPureStreamErrorFallbackAssistantMessage(t) || Boolean(readSessionTranscriptRunId(t)) && !hasAssistantDisplayableNonTextContent(t) && !hasTranscriptMediaFacts(t) && (!hasVisibleAssistantDisplayContent(t) || extractAssistantTextForSilentCheck(t)?.trim().replace(/^⚠️\s*/u, "") === "Context overflow: prompt too large for the model. Try /reset (or /new) to start a fresh session, or use a larger-context model."));
}
function isPendingAssistantError(e) {
const t = asOptionalRecord(e);
return Boolean(t?.role === "assistant" && t.display !== false && t.stopReason === "error" && (readSessionTranscriptRunId(t) || isPureStreamErrorFallbackAssistantMessage(t)));
}
/** Retain authored output, never a model attempt's host-owned failure copy. */
function projectAssistantAttemptContent(e) {
const t = isDiagnosticOnlyAssistantError(e);
const n = sanitizeAssistantErrorDisplayMessage(e, false);
delete n.stopReason;
delete n.openclawRunError;
if (t) {
n.content = [];
delete n.text;
}
return hasVisibleAssistantDisplayContent(n) ? n : void 0;
}
/** Hidden retry prompts continue a turn; only a real user input ends recovery matching. */
function isChatHistoryRecoveryUserBoundary(e) {
const t = asOptionalRecord(e);
return t?.role === "user" && !(t.display === false && asOptionalRecord(t.provenance)?.kind === "internal_system");
}
function createChatHistoryRecoveryProjection(e) {
const t = createSubagentCoordinationHistoryProjection(e?.subagentCoordination);
const n = [];
let r = e?.assistantErrorPending ?? false;
let i = false;
let a = [];
const o = /* @__PURE__ */ new Set();
const append = (t) => {
const s = readSessionTranscriptFailureRunId(t) ?? readRunFailureNotice(t)?.runId;
if (s) a = a.filter((e) => {
if (readSessionTranscriptRunId(n[e]) !== s) return true;
o.add(e);
i = true;
return false;
});
const c = n.length;
n.push(t);
if (isChatHistoryRecoveryUserBoundary(t)) {
r = false;
a = [];
return;
}
if (isPendingAssistantError(t) || readRunFailureNotice(t)) {
a.push(c);
return;
}
const l = hasVisibleAssistantDisplayContent(t, r || a.length > 0 ? Number.MAX_SAFE_INTEGER : e?.maxChars ?? 8e3);
if (!r && a.length === 0 || !l) return;
i ||= r;
r = false;
const u = (t.stopReason === "stop" || t.stopReason === "length") && !isTranscriptOnlyOpenClawAssistantMessage(t) ? readSessionTranscriptRunId(t) : void 0;
a = a.filter((e) => {
const t = readSessionTranscriptRunId(n[e]);
if (t && t !== u) return true;
o.add(e);
i = true;
return false;
});
};
return {
append(n) {
const r = t(prepareChatHistoryRecoveryMessages(n, e));
for (const e of toProjectedMessages(r)) if (!isOpenClawMessageToolMirrorAssistantMessage(e)) append(e);
},
get pending() {
return r || a.length > 0;
},
result() {
return {
messages: o.size > 0 ? n.flatMap((e, t) => {
if (!o.has(t)) return [e];
const n = projectAssistantAttemptContent(e);
return n ? [n] : [];
}) : n.slice(),
pending: r || a.length > 0,
recoveryObserved: i
};
}
};
}
/** Only the terminal lifecycle owner may turn attempt diagnostics into a notice. */
function projectRunFailureNotices(e) {
return e.flatMap((e) => {
if (e.role === "custom" && e.customType === "run-failed-before-reply") {
const t = readSessionTranscriptFailureRunId(e) ?? readSessionTranscriptRunId(e);
const n = readRunFailureNotice(e)?.summary ?? (typeof e.content === "string" ? e.content.trim() : void 0);
return t && n ? [{
...e,
openclawRunError: {
runId: t,
summary: n
}
}] : [e];
}
if (readSessionTranscriptRunId(e) && isPendingAssistantError(e)) {
const t = projectAssistantAttemptContent(e);
return t ? [t] : [];
}
return [e];
});
}
function projectEmptyAssistantErrorMessages(e) {
return mapChatDisplayMessages(e, (e) => {
if (e.role !== "assistant" || e.stopReason !== "error") return e;
if (hasAssistantDisplayableNonTextContent(e) || hasTranscriptMediaFacts(e)) return sanitizeAssistantErrorDisplayMessage(e);
const t = sanitizeChatHistoryMessage(e, Number.MAX_SAFE_INTEGER).message;
if (!shouldDropAssistantHistoryMessage(t) && hasVisibleAssistantReplyText(t)) return sanitizeAssistantErrorDisplayMessage(e);
const n = {
...t,
content: [{
type: "text",
text: getAssistantErrorFallbackText(e)
}]
};
delete n.diagnostics;
delete n.errorBody;
delete n.errorCode;
delete n.errorMessage;
delete n.errorType;
delete n.phase;
delete n.text;
return n;
});
}
function prepareChatHistoryRecoveryMessages(e, t) {
const n = e.map((e) => {
const n = projectTranscriptImageArtifacts(prepareAssistantHistoryMessage(e));
const r = asOptionalRecord(n);
const i = readSessionTranscriptFailureRunId(r);
if (i) return {
...r,
__openclaw: {
...asOptionalRecord(r?.["__openclaw"]),
runId: i
}
};
const a = readNestedToolActivity(n);
if (!a) return n;
const [o, s] = nestedToolActivityContent(a);
const c = sanitizeChatHistoryMessage({
...s,
role: "toolResult"
}, t?.maxChars ?? 8e3).message;
return {
...asOptionalRecord(n),
runId: a.details.runId,
__openclaw: {
...asOptionalRecord(asOptionalRecord(n)?.["__openclaw"]),
runId: a.details.runId
},
content: [o, c]
};
});
return t?.stripEnvelope === false ? n : stripEnvelopeFromMessages(n);
}
function projectChatDisplayMessagesWithState(e, t) {
t?.subagentCoordination?.assertCurrent?.();
const n = createChatHistoryRecoveryProjection(t);
const r = e.flatMap(projectPreservedCatalogMessageForDisplay);
n.append(r);
const i = n.result();
const a = projectEmptyAssistantErrorMessages(projectRunFailureNotices(i.messages));
const o = t?.activity === false ? [] : projectAgentHistoryActivity(e.flatMap((e) => {
const t = asOptionalRecord(asOptionalRecord(e)?.["__openclaw"])?.id;
return typeof t === "string" ? [{
messageId: t,
message: e
}] : [];
}));
if (t?.activity !== false) for (const e of r) {
const t = asOptionalRecord(e);
const n = asOptionalRecord(t?.["__openclaw"])?.id;
if (asOptionalRecord(t?.["__openclaw"])?.catalogSource === true && typeof n === "string" && Array.isArray(t?.activity)) o.push({
messageId: n,
items: t.activity
});
}
const s = a.some((e) => e.openclawTtsSupplement || isTranscriptOnlyOpenClawAssistantMessage(e)) ? Number.MAX_SAFE_INTEGER : t?.maxChars ?? 8e3;
const c = sanitizeChatHistoryMessages(a, s, { includeCommentaryFallbacks: t?.includeCommentaryFallbacks }).filter((e) => !isCompletedAssistantMessage(e) || hasAssistantHistoryMaterial(e));
const l = t?.includeCommentaryFallbacks === true && c.some((e) => asOptionalRecord(e.openclawStreamFallback)?.source === "segment");
const u = filterVisibleProjectedHistoryMessages(projectForwardedMessages(t?.includePluginSteering ? mapChatDisplayMessages(c, projectPluginSteeringMessage) : c, t?.resolveCronJobName), t?.turnBoundaryPending);
const d = {
activity: o,
messages: projectCurrentUserProfileAvatars(sanitizeChatHistoryMessages(mergeTtsSupplementMessages(u.messages), t?.maxChars ?? 8e3, { toolResultMaxChars: t?.toolResultMaxChars }), t?.resolveCurrentUserProfileDisplay),
turnBoundaryPending: u.turnBoundaryPending,
assistantErrorPending: i.pending,
assistantErrorRecoveryObserved: i.recoveryObserved
};
if (l) d.commentaryFallbacksObserved = true;
t?.subagentCoordination?.assertCurrent?.();
return d;
}
function projectChatDisplayMessages(e, t) {
return projectChatDisplayMessagesWithState(e, {
...t,
activity: false
}).messages;
}
function projectChatDisplayMessage(e, t) {
const n = projectChatDisplayMessages([e], t);
if (!t?.includeCommentaryFallbacks || !n.some((e) => e.openclawStreamFallback)) return n[0];
const r = {
...n.at(-1),
content: n.flatMap(({ content: e }) => Array.isArray(e) ? e : typeof e === "string" ? [{
type: "text",
text: e
}] : [])
};
const i = n.map((e) => asOptionalRecord(e["__openclaw"])).find((e) => e?.truncated === true);
if (i) r["__openclaw"] = {
...asOptionalRecord(r["__openclaw"]),
truncated: true,
reason: i.reason
};
delete r.openclawStreamFallback;
return r;
}
//#endregion
export { prepareChatHistoryRecoveryMessages as a, projectChatDisplayMessagesWithState as c, isPendingAssistantError as i, catalogDisplayFacts as l, createCurrentUserProfileMessageProjector as n, projectChatDisplayMessage as o, isChatHistoryRecoveryUserBoundary as r, projectChatDisplayMessages as s, createChatHistoryRecoveryProjection as t, catalogItemTextPrefix as u };