UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

361 lines (360 loc) • 16.7 kB
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { t as normalizeAnyChannelId } from "./registry-normalize-guW5_4yo.mjs"; import { n as SILENT_REPLY_TOKEN } from "./tokens-CcE6ESvH.mjs"; import { t as resolveTargetPrefixedChannel } from "./channel-target-prefix-tRLuyxKs.mjs"; import { s as classifyOAuthRefreshFailure } from "./oauth-refresh-failure-DxrQiYzV.mjs"; import { t as DEFAULT_AGENT_TIMEOUT_MS } from "./timeout-BEnEcjB4.mjs"; import { r as normalizeTargetForProvider } from "./target-normalization-qHbFjVWS.mjs"; import { a as hasCanonicalCronDeliveryMode } from "./delivery-codec-BaSNePUi.mjs"; import { t as buildProviderLoginRecovery } from "./provider-login-recovery-zWN-LIXU.mjs"; import { a as wrapUntrustedPromptDataBlock } from "./sanitize-for-prompt-CAahLekM.mjs"; import { F as cronFailureDetailLines, N as cronNotificationJob, c as isJobEnabled, k as buildCronAutoDisableNotice } from "./jobs-scheduling-D3arlYs4.mjs"; import { n as resolveFailureDestination, t as resolveCronDeliveryPlan } from "./delivery-plan-BMeGAb9T.mjs"; import { randomUUID } from "node:crypto"; //#region src/cron/service/failure-repair-brief.ts const REPAIR_PAYLOAD_MAX_CHARS = 4e3; const REPAIR_ERROR_MAX_CHARS = 1e3; function buildCronFailureRepairBrief(e) { const { job: t } = e; const n = t.payload; const r = n.kind === "agentTurn" ? n.message : n.kind === "systemEvent" ? n.text : n.kind === "script" ? n.script : ""; const i = [e.errorReason ? `cause: ${e.errorReason}` : "", e.error?.trim()].filter(Boolean).join("\n"); return [ `Automation repair request from the scheduler, not a user message. Do not relay it; follow the steps below.`, e.terminal ? `A one-time automation (id ${t.id}), created in this conversation, failed and will not run again (now disabled). No failure alert was sent.` : `An automation (id ${t.id}), created in this conversation, failed ${e.consecutiveErrors} consecutive runs. No failure alert was sent.`, `Schedule: ${JSON.stringify(t.schedule)}. Payload kind: ${n.kind}.`, wrapUntrustedPromptDataBlock({ label: "Automation name", text: t.name, maxChars: 200 }), wrapUntrustedPromptDataBlock({ label: "Current payload", text: r, maxChars: REPAIR_PAYLOAD_MAX_CHARS, truncationMarker: " [truncated]" }), wrapUntrustedPromptDataBlock({ label: "Last error", text: i || "No error text recorded.", maxChars: REPAIR_ERROR_MAX_CHARS, truncationMarker: " [truncated]" }), "", "Diagnose the failure, then do exactly one:", ...e.terminal ? [ `1. If its work is still needed, do that work now or add a new automation; the failed one stays disabled, so do not update it. To resume this conversation later, use automations add with an at schedule, payload {kind:"agentTurn",message:"instructions for your next turn"}, and sessionTarget ${JSON.stringify(`session:${t.owner?.sessionKey?.trim()}`)}.`, `2. If the work is no longer needed, reply with exactly ${SILENT_REPLY_TOKEN} as the entire final answer.`, "3. Otherwise, ask the user for what you need to continue." ] : [ `1. Transient (provider outage, network, rate limit, or temporary upstream error): change nothing and reply with exactly ${SILENT_REPLY_TOKEN} as the entire final answer.`, "2. Fixable in the workspace (for example the helper script or instructions file the payload follows): change it, then reply with one line saying what you changed. Do not claim the automation is fixed; a later run must verify it.", "3. Otherwise: ask the user for exactly what you need to fix it.", "If the automation keeps failing, the user gets the normal failure alert." ], `${SILENT_REPLY_TOKEN} discards anything written this turn that was not sent, so send confirmations before ending silently.` ].join("\n"); } //#endregion //#region src/cron/service/failure-alerts.ts /** Resolves and emits cron failure-alert notifications. */ const DEFAULT_FAILURE_ALERT_AFTER = 2; const DEFAULT_FAILURE_ALERT_COOLDOWN_MS = 36e5; /** Returns the last failure-notification delivery trace persisted on a cron job. */ function failureNotificationDeliveryFromJobState(e) { const t = e.state.lastFailureNotificationDeliveryStatus; if (!t || t === "not-requested") return; return { delivered: e.state.lastFailureNotificationDelivered, status: t, error: e.state.lastFailureNotificationDeliveryError }; } function resolveFailureAlertChannel(e, t) { const n = normalizeOptionalLowercaseString(e); if (n && n !== "last") return normalizeAnyChannelId(n) ?? n; return normalizeOptionalLowercaseString(resolveTargetPrefixedChannel(t)) ?? n; } function normalizeFailureAlertRecipient(e, t) { try { return normalizeTargetForProvider(e, t) ?? t; } catch { return t; } } function clampPositiveInt(e, t) { if (typeof e !== "number" || !Number.isFinite(e)) return t; const n = Math.floor(e); return n >= 1 ? n : t; } function clampNonNegativeInt(e, t) { if (typeof e !== "number" || !Number.isFinite(e)) return t; const n = Math.floor(e); return n >= 0 ? n : t; } function hasFailureRepairOwner(e) { return Boolean(e.owner?.sessionKey?.trim() && e.payload && e.payload.kind !== "command" && e.schedule && e.schedule.kind !== "on-exit" && e.schedule.kind !== "stream"); } /** Resolves effective failure-alert policy from job config, delivery defaults, and global cron config. */ function resolveFailureAlert(e, t) { const n = e.preparedFailureAlert; if (n) { if (n.jobId !== t.id) throw new Error("cron: prepared failure-alert policy does not match the job"); return n.value; } const r = e.deps.cronConfig?.failureAlert; const i = t.failureAlert === false ? void 0 : t.failureAlert; if (t.failureAlert === false) return null; if (!i && r?.enabled === false) return null; const a = Boolean(i && (i.channel !== void 0 || i.to !== void 0 || i.accountId !== void 0 || i.mode !== void 0)); const o = resolveFailureDestination(t, r, a ? i : void 0); const s = hasCanonicalCronDeliveryMode(t.delivery) ? resolveCronDeliveryPlan(t) : void 0; const c = s?.mode === "announce" && s.requested ? s : void 0; const l = i !== void 0 || r !== void 0; const u = t.schedule?.kind === "at" && hasFailureRepairOwner(t); if (!o && !c && !l && !u) return null; const d = i?.mode ?? (i?.channel ? "announce" : void 0) ?? r?.mode; const f = o ?? (d === "webhook" && l ? { mode: "webhook", to: normalizeOptionalString(i?.to ?? r?.to), accountId: normalizeOptionalString(i?.accountId ?? r?.accountId) } : c); const p = (f?.mode ?? d) === "webhook" ? "webhook" : "announce"; const m = c ? resolveFailureAlertChannel(c.channel, c.to) ?? "last" : void 0; const h = i?.channel !== void 0 || i?.to !== void 0 || t.delivery?.failureDestination?.channel !== void 0 || t.delivery?.failureDestination?.to !== void 0 || r?.channel !== void 0 || r?.to !== void 0; const g = p === "announce" && !h && m ? m : resolveFailureAlertChannel(f?.channel, f?.to) ?? "last"; const _ = p === "announce" && c !== void 0 && g === m; const v = normalizeOptionalString(f?.to) ?? (_ ? c?.to : void 0); const y = c !== void 0 && p === "announce" && g === m && (v === c.to || v !== void 0 && c.to !== void 0 && normalizeFailureAlertRecipient(g, v) === normalizeFailureAlertRecipient(g, c.to)); const b = normalizeOptionalString(f?.accountId) ?? (y ? c?.accountId : void 0); const x = y && b === c?.accountId && (o === null || !t.delivery?.failureDestination || c?.threadId == null || i?.to !== void 0); return { after: clampPositiveInt(i?.after ?? r?.after, DEFAULT_FAILURE_ALERT_AFTER), cooldownMs: clampNonNegativeInt(i?.cooldownMs ?? r?.cooldownMs, DEFAULT_FAILURE_ALERT_COOLDOWN_MS), channel: g, to: v, mode: p, accountId: b, threadId: x ? c.threadId : void 0, includeSkipped: i?.includeSkipped ?? r?.includeSkipped ?? false, alternateRoute: o !== null && !x }; } function buildFailureAlertPayload(e) { const t = e.job.name || e.job.id; const n = e.status === "error" ? e.errorReason : void 0; let r; if (e.autoDisabled) { const t = buildCronAutoDisableNotice({ job: e.job, reason: "consecutive-failures", consecutiveErrors: e.consecutiveErrors, failureNotificationDetail: e.failureNotificationDetail }); r = e.route.mode === "webhook" ? `${t}\nLast error: ${truncateUtf16Safe(e.error?.trim() || "unknown reason", 200)}` : t; } else { const i = e.status === "skipped" ? "skipped" : "failed"; const a = e.status === "skipped" ? "Skip reason" : "Last error"; const o = e.route.mode === "webhook" ? [...n ? [`Cause: ${n}`] : [], `${a}: ${truncateUtf16Safe(e.error?.trim() || "unknown reason", 200)}`] : e.localProviderUnavailable ? [ "Cause: the local model provider is unreachable.", "Start the provider or check its configured endpoint in automation history.", isJobEnabled(e.job) && e.job.state.nextRunAtMs !== void 0 ? "OpenClaw will check again on a later scheduled run." : "After restoring the provider, use Run Now or reschedule this automation." ] : cronFailureDetailLines(n, e.failureNotificationDetail); r = [ `Automation "${t}" ${i} ${e.consecutiveErrors} times`, ...e.repairRequested ? ["An automatic repair was requested in its owner conversation; it is still failing."] : [], ...o ].join("\n"); } const i = e.error ? classifyOAuthRefreshFailure(e.error) : null; const a = e.status === "error" && (n === "auth" || n === "auth_permanent") ? buildProviderLoginRecovery({ provider: normalizeOptionalString(i?.provider), oauthReason: i?.reason }) : void 0; return { text: a ? `${r}\n${a.hint}` : r, ...a ? { presentation: a.presentation } : {} }; } function startFailureNotification(e) { e.state.lastFailureNotificationId = randomUUID(); e.state.lastFailureNotificationDelivered = void 0; e.state.lastFailureNotificationDeliveryStatus = "unknown"; e.state.lastFailureNotificationDeliveryError = void 0; } function startFailureAlertCycle(e, t, n) { startFailureNotification(e); e.state.lastFailureAlertAtMs = n; const r = e.state.failureAlertIncident; e.state.failureAlertIncident = { ...t, scope: r?.scope === "run" ? "run" : t.scope, ...r?.repair ? { repair: { ...r.repair, alerted: true } } : {} }; } function requestFailureNotification(e, t, n, r) { if (t.state.failureAlertIncident?.signature === r.signature) return false; const i = e.deps.nowMs(); const a = t.state.lastFailureAlertAtMs; if (typeof a === "number" && a <= i && i - a < Math.max(0, n.cooldownMs)) return false; startFailureAlertCycle(t, r, i); return true; } function failureRecoveryScope(e) { return e?.kind === "script-failure" && e.source === "trigger" ? "trigger" : "run"; } function recordUnresolvedFailure(e, t) { const n = failureRecoveryScope(t); const r = e.state.failureAlertIncident ??= { scope: n }; if (n === "run") r.scope = "run"; } function failureIncident(e) { const t = e.errorReason ?? e.failureNotificationDetail ?? e.error?.trim(); const n = failureRecoveryScope(e.failureNotificationDetail); return { signature: sha256Hex(JSON.stringify([ e.status, n, t, e.route.mode, e.route.channel, e.route.to, e.route.accountId, e.route.threadId ])), scope: n }; } /** * Emits one alert per incident when threshold, best-effort, and cooldown policy allow it. * An owned job's first inherited chat alert, or terminal one-shot failure, requests repair. * A later failure alerts, naming the request, and the streak is never repaired twice. */ function maybeEmitFailureAlert(e, t) { const n = t.status === "skipped" && t.job.state.lastDiagnostics?.entries.some((e) => e.source === "model-preflight"); if (t.status === "skipped" && !t.alertConfig?.includeSkipped && !n) return "suppressed"; recordUnresolvedFailure(t.job, t.failureNotificationDetail); const r = t.terminalOneShot === true; const i = t.terminalRecurring === true; const a = r || i; const o = t.alertConfig; if (!o) return "unavailable"; if (!a && t.consecutiveCount < o.after) return "suppressed"; if (t.job.delivery?.bestEffort === true && !t.job.failureAlert) return "unavailable"; const s = failureIncident({ ...t, route: o }); const c = e.deps.nowMs(); const l = t.job.state.failureAlertIncident?.repair; if (!i && l?.deadlineAtMs !== void 0 && (l.settledAtMs !== void 0 && l.settledAtMs < l.deadlineAtMs ? t.runAtMs <= l.settledAtMs : c < l.deadlineAtMs)) return "suppressed"; if (a || l && !l.alerted) startFailureAlertCycle(t.job, s, c); else if (!requestFailureNotification(e, t.job, o, s)) return "suppressed"; const u = cronNotificationJob(t.job); const d = { kind: "failure-alert", job: u, payload: buildFailureAlertPayload({ job: t.job, error: t.error, errorReason: t.errorReason, failureNotificationDetail: t.failureNotificationDetail, consecutiveErrors: t.consecutiveCount, route: o, status: t.status, repairRequested: l !== void 0, localProviderUnavailable: n, autoDisabled: a }), runAtMs: t.runAtMs, route: o }; const f = [t.job.failureAlert, t.job.delivery?.failureDestination].some((e) => e && (e.channel !== void 0 || e.to !== void 0 || e.accountId !== void 0)); if (!l && !f && !i && (r || o.mode === "announce") && t.status === "error" && hasFailureRepairOwner(t.job) && (r || isJobEnabled(t.job))) { const n = t.job.state.failureAlertIncident ?? s; t.job.state.failureAlertIncident = { ...n, repair: { atMs: c, deadlineAtMs: c + (e.deps.failureRepairTimeoutMs ?? 1728e5) } }; t.job.state.lastFailureNotificationDeliveryStatus = r ? "unknown" : "not-requested"; t.deferredNotifications.push({ kind: "failure-repair", job: u, ...r ? { fallback: d } : {}, text: buildCronFailureRepairBrief({ job: t.job, consecutiveErrors: t.consecutiveCount, error: t.error, errorReason: t.errorReason, terminal: r }) }); return "queued"; } t.deferredNotifications.push(d); return "queued"; } /** * Resolves the incident after execution succeeds. Recovery is visible in run history and * job state only: a working automation just works, so no notification is sent. Clearing * the incident and cooldown lets the next failure alert again. */ function resolveFailureIncident(e, t) { const n = e.state.failureAlertIncident; if (!n || t?.triggerOnly && n.scope !== "trigger") return; delete e.state.failureAlertIncident; e.state.lastFailureAlertAtMs = void 0; } /** Finalizes execution or required-delivery alerts after scheduling policy settles. */ function finalizeCronFailureNotifications(e, t) { if (t.result.status === "ok" && t.completionStatus === "succeeded") { resolveFailureIncident(t.job); return; } if (t.result.errorClassification?.kind === "aborted") return; recordUnresolvedFailure(t.job, t.result.failureNotificationDetail); if (t.replay) return; if ((t.result.status === "error" || t.result.status === "skipped") && !t.pendingTransientRetry) return maybeEmitFailureAlert(e, { job: t.job, alertConfig: t.alertConfig, status: t.result.status, error: t.result.error, errorReason: t.job.state.lastErrorReason, failureNotificationDetail: t.result.failureNotificationDetail, runAtMs: t.result.startedAt, consecutiveCount: (t.result.status === "skipped" ? t.job.state.consecutiveSkipped : t.job.state.consecutiveErrors) ?? 0, terminalOneShot: t.terminalOneShot, terminalRecurring: t.terminalRecurring, deferredNotifications: t.deferredNotifications }); else if (t.result.status === "ok" && t.completionStatus === "failed" && t.job.state.lastDeliveryStatus === "not-delivered" && t.alertConfig?.alternateRoute) { if (!requestFailureNotification(e, t.job, t.alertConfig, failureIncident({ status: "delivery", error: t.job.state.lastDeliveryError, errorReason: t.job.state.lastErrorReason, route: t.alertConfig }))) return; const n = cronNotificationJob(t.job); const r = t.alertConfig; const i = r.mode === "webhook" ? [`Last error: ${truncateUtf16Safe(t.job.state.lastDeliveryError?.trim() || "unknown reason", 200)}`] : cronFailureDetailLines(t.job.state.lastErrorReason); const a = { text: [`Automation "${n.name || n.id}" delivery failed`, ...i].join("\n") }; t.deferredNotifications.push({ kind: "failure-alert", job: n, payload: a, runAtMs: t.result.startedAt, route: r }); } } //#endregion export { resolveFailureIncident as i, finalizeCronFailureNotifications as n, resolveFailureAlert as r, failureNotificationDeliveryFromJobState as t };