UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

710 lines (709 loc) • 27.8 kB
import { l as normalizeOptionalString, m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord, i as asOptionalObjectRecord, l as isRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { n as safeParseJsonRecord, t as safeParseJson } from "./json-coercion-CaJLaav-.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { i as readPluginInlineViewDescriptor, r as readPluginInlineViewBlock } from "./plugin-inline-view-mk_5B-dj.mjs"; import { a as isAssistantTextContentBlockType, o as isSilentAssistantTranscriptMessage } from "./chat-message-content-DNUdbbJ8.mjs"; import { n as SILENT_REPLY_TOKEN, t as HEARTBEAT_TOKEN } from "./tokens-CcE6ESvH.mjs"; import { _ as normalizeInputProvenance } from "./input-provenance-DupvvURj.mjs"; import { a as isHeartbeatAcknowledgementText, i as INTERNAL_WAKE_TRANSCRIPT_PROMPTS, n as HEARTBEAT_RESPONSE_TOOL_INSTRUCTIONS, o as resolveHeartbeatPromptForResponseTool, r as HEARTBEAT_RESPONSE_TOOL_PROMPT } from "./heartbeat-DHK32_6H.mjs"; import { t as MESSAGE_TOOL_DELIVERY_HINTS } from "./message-tool-delivery-hints-Bfbq9j9C.mjs"; import { a as readToolCallName, n as isContractToolCallBlock, r as isContractToolResultBlock, t as collectToolCallIds } from "./tool-block-contract-BsnlYLrK.mjs"; import { i as isToolResultContentType, n as isToolCallContentType } from "./tool-content-DG-uYHoo.mjs"; import { c as isMeaningfulMediaFact, p as readPersistedMediaFacts } from "./media-facts-B-0Dpo5L.mjs"; import { t as findMarkdownCodeRegions } from "./markdown-code-regions-CUsfah9M.mjs"; import { r as isInsideCode } from "./code-ranges-2XaqsF-S.mjs"; import { n as splitMediaOutput, t as isRelativeAssistantMediaReference } from "./parse-output-BsYrumRW.mjs"; //#region src/auto-reply/heartbeat-filter.ts const HEARTBEAT_RESPONSE_TOOL_NAME = "heartbeat_respond"; const HEARTBEAT_TASK_PROMPT_PREFIX = "Run the following periodic tasks (only those due based on their intervals):"; const HEARTBEAT_TASK_PROMPT_COMPLETIONS = [ ...[HEARTBEAT_TOKEN, SILENT_REPLY_TOKEN].map((e) => `After completing all due tasks, reply ${e}.`), HEARTBEAT_RESPONSE_TOOL_INSTRUCTIONS, `After completing all due tasks, reply with exactly ${SILENT_REPLY_TOKEN} as the entire final answer.`, `After completing all due tasks, use ${HEARTBEAT_RESPONSE_TOOL_NAME}` ]; function isVisibleHeartbeatResponseToolCall(e) { const t = isRecord(e.function) ? e.function : void 0; const n = e.arguments ?? e.args ?? e.input ?? t?.arguments ?? t?.args ?? t?.input; const r = isRecord(n) ? n : typeof n === "string" ? safeParseJsonRecord(n) : void 0; return r?.notify === true || r?.notify === "true"; } function collectAssistantToolCalls(e) { if (e.role !== "assistant") return []; const t = e.tool_calls; return [...Array.isArray(t) ? t.filter(isRecord) : [], ...Array.isArray(e.content) ? e.content.filter(isContractToolCallBlock) : []]; } function isEmbeddedToolResultOnlyContent(e) { return Array.isArray(e) && e.length > 0 && e.every((e) => isContractToolResultBlock(e)); } function isToolResultMessage(e) { return e.role === "toolResult" || e.role === "tool" || e.role === "user" && isEmbeddedToolResultOnlyContent(e.content); } function matchesHeartbeatPromptText(e, t) { return Boolean(t) && (e === t || e.startsWith(`${t}\n`)); } function resolveMessageText(e) { if (typeof e === "string") return { text: e, hasNonTextContent: false }; if (!Array.isArray(e)) return { text: "", hasNonTextContent: e != null }; let t = false; let n = ""; for (const r of e) { if (typeof r !== "object" || r === null || !("type" in r)) { t = true; continue; } if (r.type === "thinking" || r.type === "reasoning" || r.type === "redacted_thinking") continue; if (r.type !== "text" && r.type !== "input_text" && r.type !== "output_text") { t = true; continue; } const e = r.text; if (typeof e !== "string") { t = true; continue; } n += e; } return { text: n, hasNonTextContent: t }; } /** Return whether a user message is an internal heartbeat prompt. */ function isHeartbeatUserMessage(e, t, n = {}) { if (e.role !== "user") return false; const { text: r } = resolveMessageText(e.content); const i = r.trim(); if (!i) return false; const a = t?.trim(); const o = n.heartbeatOnly ? [INTERNAL_WAKE_TRANSCRIPT_PROMPTS.heartbeat] : Object.values(INTERNAL_WAKE_TRANSCRIPT_PROMPTS); if (o.some((e) => i === e)) return true; if (MESSAGE_TOOL_DELIVERY_HINTS.some((e) => i.startsWith(e)) && o.some((e) => i.endsWith(e))) return true; if (matchesHeartbeatPromptText(i, a) || matchesHeartbeatPromptText(i, HEARTBEAT_RESPONSE_TOOL_PROMPT) || a && matchesHeartbeatPromptText(i, resolveHeartbeatPromptForResponseTool(a))) return true; return i.startsWith(HEARTBEAT_TASK_PROMPT_PREFIX) && HEARTBEAT_TASK_PROMPT_COMPLETIONS.some((e) => i.includes(e)); } /** Return whether an assistant message is only a heartbeat acknowledgement. */ function isHeartbeatOkResponse(e, t, n = false) { if (e.role !== "assistant" || collectAssistantToolCalls(e).length > 0) return false; const { text: r, hasNonTextContent: i } = resolveMessageText(e.content); return !i && (isSilentAssistantTranscriptMessage(e) || isHeartbeatAcknowledgementText(r, t, n)); } function advancePastAdjacentToolResults(e, t) { let n = t; while (n < e.length) { const t = e.at(n); if (!t || !isToolResultMessage(t)) break; n++; } return n; } function hasCompletedVisibleHeartbeatResponseToolCall(e, t, n) { const r = new Set(n.flatMap((e) => collectToolCallIds(e))); for (let n = t + 1; n < e.length; n++) { const t = expectDefined(e[n], "messages entry at resultIndex"); const { content: i } = t; const a = Array.isArray(i) ? i.filter(isContractToolResultBlock) : []; if (a.length === 0 && !isToolResultMessage(t)) break; if ((a.length > 0 ? a : [t]).some((e) => e.isError !== true && e.is_error !== true && normalizeOptionalString(e.type) !== "tool_result_error" && (r.size === 0 || collectToolCallIds(e).some((e) => r.has(e))))) return true; } return false; } function resolveHeartbeatArtifactSpanEnd(e, t, n, r = false) { let i = t + 1; let a = false; let o = false; while (i < e.length) { const t = e.at(i); if (!t) break; if (t.role === "user" && !isEmbeddedToolResultOnlyContent(t.content)) break; if (isHeartbeatOkResponse(t, n, r)) { a = true; i = advancePastAdjacentToolResults(e, i + 1); continue; } const s = collectAssistantToolCalls(t); const c = s.filter((e) => readToolCallName(e) === HEARTBEAT_RESPONSE_TOOL_NAME); const l = c.filter(isVisibleHeartbeatResponseToolCall); if (l.length > 0) { if (hasCompletedVisibleHeartbeatResponseToolCall(e, i, l)) return; } else if (c.length > 0) { a = true; i = advancePastAdjacentToolResults(e, i + 1); continue; } else if (!a && !isToolResultMessage(t) && s.length === 0) { if (t.role !== "assistant") return; o = true; } i++; } if (o && !a) return; return i; } /** Remove heartbeat-only prompt, ack, and silent tool artifacts from a transcript. */ function filterHeartbeatTranscriptArtifacts(e, t, n) { if (e.length === 0) return e; const r = []; for (let i = 0; i < e.length;) { const a = expectDefined(e[i], "messages entry at i"); const o = isHeartbeatUserMessage(a, n) ? resolveHeartbeatArtifactSpanEnd(e, i, t, isHeartbeatUserMessage(a, n, { heartbeatOnly: true })) : void 0; if (o === void 0) r.push(a); i = o ?? i + 1; } return r; } //#endregion //#region src/gateway/chat-display-projection.helpers.ts const DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS = 8e3; /** Removes private yield inputs from a display copy without changing the source argument objects. */ function stripPrivateToolCallContextForDisplay(e) { if (e.type !== "toolCall" || e.name !== "sessions_yield") return false; let t = false; for (const n of ["arguments", "input"]) { const r = asOptionalRecord(e[n]); if (!r || !("message" in r)) continue; const { message: i, ...a } = r; e[n] = a; t = true; } return t; } function takeAssistantManagedMediaUrlsForDisplay(e, t) { const n = t === "assistant" ? asOptionalRecord(e.openclawDelivery) : void 0; const r = Array.isArray(n?.mediaUrls) ? n.mediaUrls.filter((e) => typeof e === "string") : []; if (!n || !Object.hasOwn(n, "mediaUrls")) return { changed: false, urls: r }; const i = { ...n }; delete i.mediaUrls; if (Object.keys(i).length > 0) e.openclawDelivery = i; else delete e.openclawDelivery; return { changed: true, urls: r }; } /** Keeps managed attachment commands in the raw transcript while removing them from display text. */ function stripAssistantMediaDirectivesForDisplay(e, t) { if (t.length === 0 || !/(?:^|[\r\n])\s*MEDIA:/iu.test(e)) return e; const n = new Set(t.map((e) => e.trim()).filter(Boolean)); const r = splitMediaOutput(e, { extractAudioDirectives: false }); if (!r.mediaUrls?.some((e) => isRelativeAssistantMediaReference(e) && n.has(e.trim()))) return e; return (r.segments ?? []).filter((e) => e.type !== "media" || !isRelativeAssistantMediaReference(e.url) || !n.has(e.url.trim())).map((e) => e.type === "media" ? `MEDIA:${e.url}` : e.text).join("\n"); } function resolveEffectiveChatHistoryMaxChars(e) { if (typeof e === "number") return e; return DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS; } function truncateChatHistoryText(e, t = DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS, n = false, r) { let i = t; if (r !== void 0 && r < Math.min(e.length, t)) { const n = truncateUtf16Safe(e, t); if (!/^\s*[[{]/u.test(n) || safeParseJson(n) === void 0) i = r; } if (e.length <= i) return { text: e, truncated: false }; const a = truncateUtf16Safe(e, i); return { text: n || !a.trim() ? a : `${a}\n...(truncated)...`, truncated: true }; } function extractAssistantTextForSilentCheck(e) { const t = asOptionalObjectRecord(e); if (t?.role !== "assistant") return; if (typeof t.text === "string") return t.text; if (typeof t.content === "string") return t.content; if (!Array.isArray(t.content) || t.content.length === 0) return; const n = []; for (const e of t.content) { const t = asOptionalObjectRecord(e); if (!t) return; if (isAssistantInternalReasoningContentType(t.type)) continue; if (!isAssistantTextContentBlockType(t.type) || typeof t.text !== "string") return; n.push(t.text); } return n.length > 0 ? n.join("\n") : void 0; } function isAssistantInternalReasoningContentType(e) { return e === "thinking" || e === "reasoning" || e === "redacted_thinking"; } function hasAssistantNonTextContent(e, t = true) { const n = asOptionalObjectRecord(e)?.content; return Array.isArray(n) && n.some((e) => { const n = asOptionalObjectRecord(e); return n && !isAssistantTextContentBlockType(n.type) && (t || !isAssistantInternalReasoningContentType(n.type)); }); } function hasAssistantDisplayableNonTextContent(e) { return hasAssistantNonTextContent(e, false); } function shouldPreserveAssistantControlReplyText(e) { if (isProjectedForwardedMessage(e)) return true; return hasAssistantDisplayableNonTextContent(e); } function asRoleContentMessage(e) { const t = typeof e.role === "string" ? e.role.toLowerCase() : ""; if (!t) return null; return { ...e, role: t, ...e.content !== void 0 ? { content: e.content } : e.text !== void 0 ? { content: e.text } : {} }; } function isEmptyTextOnlyContent(e) { if (typeof e === "string") return e.trim().length === 0; if (!Array.isArray(e)) return false; for (const t of e) { const e = asOptionalObjectRecord(t); if (e?.type !== "text" || typeof e.text !== "string" || e.text.trim().length > 0) return false; } return true; } function hasTranscriptMediaFacts(e) { return (readPersistedMediaFacts(e) ?? []).some(isMeaningfulMediaFact); } function extractProjectedText(e) { if (typeof e === "string") return e; if (!Array.isArray(e)) return ""; const t = []; for (const n of e) { const e = asOptionalObjectRecord(n)?.text; if (typeof e === "string") t.push(e); } return t.join("\n"); } function isCronRunMessage(e) { const t = normalizeInputProvenance(e.provenance); return t?.kind === "internal_system" && t.sourceTool === "cron" && Boolean(t.jobId && t.runId && t.sourceSessionKey); } function isForwardedUserMessage(e) { return e.role === "user" && hasForwardedMessageProvenance(e); } const TOOL_MESSAGE_ENVELOPE_FIELDS = [ "toolCallId", "tool_call_id", "toolUseId", "tool_use_id", "toolName", "tool_name" ]; /** Tool-shaped user rows display as tool results, so they do not start a chat turn. */ function userMessageStartsDisplayTurn(e) { if (TOOL_MESSAGE_ENVELOPE_FIELDS.some((t) => typeof e[t] === "string")) return false; return !Array.isArray(e.content) ? true : !e.content.some((e) => { const t = asOptionalRecord(e)?.type; return isToolCallContentType(t) || isToolResultContentType(t); }); } function isProjectedForwardedMessage(e) { return e.role === "assistant" && hasForwardedMessageProvenance(e); } function hasForwardedMessageProvenance(e) { const t = normalizeInputProvenance(e.provenance); return t?.kind === "inter_session" && t.sourceTool === "sessions_send" || isCronRunMessage(e); } //#endregion //#region src/chat/canvas-render.ts function coerceMcpAppDescriptor(e) { const t = readNonBlankString(e?.viewId); if (!t || t.length > 128) return; const n = readNonBlankString(e?.serverName); const r = readNonBlankString(e?.toolName); const i = readNonBlankString(e?.uiResourceUri); const a = readNonBlankString(e?.toolCallId); const o = readNonBlankString(e?.originSessionKey); const s = e?.resultMetaState === "unavailable" ? "unavailable" : void 0; return Boolean(n && n.length <= 256 && r && r.length <= 256 && i?.startsWith("ui://") && i.length <= 2048 && a && a.length <= 512) ? { viewId: t, serverName: n, toolName: r, uiResourceUri: i, toolCallId: a, ...o && o.length <= 512 ? { originSessionKey: o } : {}, ...s ? { resultMetaState: s } : {} } : { viewId: t }; } function normalizePreferredHeight(e) { return typeof e === "number" && Number.isFinite(e) && e >= 160 ? Math.min(Math.trunc(e), 1200) : void 0; } function isCanvasBoardWidgetName(e) { return typeof e === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/u.test(e); } function extractCanvasFromRecord(e) { const t = asOptionalRecord(e); if (!t) return; if (readNonBlankString(t?.kind)?.trim().toLowerCase() !== "canvas") return; const n = asOptionalRecord(t.presentation); const r = asOptionalRecord(t.view); const i = asOptionalRecord(t.source); const a = coerceMcpAppDescriptor(asOptionalRecord(t.mcpApp)); const o = a?.viewId; const s = readNonBlankString(n?.target) ?? readNonBlankString(t?.target) ?? "assistant_message"; if (s !== "assistant_message" && s !== "node_panel") return; const c = readNonBlankString(n?.title) ?? readNonBlankString(r?.title); const l = normalizePreferredHeight(asFiniteNumber(n?.preferred_height) ?? asFiniteNumber(n?.preferredHeight) ?? asFiniteNumber(r?.preferred_height) ?? asFiniteNumber(r?.preferredHeight)); const u = readNonBlankString(n?.class_name) ?? readNonBlankString(n?.className); const d = readNonBlankString(n?.style); const f = readNonBlankString(n?.sandbox); const p = readNonBlankString(r?.url) ?? readNonBlankString(r?.entryUrl); const m = readNonBlankString(r?.id) ?? readNonBlankString(r?.docId); const h = readNonBlankString(r?.boardWidgetName); const g = isCanvasBoardWidgetName(h) ? h : void 0; const _ = { kind: "canvas", surface: s, render: "url", ...c ? { title: c } : {}, ...l ? { preferredHeight: l } : {}, ...f === "strict" || f === "scripts" ? { sandbox: f } : {}, ...a ? { mcpApp: a } : {} }; if (o && m === o) return { ..._, viewId: m }; const v = p ?? (readNonBlankString(i?.type)?.trim().toLowerCase() === "url" ? readNonBlankString(i?.url) : void 0); if (!v) return; return { ..._, url: v, ...p && m ? { viewId: m } : {}, ...u ? { className: u } : {}, ...d ? { style: d } : {}, ...p && g ? { boardWidgetName: g } : {} }; } /** Extracts an MCP App Canvas preview from sanitized tool-result details. */ function extractCanvasFromDetails(e) { return extractCanvasFromRecord(asOptionalRecord(e)?.mcpAppPreview); } function parseCanvasAttributes(e) { const t = {}; const n = /([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/g; let r; while (r = n.exec(e)) { const e = r[1]?.toLowerCase(); const n = (r[2] ?? r[3] ?? "").trim(); if (e && n) t[e] = n; } return t; } function previewFromShortcode(e) { if (e.target && e.target !== "assistant_message") return; const { title: t, style: n, ref: r, url: i } = e; const a = normalizePreferredHeight(Number(e.height)); const o = e.class ?? e.class_name; if (i || r) return { kind: "canvas", surface: "assistant_message", render: "url", url: i ?? `/__openclaw__/canvas/documents/${encodeURIComponent(expectDefined(r, "canvas reference"))}/index.html`, ...r ? { viewId: r } : {}, ...t ? { title: t } : {}, ...a ? { preferredHeight: a } : {}, ...o ? { className: o } : {}, ...n ? { style: n } : {} }; } /** Extracts a canvas preview from a JSON-shaped tool or assistant payload. */ function extractCanvasFromText(e) { return extractCanvasFromRecord(e ? safeParseJsonRecord(e) : void 0); } /** Extracts [embed ...] shortcodes outside Markdown code and returns stripped text. */ function extractCanvasShortcodes(e, t) { if (!e?.trim() || !e.toLowerCase().includes("[embed")) return { text: e ?? "", previews: [] }; const n = findMarkdownCodeRegions(e); const r = []; for (const t of [/\[embed\s+([^\]]*?[^\]/]|)\]([\s\S]*?)\[\/embed\]/gi, /\[embed\s+([^\]]*?)\/\]/gi]) { let i; while (i = t.exec(e)) { const e = i.index; if (isInsideCode(e, n)) continue; r.push({ start: e, end: e + i[0].length, attrs: parseCanvasAttributes(i[1] ?? "") }); } } if (r.length === 0) return { text: e, previews: [] }; r.sort((e, t) => e.start - t.start); const i = []; let a = 0; let o = ""; for (const n of r) { if (n.start < a) continue; o += e.slice(a, n.start); const r = previewFromShortcode(n.attrs); if (!r || t && !t(r)) o += e.slice(n.start, n.end); else i.push(r); a = n.end; } o += e.slice(a); return { text: o, previews: i }; } //#endregion //#region src/shared/tool-approval-reviews.ts const REVIEW_STATUSES = /* @__PURE__ */ new Set([ "in_progress", "approved", "denied", "timed_out", "aborted" ]); function boundedString(e, t) { const n = typeof e === "string" ? e.trim() : ""; return n ? truncateUtf16Safe(n, t) : void 0; } function isReviewStatus(e) { return e !== void 0 && REVIEW_STATUSES.has(e); } function normalizeToolApprovalReview(e) { const t = asNullableRecord(e); const n = boundedString(t?.id, 256); const r = boundedString(t?.label, 80); const i = boundedString(t?.status, 32); if (!n || !r || !isReviewStatus(i)) return null; const a = boundedString(t?.riskLevel, 40); const o = boundedString(t?.userAuthorization, 40); const s = boundedString(t?.rationale, 2e3); return { id: n, label: r, status: i, ...a ? { riskLevel: a } : {}, ...o ? { userAuthorization: o } : {}, ...s ? { rationale: s } : {} }; } //#endregion //#region src/gateway/chat-display-projection.inline-view.ts /** Preserve the admitted record regardless of installed renderers. The browser owns availability. */ function projectPluginInlineView(e, t) { const n = asOptionalRecord(e); const r = readPluginInlineViewDescriptor(n?.pluginInlineView); const i = asOptionalRecord(n?.pluginInlineViewInvocation); const a = r && i?.pluginId === r.pluginId && typeof i.toolCallId === "string" && typeof i.toolName === "string" ? { type: "plugin_view", ...r, toolCallId: i.toolCallId, toolName: i.toolName } : readPluginInlineViewBlock(n?.pluginView); const o = t.toolCallId ?? t.tool_call_id ?? t.id; const s = t.toolName ?? t.tool_name ?? t.name; return a?.toolCallId === o && a?.toolName === s ? a : void 0; } //#endregion //#region src/gateway/chat-display-projection.canvas.ts function isDisplayRouteIdentifier(e, t) { return typeof e === "string" && e.length > 0 && e.length <= t && e.trim() === e; } /** Return true for known tool-call/tool-result block type spellings in transcripts. */ function isToolHistoryBlockType(e) { if (typeof e !== "string") return false; const t = e.trim(); return isToolCallContentType(t) || isToolResultContentType(t); } function isToolResultHistoryBlockType(e) { return typeof e === "string" && isToolResultContentType(e.trim()); } function projectToolResultDetails(e, t, n = {}) { const r = asOptionalRecord(e); if (!r) return { details: void 0, truncated: false }; const i = {}; const a = projectPluginInlineView(r, n); if (a) i.pluginView = a; const o = asOptionalRecord(r.browserTab); if (isDisplayRouteIdentifier(o?.targetId, 128) && isDisplayRouteIdentifier(o?.profile, 128) && (o?.target === "host" && o.node === void 0 || o?.target === "node" && isDisplayRouteIdentifier(o.node, 256))) i.browserTab = { targetId: o.targetId, profile: o.profile, target: o.target, ...o.target === "node" ? { node: o.node } : {}, ...typeof o.url === "string" ? { url: truncateUtf16Safe(o.url, 2048) } : {}, ...typeof o.title === "string" ? { title: truncateUtf16Safe(o.title, 512) } : {} }; let s = false; for (const e of ["exitCode", "durationMs"]) { const t = r[e]; if (typeof t === "number" && Number.isFinite(t)) i[e] = t; } if (typeof r.cwd === "string") { const e = truncateChatHistoryText(r.cwd, t); i.cwd = e.text; s ||= e.truncated; } if (isDisplayRouteIdentifier(r.sessionKey, t)) i.sessionKey = r.sessionKey; for (const e of [ "ok", "changed", "created" ]) if (typeof r[e] === "boolean") i[e] = r[e]; if (typeof r.diff === "string" && r.diff.trim()) { const e = truncateChatHistoryText(r.diff, t); i.diff = e.text; s ||= e.truncated; } if (Array.isArray(r.approvalReviews)) { const e = r.approvalReviews.slice(-16).flatMap((e) => normalizeToolApprovalReview(e) ?? []); if (e.length > 0) i.approvalReviews = e; } const c = r.approvalReviewOutcome; if (c === "approved" || c === "denied" || c === "reviewing") i.approvalReviewOutcome = c; const l = extractCanvasFromDetails(r); if (l?.mcpApp && l.viewId) i.mcpAppPreview = { kind: "canvas", view: { id: l.viewId, ...l.url ? { url: l.url } : {}, ...l.title ? { title: l.title } : {} }, presentation: { target: "assistant_message", ...l.title ? { title: l.title } : {}, ...l.preferredHeight ? { preferred_height: l.preferredHeight } : {}, ...l.sandbox ? { sandbox: l.sandbox } : {} }, mcpApp: l.mcpApp }; return { details: Object.keys(i).length > 0 ? i : void 0, truncated: s }; } function messageHasToolResultShape(e) { const t = typeof e.role === "string" ? e.role.toLowerCase() : ""; if (t === "toolresult" || t === "tool_result" || t === "tool" || t === "function") return true; const n = Array.isArray(e.content) ? e.content : []; if (n.some((e) => isToolResultHistoryBlockType(asOptionalObjectRecord(e)?.type))) return true; const r = n.some((e) => { const t = asOptionalObjectRecord(e)?.type; return isToolHistoryBlockType(t) && !isToolResultHistoryBlockType(t); }); const i = typeof e.toolCallId === "string" || typeof e.tool_call_id === "string" || typeof e.toolUseId === "string" || typeof e.tool_use_id === "string"; const a = typeof e.toolName === "string" || typeof e.tool_name === "string"; return i && a && !r; } function extractChatHistoryBlockText(e) { const t = asOptionalObjectRecord(e); if (!t) return; if (typeof t.content === "string") return t.content; if (typeof t.text === "string") return t.text; if (!Array.isArray(t.content)) return; const n = t.content.map((e) => asOptionalObjectRecord(e)?.text).filter((e) => typeof e === "string"); return n.length > 0 ? n.join("\n") : void 0; } function extractChatHistoryCanvasPreview(e) { const t = extractCanvasFromDetails(e.details); if (t) return t; if (!Array.isArray(e.content)) return; for (const t of e.content) { const e = extractCanvasFromDetails(asOptionalRecord(t)?.details); if (e) return e; } } function extractChatToolResultCanvasPreview(e) { const t = asOptionalRecord(e); if (!t) return; const n = extractChatHistoryCanvasPreview(t); const r = n ? void 0 : extractChatHistoryBlockText(t); const i = n ?? extractCanvasFromText(r); return i ? { preview: i, rawText: n ? null : r ?? null } : void 0; } function appendChatCanvasBlocks(e, t) { const n = [...e]; for (const { preview: e, rawText: r } of t) if (!n.some((t) => { const n = asOptionalObjectRecord(t); const r = n?.type === "canvas" ? asOptionalObjectRecord(n.preview) : void 0; return Boolean(r && (r.viewId && r.viewId === e.viewId || r.url && r.url === e.url)); })) n.push({ type: "canvas", preview: e, rawText: r }); return n; } function appendChatCanvasBlocksToMessage(e, t) { if (!e || t.length === 0) return e; const n = Array.isArray(e.content) ? e.content : typeof e.content === "string" ? [{ type: "text", text: e.content }] : typeof e.text === "string" ? [{ type: "text", text: e.text }] : []; return { ...e, content: appendChatCanvasBlocks(n, t) }; } function messageContainsToolHistoryContent(e) { if (typeof e.toolCallId === "string" || typeof e.tool_call_id === "string" || typeof e.toolName === "string" || typeof e.tool_name === "string") return true; if (!Array.isArray(e.content)) return false; return e.content.some((e) => isToolHistoryBlockType(asOptionalObjectRecord(e)?.type)); } function augmentChatHistoryWithCanvasBlocks(e) { if (e.length === 0) return e; const t = [...e]; let n = false; let r = -1; let i = -1; const a = []; for (let e = 0; e < t.length; e++) { const o = asOptionalObjectRecord(t[e]); if (!o) continue; if ((typeof o.role === "string" ? o.role.toLowerCase() : "") === "assistant") { r = e; if (!messageContainsToolHistoryContent(o)) { i = e; if (a.length > 0) { t[e] = appendChatCanvasBlocksToMessage(o, a); a.length = 0; n = true; } } continue; } if (!messageContainsToolHistoryContent(o)) continue; const s = extractChatToolResultCanvasPreview(o); if (!s) continue; a.push(s); } if (a.length > 0) { const e = i >= 0 ? i : r; if (e >= 0) { t[e] = appendChatCanvasBlocksToMessage(asOptionalRecord(t[e]), a); n = true; } } return n ? t : e; } //#endregion export { truncateChatHistoryText as A, isForwardedUserMessage as C, stripAssistantMediaDirectivesForDisplay as D, shouldPreserveAssistantControlReplyText as E, filterHeartbeatTranscriptArtifacts as M, isHeartbeatOkResponse as N, stripPrivateToolCallContextForDisplay as O, isHeartbeatUserMessage as P, isEmptyTextOnlyContent as S, resolveEffectiveChatHistoryMaxChars as T, hasAssistantDisplayableNonTextContent as _, extractChatToolResultCanvasPreview as a, isAssistantInternalReasoningContentType as b, messageHasToolResultShape as c, extractCanvasFromRecord as d, extractCanvasShortcodes as f, extractProjectedText as g, extractAssistantTextForSilentCheck as h, extractChatHistoryBlockText as i, userMessageStartsDisplayTurn as j, takeAssistantManagedMediaUrlsForDisplay as k, projectToolResultDetails as l, asRoleContentMessage as m, appendChatCanvasBlocksToMessage as n, isToolHistoryBlockType as o, DEFAULT_CHAT_HISTORY_TEXT_MAX_CHARS as p, augmentChatHistoryWithCanvasBlocks as r, isToolResultHistoryBlockType as s, appendChatCanvasBlocks as t, projectPluginInlineView as u, hasAssistantNonTextContent as v, isProjectedForwardedMessage as w, isCronRunMessage as x, hasTranscriptMediaFacts as y };