openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
306 lines (305 loc) • 12.9 kB
JavaScript
import { l as normalizeOptionalString, u as normalizeOptionalStringifiedId } from "./string-coerce-CCIiB4H7.mjs";
import { o as isFastTestRuntimeEnv } from "./env-HehwidXj.mjs";
import { d as sleepWithAbort } from "./src-BPmQBLJp.mjs";
import { g as toAgentStoreSessionKey } from "./session-key-CqAyZeVk.mjs";
import { l as resolveSessionStorePathCore } from "./paths-DvQ5AJvD.mjs";
import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs";
import "./backoff-B-fIQi7C.mjs";
import { t as retryAsync } from "./retry-D-ulnYII.mjs";
import { o as hasReplyPayloadContent } from "./payload-Cab4FCxl.mjs";
import { o as copyReplyPayloadMetadata } from "./reply-payload-k5WsQWxi.mjs";
import { t as createCronExecutionId } from "./run-id-Be9gQ-r9.mjs";
import { s as shouldAttemptTtsPayload } from "./tts-config-CNw5woLC.mjs";
import { r as normalizeTargetForProvider } from "./target-normalization-qHbFjVWS.mjs";
import { n as hasExplicitCronDeliveryTarget } from "./delivery-target-validation-BQd2iGZZ.mjs";
import { d as resolveDeliveryNotSentRetryability, l as isProvenDeliveryNotSentError } from "./delivery-recovery.shared-3Nb7FEaL.mjs";
import { t as captureDeliveryQueueStateContext } from "./delivery-queue-state-context-Cxp-xMAQ.mjs";
import { a as inspectDeliveryQueueReceipt } from "./delivery-queue-sqlite-lyIJZlO0.mjs";
import { n as prepareTtsPreferences } from "./tts-preferences-CIrFrUQO.mjs";
import { s as hasScheduledNextRunAtMs } from "./jobs-scheduling-D3arlYs4.mjs";
//#region src/cron/isolated-agent/delivery-dispatch-policy.ts
const DIRECT_CRON_DELIVERY_COMPLETION_RETENTION = {
idPrefix: "cron-direct-delivery:v1:",
maxAgeMs: 864e5,
maxEntries: 2e3
};
/**
* Returns the conversation key when a successful persistent-session run notified its own
* conversation. Outbound skips that producer conversation, so the run records it itself.
*/
function deliveredToPersistentExecution(e, t) {
const n = e.resolvedDelivery.ok ? e.resolvedDelivery.sessionRoute?.sessionKey : void 0;
const r = toAgentStoreSessionKey({
agentId: e.agentId,
requestKey: e.agentSessionKey,
mainKey: e.cfgWithAgentDefaults.session?.mainKey
});
return t === "delivered" && e.undeliveredRunStatus === "ok" && e.job.sessionTarget.startsWith("session:") && n === r ? n : void 0;
}
/** Carry the implicit source's generation through outbound custody and recovery. */
function resolveDirectCronDeliveryGeneration(e) {
return (e.job.sessionTarget === "isolated" || e.job.sessionTarget === "current") && e.sourceSessionKey && e.sourceSessionGeneration && !hasExplicitCronDeliveryTarget(e.deliveryPlan) ? {
agentId: e.agentId,
storePath: resolveSessionStorePathCore(e.cfgWithAgentDefaults.session?.store, { agentId: e.agentId }),
sessionKey: e.sourceSessionKey,
sessionId: e.sourceSessionGeneration.sessionId,
lifecycleRevision: e.sourceSessionGeneration.lifecycleRevision ?? null
} : void 0;
}
function normalizeDeliveryTarget(e, t) {
const n = t.trim();
return normalizeTargetForProvider(e, n) ?? n;
}
const PERMANENT_DIRECT_CRON_DELIVERY_ERROR_PATTERNS = [
/unsupported channel/i,
/unknown channel/i,
/chat not found/i,
/user not found/i,
/bot.*not.*member/i,
/bot was blocked by the user/i,
/forbidden: bot was kicked/i,
/recipient is not a valid/i,
/outbound not configured for channel/i
];
const STALE_CRON_DELIVERY_MAX_START_DELAY_MS = 108e5;
const deliveryLoggerRuntimeLoader = createLazyImportLoader(() => import("./logger-D98Tal9X.mjs"));
const ttsRuntimeLoader = createLazyImportLoader(() => import("./tts.runtime.js"));
const deliverySubagentRegistryRuntimeLoader = createLazyImportLoader(() => import("./delivery-subagent-registry.runtime.js"));
const subagentFollowupRuntimeLoader = createLazyImportLoader(() => import("./subagent-followup.runtime.js"));
/** Resolves whether descendant subagent output should replace the interim cron text. */
async function resolveDescendantSubagentFollowup(e) {
const t = await deliverySubagentRegistryRuntimeLoader.load();
let n = await t.hasUnsettledCronDescendants(e.sessionKey);
const r = !e.abortSignal?.aborted && !n && (e.spawnOnlyHandoff || !e.initialSynthesizedText.trim());
const i = r || n ? await subagentFollowupRuntimeLoader.load() : void 0;
if (e.spawnOnlyHandoff && i) {
const n = await i.waitForDescendantSubagentResult({
sessionKey: e.sessionKey,
runStartedAt: e.runStartedAt,
timeoutMs: e.timeoutMs,
abortSignal: e.abortSignal
});
return {
finalReply: n?.reply,
finalDisposition: n?.disposition,
hasUnsettledDescendants: await t.hasUnsettledCronDescendants(e.sessionKey)
};
}
const a = r ? await i?.readDescendantSubagentFallbackReply({
sessionKey: e.sessionKey,
runStartedAt: e.runStartedAt
}) : void 0;
if (!e.deliveryBestEffort && n) {
let r = await i?.waitForDescendantSubagentSummary({
sessionKey: e.sessionKey,
initialReply: e.initialSynthesizedText,
timeoutMs: e.timeoutMs,
observedActiveDescendants: n,
abortSignal: e.abortSignal
});
n = await t.hasUnsettledCronDescendants(e.sessionKey);
if (!e.abortSignal?.aborted && !r && !n) r = await i?.readDescendantSubagentFallbackReply({
sessionKey: e.sessionKey,
runStartedAt: e.runStartedAt
});
return {
finalReply: r && !n ? r : void 0,
hasUnsettledDescendants: n
};
}
return {
finalReply: a,
hasUnsettledDescendants: n
};
}
async function logCronDeliveryWarn(e) {
const { logWarn: t } = await deliveryLoggerRuntimeLoader.load();
t(e);
}
function resolveStaleCronDeliveryError(e) {
const t = e.job.state?.nextRunAtMs;
const n = hasScheduledNextRunAtMs(t) ? t : e.runStartedAt;
const r = e.runStartedAt - n;
if (r > STALE_CRON_DELIVERY_MAX_START_DELAY_MS) {
const e = Date.now();
return `skipping stale delivery scheduled at ${new Date(n).toISOString()}, started ${Math.round(r / 6e4)}m late, current age ${Math.round((e - n) / 6e4)}m`;
}
}
async function maybeApplyTtsToCronPayloads(e) {
const t = await prepareTtsPreferences();
if (!shouldAttemptTtsPayload({
cfg: e.cfg,
preparedTtsPreferences: t,
ttsAuto: e.ttsAuto,
agentId: e.agentId,
channelId: e.delivery.channel,
accountId: e.delivery.accountId
})) return e.payloads;
const { maybeApplyTtsToPayload: n } = await ttsRuntimeLoader.load();
return await Promise.all(e.payloads.map((r) => n({
payload: r,
preparedTtsPreferences: t,
cfg: e.cfg,
channel: e.delivery.channel,
kind: "final",
ttsAuto: e.ttsAuto,
agentId: e.agentId,
accountId: e.delivery.accountId
})));
}
function buildDirectCronDeliveryIdempotencyKey(e) {
const t = createCronExecutionId(e.jobId, e.runStartedAt);
const n = e.delivery.threadId == null || e.delivery.threadId === "" ? "" : normalizeOptionalStringifiedId(e.delivery.threadId) ?? "";
const r = e.delivery.accountId?.trim() ?? "";
const i = normalizeDeliveryTarget(e.delivery.channel, e.delivery.to);
const a = [
e.delivery.channel,
r,
i,
n
].map(encodeURIComponent).join(":");
return `${DIRECT_CRON_DELIVERY_COMPLETION_RETENTION.idPrefix}${t}:${a}`;
}
/** Receipts own recipient delivery; projections never stand in for custody. */
async function isCompletedDirectCronDelivery(e, t) {
const n = captureDeliveryQueueStateContext();
return (await inspectDeliveryQueueReceipt(t, e, false, n)).status === "completed";
}
/** Wait only for an active recipient owner, never for crashed ambiguous sends. */
async function waitForCompletedDirectCronDelivery(e) {
const t = captureDeliveryQueueStateContext();
for (let n = 0; n < 120; n += 1) {
e.signal?.throwIfAborted();
const { status: r, pendingEntry: i } = await inspectDeliveryQueueReceipt(e.queueName, e.id, true, t);
e.signal?.throwIfAborted();
if (r === "completed") return true;
if (!i || (i.recoveryState === "send_attempt_started" ? typeof i.platformSendStartedAt !== "number" || i.platformSendStartedAt <= Date.now() - 3e4 : i.recoveryState !== "producer_claimed" || typeof i.availableAt !== "number" || i.availableAt <= Date.now())) return false;
if (n < 119) await sleepWithAbort(250, e.signal);
}
return false;
}
function summarizeDirectCronDeliveryError(e) {
if (e instanceof Error) return e.message || "error";
if (typeof e === "string") return e;
try {
return JSON.stringify(e) || String(e);
} catch {
return String(e);
}
}
function isTransientDirectCronDeliveryError(e) {
const t = resolveDeliveryNotSentRetryability(e);
if (t !== void 0) return t;
const n = summarizeDirectCronDeliveryError(e);
if (!n) return false;
if (PERMANENT_DIRECT_CRON_DELIVERY_ERROR_PATTERNS.some((e) => e.test(n))) return false;
return isProvenDeliveryNotSentError(e);
}
async function retryTransientDirectCronDelivery(e) {
const t = isFastTestRuntimeEnv() ? [
0,
0,
0
] : [
5e3,
1e4,
2e4
];
const assertActive = () => {
if (e.signal?.aborted) throw new Error("cron delivery aborted");
if (e.deadlineAtMs !== void 0 && Date.now() >= e.deadlineAtMs) {
const e = /* @__PURE__ */ new Error("cron delivery deadline exceeded");
e.name = "TimeoutError";
throw e;
}
};
assertActive();
const runWithAbortCheck = async () => {
assertActive();
return await e.run();
};
return await retryAsync(runWithAbortCheck, {
attempts: t.length + 1,
minDelayMs: 0,
maxDelayMs: Math.max(...t),
delayMs: ({ attempt: e }) => t[e - 1] ?? 0,
shouldRetry: (t) => e.signal?.aborted !== true && (e.deadlineAtMs === void 0 || Date.now() < e.deadlineAtMs) && isTransientDirectCronDeliveryError(t) && (e.shouldRetryError?.(t) ?? true),
onRetry: async ({ attempt: t, maxAttempts: n, delayMs: r, err: i }) => {
await logCronDeliveryWarn(`[cron:${e.jobId}] transient ${e.label ?? "direct announce"} delivery failure, retrying ${t + 1}/${n} in ${Math.round(r / 1e3)}s: ${summarizeDirectCronDeliveryError(i)}`);
if (r === 0) await sleepWithAbort(0, e.signal);
},
sleep: async (t) => {
const n = e.deadlineAtMs === void 0 ? t : Math.max(0, e.deadlineAtMs - Date.now());
await sleepWithAbort(Math.min(t, n), e.signal);
assertActive();
}
});
}
//#endregion
//#region src/cron/isolated-agent/delivery-payload-normalization.ts
function shouldAttachDirectCronFallbackText(e) {
return Boolean(e.channelData) && !hasReplyPayloadContent(e, {
trimText: true,
hasChannelData: false
});
}
function normalizeDirectCronDeliveryPayloads(e) {
const t = normalizeOptionalString(e.outputText) ?? normalizeOptionalString(e.summary) ?? normalizeOptionalString(e.synthesizedText);
const n = e.deliveryPayloads.filter((e) => hasReplyPayloadContent(e, { trimText: true }));
if (n.length === 0 && t) n.push({ text: t });
const r = t ? n.findLastIndex((e) => normalizeOptionalString(e.text) === t) : -1;
let i = r >= 0 ? r : void 0;
if (t && i === void 0 && n.some(shouldAttachDirectCronFallbackText)) {
n.unshift({ text: t });
i = 0;
}
const a = n.map((e) => shouldAttachDirectCronFallbackText(e) && t && i !== void 0 ? copyReplyPayloadMetadata(e, Object.assign({}, e, { fallbackText: {
text: t,
replacesPayloadIndex: i
} })) : e);
const o = [];
let s = false;
for (const [t, n] of a.entries()) {
const r = e.channelTransform ? e.channelTransform.apply(n) : n;
if (r === null) s = true;
else o.push({
payload: r,
sourceIndex: t
});
}
if (o.length === 0) return {
kind: "suppress",
reason: s ? "channel_transform" : "empty"
};
const c = o.findIndex(({ sourceIndex: e }) => e === i);
return {
kind: "deliver",
payload: o.map(({ payload: e }) => {
const t = e.fallbackText;
if (!t || t.replacesPayloadIndex !== i) return e;
return copyReplyPayloadMetadata(e, Object.assign({}, e, { fallbackText: c < 0 ? void 0 : {
...t,
replacesPayloadIndex: c
} }));
})
};
}
/**
* Appends the Control UI run-inspection link to the last visible payload.
* Callers invoke this only after silent-reply suppression so a link cannot turn
* a silent or empty run into a visible announcement; the payload is replaced
* rather than mutated because payload objects can be aliased by the caller.
*/
function appendCronRunInspectionLink(e, t, n) {
const r = e.findLastIndex((e) => e.text?.trim());
if (!t || r < 0) return e;
const i = e[r];
const a = n === "telegram" || n === "discord" ? `[Inspect run](${t.replace(/[()]/g, (e) => e === "(" ? "%28" : "%29")})` : `Inspect: ${t}`;
const o = copyReplyPayloadMetadata(i, {
...i,
text: `${i.text}\n${a}`
});
return e.map((e, t) => t === r ? o : e);
}
//#endregion
export { deliveredToPersistentExecution as a, maybeApplyTtsToCronPayloads as c, resolveStaleCronDeliveryError as d, retryTransientDirectCronDelivery as f, buildDirectCronDeliveryIdempotencyKey as i, resolveDescendantSubagentFollowup as l, normalizeDirectCronDeliveryPayloads as n, isCompletedDirectCronDelivery as o, waitForCompletedDirectCronDelivery as p, DIRECT_CRON_DELIVERY_COMPLETION_RETENTION as r, logCronDeliveryWarn as s, appendCronRunInspectionLink as t, resolveDirectCronDeliveryGeneration as u };