UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

418 lines (417 loc) • 17.2 kB
import { i as asOptionalObjectRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as memoizeFrozenPlainDataProjection } from "./immutable-data-Y7xVjZoy.mjs"; import { Et as _enum, Fn as object, Jn as string, Lt as boolean, Nt as array, xn as literal } from "./schemas-Cy6abvsu.mjs"; import { d as runWithSessionSourceScope } from "./session-source-authority-TlTpfRVE.mjs"; import { c as RUNTIME_CONTEXT_END_MARKER, f as hasLegacyRuntimeContextEnvelope, o as RUNTIME_CONTEXT_BEGIN_MARKER } from "./types-iq-cNLsd.mjs"; import { r as stripToolResultDetails } from "./model-context-message-DOWMZ3wz.mjs"; import { h as hasPersistedMedia, m as MEDIA_ONLY_USER_TEXT } from "./chat-message-content-DNUdbbJ8.mjs"; import { r as INTER_SESSION_PROMPT_PREFIX_BASE } from "./input-provenance-DupvvURj.mjs"; import { r as isOpenClawSystemUpdateMessage } from "./operator-messages-B9HgXnnQ.mjs"; import { g as stripHistoricalRuntimeContextCustomMessages, m as retainRuntimeContextMessageForPrompt, p as resolveRuntimeContextPromptOwner, r as OPENCLAW_RUNTIME_CONTEXT_CUSTOM_TYPE, s as escapeInternalRuntimeContextDelimiters, u as projectRuntimeContextFragments } from "./internal-runtime-context-BEUlDNuI.mjs"; import { d as projectRecordedModelPrompt, f as readModelPromptProjection, r as buildLateMediaAttachedProjection } from "./session-transcript-rewrite-effects-BVKR4US3.mjs"; import "./user-turn-transcript-CQTz-i5Y.mjs"; import { n as isTextContentBlock } from "./content-blocks-DgfxPwgj.mjs"; import { a as resolveUserTimezone } from "./date-time-ChxDjIEM.mjs"; import { r as formatZonedTimestamp } from "./format-datetime-B-weOzaQ.mjs"; import { c as materializeSteeringRuntimeContext } from "./runtime-context-prompt-CRmsG0oC.mjs"; import { v as bindModelPromptProjectionAppend } from "./session-manager-DuaaMI5O.mjs"; import "./session-transcript-repair-DDBSgN6b.mjs"; import { t as normalizeAssistantReplayContent } from "./replay-history-generic-mEncANYP.mjs"; import { a as resolveUserTranscriptMessages, i as projectPersistedSenderContext, n as findActiveUserMessageIndex, r as hasNonBlankUserText, t as contentMatchesTimestampOverride } from "./attempt-history-BBUKwFe-.mjs"; import { PROVIDER_CONTEXT_HANDOFF } from "@openclaw/ai/provider-types"; //#region src/gateway/server-methods/agent-timestamp.ts const CRON_TIME_MARKER = "Current time: "; const TIMESTAMP_ENVELOPE_PATTERN = /^\[.*\d{4}-\d{2}-\d{2} \d{2}:\d{2}/; /** Stamp historical messages with their own arrival time; return undefined for invalid zones. */ function buildTimestampPrefix(e, t) { const n = formatZonedTimestamp(e, { timeZone: t?.timezone ?? "UTC", displayWeekday: true }); return n ? `[${n}] ` : void 0; } /** CLI prompts need a clock; embedded messages are stamped once at the LLM boundary. */ function injectTimestamp(e, t) { if (!e.trim() || TIMESTAMP_ENVELOPE_PATTERN.test(e) || e.includes(CRON_TIME_MARKER)) return e; const n = buildTimestampPrefix(t?.now ?? /* @__PURE__ */ new Date(), t); return n ? `${n}${e}` : e; } function timestampOptsFromConfig(e) { return { timezone: resolveUserTimezone(e.agents?.defaults?.userTimezone) }; } //#endregion //#region src/agents/embedded-agent-runner/run/attempt-llm-boundary.ts const runtimeContextDetailsSchema = object({ source: literal("openclaw-runtime-context"), runtimeContextCarrier: literal(true), fragments: array(object({ kind: _enum([ "runtime-instruction", "conversation-data", "heartbeat-outcome" ]), text: string() })) }); const systemUpdateDetailsSchema = object({ kind: _enum(["prompt-update", "runtime-context"]), turnScoped: boolean() }); /** A session keeps its model projection across replay and process restarts. */ function usesEscapedRuntimeContext(e) { if (e === void 0 || e === 3) return false; if (e === 4) return true; throw new Error(`Unsupported session prompt projection version: ${e}`); } const runtimeContextProjections = [false, true].map((e) => [false, true].map((t) => memoizeFrozenPlainDataProjection((n) => { if (n.role === "custom" && isOpenClawSystemUpdateMessage(n)) { const e = systemUpdateDetailsSchema.safeParse(n.details); if (e.success) { const r = { role: "user", content: n.content, timestamp: n.timestamp }; if (t) r.operatorMessage = { turnScoped: e.data.turnScoped }; return r; } } if (!e || n.role === "user" && n.operatorMessage) return n; if (n.role === "custom" && n.customType === OPENCLAW_RUNTIME_CONTEXT_CUSTOM_TYPE) { const e = runtimeContextDetailsSchema.safeParse(n.details); if (e.success) { const t = projectRuntimeContextFragments(e.data.fragments); return { ...n, content: typeof n.content === "string" && hasLegacyRuntimeContextEnvelope(n.content) ? `${RUNTIME_CONTEXT_BEGIN_MARKER}\n${t}\n${RUNTIME_CONTEXT_END_MARKER}` : t, details: e.data }; } } if (n.role !== "user" && n.role !== "custom") return n; const r = n.content; const i = transformUserTextContent(r, (e) => { const t = escapeInternalRuntimeContextDelimiters(e); return t === e ? void 0 : t; }); return i === r ? n : Object.assign({}, n, { content: i }); }))); function projectRuntimeContextMessages(e, t) { const n = runtimeContextProjections[Number(usesEscapedRuntimeContext(t?.sessionVersion))][Number(Boolean(t?.inHistorySystemUpdates))]; return e.map(n); } const BOUNDARY_TIMESTAMP_ENVELOPE_RE = /^\[.*\d{4}-\d{2}-\d{2} \d{2}:\d{2}/; const BOUNDARY_CRON_TIME_MARKER = "Current time: "; function normalizeMessagesForLlmBoundary(e, t) { const n = stripUnsafeBlockedRunMetadata(stripToolResultDetails(normalizeAssistantReplayContent(materializeSteeringRuntimeContext(e)))); const r = resolveUserTranscriptMessages(n, t?.userTranscriptContexts, t?.currentUserTimestampOverride); const i = normalizeUserMessagesForLlmBoundary(n.map((e, t) => projectRecordedModelPrompt(e, r?.[t])), t); const a = t?.projectPersistedSenderContext === false ? i : projectPersistedSenderContext(i, r); const o = t?.appendOnlyRuntimeContext || t?.inHistorySystemUpdates ? a : stripHistoricalRuntimeContextCustomMessages(a, t?.currentUserIdempotencyKey); if (o.length < a.length) { const e = new Set(o); t?.onRuntimeContextCarrierRemoved?.(a.filter((t) => !e.has(t))); } return projectRuntimeContextMessages(o, t); } /** Normalizes existing transcript messages as if the current prompt were appended last. */ function normalizeMessagesForCurrentPromptBoundary(e) { const { message: t, options: n } = buildCurrentPromptBoundaryInput(e); const r = normalizeMessagesForLlmBoundary([...e.messages, t], n); r.pop(); return r; } function normalizeCurrentPromptTextForLlmBoundary(e) { const { message: t, options: n } = buildCurrentPromptBoundaryInput(e); const [r] = normalizeMessagesForLlmBoundary([t], n); const i = r?.content; return typeof i === "string" ? i : e.prompt; } function buildCurrentPromptBoundaryInput(e) { const t = { role: "user", content: [{ type: "text", text: e.prompt }], timestamp: e.currentUserTimestamp ?? Date.now() }; return { message: t, options: { sessionVersion: e.sessionVersion, appendOnlyRuntimeContext: e.appendOnlyRuntimeContext, inHistorySystemUpdates: e.inHistorySystemUpdates, currentUserIdempotencyKey: e.currentUserIdempotencyKey, ...e.timezone ? { timezone: e.timezone } : {}, ...e.includeTimestamp === false ? { includeTimestamp: false } : {}, ...e.currentUserTranscriptMessage ? { userTranscriptContexts: [{ runtimeMessage: t, transcriptMessage: e.currentUserTranscriptMessage }] } : {} } }; } /** * Temporarily injects a runtime-context message for prompt conversion and retry. * Cleanup restores the original prompt/continuation hooks and removes only * the injected message object. */ function installRuntimeContextMessageForPrompt(e) { const { message: t, session: n } = e; if (!t) return () => void 0; const r = retainRuntimeContextMessageForPrompt(t); let i = false; const install = (a) => { if (i) return; const o = n.messages; if (o.includes(t)) return; const s = r.transcriptUser ?? r.user; const c = asOptionalObjectRecord(s)?.idempotencyKey; const l = r.transcriptUser === void 0 ? e.persistedUserIdempotencyKey ?? c : c; const u = l ? o.findIndex((e) => e.role === "user" && Reflect.get(e, "idempotencyKey") === l) : r.user ? o.findIndex((e) => e === r.user || e === r.transcriptUser) : a ? findActiveUserMessageIndex(o) : -1; if (a && u < 0) return; const d = u < 0 ? o.length : u; n.agent.state.messages = [ ...o.slice(0, d), t, ...o.slice(d) ]; }; install(false); const a = n.agent; const o = a.transformContext; a.transformContext = async (e, t) => { r.user ??= e[resolveRuntimeContextPromptOwner(e)?.userIndex ?? -1]; return o ? await o.call(a, e, t) : e; }; const s = a.prompt; if (s) { const e = s.bind(a); a.prompt = function promptWithRuntimeContext(t, n) { install(false); return typeof t === "string" ? e(t, n) : e(t); }; } const c = a.continue; if (c) { const e = c.bind(a); a.continue = function continueWithRuntimeContext() { install(true); return e(); }; } return () => { i = true; r.release(); a.transformContext = o; if (s) a.prompt = s; if (c) a.continue = c; n.agent.state.messages = n.messages.filter((e) => e !== t); }; } function transformUserTextContent(e, t) { if (typeof e === "string") return t(e) ?? e; let n = false; const r = Array.isArray(e) ? e.map((e) => { const r = isTextContentBlock(e) ? t(e.text) : void 0; if (r === void 0) return e; n = true; return Object.assign({}, e, { text: r }); }) : e; return n ? r : e; } /** The model-facing text of a prompt before any recorded projection. */ function resolveModelPromptText(e) { if (e.modelPrompt?.trim() && e.text === e.transcriptPrompt) return e.modelPrompt; return [ e.prependContext, e.text, e.appendContext ].filter((e) => Boolean(e?.trim())).join("\n\n"); } /** Capture the admitted prompt once; every later request reads the same transcript field. */ function installModelPromptProjection(e) { if (!e.recorder?.captureModelPromptProjection && (!e.modelPrompt?.trim() || e.modelPrompt === e.transcriptPrompt) && !e.prependContext?.trim() && !e.appendContext?.trim()) return () => {}; const t = e.session.agent; const n = t.transformContext; let r; let i; const resolveProjection = async (t, n) => { if (!e.shouldCapturePrompt()) return; await e.recorder?.waitForRuntimePersistence(); n(); const a = e.recorder?.getPersistedMessage?.(); if (!r) { const n = resolveRuntimeContextPromptOwner(t); const o = a?.idempotencyKey; const s = e.getUserTranscriptContexts?.()?.find(({ transcriptMessage: e }) => e === a || o && Reflect.get(e, "idempotencyKey") === o)?.runtimeMessage; r = e.recorder ? t.find((e) => e === s || e === a || o && e.role === "user" && Reflect.get(e, "idempotencyKey") === o) : t[n?.userIndex ?? findActiveUserMessageIndex(t)]; i = n?.owner; } const o = a ?? i?.transcriptUser ?? r; const s = asOptionalObjectRecord(o)?.idempotencyKey; const c = t.find((e) => e === r || e === o || s && e.role === "user" && Reflect.get(e, "idempotencyKey") === s); if (c?.role !== "user") return; const l = typeof c.content === "string" ? c.content : c.content.find(isTextContentBlock)?.text; const u = readModelPromptProjection(c); const d = readModelPromptProjection(o) ?? u; let f = d ?? (l === void 0 ? void 0 : resolveModelPromptText({ ...e, text: l })); if (d === void 0 && f !== void 0 && l?.startsWith("[Inter-session message]") === true && !f.includes(l)) f = l; if (f === void 0 || !(d !== void 0 || f !== l || e.recorder?.captureModelPromptProjection && !l?.startsWith("[Inter-session message]"))) return; return { target: c, targetProjection: u, frozen: d, text: f }; }; const a = e.carrier && e.recorder?.prepareModelPromptProjection ? bindModelPromptProjectionAppend(e.carrier, () => runWithSessionSourceScope(e.assertCurrent, async () => { const assertCurrent = () => e.assertCurrent?.(); const n = await resolveProjection(t.state?.messages ?? [], assertCurrent); return n && n.frozen === void 0 ? e.recorder?.prepareModelPromptProjection?.(n.text, assertCurrent) : void 0; }, { checkAfter: false })) : void 0; t.transformContext = async (r, i) => runWithSessionSourceScope(e.assertCurrent, async () => { let a = r; const assertCurrent = () => { i?.throwIfAborted(); e.assertCurrent?.(); }; const o = await resolveProjection(r, assertCurrent); if (o) { const { target: n, targetProjection: i, frozen: s } = o; let { text: c } = o; const l = e.recorder?.captureModelPromptProjection; if (s === void 0 && l) { const capture = () => l(c, assertCurrent); const t = await (e.withTranscriptWrite ? e.withTranscriptWrite(capture) : capture()); assertCurrent(); const n = readModelPromptProjection(t); if (n === void 0) throw new Error("Transcript recorder did not capture the model prompt projection"); c = n; } if (i !== c) { const e = { ...n, __openclaw: { ...asOptionalObjectRecord(Reflect.get(n, "__openclaw")), modelPromptProjection: { version: 1, text: c } } }; a = r.map((t) => t === n ? e : t); if (t.state) t.state.messages = t.state.messages.map((t) => t === n ? e : t); } } return n ? await n.call(t, a, i) : a; }, { checkAfter: false }); return () => { a?.(); t.transformContext = n; }; } function canonicalizeTextOnlyUserContent(e) { if (!Array.isArray(e) || e.length !== 1) return e; const t = e[0]; return isTextContentBlock(t) ? t.text : e; } function stampUserTextWithMessageTimestamp(e, t, n, r) { if (r === false || !n || !e.trim() || BOUNDARY_TIMESTAMP_ENVELOPE_RE.test(e) || e.includes(BOUNDARY_CRON_TIME_MARKER) || e.startsWith("[Inter-session message]") || typeof t !== "number" || !Number.isFinite(t)) return e; const i = buildTimestampPrefix(new Date(t), { timezone: n }); return i ? `${i}${e}` : e; } function messageRuntimeTimestampMatchesCurrentUserOverride(e, t) { if (typeof t.runtimeTimestamp === "number") return e === t.runtimeTimestamp; if (typeof e === "number" && Number.isFinite(e)) t.runtimeTimestamp = e; return true; } function normalizeUserMessagesForLlmBoundary(e, t) { const n = findActiveUserMessageIndex(e); const r = resolveRuntimeContextPromptOwner(e); const i = r?.userIndex ?? -1; if (r) r.owner.transcriptUser = t?.userTranscriptContexts?.find((e) => e.runtimeMessage === r.owner.user)?.transcriptMessage ?? r.owner.transcriptUser; let a = false; const o = e.map((e, r) => { if (e.role !== "user" || e.operatorMessage) return e; const o = e.content; const s = !hasNonBlankUserText(o) && hasPersistedMedia(e); const c = r === n || i >= 0 && r >= i; const l = t?.currentUserTimestampOverride; const u = e.timestamp; const d = l !== void 0 && (c || typeof l.runtimeTimestamp === "number" && l.runtimeTimestamp === u) && contentMatchesTimestampOverride(o, l) && messageRuntimeTimestampMatchesCurrentUserOverride(u, l) ? l.timestamp : u; const transformText = (n) => { return stampUserTextWithMessageTimestamp(s && !n.trim() ? buildLateMediaAttachedProjection(e).text ?? "[User sent media without caption]" : n, d, t?.timezone, t?.includeTimestamp); }; let f = false; let p = transformUserTextContent(canonicalizeTextOnlyUserContent(o), (e) => { const t = f ? e : transformText(e); f = true; return t === e ? void 0 : t; }); if (Array.isArray(p) && !f && s) { const e = p.slice(); e.unshift({ type: "text", text: transformText("") }); p = e; } if (p === o) return e; a = true; return { ...e, content: p }; }); return a ? o : e; } function stripUnsafeBlockedRunMetadata(e) { let t = false; const n = e.map((e) => { const n = asOptionalObjectRecord(Reflect.get(e, "__openclaw")); const r = asOptionalObjectRecord(n?.beforeAgentRunBlocked); if (!r) return e; const i = {}; if (typeof r.blockedBy === "string") i.blockedBy = r.blockedBy; if (typeof r.blockedAt === "number") i.blockedAt = r.blockedAt; const a = { ...n, beforeAgentRunBlocked: i }; t = true; return Object.assign({}, e, { __openclaw: a }); }); return t ? n : e; } //#endregion //#region src/agents/embedded-agent-runner/run/message-transform-stream-wrapper.ts function wrapStreamFnWithMessageTransform(e, t, n) { return (r, i, a) => { const o = i.messages; const s = t(o, r); const c = s !== o ? { ...i, messages: s } : i; if (!n) return e(r, c, a); let l; const handoff = async () => { a?.signal?.throwIfAborted(); return l ??= n({ context: c, signal: a?.signal }); }; return e(r, c, { ...a, [PROVIDER_CONTEXT_HANDOFF]: handoff }); }; } //#endregion export { normalizeMessagesForCurrentPromptBoundary as a, usesEscapedRuntimeContext as c, normalizeCurrentPromptTextForLlmBoundary as i, injectTimestamp as l, installModelPromptProjection as n, normalizeMessagesForLlmBoundary as o, installRuntimeContextMessageForPrompt as r, resolveModelPromptText as s, wrapStreamFnWithMessageTransform as t, timestampOptsFromConfig as u };