openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,997 lines • 72.4 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { f as resolveAgentWorkspaceDir, x as resolveSessionAgentId } from "./agent-scope-config-DmXgFGKP.mjs";
import { r as readTrimmedStringAlias } from "./string-readers-BtMVaphq.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { t as dedupeByKey } from "./dedupe-by-key-Cpowmfct.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { d as runWithSessionSourceScope, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs";
import { o as runInAgentRunWriteContext } from "./agent-run-terminal-writes-eqeCFAOx.mjs";
import { t as INTERNAL_MESSAGE_CHANNEL } from "./message-channel-constants-CkbqRgGl.mjs";
import { t as normalizeChatType } from "./chat-type-CL5nBDaO.mjs";
import { n as normalizeMessageChannel } from "./message-channel-core-BbYZT1a-.mjs";
import "./message-channel-DTYVLJT1.mjs";
import { d as normalizeLegacyInteractiveReply, f as normalizeMessagePresentation, n as hasLegacyInteractiveReplyBlocks, o as hasReplyPayloadContent, r as hasMessagePresentationBlocks, v as renderMessagePresentationFallbackText } from "./payload-Cab4FCxl.mjs";
import { c as getReplyPayloadMetadata, k as setReplyPayloadMetadata, o as copyReplyPayloadMetadata, r as appendReplyMediaFailures } from "./reply-payload-k5WsQWxi.mjs";
import { r as GatewayErrorDetailCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { n as jsonResult, r as textResult } from "./tool-results-CcV0sxnb.mjs";
import { f as readStringArrayParam, m as readToolStringParam, u as readPositiveIntegerParam } from "./common-njQNtpnW.mjs";
import { n as getRuntimeVisibleChannelPlugin } from "./runtime-visible-channels-CE896D4p.mjs";
import { i as readSessionEntryReadOnlyInWorker } from "./session-entry-read-runtime-1Fp1sybj.mjs";
import { r as isInsideCode } from "./code-ranges-2XaqsF-S.mjs";
import { n as parseInlineDirectives } from "./directive-tags-batch-D0CxS-zY.mjs";
import "./code-regions-CfNY0afj.mjs";
import { n as findMarkdownCodeRegions } from "./reasoning-tags-DL3sP_9k.mjs";
import { a as stripPlainTextToolCallBlocks } from "./payload-DXepDNU7.mjs";
import { m as stripReasoningTagsFromText } from "./assistant-visible-text-fPqh5m9O.mjs";
import { y as withSessionTranscriptWriteAssertion } from "./transcript-write-context-_7rz2F7z.mjs";
import "./directive-tags-C1p_t1Fd.mjs";
import "./sessions-D5Vvu3AE.mjs";
import { s as shouldAttemptTtsPayload } from "./tts-config-CNw5woLC.mjs";
import { n as resolveAgentIdentity, o as resolveResponsePrefix } from "./identity-Cd2mxvzm.mjs";
import { n as normalizeOutboundLocation } from "./location-oMDzIggt.mjs";
import "./reply-payload-CwASJYas.mjs";
import { a as resolveSendableOutboundReplyParts } from "./reply-payload-parts-0Tn7wkpR.mjs";
import { t as normalizeConversationReadInvocationOrigin } from "./conversation-read-origin-DMlgOstF.mjs";
import { t as MessageActionDeniedError } from "./message-action-denial-Csh3qR94.mjs";
import { i as withChannelReadAuthority } from "./channel-read-authority-BVl4WY3A.mjs";
import { r as normalizeTargetForProvider } from "./target-normalization-qHbFjVWS.mjs";
import { i as resolveChannelTarget } from "./target-resolver-DZ4okT3e.mjs";
import { i as missingMessageActionTargetError, n as invalidMessageActionTargetError } from "./target-errors-DefLZSM6.mjs";
import { c as buildCrossContextDecoration, f as resolveEffectiveMessageToolsConfig, l as enforceCrossContextPolicy, p as shouldApplyCrossContextMarker, r as isMessagingToolDeliveryAction, s as applyCrossContextDecoration, u as enforceMessageActionAllowlist } from "./embedded-agent-messaging-CBeq8Mz9.mjs";
import { f as stripUnsupportedCitationControlMarkers } from "./payloads-CQvywZOF.mjs";
import { a as resolveResponsePrefixTemplate } from "./normalize-reply-C8AkGgUH.mjs";
import { t as resolveLocalMediaPath } from "./local-media-path-R9G3PyAB.mjs";
import { n as resolveAgentScopedOutboundMediaAccess } from "./read-capability-XYUFrpMj.mjs";
import "./src-C9d8oFHe.mjs";
import { n as prepareTtsPreferences } from "./tts-preferences-CIrFrUQO.mjs";
import { i as resolveChannelDefaultAccountId } from "./helpers-ELZNDAnv.mjs";
import { i as actionRequiresTarget, n as resolveImplicitMessageActionTarget, o as hasPotentialPluginActionParam, t as normalizeMessageActionInput } from "./message-action-normalization-BoubNx7z.mjs";
import { r as hasPollCreationParams } from "./poll-params-CdaOp94w.mjs";
import { g as assertOutboundHandoffCurrent, h as OutboundHandoffRejectedError } from "./delivery-queue-reconciliation-CQDy7zg8.mjs";
import { r as throwIfAborted } from "./deliver-prepare-D0EzlldE.mjs";
import { y as commitConfirmedVisibleMessage } from "./delivery-queue-recovery-Cwouxa5a.mjs";
import { a as resolveOutboundMediaMaxBytes } from "./configured-max-bytes-lKIaFMol.mjs";
import { a as resolveOutboundSessionRoute, r as ensureOutboundSessionEntry } from "./outbound-session-BGK8YYPT.mjs";
import { f as isChannelPartialDeliveryError } from "./live-DOXDs-ke.mjs";
import { r as resolvePollMaxSelections } from "./polls-CTzQur-g.mjs";
import { n as listConfiguredMessageChannels, r as resolveMessageChannelSelection } from "./channel-selection-DBeuWpKq.mjs";
import { a as loadMessageGatewayRuntime, i as isUnsettledGatewayRequestTimeout, n as sendPoll, o as resolveGatewayIdempotencyKey, r as GATEWAY_SEND_RECONCILIATION_TIMEOUT_MS, s as resolveOutboundMessageGatewayOptions, t as sendMessage } from "./message-DKs6K7sM.mjs";
import { t as buildOutboundSessionContext } from "./session-context-CCVPkFMh.mjs";
import { r as validateExplicitMessageAccountSelection } from "./message-account-selection-DxhPXlSt.mjs";
import { n as resolveOutboundAttachmentFromUrl } from "./outbound-attachment-DnDdBY4R.mjs";
import { a as pluginEnvelopeHas, o as projectEmbeddedMessageDeliveryFact, s as projectPluginMessageDeliveryFact } from "./embedded-agent-message-delivery-ClVuBxqZ.mjs";
import { n as isDeliveredCurrentSourceReplyAsync, r as mirrorDeliveredSourceReplyToTranscript } from "./source-reply-mirror-D-L-Lbo_.mjs";
import { t as resolveFirstBoundAccountId } from "./bound-account-read-BQzP0D0m.mjs";
import { a as shouldDeferExternalMessageActionTargetResolution, i as prepareExternalMessageActionTargetForResolution, n as isFencedProviderReadAction, t as dispatchChannelMessageAction } from "./message-action-dispatch-Db7F0yKH.mjs";
import { t as readBooleanParam } from "./boolean-param-iT2wc5fb.mjs";
import { t as extractToolPayload } from "./tool-payload-BQ5gdJhg.mjs";
import { i as resolveMessageActionOutcome, n as messageActionRequesterMediaContext, t as createChannelActionContext } from "./message-action-contracts-Al2l9Lkb.mjs";
import { a as normalizeSandboxMediaSource, c as resolveAttachmentMediaPolicy, i as normalizeSandboxMediaParams, l as resolveExtraActionMediaSourceParamKeysAsync, n as collectAttachmentSources, o as parseJsonMessageParam, r as hydrateAttachmentParamsForAction, s as requirePresentationTableCaptions, t as collectActionMediaSourceHints, u as waitForLocalMessageMedia } from "./message-action-params-DnKd238O.mjs";
import { n as readClawHubRecommendations, t as CLAWHUB_RECOMMENDATIONS_CHANNEL_DATA_KEY } from "./clawhub-recommendations-Diy5uXfN.mjs";
import { t as shouldUseInternalSourceReplySink } from "./internal-source-reply-DPNOuFQV.mjs";
import path from "node:path";
import { randomUUID } from "node:crypto";
//#region src/infra/outbound/message-action-result-acceptance.ts
function hasAcceptedMessageActionResult(e, t = false) {
if (e.kind === "broadcast" || e.dryRun || !isMessagingToolDeliveryAction("message", { action: e.action })) return false;
const n = [e.payload, e.toolResult];
const r = n.map(projectPluginMessageDeliveryFact);
const i = projectEmbeddedMessageDeliveryFact(e, true);
if (i?.status === "dryRun" || r.some((e) => e?.status === "dryRun")) return false;
if (!resolveMessageActionOutcome(e).ok) return i?.partialDelivery || r.some((e) => e?.partialDelivery);
if (n.some((e) => pluginEnvelopeHas(e, "failure")) || r.some((e) => e && (e.status !== "settled" || e.partialDelivery)) || e.handledBy === "plugin" && !pluginEnvelopeHas(e.payload, "ok")) return false;
const a = t && e.kind === "action" && e.handledBy === "plugin" && pluginEnvelopeHas(e.payload, "ok");
return i?.status === "settled" && !i.partialDelivery && (e.kind === "send" && e.handledBy === "core" && e.sendResult?.deliveryStatus === "sent" || i.primaryPlatformMessageId && i.primaryPlatformMessageId.toLowerCase() !== "unknown" || a);
}
async function annotateSourceDelivery(e, t, n) {
const r = t.input.messageActionAuthorization;
if (e.kind === "broadcast" || !r?.toolContext) return e;
const i = {
action: e.action,
channel: t.channel,
actionParams: t.params,
cfg: t.cfg,
accountId: t.accountId,
currentAccountId: r.requesterAccountId ?? t.input.defaultAccountId,
sessionKey: t.input.sessionKey,
sessionId: t.input.sessionId,
agentId: t.agentId,
toolContext: r.toolContext,
deliveredPayload: e.payload,
replyToIsExplicit: n
};
let a;
try {
throwIfAborted(t.abortSignal);
t.input.assertDirectAdapterHandoff?.();
a = await isDeliveredCurrentSourceReplyAsync(i);
throwIfAborted(t.abortSignal);
t.input.assertDirectAdapterHandoff?.();
} catch (t) {
if (hasAcceptedMessageActionResult(e, r.scheduled !== void 0)) return e;
throw t;
}
if (!a) return e;
const o = asOptionalRecord(e.payload);
const s = asOptionalRecord(e.toolResult?.details);
return {
...e,
payload: o ? {
...o,
sourceReplyRoute: "current-source"
} : e.payload,
...e.toolResult ? { toolResult: {
...e.toolResult,
details: {
...s,
sourceReplyRoute: "current-source"
}
} } : {}
};
}
//#endregion
//#region src/infra/outbound/message-action-threading.ts
function suppressesImplicitThreading(e) {
return e.topLevel === true || e.threadId === null;
}
function resolveAndApplyOutboundThreadId(e, t) {
const n = readToolStringParam(e, "threadId");
if (!n && suppressesImplicitThreading(e)) return;
const r = readToolStringParam(e, "replyTo");
const i = n ? void 0 : t.resolveAutoThreadId?.({
cfg: t.cfg,
accountId: t.accountId,
to: t.to,
toolContext: t.toolContext,
replyToId: t.replyToIsExplicit === false ? void 0 : r
});
const a = n ?? i;
if (i && !e.threadId) e.threadId = i;
if (r && a) {
const n = t.resolveReplyTransport?.({
cfg: t.cfg,
accountId: t.accountId,
threadId: a,
replyToId: r,
replyToIsExplicit: t.replyToIsExplicit
})?.replyToId;
if (n && r !== n) e.replyTo = n;
}
return a ?? void 0;
}
function resolveAndApplyOutboundReplyToId(e, t) {
const n = readToolStringParam(e, "replyTo");
const r = t.toolContext?.replyToMode ?? "off";
const i = r === "batched" ? "first" : r;
if (n) {
if (i === "first") {
const e = t.toolContext?.hasRepliedRef;
if (e) e.value = true;
}
return {
replyToId: n,
source: "explicit"
};
}
if (suppressesImplicitThreading(e)) return;
const { channel: a, toolContext: o, matchesToolContextTarget: s } = t;
const c = o?.currentChannelId?.trim();
const l = o?.currentMessagingTarget?.trim();
if (!c && !l) return;
const u = o?.currentChannelProvider?.trim();
if (u && u !== a) return;
const d = readToolStringParam(e, "target") ?? readToolStringParam(e, "to") ?? readToolStringParam(e, "channelId");
if (d) {
const e = d.trim();
if (!(o && s?.({
target: e,
toolContext: o
})) && e !== l && e !== c) return;
}
const f = t.toolContext?.currentMessageId;
if (f == null || i === "off") return;
if (i === "first") {
const e = t.toolContext?.hasRepliedRef;
if (e?.value) return;
if (e) e.value = true;
}
const p = typeof f === "number" ? String(f) : f.trim();
if (!p) return;
e.replyTo = p;
return {
replyToId: p,
source: "implicit",
mode: i
};
}
//#endregion
//#region src/infra/outbound/outbound-send-service.ts
const log$2 = createSubsystemLogger("outbound/send-service");
function materializeMessagePresentationFallback(e) {
const t = normalizeMessagePresentation(e.payload.presentation);
const n = (e.text ?? e.payload.text ?? "").trim();
const r = t ? renderMessagePresentationFallbackText({ presentation: t }) : "";
return !r || n.includes(r) ? n : [n, r].filter(Boolean).join("\n\n");
}
function hasCorePresentationDelivery(e) {
return Boolean(e?.sendPayload || e?.sendText || e?.sendFormattedText);
}
async function tryHandleWithPluginAction(e) {
if (e.ctx.dryRun) return null;
const t = resolveAgentScopedOutboundMediaAccess({
cfg: e.ctx.cfg,
agentId: e.ctx.agentId,
mediaSources: collectActionMediaSourceHints(e.ctx.params, void 0, { structuredAttachments: e.action === "send" ? "all" : void 0 }),
sessionKey: e.ctx.input.sessionKey,
messageProvider: e.ctx.input.sessionKey ? void 0 : e.ctx.channel,
accountId: (e.ctx.input.sessionKey ? e.ctx.input.requesterAccountId ?? e.ctx.accountId : e.ctx.accountId) ?? void 0,
requesterSenderId: e.ctx.input.requesterSenderId ?? void 0,
requesterSenderName: e.ctx.input.requesterSenderName ?? void 0,
requesterSenderUsername: e.ctx.input.requesterSenderUsername ?? void 0,
requesterSenderE164: e.ctx.input.requesterSenderE164 ?? void 0,
mediaAccess: e.ctx.mediaAccess
});
const n = await dispatchChannelMessageAction(createChannelActionContext({
ctx: e.ctx,
action: e.action,
mediaAccess: t,
reply: e.reply
}));
if (!n) return null;
const r = projectPluginMessageDeliveryFact(n);
if (!r || r.status === "settled") await e.onHandled?.(r);
return {
handledBy: "plugin",
payload: extractToolPayload(n),
toolResult: n
};
}
async function executeSendAction(e) {
throwIfAborted(e.ctx.abortSignal);
const t = e.payload ?? {
text: e.message,
mediaUrl: e.mediaUrl,
mediaUrls: e.mediaUrls,
audioAsVoice: e.asVoice === true
};
const n = e.bestEffort === false || e.ctx.input.requireQueuePersistence ? "required" : "best_effort";
const r = e.ctx.input.forceCoreDelivery === true || e.ctx.input.requireQueuePersistence === true;
const i = e.ctx.channelPlugin;
const a = !r && i.outbound ? i.actions?.prepareSendPayload : void 0;
const o = a ? await a({
ctx: createChannelActionContext({
ctx: e.ctx,
action: "send",
reply: e.reply
}),
to: e.to,
payload: t,
replyToId: e.reply?.replyToId,
replyToIdSource: e.reply?.source,
threadId: e.threadId
}) : void 0;
const s = normalizeMessagePresentation(t.presentation);
const c = r ? t : o || (!a && s && hasCorePresentationDelivery(i.outbound) ? t : null);
if (!c) {
const n = s ? materializeMessagePresentationFallback({
payload: t,
text: e.message
}) : e.message;
const r = n === e.message ? e.ctx : {
...e.ctx,
params: {
...e.ctx.params,
message: n
}
};
let i;
try {
i = await tryHandleWithPluginAction({
ctx: r,
action: "send",
reply: e.reply,
onHandled: async (r) => {
try {
await e.ctx.onSendAccepted?.();
if (!r || r.partialDelivery || e.ctx.input.callerRecordsDestinationHistory) return;
if (r.createdThreadIds.length > 1) {
log$2.warn("Confirmed plugin outbound transcript skipped: multiple delivery threads");
return;
}
const i = r.createdThreadIds[0] ?? e.threadId;
const a = i != null && String(i) !== String(e.ctx.transcriptRoute?.threadId ?? e.threadId);
const o = await commitConfirmedVisibleMessage({
config: e.ctx.cfg,
channel: e.ctx.channel,
to: e.to,
accountId: e.ctx.accountId ?? void 0,
threadId: i,
route: a ? void 0 : e.ctx.transcriptRoute,
producer: buildOutboundSessionContext({
cfg: e.ctx.cfg,
sessionKey: e.ctx.input.sessionKey,
agentId: e.ctx.agentId
}),
payload: {
...t,
text: n
},
deliveryId: e.ctx.input.deliveryIntentId ?? e.ctx.idempotencyKey ?? randomUUID(),
payloadIndex: 0,
signal: e.ctx.abortSignal,
assertDirectAdapterHandoff: e.ctx.input.assertDirectAdapterHandoff
});
const s = o.ok ? o.diagnostics : o.reason;
if (s) log$2.warn(`Confirmed plugin outbound transcript: ${s}`);
} catch (e) {
log$2.warn(`Confirmed plugin outbound transcript commit failed: ${formatErrorMessage(e)}`);
}
}
});
} catch (t) {
if (isChannelPartialDeliveryError(t)) await e.ctx.onSendAccepted?.();
throw t;
}
if (i) return {
...i,
deliveredPayloads: [{
...t,
text: n
}]
};
}
throwIfAborted(e.ctx.abortSignal);
const l = c && normalizeMessagePresentation(c.presentation) && i.outbound?.deliveryMode === "gateway" ? materializeMessagePresentationFallback({
payload: c,
text: e.message
}) : e.message;
const u = [];
const d = await sendMessage({
cfg: e.ctx.cfg,
to: e.to,
content: l,
...c ? { payloads: [c] } : {},
agentId: e.ctx.agentId,
requesterSessionKey: e.ctx.input.sessionKey,
requesterAccountId: e.ctx.input.requesterAccountId ?? e.ctx.accountId ?? void 0,
requesterSenderId: e.ctx.input.requesterSenderId ?? void 0,
requesterSenderName: e.ctx.input.requesterSenderName ?? void 0,
requesterSenderUsername: e.ctx.input.requesterSenderUsername ?? void 0,
requesterSenderE164: e.ctx.input.requesterSenderE164 ?? void 0,
mediaUrl: e.mediaUrl || void 0,
mediaUrls: e.mediaUrls,
buffer: e.buffer,
filename: e.filename,
contentType: e.contentType,
asVoice: e.asVoice,
channel: e.ctx.channel || void 0,
accountId: e.ctx.accountId ?? void 0,
conversationType: e.ctx.conversationType,
conversationReadOrigin: normalizeConversationReadInvocationOrigin(e.ctx.input.conversationReadOrigin),
reply: e.reply,
threadId: e.threadId,
gifPlayback: e.gifPlayback,
forceDocument: e.forceDocument,
dryRun: e.ctx.dryRun,
bestEffort: e.bestEffort ?? void 0,
queuePolicy: n,
deps: e.ctx.input.deps,
gateway: e.ctx.gateway,
idempotencyKey: e.ctx.idempotencyKey,
runId: e.ctx.input.runId,
executionIdentityToken: e.ctx.input.executionIdentityToken,
abortSignal: e.ctx.abortSignal,
silent: e.ctx.silent,
mediaAccess: e.ctx.mediaAccess,
preparedMessageId: e.ctx.input.preparedMessageId,
preparedPlugin: e.ctx.channelPlugin,
gatewayOwnedDelivery: e.ctx.input.gatewayOwnedDelivery,
deliveryIntentId: e.ctx.input.deliveryIntentId,
deliveryCompletion: e.ctx.input.deliveryCompletion,
transcriptRoute: e.ctx.transcriptRoute,
skipDestinationHistory: e.ctx.input.callerRecordsDestinationHistory,
conversationDeliveryTarget: e.ctx.input.conversationDeliveryTarget,
deliveryRetryOwner: e.ctx.deliveryRetryOwner,
requireUnknownSendReconciliation: e.ctx.input.requireQueuePersistence ? false : void 0,
onDeliveryIntent: e.ctx.input.onDeliveryIntent,
onDeliveryAttempt: e.ctx.input.onDeliveryAttempt,
withDirectAdapterHandoff: e.ctx.input.withDirectAdapterHandoff,
onDeliveryResult: async (t) => {
await e.ctx.onSendAccepted?.();
await e.ctx.input.onDeliveryResult?.(t);
},
onPlatformSendDispatch: e.ctx.input.onPlatformSendDispatch,
assertDirectAdapterHandoff: e.ctx.input.assertDirectAdapterHandoff,
skipQueue: e.ctx.input.skipQueue,
onDeliveredPayload: (e) => u.push(e)
});
const f = d.deliveryStatus === "sent" && u.every((e) => e.mediaUrls.length === 0 && e.audioAsVoice !== true) ? u.map((e) => e.text).filter((e) => e.trim()).join("\n") : "";
return {
handledBy: "core",
payload: d,
...f ? { deliveredText: f } : {},
deliveredPayloads: u,
sendResult: d
};
}
async function executePollAction(e) {
const t = await tryHandleWithPluginAction({
ctx: e.ctx,
action: "poll"
});
if (t) return t;
const n = e.resolveCorePoll();
const r = await sendPoll({
...n,
cfg: e.ctx.cfg,
channel: e.ctx.channel,
accountId: e.ctx.accountId ?? void 0,
silent: e.ctx.silent ?? void 0,
dryRun: e.ctx.dryRun,
gateway: e.ctx.gateway,
idempotencyKey: e.ctx.idempotencyKey,
preparedPlugin: e.ctx.channelPlugin,
gatewayOwnedDelivery: e.ctx.input.gatewayOwnedDelivery,
sessionKey: e.ctx.input.sessionKey,
inboundEventKind: e.ctx.input.inboundEventKind,
onPlatformSendDispatch: e.ctx.input.onPlatformSendDispatch,
assertDirectAdapterHandoff: e.ctx.input.assertDirectAdapterHandoff
});
return {
handledBy: "core",
payload: r,
pollResult: r
};
}
//#endregion
//#region src/infra/outbound/message-action-execution.ts
const MESSAGE_ACTION_RECONCILIATION_MAX_MS = 54e4;
const MESSAGE_ACTION_INITIAL_SEND_TIMEOUT_MAX_MS = 3e4;
function assertMessageDeliveryCurrent(e) {
throwIfAborted(e.abortSignal);
e.assertDirectAdapterHandoff?.();
e.messageActionAuthorization?.scheduled?.assertCurrent();
e.messageActionAuthorization?.deliveryAttempt?.assertCurrent();
}
/** Keep the occurrence's prepared sources through transcript and transport commits. */
function captureMessageDeliveryAuthority(e) {
return composeSessionSourceAssertion([
e.assertDirectAdapterHandoff,
e.messageActionAuthorization?.scheduled?.assertCurrent,
e.messageActionAuthorization?.deliveryAttempt?.assertCurrent
], (t) => {
throwIfAborted(e.abortSignal);
t();
});
}
async function beforeMessageDeliveryAttempt(e) {
const t = e.messageActionAuthorization?.deliveryAttempt;
if (!t) return;
assertMessageDeliveryCurrent(e);
await t.beforeAttempt();
assertMessageDeliveryCurrent(e);
}
function projectMessageActionPartialDelivery(e) {
const t = isChannelPartialDeliveryError(e) ? e.deliveryResult : void 0;
const n = e instanceof Error && e.name === "GatewayClientRequestError" ? asOptionalRecord(asOptionalRecord(e)?.details)?.partialDelivery : void 0;
const r = t ?? n;
return r === void 0 ? void 0 : {
ok: false,
deliveryStatus: "partial_failed",
sentBeforeError: true,
error: formatErrorMessage(e),
result: r
};
}
function projectGatewayQueuedDeliveryResult(e) {
if (!(e instanceof Error) || e.name !== "GatewayClientRequestError") return;
if (asOptionalRecord(asOptionalRecord(e)?.details)?.code !== GatewayErrorDetailCodes.OUTBOUND_DELIVERY_QUEUED) return;
return {
status: "delivery_queued",
delivered: false,
message: `Delivery is pending: ${e.message}. The gateway owns retry or reconciliation; delivery is not yet confirmed. Do not resend it.`
};
}
async function applyMessageCrossContextMarker(e) {
if (!shouldApplyCrossContextMarker(e.action) || !e.toolContext) return e.message;
const t = await buildCrossContextDecoration({
cfg: e.cfg,
channel: e.channel,
target: e.target,
toolContext: e.toolContext,
accountId: e.accountId ?? void 0,
agentId: e.agentId ?? void 0
});
if (!t) return e.message;
const n = applyCrossContextDecoration({
message: e.message,
decoration: t,
preferPresentation: e.preferPresentation
});
e.args.message = n.message;
if (n.presentation) {
const t = normalizeMessagePresentation(e.args.presentation);
e.args.presentation = t ? {
...t,
blocks: [...n.presentation.blocks, ...t.blocks]
} : n.presentation;
}
return n.message;
}
async function executeGatewayAction(e, t) {
if (e.dryRun || !e.gateway) return null;
const n = e.channelPlugin;
const r = Boolean(e.input.messageActionAuthorization?.scheduled && e.gateway.request) && n.outbound?.deliveryMode === "gateway" && (t.action === "send" && Boolean(n.message?.send?.text || n.outbound.sendText) || t.action === "poll" && Boolean(n.outbound.sendPoll)) && (!n.actions?.handleAction || n.actions.supportsAction?.({ action: t.action }) === false);
if (!n.actions?.handleAction && !r) return null;
if ((n.actions?.resolveExecutionMode?.({ action: t.action }) ?? "local") !== "gateway" && !r) return null;
const i = normalizeConversationReadInvocationOrigin(e.input.conversationReadOrigin);
const a = await resolveGatewayIdempotencyKey(normalizeOptionalString(e.params.idempotencyKey));
const o = {
sourceReplyFinal: e.input.sourceReplyFinal,
sourceReplyToolCallId: e.input.sourceReplyToolCallId
};
const s = e.gateway.request ? void 0 : await e.gateway.resolveAgentRuntimeIdentityToken?.(o);
let c;
try {
const n = e.gateway;
const r = e.input.abortSignal;
const l = e.input.assertDirectAdapterHandoff;
const u = {
channel: e.channel,
action: t.action,
params: e.params,
...t.reply ? { reply: t.reply } : {},
accountId: e.accountId ?? void 0,
senderIsOwner: e.input.senderIsOwner,
sessionKey: e.input.sessionKey,
sessionId: e.input.sessionId,
inboundTurnKind: e.input.inboundEventKind,
agentId: e.agentId,
...i === "direct-operator" ? { conversationReadOrigin: i } : {},
idempotencyKey: a
};
const { callGatewayLeastPrivilege: d } = await loadMessageGatewayRuntime();
const f = resolveOutboundMessageGatewayOptions(n);
const p = u.action === "send" ? Math.min(f.timeoutMs, MESSAGE_ACTION_INITIAL_SEND_TIMEOUT_MAX_MS) : f.timeoutMs;
const m = {
...f,
method: "message.action",
params: u,
timeoutMs: p,
signal: r,
agentRuntimeIdentityToken: s
};
const request = (e) => n?.request ? n.request(e, o) : d(e);
try {
c = await runWithSessionSourceScope(l, async () => {
assertOutboundHandoffCurrent(l);
return request(m);
}, { checkAfter: false });
} catch (e) {
if (u.action !== "send" || !await isUnsettledGatewayRequestTimeout(e)) throw e;
throwIfAborted(r);
const t = r ? AbortSignal.any([r, AbortSignal.timeout(MESSAGE_ACTION_RECONCILIATION_MAX_MS)]) : void 0;
c = await request({
...m,
timeoutMs: r ? null : Math.max(m.timeoutMs, GATEWAY_SEND_RECONCILIATION_TIMEOUT_MS),
signal: t
});
}
} catch (t) {
const n = e.input.messageActionAuthorization?.scheduled ? projectMessageActionPartialDelivery(t) : void 0;
if (n !== void 0) c = n;
else throw t;
}
const l = t.result(c);
if (!r) return l;
const u = asOptionalRecord(c)?.deliveryStatus === "partial_failed";
if (l.kind === "send" || l.kind === "poll") return {
...l,
handledBy: "core",
...u ? {} : l.kind === "send" ? { sendResult: c } : { pollResult: c }
};
return l;
}
async function executeMessagePoll(e) {
const { cfg: t, params: n, channel: r, channelPlugin: i, accountId: a, dryRun: o, input: s, agentId: c, abortSignal: l } = e;
throwIfAborted(l);
const u = "poll";
const d = readToolStringParam(n, "to", { required: true });
const f = readBooleanParam(n, "silent");
const p = resolveAndApplyOutboundThreadId(n, {
cfg: t,
to: d,
accountId: a,
toolContext: s.toolContext,
resolveAutoThreadId: i.threading?.resolveAutoThreadId
});
const m = typeof n.message === "string" ? n.message : "";
await applyMessageCrossContextMarker({
cfg: t,
channel: r,
action: u,
target: d,
toolContext: s.toolContext,
accountId: a,
agentId: c,
args: n,
message: m,
preferPresentation: false
});
const h = await executeGatewayAction(e, {
action: u,
result: (e) => ({
kind: "poll",
channel: r,
action: u,
to: d,
handledBy: "plugin",
payload: e,
dryRun: o
})
});
const g = Boolean(readToolStringParam(n, "replyTo"));
if (h) return await annotateSourceDelivery(h, e, g);
const _ = await executePollAction({
ctx: {
...e,
mediaAccess: void 0,
input: {
cfg: t,
action: u,
params: n,
requesterAccountId: s.requesterAccountId,
requesterSenderId: s.requesterSenderId,
conversationReadOrigin: s.conversationReadOrigin,
sessionKey: s.sessionKey,
sessionId: s.sessionId,
inboundEventKind: s.inboundEventKind,
toolContext: s.toolContext,
messageActionAuthorization: s.messageActionAuthorization,
gatewayOwnedDelivery: s.gatewayOwnedDelivery,
onPlatformSendDispatch: s.onPlatformSendDispatch,
assertDirectAdapterHandoff: s.assertDirectAdapterHandoff
},
silent: f ?? void 0
},
resolveCorePoll: () => {
const e = readToolStringParam(n, "pollQuestion", { required: true });
const t = readStringArrayParam(n, "pollOption", { required: true });
if (t.length < 2) throw new Error("pollOption requires at least two values");
let r = readToolStringParam(n, "message", {
allowEmpty: true,
trim: false
});
if (r !== void 0 && !r.trim()) r = "";
const i = readBooleanParam(n, "pollMulti") ?? false;
const a = readPositiveIntegerParam(n, "pollDurationHours", { message: "pollDurationHours must be a positive integer" });
return {
to: d,
question: e,
content: r,
options: t,
maxSelections: resolvePollMaxSelections(t.length, i),
durationHours: a ?? void 0,
threadId: p ?? void 0
};
}
});
return await annotateSourceDelivery({
kind: "poll",
channel: r,
action: u,
to: d,
handledBy: _.handledBy,
payload: _.payload,
toolResult: _.toolResult,
pollResult: _.pollResult,
dryRun: o
}, e, g);
}
async function executeMessagePlugin(e) {
const { cfg: t, params: n, channel: r, channelPlugin: i, mediaAccess: a, accountId: o, dryRun: s, input: c, abortSignal: l } = e;
throwIfAborted(l);
const u = c.action;
const d = {
kind: "action",
channel: r,
action: u,
...e.resolvedTarget ? { to: e.resolvedTarget.to } : {},
dryRun: s
};
if (s) return {
...d,
handledBy: "dry-run",
payload: {
ok: true,
dryRun: true,
channel: r,
action: u
}
};
if (!i.actions?.handleAction) throw new Error(`Message action ${u} not supported for channel ${r}.`);
const f = n.message;
if (typeof f === "string" && f) n.message = stripPlainTextToolCallBlocks(stripUnsupportedCitationControlMarkers(f));
const p = normalizeOptionalString(n.to) ?? normalizeOptionalString(n.channelId) ?? "";
if (p && u !== "download-file") resolveAndApplyOutboundThreadId(n, {
cfg: t,
to: p,
accountId: o,
toolContext: c.toolContext,
resolveAutoThreadId: i.threading?.resolveAutoThreadId,
resolveReplyTransport: i.threading?.resolveReplyTransport,
replyToIsExplicit: Boolean(readToolStringParam(n, "replyTo"))
});
const m = await executeGatewayAction(e, {
action: u,
result: (e) => ({
...d,
handledBy: "plugin",
payload: e
})
});
const h = Boolean(readToolStringParam(n, "replyTo"));
if (m) return await annotateSourceDelivery(m, e, h);
const finishPluginAction = (t, n) => annotateSourceDelivery({
...d,
handledBy: "plugin",
payload: t,
...n ? { toolResult: n } : {}
}, e, h);
const g = c.messageActionAuthorization;
let _;
try {
_ = await dispatchChannelMessageAction({
...createChannelActionContext({
ctx: e,
action: u,
mediaAccess: a
}),
progressSnapshot: c.progressSnapshot,
requesterAccountId: g !== void 0 ? g.requesterAccountId : c.requesterAccountId ?? void 0,
requesterSenderId: g !== void 0 ? g.requesterSenderId : c.requesterSenderId ?? void 0,
toolContext: g !== void 0 ? g.toolContext : c.toolContext,
messageActionAuthorization: g,
deliveryRetryOwner: c.actionOrigin === "message-tool" ? "caller" : void 0,
skipQueue: c.skipQueue
});
} catch (e) {
const t = c.messageActionAuthorization?.scheduled ? projectMessageActionPartialDelivery(e) : void 0;
if (t) return await finishPluginAction(t);
throw e;
}
if (!_) throw new Error(`Message action ${u} not supported for channel ${r}.`);
return await finishPluginAction(extractToolPayload(_), _);
}
//#endregion
//#region src/infra/outbound/message-action-routing.ts
function addTargetCandidates(e, t, n) {
const r = normalizeOptionalString(t);
if (!r) return;
e.add(r);
const i = r.replace(/^(channel|group|user):/i, "").trim();
if (i && i !== r) e.add(i);
if (n !== void 0) {
const r = normalizeTargetForAccountBinding(n, t);
if (r) addTargetCandidates(e, r);
}
}
function normalizeTargetForAccountBinding(e, t) {
try {
return normalizeTargetForProvider(e, t);
} catch {
return;
}
}
function inferPeerKindForAccountBinding(e, t, n) {
const r = normalizeChatType(n?.messaging?.inferTargetChatType?.({ to: t }));
if (r) return r;
const i = [t, normalizeTargetForAccountBinding(e, t)].filter((e) => Boolean(e));
if (i.some((e) => /^user:/i.test(e))) return "direct";
if (i.some((e) => /^(channel|group):/i.test(e))) return "channel";
}
function hasExplicitSingularTargetParam(e) {
return readTrimmedStringAlias(e, [
"target",
"to",
"channelId"
]) !== void 0;
}
function hasExplicitTargetParam(e) {
return hasExplicitSingularTargetParam(e) || Array.isArray(e.targets) && e.targets.some((e) => normalizeOptionalString(e));
}
function hasPotentialActionTargetInput(e, t) {
return Boolean(hasExplicitSingularTargetParam(t) || resolveImplicitMessageActionTarget(e.toolContext) || hasPotentialPluginActionParam(t));
}
function isCurrentSourceTargetParam(e, t) {
const n = normalizeOptionalString(e.toolContext?.currentChannelId);
const r = normalizeOptionalString(e.toolContext?.currentMessagingTarget);
if (!n && !r) return false;
const i = normalizeOptionalLowercaseString(e.toolContext?.currentChannelProvider);
const a = normalizeOptionalLowercaseString(t.channel);
if (a && i && a !== i) return false;
const o = readTrimmedStringAlias(t, [
"target",
"to",
"channelId"
]);
if (!o) return false;
const s = a ?? i;
const c = /* @__PURE__ */ new Set();
for (const e of [r, n]) {
if (!e) continue;
addTargetCandidates(c, e, s);
}
const l = /* @__PURE__ */ new Set();
addTargetCandidates(l, o, s);
return Array.from(l).some((e) => c.has(e));
}
function hasExplicitNonCurrentChannelParam(e, t) {
const n = normalizeOptionalLowercaseString(t.channel);
if (!n) return false;
const r = normalizeOptionalLowercaseString(e.toolContext?.currentChannelProvider);
return !r || n !== r;
}
function applyImplicitSourceReplySendPolicy(e, t) {
if (e.action !== "send" || e.sourceReplyDeliveryMode !== "message_tool_only") return;
if (hasExplicitNonCurrentChannelParam(e, t)) return;
if (hasExplicitTargetParam(t) && !isCurrentSourceTargetParam(e, t)) return;
t.bestEffort = true;
}
async function prepareMessageRoute(e) {
const { input: t, agentId: n } = e;
const r = t.cfg;
const i = t.action;
let a = e.actionParams;
applyImplicitSourceReplySendPolicy(t, a);
if (actionRequiresTarget(i) && !hasPotentialActionTargetInput(t, a)) throw missingMessageActionTargetError(i, { hasCurrentSourceConversation: Boolean(resolveImplicitMessageActionTarget(t.toolContext, "send")) });
const o = readToolStringParam(a, "channel");
const { channel: s, plugin: c } = await resolveMessageChannelSelection({
cfg: r,
channel: o,
fallbackChannel: i === "read" && o ? void 0 : t.toolContext?.currentChannelProvider,
agentId: n
});
a.channel = s;
const l = await validateExplicitMessageAccountSelection({
cfg: r,
channel: s,
accountId: readToolStringParam(a, "accountId"),
plugin: c
});
if (i !== "send" && i !== "poll" && c.actions?.supportsAction && !c.actions.supportsAction({ action: i })) throw new Error(`Message action ${i} not supported for channel ${s}.`);
a = normalizeMessageActionInput({
action: i,
args: a,
toolContext: t.toolContext,
targetAliasSpec: c.actions?.messageActionTargetAliases?.[i] ?? null,
allowResourceOnly: t.conversationReadOrigin === "direct-operator"
});
let u = l ?? t.defaultAccountId;
if (!u && n) {
const e = readTrimmedStringAlias(a, ["to", "channelId"]);
if (!e) u = resolveFirstBoundAccountId({
cfg: r,
channelId: s,
agentId: n
});
else {
const t = /* @__PURE__ */ new Set();
addTargetCandidates(t, e, s);
const [i, ...a] = Array.from(t);
u = resolveFirstBoundAccountId({
cfg: r,
channelId: s,
agentId: n,
peerId: i,
exactPeerIdAliases: a,
peerKind: inferPeerKindForAccountBinding(s, e, c)
});
}
}
const d = Boolean(t.gateway) && c.actions?.resolveExecutionMode?.({ action: i }) === "gateway";
if (!u && i === "send" && !d && (c.outbound?.deliveryMode !== "gateway" || t.gatewayOwnedDelivery === true)) u = resolveChannelDefaultAccountId({
plugin: c,
cfg: r
});
if (u) a.accountId = u;
const f = Boolean(t.dryRun ?? readBooleanParam(a, "dryRun"));
const p = t.toolContext?.currentChannelProvider;
if (p && p !== s) enforceCrossContextPolicy({
channel: s,
action: i,
args: a,
toolContext: t.toolContext,
cfg: r,
agentId: n
});
const m = d && !f && shouldDeferExternalMessageActionTargetResolution({
channel: s,
action: i,
cfg: r,
params: a,
accountId: u ?? void 0,
conversationReadOrigin: normalizeConversationReadInvocationOrigin(t.conversationReadOrigin),
messageActionAuthorization: t.messageActionAuthorization
});
let h;
let g;
if (!d || f) {
const e = t.messageActionAuthorization;
const o = await prepareExternalMessageActionTargetForResolution({
channel: s,
action: i,
cfg: r,
params: a,
accountId: u ?? void 0,
agentId: n,
sessionKey: t.sessionKey,
sessionId: t.sessionId,
requesterAccountId: e !== void 0 ? e.requesterAccountId : t.requesterAccountId ?? void 0,
requesterSenderId: e !== void 0 ? e.requesterSenderId : t.requesterSenderId ?? void 0,
senderIsOwner: t.senderIsOwner,
conversationReadOrigin: normalizeConversationReadInvocationOrigin(t.conversationReadOrigin),
toolContext: e !== void 0 ? e.toolContext : t.toolContext,
messageActionAuthorization: e,
assertDirectAdapterHandoff: t.assertDirectAdapterHandoff
});
a = o.params;
u = o.accountId ?? u;
h = o.assertReadAuthorityCurrent;
g = o.assertTargetAuthorityCurrent;
}
return {
params: a,
channel: s,
channelPlugin: c,
accountId: u,
dryRun: f,
defersExternalTargetResolution: m,
assertReadAuthorityCurrent: h,
assertTargetAuthorityCurrent: g
};
}
async function resolveMessageTarget(e) {
let t;
if (!e.deferExternalTargetResolution) for (const n of ["to", "channelId"]) {
const r = normalizeOptionalString(e.args[n]);
if (!r) continue;
const i = await resolveChannelTarget({
cfg: e.cfg,
channel: e.channel,
input: r,
accountId: e.accountId ?? void 0,
plugin: e.plugin,
...n === "channelId" ? { preferredKind: "group" } : {}
});
if (!i.ok) throw i.error;
const a = i.target;
if (n === "channelId" && a.kind === "user") throw invalidMessageActionTargetError(`Channel id "${r}" resolved to a user target.`);
if (n === "to") t = a;
e.args[n] = n === "to" ? a.to : a.to.replace(/^(channel|group):/i, "");
}
enforceCrossContextPolicy({
channel: e.channel,
action: e.action,
args: e.args,
toolContext: e.toolContext,
cfg: e.cfg,
agentId: e.agentId
});
return t;
}
//#endregion
//#region src/infra/outbound/message-action-send-payload.ts
const LEGACY_SEND_MEDIA_SOURCE_KEYS = [
"path",
"filePath",
"fileUrl",
"image"
];
function updateSendPayloadPartsFromReplyPayload(e, t) {
const n = resolveSendableOutboundReplyParts(t);
const r = n.mediaUrls.length > 0 ? n.mediaUrls : void 0;
return {
...e,
message: t.text ?? "",
payload: t,
mediaUrl: r?.[0],
mediaUrls: r,
asVoice: t.audioAsVoice === true
};
}
function applySendLocationToActionParams(e, t) {
if (t) e.location = t;
else delete e.location;
}
function applySendPayloadPartsToActionParams(e, t) {
if (t.message || !t.payload.presentation) e.message = t.message;
else delete e.message;
e.media = t.mediaUrl;
e.mediaUrl = t.mediaUrl;
e.mediaUrls = t.mediaUrls;
e.attachments = t.payload.attachments?.map((e) => ({ ...e }));
for (const t of LEGACY_SEND_MEDIA_SOURCE_KEYS) delete e[t];
e.asVoice = t.asVoice || void 0;
e.audioAsVoice = t.asVoice || void 0;
e.asVideoNote = t.payload.videoAsNote || void 0;
applySendLocationToActionParams(e, t.payload.location);
}
function withSendNormalization(e, t) {
return t && e.kind === "send" ? {
...e,
normalization: t
} : e;
}
//#endregion
//#region src/shared/text/formatted-reasoning-message.ts
function stripFormattedReasoningMessage(e) {
const t = stripReasoningTagsFromText(e, { trim: "none" });
const n = t === e ? t : t.trimStart();
const r = n.indexOf("\n");
const i = (r === -1 ? n : n.slice(0, r)).trim();
const a = /^Thinking\.{0,3}$/u.test(i);
if (i !== "Reasoning:" && !a) return n ? t : "";
let o = r === -1 ? n.length : r + 1;
let s = false;
while (o < n.length) {
const e = n.indexOf("\n", o);
const t = e === -1 ? n.length : e;
const r = n.slice(o, t).trim();
const i = r.length >= 2 && r.startsWith("_") && r.endsWith("_");
if (r && !i) break;
s ||= i;
o = t + 1;
}
return a && !s ? t : n.slice(o).replace(/\r\n/g, "\n").replace(/\n+$/u, "");
}
//#endregion
//#region src/infra/outbound/message-action-gateway-transcript.ts
const log$1 = createSubsystemLogger("outbound/message-action-send");
/**
* Records a Gateway-executed plugin send in its destination conversation.
* The channel already accepted the send, so failures are only logged.
*/
async function recordGatewayActionSend(e) {
try {
const t = await commitConfirmedVisibleMessage({
config: e.cfg,
channel: e.channel,
to: e.to,
accountId: e.accountId,
threadId: e.route.threadId,
route: e.route,
producer: buildOutboundSessionContext({
cfg: e.cfg,
sessionKey: e.producerSessionKey,
agentId: e.agentId
}),
payload: e.payload,
deliveryId: e.deliveryId,
payloadIndex: 0,
signal: e.signal
});
const n = t.ok ? t.diagnostics : t.reason;
if (n) log$1.warn(`Confirmed gateway action transcript: ${n}`);
} catch (e) {
log$1.warn(`Confirmed gateway action transcript commit failed: ${formatErrorMessage(e)}`);
}
}
//#endregion
//#region src/infra/outbound/message-action-send.ts
const log = createSubsystemLogger("outbound/message-action");
const loadMessageActionTtsRuntime = createLazyRuntimeModule(() => import("./tts.runtime.js"));
function resolveReplyMediaAttachmentType(e) {
return e === "image" || e === "audio" || e === "video" || e === "file" ? e : void 0;
}
async function buildMessagePayload(e) {
const { actionParams: t, input: n } = e;
if (t.pin === true && t.delivery == null) t.delivery = { pin: { enabled: true } };
if (typeof t.message !== "string" || !t.message.trim()) for (const e of [
"SendMessage",
"content",
"text"
]) {
const n = t[e];
if (typeof n === "string" && n.trim()) {
t.message = stripFormattedReasoningMessage(n);
console.warn(`[message-tool] normalized alias "${e}" to "message" for send action`);
break;
}
}
const r = readToolStringParam(t, "media", { trim: false }) ?? readToolStringParam(t, "mediaUrl", { trim: false }) ?? readToolStringParam(t, "path", { trim: false }) ?? readToolStringParam(t, "filePath", { trim: false }) ?? readToolStringParam(t, "fileUrl", { trim: false }) ?? readToolStringParam(t, "image", { trim: false });
const i = readStringArrayParam(t, "mediaUrls") ?? [];
const a = collectAttachmentSources(t);
const o = Boolean(readToolStringParam(t, "buffer", { trim: false }));
const s = o || Boolean(r) || i.length > 0 || a.length > 0;
const c = hasMessagePresentationBlocks(t.presentation);
const l = hasLegacyInteractiveReplyBlocks(t.interactive);
const u = t.location;
let d = typeof u === "string" && normalizeOptionalString(u) === void 0 ? void 0 : normalizeOutboundLocation(u);
const f = readToolStringParam(t, "caption", { trim: false }) ?? "";
const p = readToolStringParam(t, "voiceText");
const m = readToolStringParam(t, "voiceProvider");
const h = readToolStringParam(t, "voiceId");
let g = readToolStringParam(t, "message", {
required: !s && !c && !l && !d && !p,
allowEmpty: true,
trim: false
}) ?? "";
let _;
g = g.replace(/\\n/g, (e, t) => isInsideCode(t, _ ??= findMarkdownCodeRegions(g)) ? e : "\n");
if (!g.trim()) g = f.trim() ? f : "";
const v = parseInlineDirectives(g, {
stripAudioTag: true,
stripReplyTags: true
});
const y = readToolStringParam(t, "filename");
const b = readToolStringParam(t, "contentType");
const x = a.map((e) => ({
url: e.value,
filename: e.filename,
mimeType: e.contentType,
type: resolveReplyMediaAttachmentType(e.attachment.type)
}));
const S = new Map(x.map(({ url: e, ...t }) => [normalizeOptionalString(e), t]));
const C = S.get(normalizeOptionalString(r));
const w = [
{
url: r,
...C,
filename: y ?? C?.filename,
mimeType: b ?? C?.mimeType
},
...i.map((e) => Object.assign({ url: e }, S.get(normalizeOptionalString(e)))),
...x
].flatMap((e) => {
const t = normalizeOptionalString(e.url);
return t ? [{
...e,
url: t
}] : [];
});
const T = await Promise.all(w.map(async (e) => {
e.url = await normalizeSandboxMediaSource({
value: e.url,
sandboxRoot: n.sandboxRoot,
sandboxContainerWorkdir: n.sandboxContainerWorkdir
});
return e;
}));
const E = dedupeByKey(T, (e) => e.url);
const D = E.map((e) => e.url);
const O = E.map((e) => Object.assign({ path: e.url }, e.type ? { type: e.type } : {}, e.filename ? { name: e.filename } : {}, e.mimeType ? { mimeType: e.mimeType } : {}));
g = stripPlainTextToolCallBlocks(stripUnsupportedCitationControlMarkers(v.text), { resolveProtectedRanges: findMarkdownCodeRegions });
const updateActionMessage = () => {
if (g || !c) t.message = g;
else delete t.message;
};
updateActionMessage();
if (!t.replyTo && v.replyToId) t.replyTo = v.replyToId;
if (!t.media) t.media = D[0] || void 0;
t.mediaUrls = D.length > 0 ? [...D] : void 0;
const k = Boolean(d && (g.trim() || p || o || D.length > 0 || c || l));
const A = k && n.actionOrigin === "message-tool" ? {
locationOmitted: true,
notice: "Content sent; location omitted because locations must be sent separately. Do not retry this send. Send a standalone location only if the user explicitly requested it."
} : void 0;
if (k && !A) throw new Error("Location sends cannot be combined with message text or media.");
if (A) d = void 0;
applySendLocationToActionParams(t, d);
if (e.channel && e.target) {
const { channel: r, target: i } = e;
g = await withChannelReadAuthority(n.messageActionAuthorization?.scheduled ? n.assertDirectAdapterHandoff : void 0, () => applyMessageCrossContextMarker({
cfg: n.cfg,
channel: r,
action: "send",
target: i,
toolContext: n.toolContext,
accountId: e.accountId,
agentId: e.agentId,
args: t,
message: g,
preferPresentation: true
}));
}
const j = readToolStringParam(t, "media", { trim: false });
if (!p && !hasReplyPayloadContent({
text: g,
mediaUrl: j,
mediaUrls: D,
presentation: t.presentation,
interactive: t.interactive,
location: d
})) throw new Error("send requires text or media or location");
updateActionMessage();
const M = readBooleanParam(t, "gifPlayback") ?? false;
const N = readBooleanParam(t, "forceDocument") ?? readBooleanParam(t, "asDocument") ?? false;
const P = readBooleanParam(t, "asVoice") ?? readBooleanParam(t, "audioAsVoice") ?? v.audioAsVoice;
const F = readBooleanParam(t, "asVideoNote") ?? false;
const I = readBooleanParam(t, "bestEffort");
const L = readBooleanParam(t, "silent");
const R = D.length > 0 ? D : j ? [j] : void 0;
const z = t.delivery;
const B = z && typeof z === "object" && !Array.isArray(z) ? z : void 0;
const V = asOptionalRecord(t.channelData);
const H = normalizeMessagePresentation(t.presentation);
const U = normalizeLegacyInteractiveReply(t.interactive);
const W = {
text: g,
...j ? { mediaUrl: j } : {},
...D.length ? { mediaUrls: D } : {},
...O.some((e) => Object.keys(e).length > 1) ? { attachments: O } : {},
...P ? { audioAsVoice: true } : {},
...F ? { videoAsNote: true } : {},
...d ? { location: d } : {},
...H ? { presentation: H } : {},
...U ? { interactive: U } : {},
...B ? { delivery: B } : {},
...V ? { channelData: V } : {}
};
const G = p || m || h ? {
tagged: true,
...p ? { text: p } : {},
...m || h ? { directives: [{
...m ? { provider: m.toLowerCase() } : {},
values: h ? { voiceid: h } : {}
}] } : {}
} : void 0;
return {
message: g,
payload: G ? setReplyPayloadMetadata(W, {
tts: G,
ttsExplicit: true
}) : W,
...j ? { mediaUrl: j } : {},
...R ? { mediaUrls: R } : {},
asVoice: P,
gifPlayback: M,
forceDocument: N,
...I !== void 0 ? { bestEffort: I } : {},
...L !== void 0 ? { silent: L } : {},
...A ? { normalization: A } : {}
};
}
const UNRESOLVED_PREFIX_VAR_PATTERN = /\{[a-zA-Z][a-zA-Z0-9.]*\}/;
async function executeMessageSend(e) {
const { cfg: t, params: n, channel: r, channelPlugin: i, accountId: a, dryRun: o, gateway: s, input: c, agentId: l, resolvedTarget: u, abortSignal: d } = e;
throwIfAborted(d);
const f = "send";
const p = readToolStringParam(n, "to", { required: true });
let m = await buildMessagePayload({
actionParams: n,
input: c,
channel: r,
target: p,
accountId: a,
agentId: l
});
const h = resolveResponsePrefixTemplate(resolveResponsePrefix(t, l ?? "", {
channel: r,
accountId: a ?? void 0
}), { identityName: normalizeOptionalString(resolveAgentIdentity(t, l ?? "")?.name) });
const g = h !== void 0 && UNRESOLVED_PREFIX_VAR_PATTERN.test(h);
if (h && !g && m.message && !m.message.startsWith(h)) {
const e = `${h} ${m.message}`;
m = {
...m,
message: e,
payload: copyReplyPayloadMetadata(m.payload, {
...m.payload,
text: e
})
};
applySendPayloadPartsToActionParams(n, m);
}
const _ = resolveAndApplyOutboundReplyToId(n, {
channel: r,
toolContext: c.toolContext,
matchesToolContextTarget: i.threading?.matchesToolContextTarget
});
const v = resolveAndApplyOutboundThreadId(n, {
cfg: t,
to: p,
accountId: a,
toolContext: c.toolContext,
resolveAutoThreadId: i.threading?.resolveAutoThreadId,
resolveReplyTransport: i.threading?.resolveReplyTransport,
replyToIsExplicit: _?.source === "explicit"
});
const y = l && !o ? await resolveOutboundSessionRoute({
cfg: t,
channel: r,
agentId: l,
accountId: a,
target: p,
currentSessionKey: c.sessionKey,
resolvedTarget: u,
replyToId: readToolStringParam(n, "replyTo"),
threadId: v
}) : null;
if (y) n["__sessionKey"] = y.sessionKey;
if (l) n["__agentId"] = l;
const b = readToolStringParam(n, "replyTo");
const x = _ && b && b !== _.replyToId ? {
..._,
replyToId: b
} : _;
let S = false;
const commitOutboundSessionRoute = async () => {
if (S || !y) return;
S = true;
await ensureOutboundSessionEntry({
cfg: t,
channel: r,
accountId: a,
route: y,
sourceSessionKey: c.sessionKey
});
};
throwIfAborted(d);
let C = m.payload;
if (!o) {
const e = c.sessionKey?.trim();
let n;
if (e) try {
const r = resolveSessionStorePathCore(t.session?.store, { agentId: l });
n = (await readSessionEntryReadOnlyInWorker({
agentId: l,
sessionKey: e,
storePath: r
}))?.ttsAuto;
} catch {}
const i = getReplyPayloadMetadata(C)?.ttsExplicit === true;
const o = await prepareTtsPreferences();
if (i || shouldAttemptTtsPayload({
cfg: t,
preparedTtsPreferences: o,
ttsAuto: n,
agentId: l,
channelId: r,
accountId: a ?? void 0
})) {
const { maybeApplyTtsToPayload: e } = await loadMessageActionTtsRuntime();
C = await e({
payload: C,
preparedTtsPreferences: o,
cfg: t,
channel: r,
kind: "final",
inboundAudio: c.inboundAudio,
ttsAuto: n,
agentId: l,
accountId: a ?? void 0
});
}
}
if (C !== m.payload) {
m = updateSendPayloadPartsFromReplyPayload(m, C);
applySendPayloadPartsToActionParams(n, m);
}
delete n.voiceText;
delete n.voiceProvider;
delete n.voiceId;
throwIfAborted(d);
const w = c.mediaAccess ?? resolveAgentScopedOutboundMediaAccess({
cfg: t,
agentId: l,
mediaSources: m.mediaUrls,
...messageActionRequesterMediaContext(c),
messageProvider: c.sessionKey ? void 0 : r,
accountId: c.sessionKey ? c.requesterAccountId ?? a : a
});
const T = c.forceCoreDelivery === true || c.requireQueuePersistence === true;
if (!T && Boolean(s) && (i.actions?.resolveExecutionMode?.({ action: f }) === "gateway" || i.outbound?.deliveryMode === "gateway") && !o) {
let e = m.payload;
const i = m.mediaUrls;
const o = c.workspaceMediaAccess?.localRoots ?? [];
if (i?.length && o.length > 0) {
const n = resolveOutboundMediaMaxBytes({
cfg: t,
channel: r,
accountId: a
});
const s = await Promise.all(i.map(async (e) => {
const t = resolveLocalMediaPath(e);
if (!t || !o.some((e) => isPathInside(path.resolve(e), path.resolve(t)))) return e;
return (await resolveOutboundAttachmentFromUrl(e, n, { mediaAccess: w })).path;
}));
if (!s.every((e, t) => e === i[t])) {
const t = e.attachments?.map((e, t) => {
const { url: n, mediaUrl: r, filePath: i, ...a } = e;
return {
...a,
path: s[t]
};
});
e = {
...e,
mediaUrl: s[0],
mediaUrls: s,
...t ? { attachments: t } : {}
};
}
}
m = updateSendPayloadPartsFromReplyPayload(m, e);
applySendPayloadPartsToActionParams(n, m);
}
const E = T ? null : await executeGatewayAction(e, {
action: f,
reply: x,
result: (e) => ({
kind: "send",
channel: r,
action: f,
to: p,
accountId: a ?? void 0,
handledBy: "plugin",
payload: e,
dryRun: o
})
});
if (E) {
const i = projectPluginMessageDeliveryFact(E.payload);
if (!i || i.status === "settled") {
await commitOutboundSessionRoute();
if (!o && y && !i?.partialDelivery) await recordGatewayActionSend({
cfg: t,
channel: r,
to: p,
accountId: e.accountId ?? void 0,
route: y,
producerSessionKey: c.sourceReplySessionKey ?? c.sessionKey,
agentId: l,
payload: m.payload,
deliveryId: normalizeOptionalString(n.idempotencyKey) ?? c.deliveryIntentId ?? randomUUID(),
signal: e.abortSignal
});
}
return await annotateSourceDelivery(withSendNormalization(E, m.normalization), e, x?.source === "explicit");
}
const D = Boolean(m.payload.presentation && hasCorePresentationDelivery(i.outbound));
if (m.payload.presentation && !D) {
const e = materializeMessagePresentationFallback({
payload: m.payload,
text: m.message
});
m = {
...m,
message: e,
payload: {
...m.payload,
text: e
}
};
applySendPayloadPartsToActionParams(n, m);
}
const O = await executeSendAction({
ctx: {
...e,
mediaAccess: w,
conversationType: y?.chatType,
deliveryRetryOwner: c.actionOrigin === "message-tool" ? "caller" : void 0,
onSendAccepted: commitOutboundSessionRoute,
transcriptRoute: y ?? void 0,
silent: m.silent ?? void 0
},
to: p,
message: m.message,
payload: m.payload,
mediaUrl: m.mediaUrl,
mediaUrls: m.mediaUrls,
buffer: readToolStringParam(n, "buffer", { trim: false }) ?? void 0,
filename: readToolStringParam(n, "filename") ?? void 0,
contentType: readToolStringParam(n, "contentType") ?? void 0,
asVoice: m.asVoice,
gifPlayback: m.gifPlayback,
forceDocument: m.forceDocument,
bestEffort: m.bestEffort,
reply: x,
threadId: v ?? void 0
});
if (O.handledBy === "core") {
const e = O.sendResult?.deliveryStatus;
const t = projectPluginMessageDeliveryFact(O.payload);
if (e !== "failed" && e !== "suppressed" && (!t || t.status === "settled")) await commitOutboundSessionRoute();
}
const k = {
kind: "send",
channel: r,
action: f,
to: p,
accountId: a ?? void 0,
handledBy: O.handledBy,
payload: O.payload,
...O.deliveredText ? { deliveredText: O.deliveredText } : {},
toolResult: O.toolResult,
sendResult: O.sendResult,
dryRun: o
};
const A = projectPluginMessageDeliveryFact(O.payload);
if (!o && !c.gatewayOwnedDelivery && O.deliveredPayloads?.length && A?.status === "settled" && !A.partialDelivery) try {
await mirrorDeliveredSourceReplyToTranscript({
action: f,
channel: r,
actionParams: n,
cfg: t,
accountId: a,
agentId: l,
currentAccountId: c.messageActionAuthorization?.requesterAccountId,
sessionKey: c.sourceReplySessionKey ?? c.sessionKey,
sessionId: c.sessionId,
toolContext: c.messageActionAuthorization?.toolContext,
idempotencyKey: e.idempotencyKey,
sourceReplyFinal: c.sourceReplyFinal,
toolCallId: c.sourceReplyToolCallId,
deliveredPayload: O.payload,
deliveredPayloads: O.deliveredPayloads,
replyToIsExplicit: x?.source === "explicit",
runId: c.runId
});
} catch (e) {
log.warn(`Source reply transcript commit failed: ${formatErrorMessage(e)}`);
}
return await annotateSourceDelivery(withSendNormalization(k, m.normalization), e, x?.source === "explicit");
}
//#endregion
//#region src/infra/outbound/message-action-runner.ts
const loadInternalSourceReplyPersistence = createLazyRuntimeModule(() => import("./internal-source-reply-persistence-Cj_iYel-.mjs"));
const loadClawHubRecommendations = createLazyRuntimeModule(() => import("./clawhub-recommendations-DzNocdwi.mjs"));
function getToolResult(e) {
const t = "toolResult" in e ? e.toolResult : void 0;
if (e.kind !== "send" || !e.accountId) return t;
const n = t ?? jsonResult(e.payload);
return {
...n,
details: {
...asOptionalRecord(n.details),
accountId: e.accountId
}
};
}
function withMessageTargetPreparation(e, t, n) {
const r = n ? () => {
throwIfAborted(n);
e?.();
} : e;
return withChannelReadAuthority(r, t, n).catch((e) => {
assertOutboundHandoffCurrent(r);
throw e;
});
}
async function handleBroadcastAction(e, t) {
if (!(resolveEffectiveMessageToolsConfig({
cfg: e.cfg,
agentId: e.agentId
})?.broadcast?.enabled !== false)) throw new MessageActionDeniedError("Broadcast is disabled. Set tools.message.broadcast.enabled to true.", "message_broadcast_disabled", "message-broadcast:enabled");
const n = readStringArrayParam(t, "targets", { required: true });
const r = readToolStringParam(t, "channel");
const i = await validateExplicitMessageAccountSelection({
cfg: e.cfg,
accountId: readToolStringParam(t, "accountId"),
checkResolvedAccount: false
});
if (e.broadcastAccountPlan && e.broadcastAccountPlan.accountId !== i) throw new Error("Broadcast account plan does not match the requested account.");
let a;
if (r && normalizeOptionalLowercaseString(r) !== "all") a = [await resolveMessageChannelSelection({
cfg: e.cfg,
channel: r,
fallbackChannel: e.toolContext?.currentChannelProvider,
agentId: e.agentId
})];
else a = (e.broadcastAccountPlan ? e.broadcastAccountPlan.candidateChannels : await listConfiguredMessageChannels(e.cfg)).map((e) => ({
channel: e,
plugin: getRuntimeVisibleChannelPlugin(e)
}));
if (a.length === 0) throw new Error("Broadcast requires at least one configured channel.");
const o = [];
const s = e.messageActionAuthorization?.scheduled ? normalizeOptionalString(t.idempotencyKey) : void 0;
const hasAcceptedResult = () => !e.dryRun && o.some((e) => e.ok || e.sentBeforeError);
const errorSentBefore = (e) => e !== null && typeof e === "object" && e.sentBeforeError === true;
const captureInterruption = () => {
try {
throwIfAborted(e.abortSignal);
e.assertDirectAdapterHandoff?.();
} catch (e) {
return toErrorObject(e, "Message action interrupted");
}
};
let c = false;
for (const { channel: r, plugin: l } of a) for (const a of n) {
const n = `broadcast:${o.length}`;
const u = !c && hasAcceptedResult();
if (!c) try {
throwIfAborted(e.abortSignal);
e.assertDirectAdapterHandoff?.();
} catch (e) {
if (!u) throw e;
c = true;
}
if (c) {
o.push({
channel: r,
to: a,
ok: false,
attempted: false,
error: "Broadcast canceled before this target was attempted."
});
continue;
}
try {
const d = await validateExplicitMessageAccountSelection({
cfg: e.cfg,
channel: r,
accountId: i
});
const f = { to: a };
const p = await withMessageTargetPreparation(e.assertDirectAdapterHandoff, () => resolveMessageTarget({
cfg: e.cfg,
channel: r,
action: "send",
args: f,
accountId: d,
plugin: l
}), e.abortSignal);
if (!p) throw new Error("Broadcast target resolution unexpectedly deferred.");
const m = await runMessageAction({
...e,
action: "send",
params: {
...t,
channel: r,
target: p.to,
...s ? { idempotencyKey: `${s}:${n}` } : {}
}
});
const h = resolveMessageActionOutcome(m, "Broadcast");
const g = {
channel: r,
to: p.to,
...h,
payload: m.kind === "send" ? m.payload : void 0,
result: m.kind === "send" ? m.sendResult : void 0
};
const _ = h.ok ? void 0 : captureInterruption();
if (_) {
if (!u && !h.ok && !h.sentBeforeError) throw _;
c = true;
}
o.push(g);
} catch (t) {
if (t instanceof MessageActionDeniedError) e.onActionDenied?.(t, r, n);
const i = t instanceof OutboundHandoffRejectedError ? t : captureInterruption();
let s;
if (i) {
s = errorSentBefore(t);
if (!u && !s) throw t;
c = true;
}
o.push({
channel: r,
to: a,
ok: false,
...i && !s && t instanceof OutboundHandoffRejectedError ? {
attempted: false,
error: "Broadcast canceled before this target was attempted."
} : {
error: formatErrorMessage(t),
...s ?? errorSentBefore(t) ? { sentBeforeError: true } : {}
}
});
}
}
return {
kind: "broadcast",
channel: a[0]?.channel ?? normalizeOptionalLowercaseString(r) ?? "unknown",
action: "broadcast",
handledBy: e.dryRun ? "dry-run" : "core",
payload: { results: o },
dryRun: Boolean(e.dryRun)
};
}
async function handleInternalSourceReplySendAction(e, t) {
throwIfAborted(e.abortSignal);
const n = Boolean(e.dryRun ?? readBooleanParam(t, "dryRun"));
const r = e.agentId;
let i;
if (t.clawhub !== void 0) {
if (normalizeMessageChannel(e.toolContext?.currentChannelProvider) !== "webchat") throw new Error("ClawHub recommendation cards require the current Control UI conversation.");
const { resolveClawHubRecommendations: n } = await loadClawHubRecommendations();
i = await n({
request: t.clawhub,
config: e.cfg,
agentId: r,
workspaceDir: e.workspaceDir ?? (r ? resolveAgentWorkspaceDir(e.cfg, r) : void 0)
});
throwIfAborted(e.abortSignal);
if (!normalizeOptionalString(t.message) && !normalizeOptionalString(t.caption)) t.message = i.text;
}
const a = collectActionMediaSourceHints(t, [], { structuredAttachments: "all" });
await waitForLocalMessageMedia({
...e,
sources: a,
assertCurrent: e.assertDirectAdapterHandoff
});
const o = e.mediaAccess ?? resolveAgentScopedOutboundMediaAccess({
cfg: e.cfg,
agentId: r,
workspaceDir: e.workspaceDir,
mediaSources: a,
...messageActionRequesterMediaContext(e),
messageProvider: e.sessionKey ? void 0 : "webchat",
accountId: e.sessionKey ? e.requesterAccountId : void 0
});
const s = e.workspaceMediaAccess?.readFile ? o.readFile : void 0;
await hydrateAttachmentParamsForAction({
cfg: e.cfg,
channel: INTERNAL_MESSAGE_CHANNEL,
args: t,
action: "send",
dryRun: n,
mediaPolicy: resolveAttachmentMediaPolicy({
sandboxRoot: e.sandboxRoot,
sandboxContainerWorkdir: e.sandboxContainerWorkdir,
mediaAccess: o,
mediaReadFile: s
})
});
const c = await buildMessagePayload({
actionParams: t,
input: e,
agentId: r
});
let l = c.payload;
if (i) l = {
...l,
channelData: {
...l.channelData,
[CLAWHUB_RECOMMENDATIONS_CHANNEL_DATA_KEY]: i.cards
}
};
const u = resolveSendableOutboundReplyParts(l).mediaUrls.length;
if (!n && u > 0) {
const t = e.workspaceDir ?? o.workspaceDir ?? (r ? resolveAgentWorkspaceDir(e.cfg, r) : void 0);
if (!t) throw new Error("Current-source media requires an agent workspace.");
const { createReplyMediaPathNormalizer: n } = await import("./reply-media-paths-B8_L2AXz.mjs");
l = await n({
cfg: e.cfg,
sessionKey: e.sessionKey,
agentId: r,
workspaceDir: t,
messageProvider: INTERNAL_MESSAGE_CHANNEL,
requesterSenderId: e.requesterSenderId ?? void 0,
requesterSenderName: e.requesterSenderName ?? void 0,
requesterSenderUsername: e.requesterSenderUsername ?? void 0,
requesterSenderE164: e.requesterSenderE164 ?? void 0,
mediaAccess: o,
workspaceMediaAccess: e.workspaceMediaAccess,
htmlPublication: "explicit",
sandboxRoot: e.sandboxRoot,
sandboxContainerWorkdir: e.sandboxContainerWorkdir
})(l);
if (resolveSendableOutboundReplyParts(l).mediaUrls.length !== u) {
const e = appendReplyMediaFailures(void 0, getReplyPayloadMetadata(l)?.assistantMediaFailures ?? []);
throw new Error(e ? `Current-source media could not be staged.\n${e}` : "Current-source media could not be staged. Use an accessible URL, a file inside the agent workspace, or the buffer field.");
}
}
const d = resolveSendableOutboundReplyParts(l).mediaUrls;
const f = l.text ?? c.message;
const p = normalizeOptionalString(t.idempotencyKey);
let m = false;
if (!n) await beforeMessageDeliveryAttempt(e);
if (!n && e.sessionId) {
const t = e.sourceReplySessionKey ?? e.sessionKey;
if (!t) throw new Error("Internal source reply requires a session key");
const { persistInternalSourceReply: n } = await loadInternalSourceReplyPersistence();
const persist = () => runInAgentRunWriteContext(e.runId, persistReply);
const persistReply = () => n({
cfg: e.cfg,
sessionKey: t,
expectedSessionId: e.sessionId,
agentId: e.agentId ?? resolveSessionAgentId({
sessionKey: t,
config: e.cfg
}),
payload: l,
idempotencyKey: p,
runId: e.runId,
sourceReplyFinal: e.sourceReplyFinal,
toolCallId: e.sourceReplyToolCallId,
sourceTurnId: e.messageActionAuthorization?.toolContext?.currentSourceTurnId
});
if (e.messageActionAuthorization?.scheduled || e.messageActionAuthorization?.deliveryAttempt) await withSessionTranscriptWriteAssertion({
agentId: e.agentId ?? resolveSessionAgentId({
sessionKey: t,
config: e.cfg
}),
sessionKey: t,
sessionId: e.sessionId,
storePath: resolveSessionStorePathCore(e.cfg.session?.store, { agentId: r })
}, captureMessageDeliveryAuthority(e), persist);
else await persist();
m = true;
}
const h = {
status: "ok",
deliveryStatus: n ? "dry_run" : "sent",
channel: INTERNAL_MESSAGE_CHANNEL,
target: "current-run",
sourceReplyDeliveryMode: e.sourceReplyDeliveryMode,
...m && p ? { idempotencyKey: p } : {},
...m ? { sourceReplyTranscriptOwner: true } : {},
...n ? {} : { sourceReplySink: "internal-ui" },
sourceReply: l,
...f ? { message: f } : {},
...d[0] ? { mediaUrl: d[0] } : {},
...d.length ? { mediaUrls: d } : {},
dryRun: n
};
const g = h.sourceReplySink ? ` via ${h.sourceReplySink}` : "";
const _ = e.sourceReplyTranscriptOnly ? h.dryRun ? "Prepared reply for the current session transcript." : `Recorded reply in the current session transcript${g}. This send did not deliver it to an external channel.` : `${h.dryRun ? "Prepared" : "Sent"} visible reply to the current source conversation${g}.`;
const v = readClawHubRecommendations(h.sourceReply.channelData);
const y = v.length ? v.map((e) => `${e.name}: ${e.installed ? "Installed" : "Available to install"}.`).join("\n") : i?.text;
const { sourceReplyDeliveryMode: b, ...x } = h;
const S = textResult(`${_}${y ? `\n${y}` : ""}`, {
...x,
...b ? { sourceReplyDeliveryMode: b } : {}
});
return withSendNormalization({
kind: "send",
channel: INTERNAL_MESSAGE_CHANNEL,
action: "send",
to: "current-run",
handledBy: "internal-source",
payload: h,
toolResult: S,
dryRun: n
}, c.normalization);
}
async function runMessageAction(e) {
throwIfAborted(e.abortSignal);
const t = e.cfg;
let n = { ...e.params };
const r = e.agentId ?? (e.sessionKey ? resolveSessionAgentId({
sessionKey: e.sessionKey,
config: t
}) : void 0);
parseJsonMessageParam(n, "presentation");
requirePresentationTableCaptions(n);
parseJsonMessageParam(n, "delivery");
parseJsonMessageParam(n, "interactive");
const i = e.action;
enforceMessageActionAllowlist({
cfg: t,
agentId: r,
action: i
});
if (n.clawhub !== void 0 && i !== "send") throw new Error("ClawHub recommendations require action=\"send\".");
if (i === "broadcast") return handleBroadcastAction({
...e,
agentId: r
}, n);
if (i === "send" && hasPollCreationParams(n)) throw new Error("Poll fields require action \"poll\"; use action \"poll\" instead of \"send\".");
if (await shouldUseInternalSourceReplySink(e, n)) return handleInternalSourceReplySendAction({
...e,
agentId: r
}, n);
if (n.clawhub !== void 0) throw new Error("ClawHub recommendation cards require action=\"send\" to the current Control UI conversation; omit channel and target.");
const a = await prepareMessageRoute({
input: e,
actionParams: n,
agentId: r
});
return await withChannelReadAuthority(a.assertReadAuthorityCurrent, async () => {
const o = await withMessageTargetPreparation(a.assertTargetAuthorityCurrent ?? e.assertDirectAdapterHandoff, async () => {
n = a.params;
const { channel: o, channelPlugin: s, accountId: c, dryRun: l, defersExternalTargetResolution: u } = a;
const d = await resolveExtraActionMediaSourceParamKeysAsync({
cfg: t,
action: i,
args: n,
channel: o,
accountId: c,
sessionKey: e.sessionKey,
sessionId: e.sessionId,
agentId: r,
requesterSenderId: e.requesterSenderId,
senderIsOwner: e.senderIsOwner
});
(a.assertTargetAuthorityCurrent ?? e.assertDirectAdapterHandoff)?.();
const f = i === "send" ? "all" : "selected";
const p = collectActionMediaSourceHints(n, d, { structuredAttachments: f });
await waitForLocalMessageMedia({
...e,
sources: p,
assertCurrent: a.assertTargetAuthorityCurrent ?? e.assertDirectAdapterHandoff
});
const m = e.mediaAccess ?? resolveAgentScopedOutboundMediaAccess({
cfg: t,
agentId: r,
mediaSources: p,
...messageActionRequesterMediaContext(e),
messageProvider: e.sessionKey ? void 0 : o,
accountId: e.sessionKey ? e.requesterAccountId ?? c : c
});
const h = e.workspaceMediaAccess?.readFile ? m.readFile : void 0;
const g = resolveAttachmentMediaPolicy({
sandboxRoot: e.sandboxRoot,
sandboxContainerWorkdir: e.sandboxContainerWorkdir,
mediaAccess: m,
mediaReadFile: h
});
await normalizeSandboxMediaParams({
args: n,
mediaPolicy: g,
extraParamKeys: d,
structuredAttachments: f
});
const _ = e.gateway;
const v = i === "send" && Boolean(_) && (s.actions?.resolveExecutionMode?.({ action: "send" }) === "gateway" || s.outbound?.deliveryMode === "gateway");
const hydrateActionAttachmentParams = () => hydrateAttachmentParamsForAction({
cfg: t,
channel: o,
accountId: c,
args: n,
action: i,
dryRun: l,
preserveSendBuffer: v,
mediaPolicy: g,
extraParamKeys: d
});
const y = i === "send" || i === "thread-reply";
if (!y) await hydrateActionAttachmentParams();
const b = await resolveMessageTarget({
cfg: t,
channel: o,
action: i,
args: n,
accountId: c,
toolContext: e.toolContext,
agentId: r,
deferExternalTargetResolution: u,
plugin: s
});
if (y) await hydrateActionAttachmentParams();
return {
cfg: t,
params: n,
idempotencyKey: normalizeOptionalString(n.idempotencyKey),
channel: o,
channelPlugin: s,
mediaAccess: m,
accountId: c,
dryRun: l,
gateway: _,
input: a.assertTargetAuthorityCurrent ? {
...e,
assertDirectAdapterHandoff: a.assertTargetAuthorityCurrent
} : e,
agentId: r,
resolvedTarget: b,
abortSignal: e.abortSignal
};
}, e.abortSignal);
if (!o.dryRun && !isFencedProviderReadAction(i)) {
await beforeMessageDeliveryAttempt(o.input);
if (o.input.messageActionAuthorization?.scheduled || o.input.messageActionAuthorization?.deliveryAttempt) {
const e = o.input;
o.input = {
...e,
assertDirectAdapterHandoff: captureMessageDeliveryAuthority(e)
};
}
}
if (i === "send") return executeMessageSend(o);
if (i === "poll") return executeMessagePoll(o);
return executeMessagePlugin(o);
}, e.abortSignal);
}
//#endregion
export { projectMessageActionPartialDelivery as a, projectGatewayQueuedDeliveryResult as i, runMessageAction as n, hasAcceptedMessageActionResult as o, stripFormattedReasoningMessage as r, getToolResult as t };