UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

239 lines (238 loc) • 10.8 kB
import { m as asSafeIntegerInRange, t as MAX_DATE_TIMESTAMP_MS } from "./number-coercion-D6u-4YD8.mjs"; import { l as isRecord, o as asRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs"; import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs"; import { t as compileSafeRegex } from "./safe-regex-sRheBeEI.mjs"; import { t as sha256Base64Url } from "./crypto-digest-B2m8wIBj.mjs"; import { t as AutomationLastMeaningfulResultSchema } from "./cron-automation-result-CAvrSzG4.mjs"; import { u as stripCronPinnedExecGrant } from "./scheduled-tool-policy-C_pucbBp.mjs"; import { a as hasCanonicalCronDeliveryMode, i as deliveryToJson, r as decodeCronJobConfig } from "./delivery-codec-BaSNePUi.mjs"; import { t as parseAbsoluteTimeMs } from "./parse-CSwpxE6Q.mjs"; import { l as parseCronStreamSandboxTarget } from "./stream-schedule-BFX6oe0X.mjs"; import { t as assertCronActiveHours } from "./active-hours-DyXD6x9W.mjs"; import { d as PLUGIN_COMMAND_SCHEDULE_MESSAGE, i as decodePluginCommandSchedule } from "./plugin-command-schedule-BIe4jM25.mjs"; import { r as isCronEventSchedule } from "./source-schedule-DlDKIQwQ.mjs"; import { Value } from "typebox/value"; //#region src/cron/definition-hash.ts /** Hashes one canonical cron definition while preserving meaningful env-key order. */ function hashCronJobDefinition(e) { const t = isRecord(e.payload) ? e.payload : void 0; const n = t && isRecord(t.env) ? t.env : void 0; if (t?.kind !== "command" || !n) return `sha256:${sha256Base64Url(stableStringify(e))}`; const r = /* @__PURE__ */ new Set(); if (!Object.keys(n).some((e) => { const t = e.toLowerCase(); if (r.has(t)) return true; r.add(t); return false; })) return `sha256:${sha256Base64Url(stableStringify(e))}`; const { env: i, ...a } = t; const o = { ...e, payload: { ...a, envEntries: Object.entries(n) } }; return `sha256:${sha256Base64Url(stableStringify(o))}`; } //#endregion //#region src/cron/persisted-shape.ts /** Validates persisted cron job records before loading them from disk/state. */ const CRON_STATE_TIMESTAMP_FIELDS = [ "nextRunAtMs", "scheduleActivatedAtMs", "startupCatchupAtMs", "pacedNextRunAtMs", "forcePreservedNextRunAtMs", "queuedAtMs", "runningAtMs", "lastRunAtMs", "lastFailureAlertAtMs", "lastTriggerEvalAtMs", "lastTriggerFireAtMs", "streamLastStartedAtMs", "streamLastExitAtMs" ]; function isValidStateTimestamp(e) { return asSafeIntegerInRange(e, { min: 0, max: MAX_DATE_TIMESTAMP_MS }) !== void 0; } function getInvalidCronJobStateTimestampField(e) { const t = asRecord(e); const n = CRON_STATE_TIMESTAMP_FIELDS.find((e) => t[e] !== void 0 && !isValidStateTimestamp(t[e])); if (n) return n; const r = asRecord(t.autoDisabled).atMs; return r !== void 0 && !isValidStateTimestamp(r) ? "autoDisabled.atMs" : void 0; } /** Rejects caller-authored state timestamps that cannot round-trip through Date and SQLite. */ function assertCronJobStateTimestamps(e) { if (Object.hasOwn(e, "pluginCommandRuns")) throw new Error("cron state.pluginCommandRuns is private launch accounting and cannot be authored"); if (Object.hasOwn(e, "pluginCommandBinding")) throw new Error("cron state.pluginCommandBinding is private restart continuity and cannot be authored"); const t = getInvalidCronJobStateTimestampField(e); if (t) throw new Error(`cron state.${t} must be a non-negative Date-valid integer timestamp`); } /** Returns the first structural reason a persisted cron job cannot be loaded safely. */ function getInvalidPersistedCronJobReason(e) { const t = e.id; if (typeof t !== "string" || !t.trim()) return "missing-id"; const n = asRecord(e.state).lastMeaningfulResult; if (n !== void 0 && !Value.Check(AutomationLastMeaningfulResultSchema, n)) return "invalid-state"; if (getInvalidCronJobStateTimestampField(e.state)) return "invalid-state"; if (e.pluginCommand !== void 0) try { decodePluginCommandSchedule(e.pluginCommand); } catch { return "invalid-plugin-command"; } if (e.idleOnly !== void 0 && typeof e.idleOnly !== "boolean") return "invalid-execution-policy"; if (e.activeHours !== void 0) { const { start: t, end: n, timezone: r } = asRecord(e.activeHours); if (typeof t !== "string" || typeof n !== "string" || r !== void 0 && typeof r !== "string") return "invalid-execution-policy"; try { assertCronActiveHours({ start: t, end: n, timezone: r }); } catch { return "invalid-execution-policy"; } } const r = e.schedule; if (!r || Array.isArray(r)) return "missing-schedule"; const i = typeof r === "string"; if (!i && typeof r !== "object") return "missing-schedule"; const a = asRecord(r); const o = a.kind; if (!i && o !== "at" && o !== "every" && o !== "cron" && o !== "on-exit" && o !== "stream" && o !== "event" && o !== "sandbox-stream") return "invalid-schedule"; if ((o === "sandbox-stream" || e.streamSandbox !== void 0) && (o !== "stream" && o !== "sandbox-stream" || !parseCronStreamSandboxTarget(e.streamSandbox))) return "invalid-schedule"; if (o === "event" && !isCronEventSchedule(r)) return "invalid-schedule"; if (o === "at") { const e = a.at; if (typeof e !== "string" || parseAbsoluteTimeMs(e) === null) return "invalid-schedule"; } if (o === "every") { const e = a.everyMs; const t = a.anchorMs; if (asSafeIntegerInRange(e, { min: 1, max: 864e13 }) === void 0 || t !== void 0 && asSafeIntegerInRange(t, { min: 0, max: 864e13 }) === void 0) return "invalid-schedule"; } if (o === "cron") { const e = a.expr; const t = a.staggerMs; if (typeof e !== "string" || e.trim().length === 0 || t !== void 0 && asSafeIntegerInRange(t, { min: 0, max: 864e13 }) === void 0) return "invalid-schedule"; } if (o === "on-exit") { const e = a.command; if (typeof e !== "string" || e.trim().length === 0) return "invalid-schedule"; } if (o === "stream" || o === "sandbox-stream") { const e = a.command; const t = a.mode ?? "line"; const batchFieldValid = (e) => e === void 0 || asSafeIntegerInRange(e, {}) !== void 0; if (!Array.isArray(e) || e.length === 0 || e.some((e) => typeof e !== "string" || e.length === 0) || t !== "line" && t !== "match" || t === "match" && typeof a.match !== "string" || t === "line" && a.match !== void 0 || !batchFieldValid(a.batchMs) || !batchFieldValid(a.maxBatchBytes)) return "invalid-schedule"; if (t === "match") { if (!compileSafeRegex(a.match)) return "invalid-schedule"; } } if ("trigger" in e) { const t = e.trigger; if (!t || typeof t !== "object" || Array.isArray(t)) return "invalid-trigger"; const n = t.script; if (typeof n !== "string" || n.trim().length === 0 || o === "at" || o === "on-exit" || o === "event") return "invalid-trigger"; } const s = e.payload; if (!s || typeof s !== "object" || Array.isArray(s)) return "missing-payload"; const c = s; const l = c.kind; if (l === "pluginCommand" || e.pluginCommand !== void 0) { const t = l === "pluginCommand" && Object.keys(c).every((e) => e === "kind" || e === "toolsAllow"); const n = l === "agentTurn" && c.message === "[plugin-command-scheduled-turn:v1]"; return e.pluginCommand !== void 0 && (t || n) && Array.isArray(c.toolsAllow) && c.toolsAllow.every((e) => typeof e === "string") && o !== "event" ? null : "invalid-payload"; } if (l !== "systemEvent" && l !== "agentTurn" && l !== "command" && l !== "script") return "invalid-payload"; const u = l === "systemEvent" ? c.text : l === "agentTurn" ? c.message : l === "script" ? c.script : void 0; if ((l === "systemEvent" || l === "agentTurn" || l === "script") && (typeof u !== "string" || l !== "systemEvent" && !u.trim())) return "invalid-payload"; if (o === "event" && l !== "agentTurn") return "invalid-payload"; if (l === "agentTurn" && ["skipIfScratchEmpty", "includeReasoning"].some((e) => c[e] !== void 0 && typeof c[e] !== "boolean")) return "invalid-payload"; if (l === "command") { const e = c.argv; if (!Array.isArray(e) || e.length === 0 || e.some((e) => typeof e !== "string" || e.length === 0)) return "invalid-payload"; if (o === "stream" || o === "sandbox-stream") return "invalid-payload"; } return null; } //#endregion //#region src/cron/store/job-config-codec.ts function stripJobRuntimeFields(e) { const { streamSandbox: t, runtimeAuthority: n, runtimeAuthorityRecoveryRequired: r, state: i, updatedAtMs: a, ...o } = e; const s = parseCronStreamSandboxTarget(t); if (t !== void 0 && (!s || e.schedule.kind !== "stream")) throw new Error(`Cannot persist invalid sandbox stream target for cron job ${e.id}`); const c = isRecord(o.payload) ? o.payload : void 0; const l = Array.isArray(c?.toolsAllow) ? c.toolsAllow.filter((e) => typeof e === "string") : void 0; const u = stripCronPinnedExecGrant({ toolsAllow: l, requirement: o.toolsAllowExecTargetRequirement }); if (o.pluginCommand !== void 0 && (c?.kind !== "agentTurn" || c.message !== "[plugin-command-scheduled-turn:v1]")) throw new Error(`Cannot persist plugin command cron job ${e.id} without its reserved payload`); return { ...o, ...s ? { streamSandbox: s, schedule: { ...e.schedule, kind: "sandbox-stream" } } : {}, ...c && u ? { payload: { ...c, toolsAllow: u } } : {}, ...o.pluginCommand !== void 0 ? { payload: { kind: "pluginCommand", toolsAllow: u ?? l } } : {}, ...o.delivery && hasCanonicalCronDeliveryMode(o.delivery) ? { delivery: deliveryToJson(o.delivery) } : {}, state: {} }; } function resolveCronJobGrantDefinitionRevision(e) { const t = safeParseJsonRecord(JSON.stringify(stripJobRuntimeFields(e))); if (!t) throw new Error(`Cannot canonicalize cron job ${e.id} for grant revision`); const { enabled: n, state: r, ...i } = t; return hashCronJobDefinition(i); } /** Restore supported runtime config without changing the marker retained for recovery. */ function decodeStoredCronJobConfig(e) { const t = isRecord(e.schedule) ? e.schedule : void 0; const n = isRecord(e.payload) ? e.payload : void 0; const r = parseCronStreamSandboxTarget(e.streamSandbox); return { ...decodeCronJobConfig(e), ...t?.kind === "sandbox-stream" && r ? { schedule: { ...t, kind: "stream" }, streamSandbox: r } : {}, ...n?.kind === "pluginCommand" && isRecord(e.pluginCommand) ? { payload: { kind: "agentTurn", message: PLUGIN_COMMAND_SCHEDULE_MESSAGE, ...n.toolsAllow === void 0 ? {} : { toolsAllow: n.toolsAllow } } } : {} }; } //#endregion export { getInvalidPersistedCronJobReason as a, assertCronJobStateTimestamps as i, resolveCronJobGrantDefinitionRevision as n, hashCronJobDefinition as o, stripJobRuntimeFields as r, decodeStoredCronJobConfig as t };