openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
350 lines (349 loc) • 14 kB
JavaScript
import { R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { n as GatewayProtocolRequestTimeoutError } from "./protocol-request-CsClAJsG.mjs";
import { r as normalizeOutboundReplyFacts } from "./reply-policy-h9jv5pGH.mjs";
import { c as projectOutboundPayloadPlanForMirror, o as projectOutboundPayloadPlanForDelivery, t as createOutboundPayloadPlan } from "./payloads-CQvywZOF.mjs";
import { n as deriveDurableFinalDeliveryRequirementsForBatch } from "./capabilities-Cm5mmzL6.mjs";
import { i as serializeDurableMessagePayloadOutcomes, n as sendDurableMessageBatchCore, t as durableMessageBatchMayHaveReachedRecipient } from "./send-C6MWAmk5.mjs";
import { _ as findOutboundHandoffRejectedError, g as assertOutboundHandoffCurrent } from "./delivery-queue-reconciliation-CQDy7zg8.mjs";
import { s as resolveOutboundDurableFinalDeliverySupport } from "./deliver-prepare-D0EzlldE.mjs";
import "./deliver-dx0iSMKq.mjs";
import { d as createChannelPartialDeliveryError } from "./live-DOXDs-ke.mjs";
import "./runtime-BgdHhvEU.mjs";
import { n as normalizePollInput } from "./polls-CTzQur-g.mjs";
import { r as resolveMessageChannelSelection } from "./channel-selection-DBeuWpKq.mjs";
import { t as buildOutboundSessionContext } from "./session-context-CCVPkFMh.mjs";
import { n as resolveOutboundTarget } from "./targets-CiRFkgHi.mjs";
//#region src/infra/outbound/message-gateway-options.ts
const loadMessageGatewayRuntime = createLazyRuntimeModule(() => import("./message.gateway.runtime.js"));
/** How long a same-key send retry may wait for the Gateway's original work. */
const GATEWAY_SEND_RECONCILIATION_TIMEOUT_MS = 6e4;
/** A caller-side timeout after dispatch leaves the Gateway's work running. */
async function isUnsettledGatewayRequestTimeout(e) {
if (e instanceof GatewayProtocolRequestTimeoutError) return e.requestSent;
if (!(e instanceof Error) || e.name !== "GatewayTransportError") return false;
const { isGatewayTransportError: t } = await loadMessageGatewayRuntime();
return t(e) && e.kind === "timeout" && e.requestDispatched === true;
}
async function resolveGatewayIdempotencyKey(e) {
if (e) return e;
const { randomIdempotencyKey: t } = await loadMessageGatewayRuntime();
return t();
}
/** Normalizes outbound gateway options and fills CLI defaults. */
function resolveOutboundMessageGatewayOptions(e) {
const t = e?.clientName ?? GATEWAY_CLIENT_NAMES.CLI;
const n = e?.mode ?? GATEWAY_CLIENT_MODES.CLI;
const r = n === GATEWAY_CLIENT_MODES.BACKEND || t === GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT ? void 0 : e?.url;
return {
config: e?.config,
localPortOverride: e?.localPortOverride,
ignoreEnvUrlOverride: e?.ignoreEnvUrlOverride,
tlsFingerprint: e?.tlsFingerprint,
url: r,
token: e?.token,
timeoutMs: resolveTimerTimeoutMs(e?.timeoutMs, 1e4),
clientName: t,
clientDisplayName: e?.clientDisplayName,
mode: n
};
}
//#endregion
//#region src/infra/outbound/message.ts
const SEND_BUFFER_MEDIA_URL = "buffer://message-send/attachment";
const loadMessageConfigRuntime = createLazyRuntimeModule(() => import("./message.config.runtime.js"));
function normalizeMessagePollDeliveryResult(e) {
const { channelId: t, conversationId: n, ...r } = e;
return {
...r,
...t ? { target: {
kind: "channel",
id: t
} } : n ? { target: {
kind: "conversation",
id: n
} } : {}
};
}
async function callMessageGateway(e) {
const t = resolveOutboundMessageGatewayOptions(e.gateway);
const n = e.gateway?.request ? void 0 : await e.gateway?.resolveAgentRuntimeIdentityToken?.();
await e.onPlatformSendDispatch?.();
assertOutboundHandoffCurrent(e.assertDirectAdapterHandoff);
const request = async (r) => {
if (e.gateway?.request) return await e.gateway.request({
method: e.method,
params: e.params,
timeoutMs: r
});
const { callGatewayLeastPrivilege: i } = await loadMessageGatewayRuntime();
return await i({
...t,
method: e.method,
params: e.params,
timeoutMs: r,
agentRuntimeIdentityToken: n
});
};
try {
return await request(t.timeoutMs);
} catch (n) {
if (e.method !== "send" || !await isUnsettledGatewayRequestTimeout(n)) throw n;
assertOutboundHandoffCurrent(e.assertDirectAdapterHandoff);
return await request(Math.max(t.timeoutMs, GATEWAY_SEND_RECONCILIATION_TIMEOUT_MS));
}
}
async function resolveMessageConfig(e) {
if (e) return e;
const { getRuntimeConfig: t } = await loadMessageConfigRuntime();
return t();
}
async function resolveDirectMessageTarget(e, t, n, r) {
const i = await resolveOutboundTarget({
channel: n,
plugin: r,
to: e.to,
cfg: t,
accountId: e.accountId,
mode: "explicit"
});
if (!i.ok) throw i.error;
return i;
}
async function sendMessage(e) {
const t = await resolveMessageConfig(e.cfg);
const n = normalizeOutboundReplyFacts({
reply: e.reply,
replyToId: e.replyToId
});
const { channel: r, plugin: i } = e.preparedPlugin ? {
channel: e.preparedPlugin.id,
plugin: e.preparedPlugin
} : await resolveMessageChannelSelection({
cfg: t,
channel: e.channel
});
const a = i.outbound?.deliveryMode ?? "direct";
const o = [e.mediaUrl, ...e.mediaUrls ?? []].filter((e) => Boolean(e)).some((e) => e !== SEND_BUFFER_MEDIA_URL);
const s = a === "gateway" && Boolean(e.buffer) && !o;
const c = e.mediaUrl ?? (s ? SEND_BUFFER_MEDIA_URL : void 0);
const l = e.mediaUrls ?? (s ? [SEND_BUFFER_MEDIA_URL] : void 0);
const u = e.payloads && e.payloads.length > 0 ? e.payloads : [{
text: e.content,
mediaUrl: c,
mediaUrls: l,
audioAsVoice: e.asVoice === true
}];
const d = createOutboundPayloadPlan(u);
const f = projectOutboundPayloadPlanForDelivery(d);
const p = projectOutboundPayloadPlanForMirror(d).mediaUrls;
const m = p[0] ?? c ?? null;
const h = {
channel: r,
to: e.to,
via: a === "gateway" ? "gateway" : "direct",
mediaUrl: m,
mediaUrls: p.length ? p : void 0
};
if (e.dryRun) return {
...h,
dryRun: true
};
if (a !== "gateway" || e.gatewayOwnedDelivery === true) {
const a = await resolveDirectMessageTarget(e, t, r, i);
const o = e.session ?? buildOutboundSessionContext({
cfg: t,
agentId: e.agentId,
sessionKey: e.requesterSessionKey,
conversationType: e.conversationType,
requesterAccountId: e.requesterAccountId ?? e.accountId,
requesterSenderId: e.requesterSenderId,
requesterSenderName: e.requesterSenderName,
requesterSenderUsername: e.requesterSenderUsername,
requesterSenderE164: e.requesterSenderE164
});
const s = e.requireUnknownSendReconciliation ?? e.queuePolicy === "required";
if (s) {
const i = await resolveOutboundDurableFinalDeliverySupport({
cfg: t,
agentId: e.agentId,
channel: r,
requirements: deriveDurableFinalDeliveryRequirementsForBatch({
payloads: f,
replyToId: n?.replyToId,
threadId: e.threadId,
silent: e.silent,
reconcileUnknownSend: true
})
});
if (!i.ok) {
const e = i.reason === "capability_mismatch" && i.capability ? `missing ${i.capability}` : i.reason;
throw new Error(`Required durable message send is unsupported for ${r}: ${e}. Use queuePolicy:"best_effort" for best-effort delivery, omit bestEffort:false in message-tool calls, or use a channel with required durable delivery support.`);
}
}
const c = await sendDurableMessageBatchCore({
cfg: t,
channel: r,
to: a.to,
session: o,
runId: e.runId,
executionIdentityToken: e.executionIdentityToken,
accountId: e.accountId,
conversationReadOrigin: e.conversationReadOrigin,
payloads: f,
reply: n,
threadId: e.threadId,
gifPlayback: e.gifPlayback,
forceDocument: e.forceDocument,
deps: e.deps,
bestEffort: e.bestEffort,
...s ? { requireUnknownSendReconciliation: true } : {},
durability: e.bestEffort || e.queuePolicy === "best_effort" ? "best_effort" : "required",
signal: e.abortSignal,
silent: e.silent,
mediaAccess: e.mediaAccess,
formatting: e.parseMode ? { parseMode: e.parseMode } : void 0,
preparedMessageId: e.preparedMessageId,
deliveryIntentId: e.deliveryIntentId ?? e.idempotencyKey,
deliveryCompletion: e.deliveryCompletion,
transcriptRoute: e.transcriptRoute,
skipDestinationHistory: e.skipDestinationHistory,
transcriptExpectedGeneration: e.transcriptExpectedGeneration,
transcriptProvenance: e.transcriptProvenance,
onTranscriptDiagnostic: e.onTranscriptDiagnostic,
assertTranscriptCurrent: e.assertTranscriptCurrent,
reusePendingDeliveryIntent: e.reusePendingDeliveryIntent,
deliveryRetryOwner: e.deliveryRetryOwner,
completionRetention: e.completionRetention,
...e.onDeliveryIntent ? { onDeliveryIntent: e.onDeliveryIntent } : {},
...e.onDeliveryAttempt ? { onDeliveryAttempt: e.onDeliveryAttempt } : {},
withDirectAdapterHandoff: e.withDirectAdapterHandoff,
...e.onDeliveryResult ? { onDeliveryResult: e.onDeliveryResult } : {},
...e.onPlatformSendDispatch ? { onPlatformSendDispatch: e.onPlatformSendDispatch } : {},
assertDirectAdapterHandoff: e.assertDirectAdapterHandoff,
skipQueue: e.skipQueue,
...e.onDeliveredPayload ? { onDeliveredPayload: e.onDeliveredPayload } : {}
}, e.conversationDeliveryTarget);
const l = durableMessageBatchMayHaveReachedRecipient(c);
const u = c.status === "failed" && !l ? c.payloadOutcomes?.map((e) => e.status === "failed" ? findOutboundHandoffRejectedError(e.error) : void 0).find((e) => e !== void 0) ?? findOutboundHandoffRejectedError(c.error) : void 0;
if (u) throw u;
if (!e.bestEffort && e.gateway?.clientName !== GATEWAY_CLIENT_NAMES.CLI && (c.status === "failed" || c.status === "partial_failed")) {
if (c.status === "partial_failed") throw createChannelPartialDeliveryError(c.error, {
messageIds: c.results.map((e) => e.messageId),
receipt: c.receipt,
visibleReplySent: true
});
throw c.error;
}
const d = c.status === "sent" || c.status === "partial_failed" ? c.results : [];
const p = serializeDurableMessagePayloadOutcomes(c.payloadOutcomes);
const m = c.status !== "sent" && l;
return {
...h,
result: d.at(-1),
deliveryStatus: c.status,
...c.status === "suppressed" ? { suppressionReason: c.reason } : {},
...c.status === "failed" || c.status === "partial_failed" ? { error: formatErrorMessage(c.error) } : {},
...m ? { sentBeforeError: true } : {},
...p ? { payloadOutcomes: p } : {}
};
}
const g = await callMessageGateway({
gateway: e.gateway,
method: "send",
onPlatformSendDispatch: e.onPlatformSendDispatch,
assertDirectAdapterHandoff: e.assertDirectAdapterHandoff,
params: {
to: e.to,
message: e.content,
mediaUrl: c,
mediaUrls: p.length ? p : l,
buffer: s ? e.buffer : void 0,
filename: s ? e.filename : void 0,
contentType: s ? e.contentType : void 0,
asVoice: e.asVoice,
gifPlayback: e.gifPlayback,
accountId: e.accountId,
agentId: e.agentId,
channel: r,
replyToId: n?.replyToId,
threadId: e.threadId != null ? String(e.threadId) : void 0,
forceDocument: e.forceDocument,
silent: e.silent,
parseMode: e.parseMode,
sessionKey: e.requesterSessionKey,
idempotencyKey: await resolveGatewayIdempotencyKey(e.idempotencyKey)
}
});
return {
...h,
result: g
};
}
async function sendPoll(e) {
const t = await resolveMessageConfig(e.cfg);
const { channel: n, plugin: r } = e.preparedPlugin ? {
channel: e.preparedPlugin.id,
plugin: e.preparedPlugin
} : await resolveMessageChannelSelection({
cfg: t,
channel: e.channel
});
const i = r.outbound;
if (!i?.sendPoll) throw new Error(`Unsupported poll channel: ${n}`);
const a = i.deliveryMode ?? "direct";
const o = normalizePollInput(e, i.pollMaxOptions ? { maxOptions: i.pollMaxOptions } : void 0);
const buildResult = (t) => ({
channel: n,
to: e.to,
question: o.question,
options: o.options,
maxSelections: o.maxSelections,
durationSeconds: o.durationSeconds ?? null,
durationHours: o.durationHours ?? null,
via: a === "gateway" ? "gateway" : "direct",
...t
});
if (e.dryRun) return buildResult({ dryRun: true });
if (typeof e.durationSeconds === "number" && i.supportsPollDurationSeconds !== true) throw new Error(`durationSeconds is not supported for ${n} polls`);
if (typeof e.isAnonymous === "boolean" && i.supportsAnonymousPolls !== true) throw new Error(`isAnonymous is not supported for ${n} polls`);
if (a !== "gateway" || e.gatewayOwnedDelivery === true) {
const a = await resolveDirectMessageTarget(e, t, n, r);
e.assertDirectAdapterHandoff?.();
return buildResult({ result: normalizeMessagePollDeliveryResult(await i.sendPoll({
cfg: t,
to: a.to,
poll: o,
content: e.content,
accountId: e.accountId,
threadId: e.threadId,
silent: e.silent,
isAnonymous: e.isAnonymous,
sessionKey: e.sessionKey,
inboundEventKind: e.inboundEventKind,
onPlatformSendDispatch: e.onPlatformSendDispatch,
assertDirectAdapterHandoff: e.assertDirectAdapterHandoff
})) });
}
return buildResult({ result: normalizeMessagePollDeliveryResult(await callMessageGateway({
gateway: e.gateway,
method: "poll",
onPlatformSendDispatch: e.onPlatformSendDispatch,
assertDirectAdapterHandoff: e.assertDirectAdapterHandoff,
params: {
...o,
to: e.to,
threadId: e.threadId,
silent: e.silent,
isAnonymous: e.isAnonymous,
channel: n,
accountId: e.accountId,
idempotencyKey: await resolveGatewayIdempotencyKey(e.idempotencyKey)
}
})) });
}
//#endregion
export { loadMessageGatewayRuntime as a, isUnsettledGatewayRequestTimeout as i, sendPoll as n, resolveGatewayIdempotencyKey as o, GATEWAY_SEND_RECONCILIATION_TIMEOUT_MS as r, resolveOutboundMessageGatewayOptions as s, sendMessage as t };