UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

472 lines (471 loc) • 17.2 kB
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { o as writeRuntimeJson, s as writeRuntimeStdout } from "./runtime-B-SLYP-m.mjs"; import "./errors-BKzCeTYb.mjs"; import { _ as resolveDefaultAgentId, f as resolveAgentWorkspaceDir, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs"; import "./agent-scope-BwB8YH6y.mjs"; import { l as prepareSessionSourceScope, u as releaseSessionSourceAuthorities } from "./session-source-authority-TlTpfRVE.mjs"; import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs"; import { _ as normalizeSentMediaUrlsForDelivery } from "./chat-message-content-DNUdbbJ8.mjs"; import { t as getChannelPlugin } from "./registry-ByqVE5S3.mjs"; import { a as isInternalMessageChannel } from "./message-channel-DTYVLJT1.mjs"; import { u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs"; import { o as hasReplyPayloadContent } from "./payload-Cab4FCxl.mjs"; import { o as copyReplyPayloadMetadata, s as formatBtwTextForExternalDelivery } from "./reply-payload-k5WsQWxi.mjs"; import { t as CommandOwnerRevokedError } from "./command-owner-authority-BIUd20IP.mjs"; import "./plugins-BoMiRtiY.mjs"; import { a as isSessionWorkStartInvalidatedError, t as SESSION_WORK_START_INVALIDATED_ERROR_CODE } from "./work-start-error-DaHE71YG.mjs"; import "./lifecycle-BFcckgci.mjs"; import { t as createOutboundSendDeps } from "./outbound-send-deps-BV7tqdFC.mjs"; import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs"; import { i as formatOutboundPayloadLog, l as projectOutboundPayloadPlanForOutbound, o as projectOutboundPayloadPlanForDelivery, s as projectOutboundPayloadPlanForJson, t as createOutboundPayloadPlan } from "./payloads-CQvywZOF.mjs"; import { a as resolveResponsePrefixTemplate, r as normalizeReplyPayloadOutcome } from "./normalize-reply-C8AkGgUH.mjs"; import { n as isNestedAgentLane } from "./lanes-FWlQGbs4.mjs"; import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs"; import { a as formatUnknownChannelMessage } from "./error-format-O7EzXfiI.mjs"; import { l as resolvePendingFinalDeliveryCompletion, n as sendDurableMessageBatchCore } from "./send-C6MWAmk5.mjs"; import "./runtime-BgdHhvEU.mjs"; import { r as resolveMessageChannelSelection } from "./channel-selection-DBeuWpKq.mjs"; import { t as createReplyPrefixContext } from "./reply-prefix-BwGB0d8b.mjs"; import { r as createChannelReplyTransform } from "./reply-transform-VMjxflBU.mjs"; import { t as resolveAgentOutboundIdentity } from "./identity-DpbdIy02.mjs"; import { r as resolveAgentOutboundTarget, t as resolveAgentDeliveryPlanWithSessionRoute } from "./agent-delivery-U5Z9_Vg5.mjs"; import { a as selectSourceDeliverablePayloads, i as preDeliveryFailureStatus, n as deliveryStatusFromDurableSend, r as noVisiblePayloadStatus, t as buildDeliveryResult } from "./delivery-result-DjNqf0Pj.mjs"; import { i as resolveMessagingToolPayloadDedupe, r as hasEnabledDeliveryOperation, t as filterMessagingToolMediaDuplicates } from "./reply-payloads-dedupe-xQRy9T4a.mjs"; import { r as createReplyMediaPathNormalizer } from "./reply-media-paths-B3zuAx71.mjs"; //#region src/agents/command/delivery-authority.ts function createRestartOnlyAbortSignal(e) { if (!e) return { dispose: () => {} }; const t = new AbortController(); const onAbort = () => { if (isAgentRunRestartAbortReason(e.reason)) t.abort(e.reason); }; if (e.aborted) onAbort(); else e.addEventListener("abort", onAbort, { once: true }); return { signal: t.signal, dispose: () => e.removeEventListener("abort", onAbort) }; } function createAgentCommandDeliveryGuard(e, t) { let n; const release = async () => { const e = n; n = void 0; if (e) await releaseSessionSourceAuthorities([e]); }; const rethrowDeliveryError = (n) => { const r = isAgentRunRestartAbortReason(n) || isAgentRunRestartAbortReason(e.opts.abortSignal?.reason) && t?.commandOwnerReference != null && (n instanceof CommandOwnerRevokedError || isSessionWorkStartInvalidatedError(n) && n.code === "SESSION_WORK_START_INVALIDATED"); throw new PlatformMessageNotDispatchedError(n instanceof Error ? n.message : "Agent final delivery source check failed", { cause: n, retryable: r }); }; const assertCurrent = () => { try { if (n) n.assertCurrent(); else e.assertDeliveryCurrent?.(); } catch (e) { rethrowDeliveryError(e); } }; return Object.assign(assertCurrent, { prepare: async () => { await release(); try { n = await prepareSessionSourceScope(e.assertDeliveryCurrent); } catch (e) { rethrowDeliveryError(e); } assertCurrent(); }, release }); } //#endregion //#region src/agents/command/delivery.ts const UNRESOLVED_RESPONSE_PREFIX_VAR_PATTERN = /\{[a-zA-Z][a-zA-Z0-9.]*\}/; async function deliverAgentCommandResult(e) { e.assertDeliveryCurrent?.(); const { cfg: t, deps: n, runtime: r, opts: i, outboundSession: a, sessionEntry: o, result: s } = e; const c = a?.key ?? i.sessionKey; const l = a?.agentId ?? resolveSessionAgentId({ sessionKey: c, config: t }) ?? resolveDefaultAgentId(t); const u = i.deliver === true; const d = u && e.payloads ? selectSourceDeliverablePayloads(e.payloads, i) : e.payloads; const f = u && i.sourceReplyDeliveryMode === "message_tool_only" && !d?.length; const p = f ? e.payloads : d; const m = u && !f; const h = i.bestEffortDeliver === true; const g = i.runContext?.messageChannel ?? i.messageChannel; const _ = i.runContext?.currentChannelId ?? i.to; const v = i.runContext?.accountId ?? i.accountId; const y = i.runContext?.currentThreadTs ?? i.threadId; const b = (i.replyChannel ?? i.channel)?.trim(); const resolveDeliveryRouting = async (n) => { const r = await resolveAgentDeliveryPlanWithSessionRoute({ cfg: t, agentId: l, currentSessionKey: c, sessionEntry: n, requestedChannel: i.replyChannel ?? i.channel, explicitTo: i.replyTo ?? i.to, explicitThreadId: i.threadId, accountId: i.replyAccountId ?? i.accountId, wantsDelivery: m, preparedPlugin: e.preparedPlugin, turnSourceChannel: g, turnSourceTo: _, turnSourceAccountId: v, turnSourceThreadId: y }); e.assertDeliveryCurrent?.(); let a = r.resolvedChannel; let o = r.plugin; if (m && isInternalMessageChannel(a) && !b) try { const n = await resolveMessageChannelSelection({ cfg: t }); e.assertDeliveryCurrent?.(); a = n.channel; o = n.plugin; } catch {} const s = m && !isInternalMessageChannel(a) ? o ?? getChannelPlugin(normalizeAnyChannelId(a) ?? a) : void 0; const u = isInternalMessageChannel(a) || Boolean(s); const d = i.deliveryTargetMode ?? r.deliveryTargetMode ?? (i.to ? "explicit" : "implicit"); const f = !r.resolvedAccountId && s?.config?.listAccountIds ? resolveChannelDefaultAccountId({ plugin: s, cfg: t }) : void 0; const p = r.resolvedAccountId ?? f; const h = m && u && a ? await resolveAgentOutboundTarget({ cfg: t, plan: { ...r, resolvedChannel: a, plugin: s ?? o, resolvedAccountId: p }, targetMode: d, validateExplicitTarget: true }) : { resolvedTarget: null, resolvedTo: r.resolvedTo, targetMode: d }; const x = r.resolvedThreadId ?? i.threadId; const S = s?.threading?.resolveReplyTransport?.({ cfg: t, accountId: p, threadId: x }) ?? null; return { deliveryChannel: a, deliveryPlugin: s, isDeliveryChannelKnown: u, defaultAccountId: f, resolvedAccountId: p, resolvedTarget: h.resolvedTarget, deliveryTarget: h.resolvedTo, resolvedReplyToId: S?.replyToId ?? void 0, resolvedThreadTarget: S && Object.hasOwn(S, "threadId") ? S.threadId ?? null : x ?? null }; }; const deliveryRoutingFailureReason = (e) => { if (!m) return; if (isInternalMessageChannel(e.deliveryChannel)) return "channel_resolved_to_internal"; if (!e.isDeliveryChannelKnown) return "unknown_channel"; if (e.resolvedTarget && !e.resolvedTarget.ok) return "invalid_delivery_target"; if (!e.deliveryTarget) return "no_delivery_target"; }; let x = await resolveDeliveryRouting(o); e.assertDeliveryCurrent?.(); const S = deliveryRoutingFailureReason(x); if (S && S !== "unknown_channel") { const t = await e.resolveFreshSessionEntryForDelivery?.(); e.assertDeliveryCurrent?.(); const n = (e.expectedSessionIdForFreshDelivery ?? o?.sessionId)?.trim(); if (t && t !== o && n && t.sessionId === n) { const n = await resolveDeliveryRouting(t); e.assertDeliveryCurrent?.(); if (!deliveryRoutingFailureReason(n)) { if (!i.json) r.log(`[delivery] refreshed session routing before final delivery (session=${c ?? "unknown"} channel=${n.deliveryChannel})`); x = n; } } } const { deliveryChannel: C, isDeliveryChannelKnown: w, defaultAccountId: T, resolvedAccountId: E, resolvedTarget: D, deliveryTarget: O, resolvedReplyToId: k, resolvedThreadTarget: A, deliveryPlugin: j } = x; let M = false; const logDeliveryError = (e) => { M = true; const t = `Delivery failed (${C}${O ? ` to ${O}` : ""}): ${String(e)}`; r.error(t); }; let N; let P; const handlePreDeliveryError = (e, t) => { P = preDeliveryFailureStatus(t); if (!h) { if (i.json) { N = e; return; } throw e; } logDeliveryError(e); }; if (m) { if (isInternalMessageChannel(C)) handlePreDeliveryError(/* @__PURE__ */ new Error("delivery channel is required: pass --channel/--reply-channel or use a main session with a previous channel"), "channel_resolved_to_internal"); else if (!w) handlePreDeliveryError(new Error(formatUnknownChannelMessage({ channel: C })), "unknown_channel"); else if (D && !D.ok) handlePreDeliveryError(D.error, "invalid_delivery_target"); } const normalizeReplyPayloads = (e, n = true) => { const r = e ?? []; if (r.length === 0) return { kind: "suppress", reason: "empty" }; const o = C && !isInternalMessageChannel(C) ? normalizeAnyChannelId(C) ?? C : void 0; if (!o) return { kind: "deliver", payload: r }; const c = m ? j : void 0; const l = a?.key ?? i.sessionKey; const u = a?.agentId ?? resolveSessionAgentId({ sessionKey: l, config: t }); const d = createReplyPrefixContext({ cfg: t, agentId: u, channel: o, accountId: E }); const f = s.meta.agentMeta?.model; const p = s.meta.agentMeta?.provider; if (n && p && f) d.onModelSelected({ provider: p, model: f, thinkLevel: void 0 }); const h = d.responsePrefixContextProvider(); const g = resolveResponsePrefixTemplate(d.responsePrefix, h); const _ = !n && g && UNRESOLVED_RESPONSE_PREFIX_VAR_PATTERN.test(g) ? void 0 : d.responsePrefix; const v = c?.messaging; const y = createChannelReplyTransform({ messaging: v, cfg: t, accountId: E }); const b = []; let x; for (const e of r) { const t = normalizeReplyPayloadOutcome(e, { responsePrefix: _, applyChannelTransforms: m, responsePrefixContext: h, transformReplyPayload: y }); if (t.kind === "deliver") b.push(t.payload); else if (x === void 0 || t.reason === "channel_transform") x = t.reason; } return b.length > 0 ? { kind: "deliver", payload: b } : { kind: "suppress", reason: x ?? "empty" }; }; const F = normalizeReplyPayloads(p); const I = F.kind === "deliver" ? F.payload : []; const L = projectOutboundPayloadPlanForDelivery(createOutboundPayloadPlan(I)); const R = m && !P && Boolean(O) && !isInternalMessageChannel(C); const normalizeSentTexts = (e) => { const t = normalizeReplyPayloads(e.map((e) => ({ text: e })), false); return (t.kind === "deliver" ? t.payload : []).flatMap((e) => e.text?.trim() ? [e.text] : []); }; const filterDeliveredPayloads = async (e, n) => { if (!R || !O) return e; const r = s.messagingToolSentTexts ?? []; const i = s.messagingToolSentMediaUrls ?? []; const a = v ?? T; const o = (s.messagingToolSentTargets ?? []).flatMap((e) => { if (e.accountId || !E) return [e]; return a ? [{ ...e, accountId: a }] : []; }); if (r.length === 0 && i.length === 0 && o.length === 0) return e; const c = resolveMessagingToolPayloadDedupe({ config: t, messageProvider: C, messagingToolSentTargets: o, originatingTo: O, originatingThreadId: A ?? k ?? void 0, accountId: E }); if (!c.matchingRoute) return e; const l = c.useGlobalSentMediaUrlEvidenceFallback ? i : c.routeSentMediaUrls; const u = c.useGlobalSentTextEvidenceFallback ? r : c.routeSentTexts; const d = normalizeSentTexts(u); const f = new Set(d.filter((e) => Boolean(e.trim()))); const p = await normalizeSentMediaUrlsForDelivery({ sentMediaUrls: l, normalizeMediaPaths: n }); return filterMessagingToolMediaDuplicates({ payloads: e, sentMediaUrls: p }).flatMap((e) => { if (hasEnabledDeliveryOperation(e)) return [e]; const t = formatBtwTextForExternalDelivery(e) ?? e.text ?? ""; if (!t.trim() || !f.has(t)) return [e]; const n = copyReplyPayloadMetadata(e, { ...e, text: void 0 }); return hasReplyPayloadContent(n, { trimText: true, extraContent: n.location != null }) ? [n] : []; }); }; const z = await filterDeliveredPayloads(L); const B = { payloads: z }; if (m && !P && !isInternalMessageChannel(C) && z.length > 0) { const e = a?.agentId ?? resolveSessionAgentId({ sessionKey: c, config: t }); const n = e ? resolveAgentWorkspaceDir(t, e) : void 0; if (n) { const r = createReplyMediaPathNormalizer({ cfg: t, sessionKey: c, agentId: e, workspaceDir: n, messageProvider: C, accountId: E }); const i = []; for (const e of z) i.push(await r(e)); B.payloads = i; B.normalizeMediaPaths = r; } } const V = await filterDeliveredPayloads(B.payloads, B.normalizeMediaPaths); e.assertDeliveryCurrent?.(); const H = createOutboundPayloadPlan(V); const U = projectOutboundPayloadPlanForJson(H); const completeDelivery = (t, n) => { if (!i.json && s.meta.requestShaping?.thinkingClamp) r.log(s.meta.requestShaping.thinkingClamp); if (i.json) { const e = s.meta; writeRuntimeJson(r, { payloads: [...U], ...e ? { meta: e } : {}, ...t ? { deliveryStatus: t } : {} }); } const a = buildDeliveryResult({ payloads: U, meta: s.meta, result: s, deliverySucceeded: n, deliveryStatus: t }); e.onDeliveryResult?.(a, projectOutboundPayloadPlanForDelivery(H)); return a; }; if (N) { completeDelivery(P); throw toErrorObject(N, "Non-Error thrown"); } const W = projectOutboundPayloadPlanForOutbound(H); if (W.length === 0) { P = u ? P ?? noVisiblePayloadStatus(F.kind === "suppress" ? F.reason : void 0) : void 0; return completeDelivery(P, P?.succeeded === true ? true : void 0); } let G = false; const printPayload = (e) => { if (i.json || isNestedAgentLane(i.lane)) return; const t = formatOutboundPayloadLog(e); if (!t) return; writeRuntimeStdout(r, t); }; if (!m) { for (const e of W) printPayload(e); return u && f ? completeDelivery({ ...noVisiblePayloadStatus(), reason: "message_tool_only" }, true) : completeDelivery(); } if (C && !isInternalMessageChannel(C)) { if (O && !P) { e.assertDeliveryCurrent?.(); const r = resolvePendingFinalDeliveryCompletion(p); const o = createAgentCommandDeliveryGuard(e, r); const s = createRestartOnlyAbortSignal(i.abortSignal); let u; try { u = await sendDurableMessageBatchCore({ cfg: t, channel: C, to: O, accountId: E, payloads: W, ...r ? { deliveryCompletion: r, deliveryIntentId: r.deliveryId } : {}, session: a, identity: resolveAgentOutboundIdentity(t, l), replyPayloadSendingHook: { kind: "final", channel: C, ...c ? { sessionKey: c } : {}, ...i.runId ? { runId: i.runId } : {}, context: { channelId: C, ...E ? { accountId: E } : {}, conversationId: O, ...c ? { sessionKey: c } : {}, ...i.runId ? { runId: i.runId } : {} } }, replyToId: k ?? null, threadId: A ?? null, bestEffort: h, durability: h ? "best_effort" : "required", signal: s.signal, onDeliveryIntent: s.dispose, onPlatformSendDispatch: o.prepare, assertDirectAdapterHandoff: o, onError: logDeliveryError, onPayload: printPayload, deps: createOutboundSendDeps(n) }); } finally { s.dispose(); await o.release(); } if (s.signal?.aborted && u.status === "failed") throw s.signal.reason; P = deliveryStatusFromDurableSend(u); if (!h && (u.status === "failed" || u.status === "partial_failed")) { completeDelivery(P, false); throw u.error; } G = u.status === "sent" || u.status === "suppressed"; } } if (!P) P = preDeliveryFailureStatus("no_delivery_target"); if (!G && !i.json && !M) { const e = `[delivery] delivery requested but not completed: ${P?.status ?? "unknown"} (reason=${P?.reason ?? "none"} session=${c ?? "unknown"} channel=${C ?? "none"} target=${O ?? "none"} payloads=${W.length})`; r.error(e); } return completeDelivery(P, G); } //#endregion export { deliverAgentCommandResult };