openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
905 lines (904 loc) • 29.1 kB
JavaScript
import { R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import "./session-key-CqAyZeVk.mjs";
import { n as normalizeAccountId } from "./account-id-BqKT3GuY.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs";
import { t as warnPluginSdkDeprecation } from "./sdk-deprecation-D5N9acnu.mjs";
import { c as getReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs";
import { r as resolveChannelAccountEntry } from "./account-lookup-FhQZVFfo.mjs";
import { n as preserveReplyPayloadMediaSelectionCore } from "./reply-media-entries-BE-R1jqq.mjs";
import "./ingress-drain-CMuOTwGV.mjs";
import "./reply-policy-h9jv5pGH.mjs";
import "./agent-activity-presentation-BIQtAp6v.mjs";
import { i as classifyGatewayStaleInstall } from "./stale-install-DESh14Fs.mjs";
import { r as PlatformMessageNotDispatchedError } from "./deliver-types-BnSKrpHG.mjs";
import "./payloads-CQvywZOF.mjs";
import { o as resolveReceiptSourceId, t as createMessageReceiptFromOutboundResults } from "./receipt-D4ZtbK66.mjs";
import { C as resolveChannelStreamingPreviewChunk, g as resolveChannelProgressDraftConfig } from "./streaming-DsQF8isK.mjs";
import { c as resolveTextChunkLimit } from "./chunk-D9JRZpRm.mjs";
import "./outbound-echo-CP5L3mPZ.mjs";
import { i as livePreviewFinalizerCapabilities, n as channelMessageReceiveAckPolicies, r as durableFinalDeliveryCapabilities, t as channelMessageLiveCapabilities } from "./types-CmDDsrSP.mjs";
import "./live-DOXDs-ke.mjs";
import "./session-context-CCVPkFMh.mjs";
import "./progress-draft-compositor-ClWAxBC_.mjs";
import "./reply-pipeline-BLDOfhMa.mjs";
import "./logging-DyCvEa9E.mjs";
import "./ingress-monitor-CkIIn1aC.mjs";
import { t as createDraftStreamLoop } from "./draft-stream-loop-VIZuBFdU.mjs";
import "./identity-DpbdIy02.mjs";
import "./sanitize-text-khTbEIqM.mjs";
//#region src/channels/message/ingress-drain-lifecycle.ts
/** Maps a drain lifecycle onto the reply-lane ownership surface. */
function bindIngressLifecycleToReplyOptions(e) {
return { turnAdoptionLifecycle: {
admission: "exclusive",
onAdopted: e.onAdopted,
onDeferred: e.onDeferred,
onDeferredHeartbeat: e.onDeferredHeartbeat,
deferredHeartbeatIntervalMs: e.deferredHeartbeatIntervalMs,
onAbandoned: e.onAbandoned,
abortSignal: e.abortSignal
} };
}
//#endregion
//#region src/channels/message/ingress-errors.ts
function createChannelIngressError(e, t) {
const IngressError = class extends Error {
constructor(n, r, i) {
const a = t?.withReason === true;
super(a && typeof r === "string" ? r : n, a ? i : typeof r === "string" ? void 0 : r);
this.name = e;
if (a) this.reason = n;
}
};
Object.defineProperty(IngressError, "name", {
configurable: true,
value: e
});
return IngressError;
}
//#endregion
//#region src/channels/draft-stream-controls.ts
/**
* Creates controls for streaming preview messages that can be finalized, sealed, or cleared.
*/
function createFinalizableDraftStreamControls(e) {
const t = createDraftStreamLoop({
throttleMs: e.throttleMs,
coalesceInFlight: e.coalesceInFlight,
isStopped: e.isStopped,
sendOrEditStreamMessage: e.sendOrEditStreamMessage,
...e.emptyValue !== void 0 ? { emptyValue: e.emptyValue } : {},
...e.isEmpty ? { isEmpty: e.isEmpty } : {}
});
const update = (n) => {
if (e.isStopped() || e.isFinal()) return;
t.update(n);
};
const stop = async () => {
e.markFinal();
await t.flush();
};
const stopPending = async (e) => {
e();
t.stop();
await t.waitForInFlight();
};
const stopForClear = () => stopPending(() => e.markStopped());
const seal = () => stopPending(() => e.markFinal());
return {
loop: t,
update,
stop,
seal,
discardPending: stopForClear,
stopForClear
};
}
function createFinalizableDraftStreamControlsForState(e) {
return createFinalizableDraftStreamControls({
...e,
isStopped: () => e.state.stopped,
isFinal: () => e.state.final,
markStopped: () => {
e.state.stopped = true;
},
markFinal: () => {
e.state.final = true;
}
});
}
async function takeMessageIdAfterStop(e) {
await e.stopForClear();
const t = e.readMessageId();
e.clearMessageId();
return t;
}
async function deleteFinalizableDraftMessage(e, t) {
try {
if (await e.deleteMessage(t) === false) return false;
} catch (t) {
e.warn?.(`${e.warnPrefix}: ${formatErrorMessage(t)}`);
return false;
}
try {
if (Object.is(e.readMessageId(), t)) e.clearMessageId();
e.onDeleteSuccess?.(t);
} catch (t) {
e.warn?.(`${e.warnPrefix} after delete: ${formatErrorMessage(t)}`);
}
return true;
}
/**
* Stops a draft stream and deletes its preview message when the stored id is valid.
* Claims the current id before deletion; stateful callers can retain failures through
* onDeleteFailure without making overlapping clears delete the same message twice.
*/
async function clearFinalizableDraftMessage(e) {
const t = await takeMessageIdAfterStop(e);
if (!e.isValidMessageId(t)) return;
if (!await deleteFinalizableDraftMessage(e, t)) e.onDeleteFailure?.(t);
}
function createFinalizableDraftLifecycle(e) {
const t = createFinalizableDraftStreamControlsForState(e);
const n = /* @__PURE__ */ new Map();
let r = Promise.resolve();
let i = 0;
let a = -1;
const claim = (e, t) => {
let r = n.get(e);
if (!r) {
r = { owner: t };
n.set(e, r);
}
return r;
};
const attemptDelete = (e, t) => {
t.attempt ??= Promise.resolve().then(async () => {
try {
const r = await deleteFinalizableDraftMessage(t.owner, e);
if (r) n.delete(e);
return r;
} finally {
t.attempt = void 0;
}
});
return t.attempt;
};
const drainDeletes = async (e) => {
const t = /* @__PURE__ */ new Set();
for (const [r, i] of n) {
if (t.has(r) || Object.is(r, e)) continue;
t.add(r);
await attemptDelete(r, i);
}
return n.size === 0;
};
const retire = async (t, n) => {
const r = claim(t, e);
if (!n?.defer) await attemptDelete(t, r);
};
const serializeCleanup = (e) => {
const t = r.catch(() => {}).then(e);
r = t;
return t;
};
const clearWithStop = (t, n) => {
const r = n ? {
...e,
...n
} : e;
return serializeCleanup(async () => {
await t();
const e = r.readMessageId();
if (r.isValidMessageId(e)) claim(e, r);
else r.clearMessageId();
await drainDeletes();
});
};
const stop = () => {
const n = r.catch(() => {});
const i = Promise.allSettled([t.stop(), n]).then(async ([t]) => {
if (t.status === "rejected") throw t.reason;
await drainDeletes(e.readMessageId());
});
r = i;
return i;
};
const resetMessage = (n = "reset") => {
e.clearMessageId();
t.loop.resetPending();
if (n === "reset") t.loop.resetThrottleWindow();
};
const reset = (t = "preserve", n = "reset") => {
if (t === "discard") a = i;
i += 1;
e.state.stopped = false;
e.state.final = false;
resetMessage(n);
};
const createMessage = async (t, n, r) => {
const o = i;
const s = await t();
if (o === i) return n(s);
if (o <= a && e.isValidMessageId(s)) await retire(s, r);
return true;
};
const retireCurrent = async (t) => {
const n = i;
await t();
if (n !== i) return;
const r = e.readMessageId();
e.clearMessageId();
if (e.isValidMessageId(r)) await retire(r);
};
return {
...t,
get generation() {
return i;
},
reset,
resetMessage,
createMessage,
retireCurrent,
stop,
clear: () => clearWithStop(t.stopForClear),
clearWithStop,
retire,
cleanupPending: (t) => serializeCleanup(async () => {
t?.();
await drainDeletes(e.readMessageId());
})
};
}
//#endregion
//#region src/channels/run-state-machine.ts
const DEFAULT_RUN_ACTIVITY_HEARTBEAT_MS = 6e4;
function createRunStateMachine(e) {
const t = e.heartbeatMs ?? DEFAULT_RUN_ACTIVITY_HEARTBEAT_MS;
const n = e.now ?? Date.now;
let r = 0;
let i = null;
let a = !e.abortSignal?.aborted;
const publish = () => {
if (!a) return;
e.setStatus?.({
activeRuns: r,
busy: r > 0,
lastRunActivityAt: n()
});
};
const clearHeartbeat = () => {
clearInterval(i ?? void 0);
i = null;
};
const ensureHeartbeat = () => {
if (i || r <= 0 || !a) return;
i = setInterval(publish, t).unref();
};
const deactivate = () => {
a = false;
clearHeartbeat();
e.abortSignal?.removeEventListener("abort", deactivate);
};
if (e.abortSignal?.aborted) deactivate();
else e.abortSignal?.addEventListener("abort", deactivate, { once: true });
if (a) e.setStatus?.({
activeRuns: 0,
busy: false
});
return {
isActive() {
return a;
},
onRunStart() {
r += 1;
publish();
ensureHeartbeat();
},
onRunEnd() {
r = Math.max(0, r - 1);
if (r <= 0) clearHeartbeat();
publish();
},
deactivate
};
}
//#endregion
//#region src/channels/transport/stall-watchdog.ts
/** Creates a watchdog that reports once when an armed transport goes idle. */
function createArmableStallWatchdog(e) {
const t = resolveTimerTimeoutMs(e.timeoutMs, 1);
const n = Math.min(5e3, Math.max(250, t / 6));
const r = resolveTimerTimeoutMs(e.checkIntervalMs, n, 100);
let i = false;
let a = false;
let o = Date.now();
let s = null;
const report = (t) => {
try {
e.runtime?.error?.(t);
} catch {}
};
const reportTimeoutFailure = (t) => report(`[${e.label}] transport watchdog timeout handler failed: ${String(t)}`);
const clearTimer = () => {
clearInterval(s ?? void 0);
s = null;
};
const disarm = () => {
i = false;
};
const stop = () => {
a = true;
disarm();
clearTimer();
e.abortSignal?.removeEventListener("abort", stop);
};
const arm = (e) => {
if (a) return;
o = e ?? Date.now();
i = true;
};
const touch = (e) => {
if (a) return;
o = e ?? Date.now();
};
const check = () => {
if (!i || a) return;
const n = Date.now() - o;
if (n < t) return;
disarm();
report(`[${e.label}] transport watchdog timeout: idle ${Math.round(n / 1e3)}s (limit ${Math.round(t / 1e3)}s)`);
try {
Promise.resolve(e.onTimeout({
idleMs: n,
timeoutMs: t
})).catch(reportTimeoutFailure);
} catch (e) {
reportTimeoutFailure(e);
}
};
if (e.abortSignal?.aborted) stop();
else {
e.abortSignal?.addEventListener("abort", stop, { once: true });
s = setInterval(check, r);
s.unref?.();
}
return {
arm,
touch,
disarm,
stop,
isArmed: () => i
};
}
//#endregion
//#region src/channels/draft-streaming-chunking.ts
const DEFAULT_DRAFT_STREAM_MIN = 200;
const DEFAULT_DRAFT_STREAM_MAX = 800;
function resolveChannelDraftStreamingChunking(e, t, n, r) {
const i = resolveTextChunkLimit(e, t, n, { fallbackLimit: r.fallbackLimit });
const a = normalizeAccountId(n);
const o = e?.channels?.[t];
const s = resolveChannelAccountEntry(o?.accounts, a, t);
const c = resolveChannelStreamingPreviewChunk(s) ?? resolveChannelStreamingPreviewChunk(o);
const l = Math.max(1, Math.floor(c?.maxChars ?? DEFAULT_DRAFT_STREAM_MAX));
const u = Math.max(1, Math.min(l, i));
const d = Math.max(1, Math.floor(c?.minChars ?? DEFAULT_DRAFT_STREAM_MIN));
return {
minChars: Math.min(d, u),
maxChars: u,
breakPreference: c?.breakPreference === "newline" || c?.breakPreference === "sentence" ? c.breakPreference : "paragraph"
};
}
//#endregion
//#region src/plugin-sdk/channel-lifecycle.core.ts
/** Bind a fixed account id into a status writer so lifecycle code can emit partial snapshots. */
function createAccountStatusSink(e) {
return (t) => {
e.setStatus({
accountId: e.accountId,
...t
});
};
}
/**
* Serialize channel work per key while keeping lifecycle/busy accounting out of
* channel-specific message handlers. The queue does not impose run timeouts;
* callers should rely on session/tool/runtime lifecycle for long-running work.
*/
function createChannelRunQueue(e) {
const t = new KeyedAsyncQueue();
const n = /* @__PURE__ */ new Map();
const r = createRunStateMachine({
setStatus: (t) => {
e.setStatus?.({
...t,
activeRunStartedAt: n.size > 0 ? Math.min(...n.values()) : null
});
},
abortSignal: e.abortSignal
});
const reportError = (t) => {
try {
e.onError?.(t);
} catch {}
};
return {
enqueue(i, a) {
t.enqueue(i, async () => {
if (!r.isActive()) return;
const t = Symbol("channel-run");
n.set(t, Date.now());
r.onRunStart();
try {
if (!r.isActive()) return;
await a({ lifecycleSignal: e.abortSignal });
} finally {
n.delete(t);
r.onRunEnd();
}
}).catch(reportError);
},
deactivate: r.deactivate
};
}
async function runAbortCleanup(e) {
return e?.();
}
/**
* Return a promise that resolves when the signal is aborted.
*
* If no signal is provided, the promise stays pending forever. When provided,
* `onAbort` runs once before the promise resolves.
*/
function waitUntilAbort(e, t) {
return new Promise((n, r) => {
const complete = () => {
runAbortCleanup(t).then(n, r);
};
if (!e) return;
if (e.aborted) {
complete();
return;
}
e.addEventListener("abort", complete, { once: true });
});
}
/**
* Keep a passive account task alive until abort, then run optional cleanup.
*/
async function runPassiveAccountLifecycle(e) {
const t = await e.start();
try {
await waitUntilAbort(e.abortSignal);
} finally {
await e.stop?.(t);
await e.onStop?.();
}
}
/**
* Keep a channel/provider task pending until the HTTP server closes.
*
* When an abort signal is provided, `onAbort` is invoked once and should
* trigger server shutdown. The returned promise resolves only after `close`.
*/
async function keepHttpServerTaskAlive(e) {
const { server: t, abortSignal: n, onAbort: r } = e;
const i = new Promise((e) => {
t.once("close", () => e());
});
let a = Promise.resolve();
const triggerAbort = () => {
a = runAbortCleanup(r);
a.catch(() => {});
};
if (n) {
if (n.aborted) triggerAbort();
else n.addEventListener("abort", triggerAbort, { once: true });
}
await i;
n?.removeEventListener("abort", triggerAbort);
await a;
}
//#endregion
//#region src/infra/outbound/send-deps.ts
/**
* Resolves a channel send dependency from modern channel IDs or legacy helper keys.
*/
function resolveOutboundSendDep(e, t, n) {
const r = e?.[t];
if (r !== void 0) return r;
const i = t.replace(/[^a-z0-9]+/gi, "");
const a = i.charAt(0).toUpperCase() + i.slice(1);
const o = [...i ? a.startsWith("Ms") && a.length > 2 ? [`send${a}`, `sendMS${a.slice(2)}`] : [`send${a}`] : [], ...n?.legacyKeys ?? []];
for (const t of o) {
const n = e?.[t];
if (n !== void 0) return n;
}
}
//#endregion
//#region src/channels/message/adapter.ts
const defaultManualReceiveAdapter = {
defaultAckPolicy: "manual",
supportedAckPolicies: ["manual"]
};
/** Defines a message adapter while defaulting receive acknowledgement to manual. */
function defineChannelMessageAdapter(e) {
return {
...e,
receive: e.receive ?? defaultManualReceiveAdapter
};
}
//#endregion
//#region src/channels/message/outbound-bridge.ts
/**
* Legacy outbound bridge adapter.
*
* Wraps old channel send functions in the newer channel message adapter contract.
*/
function toMessageSendResult(e, t) {
const n = e.receipt ? t.kind === "poll" ? {
...e.receipt,
parts: e.receipt.parts.map((e) => ({
...e,
kind: t.kind
}))
} : e.receipt : createMessageReceiptFromOutboundResults({
results: [e],
kind: t.kind,
threadId: t.threadId == null ? void 0 : String(t.threadId),
replyToId: t.replyToId ?? void 0
});
const r = resolveReceiptSourceId({
...e,
receipt: n
});
return {
...e.outcome !== void 0 ? { outcome: e.outcome } : {},
...e.target !== void 0 ? { target: e.target } : {},
...e.chatId !== void 0 ? { chatId: e.chatId } : {},
...e.channelId !== void 0 ? { channelId: e.channelId } : {},
...e.roomId !== void 0 ? { roomId: e.roomId } : {},
...e.conversationId !== void 0 ? { conversationId: e.conversationId } : {},
...e.toJid !== void 0 ? { toJid: e.toJid } : {},
...e.pollId !== void 0 ? { pollId: e.pollId } : {},
...e.timestamp !== void 0 ? { timestamp: e.timestamp } : {},
...e.meta !== void 0 ? { meta: e.meta } : {},
receipt: n,
...r ? { messageId: r } : {}
};
}
async function sendThroughOutboundBridge(e, t, n) {
const r = {
kind: t,
threadId: e.threadId,
replyToId: e.replyToId
};
const { onDeliveryResult: i, ...a } = e;
return toMessageSendResult(await n({
...a,
...i ? { onDeliveryResult: async (e) => {
await i(toMessageSendResult(e, r));
} } : {}
}), r);
}
function hasRenderedPresentationBlocks(e) {
return Object.values(e ?? {}).some((e) => {
if (!e || typeof e !== "object" || Array.isArray(e)) return false;
const t = e.presentationBlocks;
return Array.isArray(t) && t.length > 0;
});
}
function resolvePayloadReceiptKind(e) {
if (e.mediaUrl || e.payload.mediaUrl || e.payload.mediaUrls?.length) return e.payload.audioAsVoice ? "voice" : "media";
if (Boolean(e.payload.presentation?.title || e.payload.presentation?.blocks?.length) || hasRenderedPresentationBlocks(e.payload.channelData) || e.payload.interactive || e.payload.location) return "card";
if (e.payload.text?.trim() || e.text.trim()) return "text";
return "unknown";
}
/** Converts legacy outbound send methods into a typed channel message adapter. */
function createChannelMessageAdapterFromOutbound(e) {
const t = {};
if (e.outbound.sendText) t.text = async (t) => sendThroughOutboundBridge(t, "text", (t) => e.outbound.sendText(t));
if (e.outbound.sendMedia) t.media = async (t) => sendThroughOutboundBridge(t, t.audioAsVoice ? "voice" : "media", (t) => e.outbound.sendMedia(t));
if (e.outbound.sendPayload) t.payload = async (t) => sendThroughOutboundBridge(t, resolvePayloadReceiptKind(t), (t) => e.outbound.sendPayload(t));
if (e.outbound.sendPoll) t.poll = async (t) => sendThroughOutboundBridge(t, "poll", (t) => e.outbound.sendPoll(t));
return {
...e.id ? { id: e.id } : {},
durableFinal: { capabilities: e.capabilities ?? e.outbound.deliveryCapabilities?.durableFinal },
send: t,
...e.live ? { live: e.live } : {},
receive: e.receive ?? defaultManualReceiveAdapter
};
}
//#endregion
//#region src/channels/message/durable-receive.ts
function normalizeDurableInboundReceiveId(e) {
const t = e.trim();
if (!t) throw new Error("Durable inbound receive id cannot be empty");
return t;
}
function createDurableInboundReceiveJournalFromQueue(e) {
const prune = async (t) => {
if (e.retention) await e.queue.prune({
...e.retention,
...t === void 0 ? {} : { protectIds: [t] }
});
};
return {
accept: async (t, n, r) => {
await prune();
const i = normalizeDurableInboundReceiveId(t);
const a = await e.queue.enqueue(i, n, {
...r?.metadata === void 0 ? {} : { metadata: r.metadata },
...r?.receivedAt === void 0 ? {} : { receivedAt: r.receivedAt }
});
await prune(i);
if (a.kind === "accepted") return {
kind: "accepted",
duplicate: false,
record: a.record
};
if (a.kind === "completed") return {
kind: "completed",
duplicate: true,
record: a.record
};
if (a.kind === "pending" || a.kind === "claimed") return {
kind: "pending",
duplicate: true,
record: a.record
};
return {
kind: "pending",
duplicate: true,
record: {
id: a.record.id,
payload: n,
receivedAt: a.record.failedAt,
updatedAt: a.record.failedAt,
attempts: 0
}
};
},
pending: async () => {
await prune();
return await e.queue.listPending({ limit: "all" });
},
complete: async (t, n) => {
const r = normalizeDurableInboundReceiveId(t);
await e.queue.complete(r, {
...n?.metadata === void 0 ? {} : { metadata: n.metadata },
...n?.completedAt === void 0 ? {} : { completedAt: n.completedAt }
});
await prune(r);
},
release: async (t, n) => {
const r = normalizeDurableInboundReceiveId(t);
const i = await e.queue.release(r, {
...n?.lastError === void 0 ? {} : { lastError: n.lastError },
...n?.releasedAt === void 0 ? {} : { releasedAt: n.releasedAt }
});
await prune(r);
return i;
},
deletePending: async (t) => {
const n = await e.queue.delete(normalizeDurableInboundReceiveId(t));
await prune();
return n;
}
};
}
//#endregion
//#region src/channels/message/contracts.ts
async function verifyContractProofs(e) {
const t = [];
for (const n of e.keys) {
if (!e.isDeclared(n)) {
t.push(e.result(n, "not_declared"));
continue;
}
const r = e.proofs[n];
if (!r) throw new Error(e.missingProofError(n));
await r();
t.push(e.result(n, "verified"));
}
return t;
}
async function verifyDurableFinalCapabilityProofs(e) {
return await verifyContractProofs({
keys: durableFinalDeliveryCapabilities,
isDeclared: (t) => e.capabilities?.[t] === true,
proofs: e.proofs,
missingProofError: (t) => `${e.adapterName} declares durable final capability "${t}" without a contract proof`,
result: (e, t) => ({
capability: e,
status: t
})
});
}
async function verifyChannelMessageAdapterCapabilityProofs(e) {
return await verifyDurableFinalCapabilityProofs({
adapterName: e.adapterName,
capabilities: e.adapter.durableFinal?.capabilities,
proofs: e.proofs
});
}
async function verifyChannelMessageReceiveAckPolicyAdapterProofs(e) {
const { adapterName: t } = e;
const n = e.adapter.receive;
const r = new Set(n?.supportedAckPolicies?.length ? n.supportedAckPolicies : n?.defaultAckPolicy ? [n.defaultAckPolicy] : []);
return await verifyContractProofs({
keys: channelMessageReceiveAckPolicies,
isDeclared: (e) => r.has(e),
proofs: e.proofs,
missingProofError: (e) => `${t} declares receive ack policy "${e}" without a contract proof`,
result: (e, t) => ({
policy: e,
status: t
})
});
}
async function verifyChannelMessageLiveFinalizerProofs(e) {
const { adapterName: t } = e;
const n = e.adapter.live?.finalizer?.capabilities;
return await verifyContractProofs({
keys: livePreviewFinalizerCapabilities,
isDeclared: (e) => n?.[e] === true,
proofs: e.proofs,
missingProofError: (e) => `${t} declares live preview finalizer capability "${e}" without a contract proof`,
result: (e, t) => ({
capability: e,
status: t
})
});
}
async function verifyChannelMessageLiveCapabilityAdapterProofs(e) {
const { adapterName: t } = e;
const n = e.adapter.live?.capabilities;
return await verifyContractProofs({
keys: channelMessageLiveCapabilities,
isDeclared: (e) => n?.[e] === true,
proofs: e.proofs,
missingProofError: (e) => `${t} declares live capability "${e}" without a contract proof`,
result: (e, t) => ({
capability: e,
status: t
})
});
}
//#endregion
//#region src/channels/message/receive.ts
const neverAbortedSignal = new AbortController().signal;
const ackStages = {
after_receive_record: "receive_record",
after_agent_dispatch: "agent_dispatch",
after_durable_send: "durable_send",
manual: void 0
};
/** Creates a receive context with idempotent ack and explicit nack state transitions. */
function createMessageReceiveContext(e) {
let t;
const n = {
id: e.id,
channel: e.channel,
...e.accountId ? { accountId: e.accountId } : {},
message: e.message,
ackPolicy: e.ackPolicy ?? "after_receive_record",
ackState: "pending",
receivedAt: e.receivedAt ?? Date.now(),
signal: e.signal ?? neverAbortedSignal,
shouldAckAfter: (e) => ackStages[n.ackPolicy] === e,
ack: async () => {
if (n.ackState === "acked") return;
await e.onAck?.();
n.ackState = "acked";
n.ackedAt = Date.now();
delete n.nackErrorMessage;
},
nack: async (r) => {
if (n.ackState === "nacked") return;
if (t) {
await t;
return;
}
t = (async () => {
await e.onNack?.(r);
n.ackState = "nacked";
n.nackErrorMessage = formatErrorMessage(r);
})();
try {
await t;
} finally {
t = void 0;
}
}
};
return n;
}
//#endregion
//#region src/channels/streaming-final-text.ts
const MIN_TRUNCATED_FINAL_PREFIX_CHARS = 48;
const MIN_TRUNCATED_FINAL_CONTINUATION_CHARS = 24;
function stripTrailingEllipsis(e) {
return e.replace(/(?<!\s)(?:\s*(?:\.{3}|\u2026))+$/u, "").trimEnd();
}
function isPotentialTruncatedFinal(e) {
const t = e.trimEnd();
const n = stripTrailingEllipsis(t);
return n.length >= MIN_TRUNCATED_FINAL_PREFIX_CHARS && n !== t;
}
function selectLongerFinalText(e) {
const t = e.finalText.trimEnd();
if (!isPotentialTruncatedFinal(t)) return;
const n = stripTrailingEllipsis(t);
for (const r of e.candidateTexts) {
const e = r?.trimEnd();
if (!e || e.length <= t.length || !e.startsWith(n)) continue;
const i = e.slice(n.length).trimStart();
if (i.length >= MIN_TRUNCATED_FINAL_CONTINUATION_CHARS && /^[\p{L}\p{N}]/u.test(i)) return e;
}
}
async function resolveTranscriptBackedChannelFinalText(e) {
if (e.payload && getReplyPayloadMetadata(e.payload)?.precedingInputAnswer || !isPotentialTruncatedFinal(e.finalText)) return e.finalText;
const t = await e.resolveCandidateText();
return selectLongerFinalText({
finalText: e.finalText,
candidateTexts: [t]
}) ?? e.finalText;
}
//#endregion
//#region src/plugin-sdk/channel-outbound.ts
const loadChannelMessageRuntimeModule = createLazyRuntimeModule(() => import("./runtime-Cc1BbOPB.mjs"));
/** Keep the current operation media selection when recovering other reply fields. */
function preserveReplyPayloadMediaSelection(e, t) {
return preserveReplyPayloadMediaSelectionCore(e, t);
}
/**
* @deprecated Load-only bridge: the published Slack channel package
* (2026.7.2-beta.7 and earlier) imports this at module top level, so removing
* it makes the installed plugin fail to load after a core upgrade. The config
* key it read is retired and doctor strips it, so this resolves the same
* "text"/"rich" answer pre-doctor configs produced and the default otherwise.
* Remove once managed releases have replaced the old npm latest/extended-stable
* packages and their upgrade window has closed.
*/
function resolveChannelProgressDraftRender(e, t = "text") {
const n = resolveChannelProgressDraftConfig(e).render;
return n === "rich" || n === "text" ? n : t;
}
async function loadChannelDurableDeliveryModule() {
return await import("./durable-delivery-saW2AnyD.mjs").catch((e) => {
const t = classifyGatewayStaleInstall(e);
throw new PlatformMessageNotDispatchedError(t?.error.message ?? "Reply delivery runtime could not load before dispatch", { cause: e });
});
}
/** Lazily forwards inbound reply delivery through the channel turn durable-delivery module. */
const deliverInboundReplyWithMessageSendContext = async (...e) => {
return await (await loadChannelDurableDeliveryModule()).deliverInboundReplyWithMessageSendContextCore(...e);
};
/** Delivers a producer's prepared plan without reparsing literal text. */
const deliverStructuredInboundReplyWithMessageSendContext = async (...e) => {
return await (await loadChannelDurableDeliveryModule()).deliverStructuredInboundReplyWithMessageSendContextCore(...e);
};
function omitDeprecatedMirror(e) {
if (e.mirror === void 0) return e;
warnPluginSdkDeprecation({
family: "outbound-mirror",
method: "durable-send mirror",
replacement: "automatic destination transcript recording"
});
const { mirror: t, ...n } = e;
return n;
}
/** Sends a durable message batch without eager-loading channel message runtime internals. */
async function sendDurableMessageBatch(e) {
return await (await loadChannelMessageRuntimeModule()).sendDurableMessageBatchCore(omitDeprecatedMirror(e));
}
/** Runs work inside a durable message send context loaded through the SDK lazy boundary. */
async function withDurableMessageSendContext(e, t) {
return await (await loadChannelMessageRuntimeModule()).withDurableMessageSendContextCore(omitDeprecatedMirror(e), t);
}
//#endregion
export { createFinalizableDraftStreamControls as A, runPassiveAccountLifecycle as C, createRunStateMachine as D, createArmableStallWatchdog as E, takeMessageIdAfterStop as M, createChannelIngressError as N, clearFinalizableDraftMessage as O, bindIngressLifecycleToReplyOptions as P, keepHttpServerTaskAlive as S, resolveChannelDraftStreamingChunking as T, createChannelMessageAdapterFromOutbound as _, sendDurableMessageBatch as a, createAccountStatusSink as b, resolveTranscriptBackedChannelFinalText as c, verifyChannelMessageAdapterCapabilityProofs as d, verifyChannelMessageLiveCapabilityAdapterProofs as f, createDurableInboundReceiveJournalFromQueue as g, verifyDurableFinalCapabilityProofs as h, resolveChannelProgressDraftRender as i, createFinalizableDraftStreamControlsForState as j, createFinalizableDraftLifecycle as k, selectLongerFinalText as l, verifyChannelMessageReceiveAckPolicyAdapterProofs as m, deliverStructuredInboundReplyWithMessageSendContext as n, withDurableMessageSendContext as o, verifyChannelMessageLiveFinalizerProofs as p, preserveReplyPayloadMediaSelection as r, isPotentialTruncatedFinal as s, deliverInboundReplyWithMessageSendContext as t, createMessageReceiveContext as u, defineChannelMessageAdapter as v, waitUntilAbort as w, createChannelRunQueue as x, resolveOutboundSendDep as y };