UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

284 lines (283 loc) • 9.84 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs"; import { l as makeZeroUsageSnapshot } from "./usage-CHLnzpJG.mjs"; import { i as resolveSessionWorkStartError } from "./session-work-start-CFJs8WNp.mjs"; import { X as captureSessionTarget } from "./session-controller.state-BApgK0mV.mjs"; import { i as hasReplyChannelData } from "./payload-Cab4FCxl.mjs"; import { o as copyReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs"; import { o as mediaKindFromMime } from "./constants-ChkaB-HW.mjs"; import { o as isAudioFileName, u as mimeTypeFromFilePath } from "./mime-D2wVBzpa.mjs"; import { l as withSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs"; import { t as OPENCLAW_TRANSCRIPT_ARTIFACT_PROVIDER } from "./transcript-model-DRGmnGZ9.mjs"; import { r as readAssistantDisplayContent, t as ASSISTANT_DISPLAY_CONTENT_FIELD } from "./assistant-display-content-CBuMU4m5.mjs"; import { i as OPENCLAW_TRANSCRIPT_ARTIFACT_API, t as AUTOMATION_RESULT_MODEL } from "./transcript-only-openclaw-assistant-BeEOZfu4.mjs"; import { a as persistSessionTranscriptTurn, c as findTranscriptEvent } from "./session-accessor-CizTbDQj.mjs"; import { i as runSessionMutation } from "./session-controller.lifecycle-C_Z3sybN.mjs"; import { g as readTranscriptEventMessage, h as readTranscriptEventId } from "./session-accessor.sqlite-read-DA1Bsaij.mjs"; import "./lifecycle-BFcckgci.mjs"; import { o as resolveMirroredTranscriptText } from "./transcript-CbrBMDcL.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import { t as collectReplyMediaEntries } from "./reply-media-entries-BE-R1jqq.mjs"; import { c as projectOutboundPayloadPlanForMirror, r as createStructuredOutboundPayloadPlan, u as resolveOutboundPayloadMirrorText } from "./payloads-CQvywZOF.mjs"; import { n as attachManagedOutgoingMediaToMessage, u as removeManagedOutgoingMediaBlocks } from "./managed-image-attachments-DSFNBym_.mjs"; import { a as hasManagedOutgoingAssistantContent, i as hasAssistantDisplayMediaContent, t as buildAssistantReplyContent } from "./chat-assistant-content-CmiwVcNn.mjs"; import { a as prepareWebchatReplyMediaForDisplay, n as captureWebchatReplyMediaScope } from "./chat-reply-media-Cjx1PVof.mjs"; //#region src/sessions/background-session-result.ts /** Appends a background result without waiting for the target conversation's active turn. */ async function commitBackgroundResultToSession(e) { const t = normalizeOptionalString(e.sessionKey); const n = normalizeOptionalString(e.text); const r = normalizeOptionalString(e.idempotencyKey); if (!t || !n || !r) return { ok: false, reason: "background session result is missing required data" }; const i = resolveSessionStorePathCore(e.config.session?.store, { agentId: e.agentId }); e.assertCurrent?.(); return await runSessionMutation({ diagnosticLabel: "background-result", kind: "background-result", target: captureSessionTarget({ storeScope: i, sessionKey: t, agentId: e.agentId }), signal: e.signal, policy: "allow-live", run: async () => { e.assertCurrent?.(); return withSessionEntryReadOnlyInWorker({ agentId: e.agentId, sessionKey: t, storePath: i, readConsistency: "latest" }, () => { e.assertCurrent?.(); e.signal?.throwIfAborted(); }, async (a, o) => { if (!a.ok) throw a.error; const s = a.value; if (!s?.sessionId) return { ok: false, reason: `session deleted for sessionKey: ${t}` }; const c = s.sessionId; const l = resolveSessionWorkStartError(t, s, { expectedSessionId: c, purpose: "accepted-result-settlement" }); if (l) return { ok: false, reason: l }; const u = { agentId: e.agentId, sessionKey: t, sessionId: c, storePath: i }; const d = await findTranscriptEvent(u, { kind: "idempotency", key: r }); const f = d && readTranscriptEventMessage(d.event); const p = d && readTranscriptEventId(d.event); if (d && (!f || !p)) return { ok: false, reason: "background result transcript identity is unavailable" }; const m = f ? void 0 : (await e.prepareDisplayContent?.())?.map((e) => Object.assign({}, e)); const h = { role: "assistant", content: [{ type: "text", text: n }], ...m ? { [ASSISTANT_DISPLAY_CONTENT_FIELD]: m } : {}, api: OPENCLAW_TRANSCRIPT_ARTIFACT_API, provider: OPENCLAW_TRANSCRIPT_ARTIFACT_PROVIDER, model: AUTOMATION_RESULT_MODEL, usage: makeZeroUsageSnapshot(), stopReason: "stop", timestamp: Date.now(), idempotencyKey: r, ...e.provenance ? { openclawAutomation: e.provenance } : {} }; o.assertCurrent(); e.assertCurrent?.(); const g = await persistSessionTranscriptTurn(u, { cwd: s.spawnedCwd, expectedSessionId: c, expectedLifecycleRevision: s.lifecycleRevision ?? null, assertCurrent: () => { o.assertCurrent(); e.assertCurrent?.(); e.signal?.throwIfAborted(); }, messages: [{ message: f ? { ...f, content: h.content, ...e.provenance ? { openclawAutomation: e.provenance } : {} } : h, idempotencyLookup: "scan", ...p ? { eventId: p, predicate: { kind: "active-entry", entryId: p, errorMessage: "background result no longer owns the active transcript" } } : {} }], touchSessionEntry: true, sessionLifecyclePatch: { lastInteractionAt: h.timestamp }, updateMode: "inline", publishWhen: e.prepareDisplayContent ? "always" : void 0, config: e.config, onMessageCommitted: e.onMessageCommitted }); return g.messages[0] ? { ok: true } : { ok: false, reason: g.rejectedReason ?? "background result was not committed" }; }); } }); } //#endregion //#region src/sessions/background-result-payloads.ts /** * Commits shown payloads as one model-visible row with display media. * Native-only payloads have no honest text and are skipped with a diagnostic. */ async function commitBackgroundPayloadsToSession(e) { const t = e.payloads.map(toTranscriptPayload); const n = projectOutboundPayloadPlanForMirror(createStructuredOutboundPayloadPlan(t)); const r = resolveMirroredTranscriptText(n); if (!r) return t.some((e) => hasReplyChannelData(e.channelData)) ? { ok: true, skipped: true, diagnostics: "native-only payload not added to conversation" } : { ok: false, reason: "background result has no visible payload" }; let i; let a = false; try { return await commitBackgroundResultToSession({ agentId: e.agentId, sessionKey: e.sessionKey, text: r, prepareDisplayContent: async () => { i = await buildResultDisplayContent({ agentId: e.agentId, sessionKey: e.sessionKey, config: e.config, payloads: t, signal: e.signal, assertCurrent: e.assertCurrent }); return hasAssistantDisplayMediaContent(i) ? i : void 0; }, idempotencyKey: e.idempotencyKey, provenance: e.provenance, config: e.config, signal: e.signal, assertCurrent: e.assertCurrent, onMessageCommitted: (e, t) => { a = e.appended; const n = readAssistantDisplayContent(e.message); if (hasManagedOutgoingAssistantContent(n)) t(async () => { if (!await attachManagedOutgoingMediaToMessage({ messageId: e.messageId, blocks: n })) throw new Error("Result media ownership could not be persisted"); }); } }); } finally { if (!a && i) await removeManagedOutgoingMediaBlocks({ blocks: i, messageId: null }); } } function toTranscriptPayload(e) { const t = normalizeOptionalString(e.spokenText); if (!t) return e; return copyReplyPayloadMetadata(e, { ...e, text: t, spokenText: void 0, audioAsVoice: void 0, mediaUrl: void 0, mediaUrls: [e.mediaUrl, ...e.mediaUrls ?? []].filter((e) => Boolean(e) && !isAudioFileName(e)) }); } async function buildResultDisplayContent(e) { const t = /* @__PURE__ */ new Map(); const n = e.payloads.map((e) => { const n = []; const r = collectReplyMediaEntries(e).filter(({ url: r, attachment: i }) => { const a = i?.mimeType ?? mimeTypeFromFilePath(r); if (e.sensitiveMedia === true || mediaKindFromMime(a) !== "document") return true; if (!t.has(r)) { n.push(i?.name || r); t.set(r, { type: "attachment", attachment: { kind: "document", label: resolveMirroredTranscriptText({ mediaUrls: [i?.name || r] }), mimeType: a } }); } return false; }); const i = resolveOutboundPayloadMirrorText(e); return copyReplyPayloadMetadata(e, { ...e, text: n.length ? resolveMirroredTranscriptText({ text: i, mediaUrls: n }) ?? void 0 : i, mediaUrl: void 0, mediaUrls: r.map(({ url: e }) => e), attachments: r.map(({ attachment: e }) => e ?? {}) }); }); if (!n.some((e) => collectReplyMediaEntries(e).length > 0)) { const { assistantContent: r } = await buildAssistantReplyContent({ sessionKey: e.sessionKey, agentId: e.agentId, payloads: n, includeSensitiveMedia: false }); return [...r ?? [], ...t.values()]; } const r = await captureWebchatReplyMediaScope({ cfg: e.config, agentId: e.agentId, sessionKey: e.sessionKey, assertCurrent: e.assertCurrent }); try { const { assistantContent: i } = await prepareWebchatReplyMediaForDisplay({ scope: r, inputs: n.map((e) => ({ kind: "raw", payload: e })), abortSignal: e.signal, includeSensitiveMedia: false, logGateway: { warn: (e) => logWarn(e) } }); return [...i ?? [], ...t.values()]; } finally { r.release(); } } //#endregion export { commitBackgroundPayloadsToSession as t };