openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
594 lines (593 loc) • 20.9 kB
JavaScript
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { m as normalizeTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { i as createAbortError } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { d as withPluginRuntimeRegistryScope, o as getPluginRuntimeGatewayRequestScope } from "./gateway-request-scope-BvvDhs5D.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { c as getReplyPayloadMetadata, k as setReplyPayloadMetadata, o as copyReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { r as normalizeOutboundReplyFacts, t as createReplyToDeliveryPolicy } from "./reply-policy-h9jv5pGH.mjs";
import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs";
import { t as splitMediaFromOutput } from "./parse-CBUOvLUG.mjs";
import { d as summarizeOutboundPayloadForTransport, n as createOutboundPayloadPlanWithAdmittedReasoning, r as createStructuredOutboundPayloadPlan, t as createOutboundPayloadPlan } from "./payloads-CQvywZOF.mjs";
import { n as applyReplyPayloadSendingHook, t as applyMessageSendingHook } from "./deliver-hooks-B6z0_4Yo.mjs";
import { c as resolveChannelHandlerParams, o as normalizePayloadsForChannelDelivery, s as normalizeTransformedPayloadForDelivery, u as stripInternalRuntimeScaffoldingFromPayload } from "./deliver-payload-CXD-N8EQ.mjs";
import { t as createChannelRegistryLoader } from "./registry-loader-D9hTqySm.mjs";
import { a as unknownSendReconciliationKinds } from "./types-CmDDsrSP.mjs";
import { f as attachOutboundDeliveryCommitHook, g as assertOutboundHandoffCurrent } from "./delivery-queue-reconciliation-CQDy7zg8.mjs";
//#region src/infra/outbound/deliver-channel.ts
const log = createSubsystemLogger("outbound/deliver");
const loadChannelBootstrapRuntime = createLazyRuntimeModule(() => import("./channel-bootstrap.runtime.js"));
const loadChannelPluginFromRegistry = createChannelRegistryLoader((e) => e.plugin);
async function createChannelHandler(e) {
const { plugin: t, pluginRegistry: n } = await loadBootstrappedChannelPlugin(e);
const r = withPluginRuntimeRegistryScope(n, () => createPluginHandler({
...e,
outbound: t?.outbound,
message: t?.message
}));
if (!r) {
const t = `Outbound not configured for channel: ${e.channel}`;
throw new PlatformMessageNotDispatchedError(t, { cause: new Error(t) });
}
return scopeChannelHandler(r, n);
}
async function loadBootstrappedChannelPlugin(e) {
const t = getPluginRuntimeGatewayRequestScope()?.pluginRegistry;
const n = await loadChannelPluginFromRegistry(e.channel);
if (n?.outbound || n?.message?.send?.text) return {
plugin: n,
pluginRegistry: t
};
const { bootstrapOutboundChannelPluginAsync: r } = await loadChannelBootstrapRuntime();
const i = await r({
channel: e.channel,
cfg: e.cfg,
agentId: e.agentId
});
return {
plugin: i?.channels.find((t) => t.plugin.id === e.channel)?.plugin,
pluginRegistry: i
};
}
function scopeChannelHandler(e, t) {
if (!t) return e;
return Object.fromEntries(Object.entries(e).map(([e, n]) => {
if (typeof n !== "function") return [e, n];
const r = n;
return [e, (...e) => withPluginRuntimeRegistryScope(t, () => r(...e))];
}));
}
async function resolveOutboundDurableFinalDeliverySupport(e) {
const { plugin: t } = await loadBootstrappedChannelPlugin(e);
const n = t?.outbound;
const r = t?.message;
if (!r?.send?.text && !n?.sendText) return {
ok: false,
reason: "missing_outbound_handler"
};
const i = r?.durableFinal;
const a = i?.capabilities ?? n?.deliveryCapabilities?.durableFinal;
for (const [t, n] of Object.entries(e.requirements ?? {})) if (n === true && (a?.[t] !== true || t === "reconcileUnknownSend" && typeof i?.reconcileUnknownSend !== "function")) return {
ok: false,
reason: "capability_mismatch",
capability: t
};
if (e.requirements?.reconcileUnknownSend === true) {
const t = i?.reconcileUnknownSendKinds;
const n = e.requirements.batch ? unknownSendReconciliationKinds.filter((t) => e.requirements?.[t] === true) : unknownSendReconciliationKinds.toReversed().filter((t) => e.requirements?.[t] === true).slice(0, 1);
if (t !== void 0 && n.some((e) => t[e] !== true)) return {
ok: false,
reason: "capability_mismatch",
capability: "reconcileUnknownSend"
};
}
return {
ok: true,
automaticUnknownSendReconciliation: i?.automaticUnknownSendReconciliation === true
};
}
function createPluginHandler(e) {
const t = e.outbound;
const n = e.message?.send?.text;
const r = e.message?.send?.media;
const i = e.message?.send?.payload;
const a = e.message?.send?.lifecycle;
const o = e.message?.durableFinal;
const supportsUnknownSendKind = (t) => !e.requiredUnknownSendReconciliation || o?.capabilities?.reconcileUnknownSend !== true || o.reconcileUnknownSendKinds === void 0 || o.reconcileUnknownSendKinds[t] === true;
const assertUnknownSendReconciliationKind = (t) => {
if (!supportsUnknownSendKind(t)) throw new Error(`Required durable message send became unsupported after outbound transforms: ${t} unknown-send reconciliation is unavailable for ${e.channel}`);
};
if (!n && !t?.sendText) return null;
const s = {
cfg: e.cfg,
to: e.to,
sessionKey: e.sessionKey,
accountId: e.accountId,
replyToId: e.replyToId,
replyToIdSource: void 0,
replyToMode: e.replyToMode,
formatting: e.formatting,
threadId: e.threadId,
identity: e.identity,
gifPlayback: e.gifPlayback,
forceDocument: e.forceDocument,
deps: e.deps,
silent: e.silent,
signal: e.abortSignal,
abortSignal: e.abortSignal,
mediaAccess: e.mediaAccess,
mediaLocalRoots: e.mediaAccess?.localRoots,
mediaReadFile: e.mediaAccess?.readFile,
gatewayClientScopes: e.gatewayClientScopes,
conversationReadOrigin: e.conversationReadOrigin,
deliveryQueueId: e.deliveryQueueId,
preparedMessageId: e.preparedMessageId,
assertDirectAdapterHandoff: e.assertDirectAdapterHandoff,
onPlatformSendDispatch: e.onPlatformSendDispatch,
onDeliveryResult: e.onDeliveryResult
};
const c = t?.sendText;
const l = t?.sendMedia;
const dispatchToAdapter = async (t, n) => {
await e.onPlatformSendStart?.(t);
let r;
try {
await e.onDirectAdapterHandoff?.();
} catch (e) {
r = { error: e };
}
const initiate = () => {
assertOutboundHandoffCurrent(e.assertDirectAdapterHandoff);
if (r) throw r.error;
return n();
};
return e.withDirectAdapterHandoff ? await e.withDirectAdapterHandoff(initiate) : await initiate();
};
const u = s.preparedMessageId ? null : t?.chunker ?? null;
const d = t?.chunkerMode;
const f = e.onDeliveryResult ? async (t) => {
await e.onDeliveryResult?.(normalizeChannelMessageSendResult(e.channel, t));
} : void 0;
const sendMessage = async (t, n, r) => {
assertUnknownSendReconciliationKind(t.kind);
if (!n) return dispatchToAdapter(t, () => r({
...t,
onDeliveryResult: e.onDeliveryResult
}));
if (!a) return normalizeChannelMessageSendResult(e.channel, await dispatchToAdapter(t, () => n(t)));
let i;
let o;
let afterCommit;
try {
i = await a.beforeSendAttempt?.(t);
o = await dispatchToAdapter(t, () => n(t));
if (o.outcome !== "not_sent") {
const e = {
...t,
result: o,
...i !== void 0 ? { attemptToken: i } : {}
};
try {
await a.afterSendSuccess?.(e);
} catch (e) {
log.warn(`channel message send success hook failed after platform send; preserving send result: ${formatErrorMessage(e)}`);
}
if (a.afterCommit) afterCommit = async () => {
await a.afterCommit?.(e);
};
}
} catch (e) {
try {
await a.afterSendFailure?.({
...t,
error: e,
...i !== void 0 ? { attemptToken: i } : {}
});
} catch (e) {
log.warn(`channel message send failure cleanup failed; preserving original send error: ${formatErrorMessage(e)}`);
}
throw e;
}
return attachOutboundDeliveryCommitHook(normalizeChannelMessageSendResult(e.channel, o), afterCommit);
};
const resolveCtx = (e) => ({
...s,
replyToId: e && "replyToId" in e ? e.replyToId : s.replyToId,
replyToIdSource: e && "replyToIdSource" in e ? e.replyToIdSource : s.replyToIdSource,
threadId: e && "threadId" in e ? e.threadId : s.threadId,
audioAsVoice: e?.audioAsVoice,
deliveryPartIndex: e?.deliveryPartIndex,
deliveryPartCount: e?.deliveryPartCount,
preparedMessageId: e?.deliveryPartIndex === void 0 || e.deliveryPartIndex === 0 ? s.preparedMessageId : void 0,
formatting: e && "formatting" in e ? {
...s.formatting,
...e.formatting
} : s.formatting
});
const resolveMessageCtx = (e) => ({
...resolveCtx(e),
onDeliveryResult: f
});
return {
chunker: u,
chunkerMode: d,
chunkedTextFormatting: t?.chunkedTextFormatting,
textChunkLimit: t?.textChunkLimit,
extractMarkdownImages: t?.extractMarkdownImages === true ? true : void 0,
preserveMarkdownDetails: t?.preserveMarkdownDetails?.({
cfg: e.cfg,
accountId: e.accountId
}) === true,
supportsMedia: Boolean(r ?? l ?? t?.sendFormattedMedia),
supportsMediaPayload: t?.sendPayloadGroupsMedia === true && (o?.capabilities ?? t?.deliveryCapabilities?.durableFinal)?.payload === true && supportsUnknownSendKind("payload"),
sanitizeText: t?.sanitizeText ? (n) => t.sanitizeText({
text: n.text ?? "",
payload: n,
cfg: e.cfg,
accountId: e.accountId
}) : void 0,
normalizePayload: t?.normalizePayload ? (n) => t.normalizePayload({
payload: n,
cfg: e.cfg,
accountId: e.accountId
}) : void 0,
normalizePayloadBatch: t?.normalizePayloadBatch ? (n) => {
const r = t.normalizePayloadBatch({
payloads: n,
cfg: e.cfg,
accountId: e.accountId
});
return n.flatMap((e, t) => {
const n = r[t];
return n ? [{
...e,
payload: n
}] : [];
});
} : void 0,
sendTextOnlyErrorPayloads: t?.sendTextOnlyErrorPayloads === true,
presentationCapabilities: t?.resolvePresentationCapabilities ? t.resolvePresentationCapabilities({
cfg: e.cfg,
accountId: e.accountId,
formatting: e.formatting
}) : t?.presentationCapabilities,
renderPresentation: t?.renderPresentation ? async (e, n) => {
const r = e.presentation;
if (!r) return e;
const i = {
...resolveCtx({
replyToId: e.replyToId ?? s.replyToId,
threadId: s.threadId,
audioAsVoice: e.audioAsVoice
}),
text: e.text ?? "",
mediaUrl: e.mediaUrl,
payload: e
};
return await t.renderPresentation({
payload: e,
presentation: r,
sourcePresentation: n,
ctx: i
});
} : void 0,
pinDeliveredMessage: t?.pinDeliveredMessage ? async (n) => t.pinDeliveredMessage({
cfg: e.cfg,
...n
}) : void 0,
afterDeliverPayload: t?.afterDeliverPayload ? async (n) => t.afterDeliverPayload({
cfg: e.cfg,
...n
}) : void 0,
adoptTargetFromDelivery: t?.adoptTargetFromDelivery ? (n) => t.adoptTargetFromDelivery({
cfg: e.cfg,
...n
}) : void 0,
shouldSkipPlainTextSanitization: t?.shouldSkipPlainTextSanitization ? (e) => t.shouldSkipPlainTextSanitization({ payload: e }) : void 0,
resolveEffectiveTextChunkLimit: t?.resolveEffectiveTextChunkLimit ? ({ fallbackLimit: n, formatting: r }) => t.resolveEffectiveTextChunkLimit({
cfg: e.cfg,
accountId: e.accountId ?? void 0,
fallbackLimit: n,
formatting: r
}) : void 0,
sendPayload: i || t?.sendPayload ? (e, n) => sendMessage({
...resolveMessageCtx(n),
kind: "payload",
text: e.text ?? "",
mediaUrl: e.mediaUrl,
payload: e
}, i, (e) => t.sendPayload(e)) : void 0,
sendFormattedText: t?.sendFormattedText ? async (e, n) => {
const r = {
...resolveCtx(n),
text: e
};
assertUnknownSendReconciliationKind("text");
return await dispatchToAdapter(r, () => t.sendFormattedText(r));
} : void 0,
sendFormattedMedia: t?.sendFormattedMedia ? async (e, n, r) => {
const i = {
...resolveCtx(r),
text: e,
mediaUrl: n
};
assertUnknownSendReconciliationKind("media");
return await dispatchToAdapter(i, () => t.sendFormattedMedia(i));
} : void 0,
sendText: (e, t) => sendMessage({
...resolveMessageCtx(t),
kind: "text",
text: e
}, n, c),
buildTargetRef: (t) => ({
channel: e.channel,
to: e.to,
accountId: e.accountId ?? void 0,
threadId: t?.threadId ?? s.threadId
}),
sendMedia: (e, t, n) => sendMessage({
...resolveMessageCtx(n),
kind: "media",
text: e,
mediaUrl: t
}, r, l ?? c)
};
}
function normalizeChannelMessageSendResult(e, t) {
return {
...t,
channel: e,
messageId: t.messageId ?? t.receipt.primaryPlatformMessageId ?? t.receipt.platformMessageIds[0] ?? "",
receipt: t.receipt
};
}
//#endregion
//#region src/channels/message/rendered-batch.ts
function createRenderedMessageBatchPlanItem(e, t) {
const n = e.text?.trim();
const r = normalizeTrimmedStringList(e.mediaUrls);
const i = e.mediaUrl?.trim();
if (i && !r.includes(i)) r.unshift(i);
const a = e.presentation?.blocks?.length ?? 0;
const o = [];
if (n) o.push("text");
if (r.length > 0) o.push(e.audioAsVoice ? "voice" : "media");
if (a > 0 || e.presentation?.title?.trim()) o.push("presentation");
if (e.interactive) o.push("interactive");
if (e.channelData || e.location) o.push("channelData");
return {
index: t,
kinds: o.length > 0 ? o : ["empty"],
...n ? { text: n } : {},
mediaUrls: r,
...e.audioAsVoice && r.length > 0 ? { audioAsVoice: true } : {},
...a > 0 ? { presentationBlockCount: a } : {},
...e.interactive ? { hasInteractive: true } : {},
...e.channelData || e.location ? { hasChannelData: true } : {}
};
}
function createRenderedMessageBatchPlan(e) {
const t = e.map(createRenderedMessageBatchPlanItem);
return t.reduce((e, t) => {
e.payloadCount += 1;
e.textCount += t.text ? 1 : 0;
e.mediaCount += t.mediaUrls.length;
e.voiceCount += t.audioAsVoice ? 1 : 0;
e.presentationCount += t.kinds.includes("presentation") ? 1 : 0;
e.interactiveCount += t.hasInteractive ? 1 : 0;
e.channelDataCount += t.hasChannelData ? 1 : 0;
return e;
}, {
payloadCount: 0,
textCount: 0,
mediaCount: 0,
voiceCount: 0,
presentationCount: 0,
interactiveCount: 0,
channelDataCount: 0,
items: t
});
}
function createRenderedMessageBatch(e) {
return {
payloads: e,
plan: createRenderedMessageBatchPlan(e)
};
}
//#endregion
//#region src/infra/outbound/abort.ts
/**
* Throws an AbortError if the given signal has been aborted.
* Use at async checkpoints to support cancellation.
*/
function throwIfAborted(e) {
if (e?.aborted) throw createAbortError("Operation aborted");
}
//#endregion
//#region src/infra/outbound/deliver-prepare.ts
var OutboundPayloadPreparationError = class extends Error {
constructor(e) {
super(e instanceof Error ? e.message : String(e), { cause: e });
this.name = "OutboundPayloadPreparationError";
}
};
function throwIfPreparationAborted(e) {
try {
throwIfAborted(e);
} catch (e) {
throw new OutboundPayloadPreparationError(e);
}
}
function compactPreparedPayload(e) {
const t = summarizeOutboundPayloadForTransport(e);
const { audioAsVoice: n, mediaUrl: r, mediaUrls: i, replyToCurrent: a, replyToId: o, replyToTag: s, text: c, ...l } = e;
return copyReplyPayloadMetadata(e, Object.fromEntries(Object.entries({
...l,
text: typeof e.text === "string" ? t.text : void 0,
mediaUrl: t.mediaUrls.length === 1 ? t.mediaUrls[0] : void 0,
mediaUrls: t.mediaUrls.length > 1 ? t.mediaUrls : void 0,
replyToId: o,
replyToTag: s === true ? true : void 0,
replyToCurrent: a === true ? true : void 0,
audioAsVoice: n === true ? true : void 0
}).filter(([, e]) => e !== void 0)));
}
function preserveTransformedPayloadMetadata(e, t) {
const n = getReplyPayloadMetadata(t);
copyReplyPayloadMetadata(e, t);
return n ? setReplyPayloadMetadata(t, n) : t;
}
function projectMarkdownImages(e) {
const t = splitMediaFromOutput(e.text ?? "", {
extractMediaDirectives: false,
extractAudioDirectives: false,
extractMarkdownImages: true,
preserveTrailingWhitespace: true
});
if (!t.mediaUrls?.length) return e;
const [n] = createStructuredOutboundPayloadPlan([{
mediaUrl: e.mediaUrl ?? t.mediaUrls[0],
mediaUrls: [
...e.mediaUrls ?? [],
...e.mediaUrl ? [e.mediaUrl] : [],
...t.mediaUrls
],
attachments: e.attachments
}]);
const r = expectDefined(n, "Markdown images must produce a media payload").payload;
return copyReplyPayloadMetadata(e, {
...e,
text: t.text,
mediaUrl: r.mediaUrl,
mediaUrls: r.mediaUrls,
...e.attachments ? { attachments: r.attachments } : {}
});
}
/**
* Runs each modifier exactly once and returns the sole payload representation
* eligible for durable persistence or provider delivery.
*/
async function prepareOutboundPayloadBatch(e, t) {
return await prepareStructuredOutboundPayloadBatch(e, void 0, t);
}
async function prepareStructuredOutboundPayloadBatch(e, t, n) {
const r = await createChannelHandler(resolveChannelHandlerParams(e, normalizeOutboundReplyFacts(e), []));
const i = n?.admittedReasoning ? createOutboundPayloadPlanWithAdmittedReasoning : createOutboundPayloadPlan;
let a = t ?? i(e.payloads, { extractMarkdownImages: r.extractMarkdownImages });
if (t && r.extractMarkdownImages) a = t.flatMap((e) => {
const t = projectMarkdownImages(e.payload);
if (t === e.payload) return [e];
const [n] = createStructuredOutboundPayloadPlan([t]);
return n ? [{
...n,
sourceIndex: e.sourceIndex
}] : [];
});
const o = t ? preserveTransformedPayloadMetadata : void 0;
const s = o ?? ((e, t) => t);
const c = normalizePayloadsForChannelDelivery(a, r, o);
const l = new Set(c.map((e) => e.index));
const u = [];
for (const [t] of e.payloads.entries()) if (!l.has(t)) u.push({
sourceIndex: t,
status: "suppressed",
reason: "no_visible_payload"
});
const d = n?.hookRunner ?? getGlobalHookRunner();
const f = e.replyPayloadSendingHook !== void 0 && (d?.hasHooks("reply_payload_sending") ?? false);
const p = d?.hasHooks("message_sending") ?? false;
const m = f || p;
const { resolveCurrentReplyTo: h } = createReplyToDeliveryPolicy(e);
const g = e.session?.key;
const _ = [{
changedKey: "replyHookChanged",
cancellationReason: "cancelled_by_reply_payload_sending_hook",
apply: (t) => applyReplyPayloadSendingHook({
hook: e.replyPayloadSendingHook,
payload: t
}, d)
}, {
changedKey: "messageHookChanged",
cancellationReason: "cancelled_by_message_sending_hook",
apply: (t) => applyMessageSendingHook({
hookRunner: d,
enabled: p,
payload: t,
payloadSummary: summarizeOutboundPayloadForTransport(t),
to: e.to,
channel: e.channel,
accountId: e.accountId,
replyToId: h(t).replyToId,
threadId: e.threadId,
sessionKey: g
})
}];
let v = false;
payloads: for (const { index: t, payload: i } of c) {
throwIfPreparationAborted(e.abortSignal);
if (m && !v) {
await n?.onBeforeFirstModifier?.();
throwIfPreparationAborted(e.abortSignal);
v = true;
}
const a = {
replyHookChanged: false,
messageHookChanged: false
};
let o = i;
for (const n of _) {
let i;
try {
i = await n.apply(o);
} catch (e) {
throw new OutboundPayloadPreparationError(e);
}
o = s(o, i.payload);
throwIfPreparationAborted(e.abortSignal);
if (i.cancelled) {
u.push({
sourceIndex: t,
status: "suppressed",
reason: n.cancellationReason,
...i.hookEffect ? { hookEffect: i.hookEffect } : {}
});
continue payloads;
}
a[n.changedKey] = i.changed;
o = stripInternalRuntimeScaffoldingFromPayload(o);
if (r.extractMarkdownImages && i.changed) o = projectMarkdownImages(o);
}
const c = normalizeTransformedPayloadForDelivery(o, r, s);
if (!c) {
u.push({
sourceIndex: t,
status: "suppressed",
reason: a.messageHookChanged ? "empty_after_message_sending_hook" : a.replyHookChanged ? "empty_after_reply_payload_sending_hook" : "no_visible_payload"
});
continue;
}
const l = compactPreparedPayload(c);
u.push({
sourceIndex: t,
status: "accepted",
payload: l,
...a,
preparedMediaCount: summarizeOutboundPayloadForTransport(l).mediaUrls.length
});
}
const y = e.runId ?? e.replyPayloadSendingHook?.runId;
return {
schemaVersion: 1,
sourcePayloadCount: e.payloads.length,
channelNormalized: true,
...y ? { runId: y } : {},
...e.executionIdentityToken ? { executionIdentityToken: e.executionIdentityToken } : {},
entries: u
};
}
//#endregion
export { createRenderedMessageBatchPlan as a, createRenderedMessageBatch as i, prepareStructuredOutboundPayloadBatch as n, createChannelHandler as o, throwIfAborted as r, resolveOutboundDurableFinalDeliverySupport as s, prepareOutboundPayloadBatch as t };