UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

449 lines (448 loc) • 17.5 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { j as parseAgentSessionKey } from "./session-key-CqAyZeVk.mjs"; import { s as readSessionTranscriptRunId } from "./transcript-events-BHwlF03q.mjs"; import { t as extractAssistantPhaseText } from "./chat-message-content-DNUdbbJ8.mjs"; import { _ as normalizeInputProvenance, d as isCronExecutionInputProvenance, g as isSubagentCoordinationInputProvenance, r as INTER_SESSION_PROMPT_PREFIX_BASE, u as isCompletionReportInputProvenance, x as stripInterSessionPromptPrefixForDisplay } from "./input-provenance-DupvvURj.mjs"; import { t as HEARTBEAT_PROMPT } from "./heartbeat-DHK32_6H.mjs"; import { C as isForwardedUserMessage, N as isHeartbeatOkResponse, P as isHeartbeatUserMessage, S as isEmptyTextOnlyContent, _ as hasAssistantDisplayableNonTextContent, g as extractProjectedText, h as extractAssistantTextForSilentCheck, i as extractChatHistoryBlockText, j as userMessageStartsDisplayTurn, m as asRoleContentMessage, v as hasAssistantNonTextContent, w as isProjectedForwardedMessage, x as isCronRunMessage, y as hasTranscriptMediaFacts } from "./chat-display-projection.canvas-XAAIxHM8.mjs"; import { n as projectAssistantDisplayContent } from "./assistant-display-content-CBuMU4m5.mjs"; import { l as isOpenClawRuntimeContextCustomMessage } from "./internal-runtime-context-BEUlDNuI.mjs"; import { o as isOpenClawDeliveryMirrorAssistantMessage } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs"; import { i as buildRunUserTurnIdempotencyKey } from "./user-turn-transcript.metadata-GFtsH_a_.mjs"; import { createHash } from "node:crypto"; //#region src/gateway/chat-display-projection.map.ts function mapChatDisplayMessages(e, t) { let n; e.forEach((r, i) => { const a = t(r); if (a !== r) { n ??= e.slice(); n[i] = a; } }); return n ?? e; } //#endregion //#region src/gateway/chat-display-projection.history.ts function isSubagentCoordinationHistoryInput(e, t) { if (e.role !== "user") return false; const n = normalizeInputProvenance(e.provenance); if (isSubagentCoordinationInputProvenance(n)) return true; return Boolean(n?.kind === "inter_session" && n.sourceTool === "sessions_send" && n.sourceSessionKey && t?.(n.sourceSessionKey)); } /** Keep coordination in the model transcript while projecting only human-facing outcomes. */ function createSubagentCoordinationHistoryProjection(e, t = { hiddenInputKeys: /* @__PURE__ */ new Set(), visibleInputKeys: /* @__PURE__ */ new Set(), visibleSteerRunIds: /* @__PURE__ */ new Set() }) { const { hiddenInputKeys: n, visibleInputKeys: r, visibleSteerRunIds: i } = t; return (t) => { e?.assertCurrent?.(); const a = t.map((t) => { const a = asOptionalRecord(t); if (!a) return t; const o = asOptionalRecord(a["__openclaw"]); if (isSubagentCoordinationHistoryInput(a, e?.isSubagentSession)) { const e = a.idempotencyKey ?? o?.idempotencyKey; if (typeof e === "string" && !o?.steerTargetRunId) n.add(e); return a.display === false ? a : { ...a, display: false }; } const s = readSessionTranscriptRunId(a); if (a.role === "user") { const e = a.idempotencyKey ?? o?.idempotencyKey; if (typeof e === "string") r.add(e); const n = o?.steerTargetRunId ?? s; if (typeof n === "string") i.add(n); return t; } if (a.display === false || isOpenClawDeliveryMirrorAssistantMessage(a)) return t; if ((a.role === "assistant" || a.role === "toolResult" || a.role === "custom") && s && !i.has(s) && (n.has(buildRunUserTurnIdempotencyKey(s)) || !r.has(buildRunUserTurnIdempotencyKey(s)) && e?.isSubagentRunMessage(s, typeof o?.seq === "number" ? o.seq : void 0))) return { ...a, display: false }; return t; }); e?.assertCurrent?.(); return a; }; } function readTtsSupplementMarker(e) { const t = asOptionalRecord(e.openclawTtsSupplement); if (!t) return; const n = normalizeOptionalString(t.textSha256); const r = normalizeOptionalString(t.spokenText); return n || r ? { textSha256: n, spokenText: r } : void 0; } function readAssistantTtsSupplementMarker(e) { const t = readTtsSupplementMarker(e); if (!t || asRoleContentMessage(e)?.role !== "assistant") return; const n = e.content; if (!Array.isArray(n)) return; let r = false; for (const e of n) { const t = asOptionalRecord(e); if (!t) continue; if (t.type !== "text") { r = true; continue; } const n = typeof t.text === "string" ? t.text.trim() : ""; if (n && n !== "Audio reply") return; } return r ? t : void 0; } /** Recognize stored supplements using the same display content as full history. */ function isAssistantTtsSupplementMessage(e) { const t = asOptionalRecord(e); return t !== void 0 && readAssistantTtsSupplementMarker(projectAssistantDisplayContent(t)) !== void 0; } function readTtsSupplementTargetText(e) { return asRoleContentMessage(e)?.role === "assistant" && !isProjectedForwardedMessage(e) && !readTtsSupplementMarker(e) ? extractProjectedText(e.content ?? e.text).trim() : ""; } function mergeTtsSupplementContent(e, t) { const n = Array.isArray(t.content) ? t.content.filter((e) => { const t = asOptionalRecord(e); return t !== void 0 && t.type !== "text"; }) : []; if (n.length === 0) return e; const r = e.content; if (Array.isArray(r)) return { ...e, content: [...r, ...n] }; const i = extractProjectedText(r ?? e.text).trim(); return { ...e, content: [...i ? [{ type: "text", text: i }] : [], ...n] }; } function mergeTtsSupplementMessages(e) { if (!e.some(readAssistantTtsSupplementMarker)) return e; const t = []; const n = []; const r = []; let i = false; for (const a of e) { const e = readAssistantTtsSupplementMarker(a); if (e) { let o = -1; for (let i = r.length - 1; i >= 0; i--) { const a = r[i]; if (!a) continue; const s = t[i] ??= readTtsSupplementTargetText(a); if (s && (e.textSha256 && (n[i] ??= createHash("sha256").update(s).digest("hex")) === e.textSha256 || e.spokenText && s === e.spokenText)) { o = i; break; } } if (o >= 0) { r[o] = mergeTtsSupplementContent(expectDefined(r[o], "merged entry at target index"), a); t[o] = n[o] = void 0; i = true; continue; } } r.push(a); } return i ? r : e; } function isSubagentAnnounceInterSessionUserMessage(e, t) { const n = normalizeInputProvenance(e.provenance); if (n?.kind === "inter_session" && (n.sourceTool === "subagent_announce" || n.sourceTool === "subagent_settle")) return true; const r = t ? t(e) : extractProjectedText(e.content ?? e.text); return typeof r === "string" && r.includes("[Inter-session message]") && r.includes("sourceTool=subagent_announce"); } function readChatHistoryRecordTimestampMs(e) { const t = asOptionalRecord(asOptionalRecord(e)?.["__openclaw"]); return asFiniteNumber(t?.recordTimestampMs) ?? asFiniteNumber(asOptionalRecord(e)?.timestamp); } function isPreSessionStartAssistantMessage(e, t) { const n = readChatHistoryRecordTimestampMs(e); return t !== void 0 && asOptionalRecord(e)?.role === "assistant" && n !== void 0 && n < t; } function createPreSessionStartAnnouncePairFilter(e) { let t = false; return (n) => { if (e === void 0 || n.length === 0) return n; let r = false; const i = []; for (const a of n) { if (t) { t = false; if (isPreSessionStartAssistantMessage(a, e)) { r = true; continue; } } const n = asOptionalRecord(a); if (n?.role === "user" && isSubagentAnnounceInterSessionUserMessage(n, extractChatHistoryBlockText)) { const n = readChatHistoryRecordTimestampMs(a); if (typeof n === "number" && n < e) { t = true; r = true; continue; } } i.push(a); } return r ? i : n; }; } function dropPreSessionStartAnnouncePairs(e, t) { return createPreSessionStartAnnouncePairFilter(t)(e); } function readPluginSteeringId(e) { const t = asOptionalRecord(e); if (t?.role !== "user") return; const n = normalizeInputProvenance(t.provenance); const r = n?.sourceTool; return n?.kind === "internal_system" && r?.startsWith("plugin:") ? r.slice(7).trim() || void 0 : void 0; } /** Plugin input stays canonical and hidden; only the Control UI requests this display copy. */ function projectPluginSteeringMessage(e) { const t = readPluginSteeringId(e); if (!t) return e; const n = asOptionalRecord(e["__openclaw"]); const r = asOptionalRecord(n?.pluginSteering); const i = typeof r?.displayText === "string" ? r.displayText : void 0; return { ...e, display: true, ...i === void 0 ? {} : { content: [{ type: "text", text: i }], text: i }, __openclaw: { ...n, pluginSteering: { pluginId: t, ...typeof r?.pluginName === "string" ? { pluginName: r.pluginName } : {} } } }; } function isDisplayHiddenProjectedMessage(e) { if (e.display === false) return true; return isOpenClawRuntimeContextCustomMessage(e); } function shouldHideProjectedHistoryMessage(e, t, n) { if (isDisplayHiddenProjectedMessage(e)) return true; if (isProjectedForwardedMessage(e)) return false; if (!t) return false; const r = normalizeInputProvenance(e.provenance); if (t.role === "user" && r?.kind === "internal_system" && (r.sourceTool === "exec" || r.sourceTool === "cron_failure_repair" || r.sourceTool === "tool_handoff")) return true; if (t.role === "user" && isCronExecutionInputProvenance(r)) return true; if (t.role === "user" && isCompletionReportInputProvenance(e.provenance)) return true; if (t.role === "user" && isSubagentAnnounceInterSessionUserMessage(e)) return true; if (t.role === "user" && isEmptyTextOnlyContent(e.content ?? e.text) && !hasTranscriptMediaFacts(e)) return true; if (t.role === "assistant" && (isEmptyTextOnlyContent(e.content ?? e.text) || hasAssistantNonTextContent(e) && !extractAssistantTextForSilentCheck(e)?.trim())) return false; return n || isHeartbeatOkResponse(t); } /** Identifies the hidden native input that starts a heartbeat-driven turn. */ function isHeartbeatHistoryTurnBoundaryMessage(e) { const t = asOptionalRecord(e); if (!t || isForwardedUserMessage(t)) return false; const n = asRoleContentMessage(t); return n?.role === "user" && isHeartbeatUserMessage(n, HEARTBEAT_PROMPT); } /** Hidden heartbeat or exec input that must keep the next reply in its own turn. */ function isProjectedHistoryTurnBoundaryMessage(e) { if (isHeartbeatHistoryTurnBoundaryMessage(e)) return true; const t = asOptionalRecord(e); if (!t || isForwardedUserMessage(t)) return false; const n = asRoleContentMessage(t); const r = normalizeInputProvenance(t.provenance); return n?.role === "user" && r?.kind === "internal_system" && r.sourceTool === "exec"; } function attachProjectedTurnBoundary(e) { const t = asOptionalRecord(e["__openclaw"]); if (t?.turnBoundary === true) return e; return { ...e, __openclaw: { ...t, turnBoundary: true } }; } function canCarryProjectedTurnBoundary(e) { return Boolean(e && e.role !== "system" && e.role !== "custom"); } function openclawAssistantModel(e) { return e.role === "assistant" && e.provider === "openclaw" && typeof e.model === "string" ? e.model : void 0; } function displayTextForDuplicateCheck(e) { const t = extractProjectedText(e.content ?? e.text).trim(); return t ? t : void 0; } function isDuplicateAssistantDelivery(e, t) { if (!t) return false; if (!(openclawAssistantModel(t) === "acp-runtime" && openclawAssistantModel(e) === "gateway-injected")) { const n = asOptionalRecord(e.openclawDeliveryMirror); if (!isOpenClawDeliveryMirrorAssistantMessage(e) || n?.kind !== "channel-final" || asRoleContentMessage(t)?.role !== "assistant" || isOpenClawDeliveryMirrorAssistantMessage(t) || isProjectedForwardedMessage(t)) return false; const r = asOptionalRecord(t["__openclaw"]); if (typeof n.sourceAssistantMessageId === "string") { if (!n.sourceAssistantMessageId || n.sourceAssistantMessageId !== r?.id || hasAssistantDisplayableNonTextContent(t) || hasAssistantNonTextContent(e) || hasTranscriptMediaFacts(t) || hasTranscriptMediaFacts(e)) return false; const i = extractAssistantPhaseText(t)?.trim(); const a = extractAssistantPhaseText(e)?.trim(); return Boolean(i && a && i === a); } if (typeof r?.mirrorIdentity !== "string" || !r.mirrorIdentity.trim()) return false; } if (hasAssistantNonTextContent(t) || hasAssistantNonTextContent(e)) return false; const n = displayTextForDuplicateCheck(t); const r = displayTextForDuplicateCheck(e); return Boolean(n && r && n === r); } function toProjectedMessages(e) { return e.flatMap((e) => { const t = asOptionalRecord(e); return t ? [projectAssistantDisplayContent(t)] : []; }); } function filterVisibleProjectedHistoryMessages(e, t = false) { if (e.length === 0) return { messages: e, turnBoundaryPending: t }; let n = t; let r = false; const i = []; const a = /* @__PURE__ */ new Map(); for (let t = 0; t < e.length; t++) { const o = e[t]; if (!o) continue; const s = asRoleContentMessage(o); const c = Boolean(s && isHeartbeatUserMessage(s, HEARTBEAT_PROMPT)); const l = c ? e[t + 1] : void 0; const u = l ? asRoleContentMessage(l) : null; if (l && u && isHeartbeatOkResponse(u, void 0, Boolean(s && isHeartbeatUserMessage(s, HEARTBEAT_PROMPT, { heartbeatOnly: true }))) && !isProjectedForwardedMessage(l)) { r = true; n = true; t++; continue; } if (shouldHideProjectedHistoryMessage(o, s, c)) { r = true; n ||= isProjectedHistoryTurnBoundaryMessage(o); continue; } const d = asOptionalRecord(o.openclawDeliveryMirror)?.sourceAssistantMessageId; if (isDuplicateAssistantDelivery(o, typeof d === "string" ? a.get(d) : e[t - 1])) { r = true; continue; } if (n && s?.role === "user" && userMessageStartsDisplayTurn(o)) { n = false; i.push(o); } else if (n && canCarryProjectedTurnBoundary(s)) { i.push(attachProjectedTurnBoundary(o)); n = false; r = true; } else i.push(o); const f = asOptionalRecord(o["__openclaw"])?.id; if (s?.role === "assistant" && typeof f === "string") a.set(f, o); } return { messages: r ? i : e, turnBoundaryPending: n }; } function stripPromptPrefixFromContent(e, t) { if (typeof e === "string") return t(e); if (!Array.isArray(e)) return e; return e.map((e) => { if (!e || typeof e !== "object" || Array.isArray(e)) return e; const n = e; if (typeof n.text !== "string") return e; const r = t(n.text); return r === n.text ? e : { ...n, text: r }; }); } function readForwardedSender(e) { const t = normalizeInputProvenance(e.provenance); const n = t?.sourceSessionKey; const r = parseAgentSessionKey(n); return { sourceSessionKey: n, agentId: r?.agentId, jobId: isCronRunMessage(e) ? t?.jobId : r?.rest.match(/^cron:([^:]+):run:[^:]+$/u)?.[1] }; } function resolveForwardedSenderSession(e, t) { const { sourceSessionKey: n, agentId: r, jobId: i } = readForwardedSender(e); const a = i ? t(i) ?? "Automation" : void 0; return n ? { sessionKey: n, ...r ? { agentId: r } : {}, ...a ? { label: a } : {} } : void 0; } function readForwardedCronJobIds(e) { return e.flatMap((e) => { const t = asOptionalRecord(e); if (!t || !isForwardedUserMessage(t) && !isProjectedForwardedMessage(t)) return []; const n = readForwardedSender(t).jobId; return n ? [n] : []; }); } function projectForwardedMessages(e, t) { const n = t ?? (() => { throw new Error("Cron job names must be prepared before projecting forwarded messages"); }); const r = /* @__PURE__ */ new Map(); const resolveName = (e) => { if (!r.has(e)) r.set(e, n(e)); return r.get(e); }; return mapChatDisplayMessages(e, (e) => { if (!isForwardedUserMessage(e) && !isProjectedForwardedMessage(e)) return e; const t = resolveForwardedSenderSession(e, resolveName); if (e.role === "assistant") { if (asOptionalRecord(e.senderSession)?.label === t?.label) return e; return { ...e, senderSession: t, senderLabel: `Forwarded from ${t?.label ?? t?.agentId}` }; } const n = isCronRunMessage(e); const r = normalizeInputProvenance(e.provenance)?.sourcePromptPrefix; const i = n ? (e) => r && e.startsWith(r) ? e.slice(r.length).replace(/^ /u, "") : e : stripInterSessionPromptPrefixForDisplay; const a = { ...e, role: "assistant", ...n ? { __openclaw: { ...asOptionalRecord(e["__openclaw"]), turnBoundary: true } } : {}, senderLabel: t?.label || t?.agentId ? `Forwarded from ${t.label ?? t.agentId}` : "Forwarded agent message", ...t ? { senderSession: t } : {} }; if ("content" in a) a.content = stripPromptPrefixFromContent(a.content, i); if (typeof a.text === "string") a.text = i(a.text); return a; }); } //#endregion export { isAssistantTtsSupplementMessage as a, isSubagentCoordinationHistoryInput as c, projectPluginSteeringMessage as d, readForwardedCronJobIds as f, mapChatDisplayMessages as h, filterVisibleProjectedHistoryMessages as i, mergeTtsSupplementMessages as l, toProjectedMessages as m, createSubagentCoordinationHistoryProjection as n, isPreSessionStartAssistantMessage as o, readPluginSteeringId as p, dropPreSessionStartAnnouncePairs as r, isProjectedHistoryTurnBoundaryMessage as s, createPreSessionStartAnnouncePairFilter as t, projectForwardedMessages as u };