openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
406 lines (405 loc) • 19.1 kB
JavaScript
import { l as normalizeOptionalString, p as normalizeStringifiedOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import "./model-ref-shared-DqE2RqZv.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs";
import { a as resolveUpdateRehearsalRoot } from "./update-rehearsal-paths-Dr1MbUA_.mjs";
import { i as normalizeChatChannelId } from "./ids-BRSWrLzE.mjs";
import { s as resolveAgentModelPrimaryValue } from "./model-input-DrM4DWHG.mjs";
import { i as buildModelAliasIndex, y as resolveModelRefFromString } from "./model-selection-shared-9Kz63Hhm.mjs";
import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs";
import { n as resolveDefaultModelForAgent } from "./model-selection-config-Bvf5WqHo.mjs";
import { n as runExec } from "./exec-aRIvS9s4.mjs";
import { r as resolveCronJobsStorePath } from "./paths-CY4cvrR6.mjs";
import { f as isUpdateDoctorLintPass } from "./update-phase-YdZvaQsy.mjs";
import { t as note } from "./note-CnLgHvug.mjs";
import { t as listReadOnlyChannelPluginsForConfig } from "./read-only-idsFCBWl.mjs";
import "./store-DaG-8LOU.mjs";
import { n as readCronStoreSelectionForDoctor, t as maybeRepairCronStoreSelection } from "./default-store-selection-OlpQeMWT.mjs";
import { t as countLabel } from "./doctor-state-integrity-format-XVQ-DkEv.mjs";
import { d as formatLegacyIssuePreview, f as formatScheduledToolPolicyAdvisory, i as loadLegacyCronRepairState, l as rethrowSqliteSchemaVersionError, o as readLegacyCronStorePath, p as formatUnresolvedPromptAdvisory, t as applyLegacyCronStoreRepair, u as formatLegacyGatewayExecAdvisory } from "./legacy-repair-D9TVWPHm.mjs";
import { i as normalizeStoredCronJobs } from "./store-migration-CzntnWoE.mjs";
import { t as resolveCronDeliveryPlan } from "./delivery-plan-BMeGAb9T.mjs";
//#region src/commands/doctor/cron/warnings.ts
const LEGACY_WHATSAPP_HEALTH_SCRIPT_RE = /(?:^|\s)(?:"[^"]*ensure-whatsapp\.sh"|'[^']*ensure-whatsapp\.sh'|[^\s#;|&]*ensure-whatsapp\.sh)\b/u;
const CRON_ADVISORY_EXAMPLE_LIMIT = 3;
const CRONTAB_READ_TIMEOUT_MS = 5e3;
function formatSortedCounts(e) {
return [...e.entries()].toSorted(([e], [t]) => e.localeCompare(t)).map(([e, t]) => `${e}=${t}`).join(", ");
}
function addJobExample(e, t, n) {
if (e.length < CRON_ADVISORY_EXAMPLE_LIMIT) {
const r = normalizeOptionalString(t.id) ?? normalizeOptionalString(t.jobId);
const i = normalizeOptionalString(t.name);
e.push(`${r ?? i ?? "<unnamed>"} -> ${n}`);
}
}
function noteCronModelOverrides(e) {
const t = resolveAgentModelPrimaryValue(e.cfg.agents?.defaults?.model);
const n = {
cfg: e.cfg,
allowManifestNormalization: false,
allowPluginNormalization: false
};
const r = t ? resolveDefaultModelForAgent(n) : void 0;
const i = r && modelKey(r.provider, r.model);
let a;
const o = /* @__PURE__ */ new Map();
const s = [];
let c = 0;
let l = 0;
for (const t of e.jobs) {
if (t.enabled === false) continue;
const e = isRecord(t.payload) ? t.payload : void 0;
const u = normalizeOptionalString(e?.kind)?.toLowerCase();
if (u && u !== "agentturn") continue;
const d = normalizeOptionalString(e?.model);
if (!d) continue;
c += 1;
const f = d.indexOf("/");
const p = f > 0 && f < d.length - 1 ? d.slice(0, f).trim().toLowerCase() : "bare/alias";
o.set(p, (o.get(p) ?? 0) + 1);
const m = r && {
...n,
defaultProvider: r.provider
};
const h = m && resolveModelRefFromString({
...m,
raw: d,
aliasIndex: a ??= buildModelAliasIndex(m)
})?.ref;
if (i && h && modelKey(h.provider, h.model) !== i) {
l += 1;
addJobExample(s, t, d);
}
}
if (c === 0) return;
const u = [
"Automation model overrides detected.",
`- ${countLabel(c, "job")} set \`payload.model\` and will not inherit \`agents.defaults.model\`${t ? ` (${t})` : ""}`,
`- Provider namespaces: ${formatSortedCounts(o)}`
];
if (l > 0) {
u.push(`- ${countLabel(l, "job")} ${l === 1 ? "uses" : "use"} a different model than \`agents.defaults.model\`${t ? ` (${t})` : ""}`);
u.push(`- Examples: ${s.join(", ")}`);
}
u.push(`Review with ${formatCliCommand("openclaw automations list")} and ${formatCliCommand("openclaw automations show <job-id>")}; remove \`payload.model\` from jobs that should inherit the default.`);
note(u.join("\n"), "Cron");
}
function canonicalChannelKey(e) {
return normalizeChatChannelId(e) ?? e.trim().toLowerCase();
}
function collectCronDeliveryTargetAdvisory(e) {
const t = [];
for (const n of e.jobs) {
if (n.enabled === false || !isRecord(n.delivery) || n.delivery.mode !== "announce") continue;
const e = resolveCronDeliveryPlan(n);
if (e.mode === "announce" && e.channel && e.channel !== "last") t.push({
channel: e.channel,
job: n
});
}
if (t.length === 0) return null;
const n = /* @__PURE__ */ new Set();
const r = listReadOnlyChannelPluginsForConfig(e.cfg, {
includePersistedAuthState: false,
includeSetupFallbackPlugins: true
});
for (const { id: e } of r) {
const t = normalizeOptionalString(e);
if (t) n.add(canonicalChannelKey(t));
}
const i = /* @__PURE__ */ new Map();
const a = [];
let o = 0;
for (const { channel: e, job: r } of t) {
if (n.has(canonicalChannelKey(e))) continue;
o += 1;
i.set(e, (i.get(e) ?? 0) + 1);
addJobExample(a, r, e);
}
if (o === 0) return null;
return [
"Automation delivery targets unavailable channels.",
`- ${countLabel(o, "job")} ${o === 1 ? "announces" : "announce"} to a channel whose plugin is not active; the next scheduled run will fail to deliver`,
`- Channels: ${formatSortedCounts(i)}`,
`- Examples: ${a.join(", ")}`,
`Reactivate the channel plugin or update the job's \`delivery.channel\` after reviewing with ${formatCliCommand("openclaw automations list")} and ${formatCliCommand("openclaw automations show <job-id>")}.`
].join("\n");
}
function noteCronDeliveryTargetAdvisory(e) {
let t;
try {
t = collectCronDeliveryTargetAdvisory(e);
} catch {
return;
}
if (t) note(t, "Cron");
}
async function collectLegacyWhatsAppCrontabHealthWarning(e = {}) {
if ((e.platform ?? process.platform) !== "linux") return null;
const t = e.env ?? process.env;
if (isUpdateDoctorLintPass(t) || resolveUpdateRehearsalRoot(t) !== void 0) return null;
let n;
try {
n = (await (e.readCrontab ? e.readCrontab() : runExec("crontab", ["-l"], {
logOutput: false,
timeoutMs: CRONTAB_READ_TIMEOUT_MS
}))).stdout;
} catch {
return null;
}
const r = (normalizeStringifiedOptionalString(n) ?? "").split(/\r?\n/u).map((e) => e.trim()).filter((e) => e.length > 0 && !e.startsWith("#")).filter((e) => LEGACY_WHATSAPP_HEALTH_SCRIPT_RE.test(e));
if (r.length === 0) return null;
return [
"Legacy WhatsApp crontab health check detected.",
"`~/.openclaw/bin/ensure-whatsapp.sh` is not maintained by current OpenClaw and can misreport `Gateway inactive` from cron when the systemd user bus environment is missing.",
`Remove the stale crontab entry with ${formatCliCommand("crontab -e")}; use ${formatCliCommand("openclaw channels status --probe")}, ${formatCliCommand("openclaw doctor")}, and ${formatCliCommand("openclaw gateway status")} for current health checks.`,
`Matched ${countLabel(r.length, "entry")}.`
].join("\n");
}
async function noteLegacyWhatsAppCrontabHealthCheck(e = {}) {
const t = await collectLegacyWhatsAppCrontabHealthWarning(e);
if (t) note(t, "Cron");
}
//#endregion
//#region src/commands/doctor/cron/index.ts
const CHRONIC_FAILURE_MIN_CONSECUTIVE_ERRORS = 3;
function inspectCronJobHealth(e) {
let t = 0;
let n = 0;
const r = [];
for (const i of e) {
const e = i.state;
if (typeof e !== "object" || e === null) continue;
if ("runningAtMs" in e && typeof e.runningAtMs === "number") t += 1;
if (i.enabled !== false && "consecutiveErrors" in e && typeof e.consecutiveErrors === "number" && e.consecutiveErrors >= CHRONIC_FAILURE_MIN_CONSECUTIVE_ERRORS) n += 1;
if (i.enabled !== false || typeof i.id !== "string" || !isRecord(e)) continue;
const a = e.autoDisabled;
if (!isRecord(a) || a.reason !== "consecutive-failures" && a.reason !== "schedule-errors" || typeof a.consecutiveErrors !== "number") continue;
r.push({
id: i.id,
name: typeof i.name === "string" && i.name.trim() ? i.name.trim() : i.id,
reason: a.reason,
consecutiveErrors: a.consecutiveErrors
});
}
return {
inFlightCount: t,
chronicFailureCount: n,
autoDisabledJobs: r
};
}
const LEGACY_CRON_STORE_CHECK_ID = "core/doctor/legacy-cron-store";
function legacyCronStoreFinding(e) {
return {
checkId: LEGACY_CRON_STORE_CHECK_ID,
severity: "warning",
message: e.message,
path: e.path,
requirement: e.requirement,
fixHint: e.fixHint ?? `Run ${formatCliCommand("openclaw doctor --fix")} to normalize legacy cron storage.`
};
}
async function collectLegacyCronStoreHealthFindings(e) {
let t;
try {
const n = await readCronStoreSelectionForDoctor(e.cfg);
if (n.status === "unresolved") return [legacyCronStoreFinding({
message: n.message,
path: n.storePath,
requirement: "cron-default-partition-selected",
fixHint: "Run openclaw doctor --fix in an interactive terminal and complete Select the default cron partition. --yes does not choose a partition."
})];
t = await loadLegacyCronRepairState({
cfg: e.cfg,
readOnly: true
});
} catch (t) {
rethrowSqliteSchemaVersionError(t);
const n = resolveCronJobsStorePath(readLegacyCronStorePath(e.cfg));
return [legacyCronStoreFinding({
message: `Unable to read cron job store at ${shortenHomePath(n)}.`,
path: n,
requirement: "cron-store-readable",
fixHint: [
`Fix the file's permissions or contents and re-run ${formatCliCommand("openclaw doctor")}.`,
"Later health checks will continue.",
`Details: ${formatErrorMessage(t)}`
].join(" ")
})];
}
if (!t) return [];
const n = [];
const { legacyQuarantine: r, rawJobs: i } = t;
const a = resolveOpenClawStateSqlitePath();
const recordFinding = (e, t = a) => n.push(legacyCronStoreFinding({
...e,
path: t
}));
if (t.persistedQuarantine.length > 0) recordFinding({
message: `${countLabel(t.persistedQuarantine.length, "quarantined cron job row")} found in SQLite at ${shortenHomePath(a)}.`,
requirement: "quarantined-cron-rows",
fixHint: "Review or repair quarantined rows before restoring any job to the active cron store."
});
if (r) recordFinding({
message: `Legacy JSON cron quarantine will be imported into SQLite from ${shortenHomePath(r.path)}.`,
requirement: "legacy-cron-quarantine"
}, r.path);
if (i.length === 0) return n;
const o = normalizeStoredCronJobs(i);
for (const e of formatLegacyIssuePreview(o.issues)) recordFinding({
message: e.replace(/^- /u, ""),
requirement: "legacy-cron-store-shape"
});
for (const e of o.unsupportedDeliveryModeJobs) recordFinding({
message: `Cron job ${e} has an unsupported delivery mode; Doctor left it unchanged.`,
requirement: "cron-delivery-mode-valid",
fixHint: "Review its intended delivery and set mode to \"none\", \"announce\", or \"webhook\"."
});
for (const e of o.legacyTriggerScriptJobs) recordFinding({
message: `Legacy cron trigger script for ${e} can be migrated to direct tool calls.`,
requirement: "legacy-cron-trigger-script"
});
for (const e of o.unsupportedLegacyTriggerScriptJobs) recordFinding({
message: `Legacy cron trigger script for ${e} cannot be safely migrated automatically.`,
requirement: "unsupported-legacy-cron-trigger-script",
fixHint: "Inspect the automation and update its trigger script manually to use direct tool calls."
});
for (const [e, t, n] of [[
o.legacyScheduledToolPolicyJobs,
"cron-scheduled-authority-reauthorization",
"require explicit scheduled authority reauthorization"
], [
o.invalidScheduledToolPolicyJobs,
"cron-scheduled-authority-valid",
"have invalid scheduled authority provenance"
]]) if (e.length > 0) recordFinding({
message: `${countLabel(e.length, "tool-bearing automation")} ${n}.`,
requirement: t,
fixHint: `Review with ${formatCliCommand("openclaw automations list --all")} and reauthorize with ${formatCliCommand("openclaw automations edit <id> --tools <tool,...>")}.`
});
if (o.legacyGatewayExecJobs.length > 0) recordFinding({
message: `${countLabel(o.legacyGatewayExecJobs.length, "automation")} require recreation because they grant the retired \`gateway_exec\` alias.`,
requirement: "legacy-gateway-exec-recreation",
fixHint: "Review the affected jobs with `openclaw automations list --all`, then recreate each one from a fresh authenticated creator turn or explicitly reauthorize its complete tool cap from a trusted operator shell."
});
const s = i.filter((e) => e.notify === true).length;
if (s > 0) recordFinding({
message: `${countLabel(s, "job")} still uses legacy notify webhook fallback.`,
requirement: "legacy-notify-fallback"
});
return n;
}
async function maybeRepairLegacyCronStore(e) {
let t;
try {
if (!await maybeRepairCronStoreSelection(e)) return;
t = await loadLegacyCronRepairState({ cfg: e.cfg });
} catch (t) {
rethrowSqliteSchemaVersionError(t);
const n = t instanceof Error ? t.message : String(t);
const r = resolveCronJobsStorePath(readLegacyCronStorePath(e.cfg));
note([
`Unable to read cron job store at ${shortenHomePath(r)}.`,
`- ${n}`,
`Fix the file's permissions or contents and re-run ${formatCliCommand("openclaw doctor")}; later health checks will continue.`
].join("\n"), "Cron");
return;
}
if (!t) return;
const { storePath: n, legacyQuarantine: r, invalidConfigRows: i, persistedQuarantine: a, rawJobs: o } = t;
const repair = async (n) => {
if (await e.prompter.confirm({
message: "Repair legacy cron jobs now?",
initialValue: true
})) {
const r = await applyLegacyCronStoreRepair({
cfg: e.cfg,
state: t,
...n ? { normalized: n } : {},
recoverQuarantinedScheduleJobs: true
});
if (r.changes.length > 0) note(r.changes.join("\n"), "Doctor changes");
if (r.warnings.length > 0) note(r.warnings.join("\n"), "Doctor warnings");
}
};
const s = a.filter((e) => e.reason === "invalid-schedule" && e.job).length;
const c = resolveOpenClawStateSqlitePath();
if (a.length > 0) note([
`Quarantined cron job rows found in SQLite at ${shortenHomePath(c)}.`,
`- ${countLabel(a.length, "row")} was removed from the active cron store after runtime validation failed.`,
"- Review or repair quarantined rows before restoring any job to the active cron store."
].join("\n"), "Cron");
const l = [];
if (r) l.push("- legacy JSON cron quarantine will be imported into SQLite");
if (i.length > 0) l.push(`- ${countLabel(i.length, "malformed cron row")} will be quarantined in SQLite`);
if (s > 0) l.push(`- ${countLabel(s, "quarantined automation")} will be revalidated and restored only if current validation passes`);
if (o.length === 0) {
if (!r && i.length === 0 && s === 0) return;
const e = r ? `Legacy cron storage detected at ${shortenHomePath(n)}.` : `Cron store issues detected at ${shortenHomePath(c)}.`;
note([
e,
...l,
`Repair with ${formatCliCommand("openclaw doctor --fix")} to finish the migration.`
].join("\n"), "Cron");
await repair();
return;
}
noteCronModelOverrides({
cfg: e.cfg,
jobs: o
});
noteCronDeliveryTargetAdvisory({
cfg: e.cfg,
jobs: o
});
const { inFlightCount: u, chronicFailureCount: d, autoDisabledJobs: f } = inspectCronJobHealth(o);
if (u > 0) {
const e = u === 1 ? "it" : "them";
note([
`${countLabel(u, "automation")} ${u === 1 ? "is" : "are"} still marked in-flight (\`state.runningAtMs\` is set).`,
`- If no gateway is currently executing ${e}, the marker is left over from an interrupted run; the gateway marks such runs interrupted the next time it starts.`,
`- Review with ${formatCliCommand("openclaw automations list --all")} or ${formatCliCommand("openclaw automations show <id>")}.`
].join("\n"), "Cron");
}
if (d > 0) note([
`${countLabel(d, "automation")} ${d === 1 ? "has" : "have"} failed ${CHRONIC_FAILURE_MIN_CONSECUTIVE_ERRORS}+ runs in a row (\`state.consecutiveErrors\`), so the scheduler only re-fires ${d === 1 ? "it" : "them"} on error backoff.`,
`- The count resets on the next successful run and also counts runs interrupted by a gateway restart, so a lasting streak means repeated task failures, repeatedly interrupted runs, or a mix. Failure alerts are opt-in, so this may be the only notice.`,
`- Review with ${formatCliCommand("openclaw automations list")} or ${formatCliCommand("openclaw automations show <id>")}.`
].join("\n"), "Cron");
if (f.length > 0) note([`${countLabel(f.length, "automation")} ${f.length === 1 ? "is" : "are"} auto-disabled after repeated failures.`, ...f.map((e) => `- ${e.name} (${e.id}): recorded reason \`${e.reason}\` after ${e.consecutiveErrors} consecutive errors. Fix the cause, then re-enable with ${formatCliCommand(`openclaw automations enable ${e.id}`)}.`)].join("\n"), "Cron");
const p = normalizeStoredCronJobs(o);
if (p.unsupportedDeliveryModeJobs.length > 0) note(`Unsupported cron delivery modes were left unchanged: ${p.unsupportedDeliveryModeJobs.join(", ")}. Review their intended delivery and set mode to "none", "announce", or "webhook".`, "Cron");
if (p.unsupportedLegacyTriggerScriptJobs.length > 0) note([
"Legacy cron trigger scripts cannot be safely migrated automatically:",
...p.unsupportedLegacyTriggerScriptJobs.map((e) => `- ${e}`),
"Inspect each automation and update its trigger script manually to use direct tool calls."
].join("\n"), "Cron");
const m = o.filter((e) => e.notify === true).length;
for (const e of [
formatUnresolvedPromptAdvisory(p.unresolvedAgentTurnCommandPromptJobs, "command"),
formatUnresolvedPromptAdvisory(p.unresolvedAgentTurnShellToolPromptJobs, "shell"),
formatScheduledToolPolicyAdvisory({
legacyJobs: p.legacyScheduledToolPolicyJobs,
invalidJobs: p.invalidScheduledToolPolicyJobs
}),
formatLegacyGatewayExecAdvisory(p.legacyGatewayExecJobs)
]) if (e) note(e, "Cron");
const h = formatLegacyIssuePreview(p.issues);
if (p.legacyTriggerScriptJobs.length > 0) h.push(`- ${countLabel(p.legacyTriggerScriptJobs.length, "legacy cron trigger script")} will be migrated to direct tool calls: ${p.legacyTriggerScriptJobs.join(", ")}`);
h.push(...l);
if (m > 0) h.push(`- ${countLabel(m, "job")} still uses legacy \`notify: true\` webhook fallback`);
if (h.length === 0) return;
const g = `Cron store issues detected at ${shortenHomePath(resolveOpenClawStateSqlitePath())}.`;
note([
g,
...h,
`Repair with ${formatCliCommand("openclaw doctor --fix")} to normalize the store before the next scheduler run.`
].join("\n"), "Cron");
await repair(p);
}
//#endregion
export { collectLegacyCronStoreHealthFindings, collectLegacyWhatsAppCrontabHealthWarning, maybeRepairLegacyCronStore, noteLegacyWhatsAppCrontabHealthCheck };