UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

346 lines (345 loc) • 14.5 kB
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs"; import { c as prepareSessionSourceAuthority, o as composeSessionSourceAssertion } from "./session-source-authority-TlTpfRVE.mjs"; import { g as resolveAdmittedRunActiveAssertion } from "./admitted-run-context-D3Jvk_f_.mjs"; import { t as notifyGatewayWorkMetricsChanged } from "./gateway-work-metrics-events-DG6KfFxk.mjs"; //#region src/cron/active-jobs.ts /** Tracks in-process cron executions so schedulers and wake paths avoid duplicate runs. */ const CRON_ACTIVE_JOB_STATE_KEY = Symbol.for("openclaw.cron.activeJobs"); function bindCronJobAdmittedRun(e, t, n) { const r = resolveAdmittedRunActiveAssertion(t, n); if (e && r && isCronActiveJobMarkerCurrent(e)) getCronActiveJobState().admittedJobRuns.set(e, { context: t, assertActive: r, signal: n }); } /** Captures one occurrence before admission without granting another prompt its authority. */ function captureCronJobMessageAuthority(e, t) { const { jobId: n } = e; const r = getCurrentCronActiveJobMarker(n); const i = t ? r?.isMessageSourceAuthorityCurrent : r?.isMessageActionAuthorityCurrent; if (!r || !i) return; const { instanceId: a, runId: o } = e.operationalRunInstance; const { admittedJobRuns: s } = getCronActiveJobState(); let c; const isMarkerCurrent = () => getCurrentCronActiveJobMarker(n) === r && !r.messageActionAuthorityRevoked && (!t || !r.messageSourceAuthorityRevoked) && !r.jobRemoved && r.cancellation?.kind !== "requested"; const inactive = () => /* @__PURE__ */ new Error("cron message action authority is no longer active"); const readOwner = () => { const e = s.get(r); if (!isMarkerCurrent() || !e || e.context.operationalRunInstance.instanceId !== a || e.context.operationalRunInstance.runId !== o || c !== void 0 && e !== c) throw inactive(); c ??= e; return c; }; const l = Object.assign(() => readOwner().assertActive(), { prepareSessionSource: () => prepareSessionSourceAuthority(readOwner().assertActive) }); return composeSessionSourceAssertion([l], (e) => { readOwner(); e(); if (!i()) { if (t) r.messageSourceAuthorityRevoked = true; else r.messageActionAuthorityRevoked = true; throw inactive(); } }); } function captureCronJobMessageActionAuthority(e) { return captureCronJobMessageAuthority(e, false); } function captureCronJobMessageSourceAuthority(e) { return captureCronJobMessageAuthority(e, true); } /** Source restoration belongs to one occurrence; returns whether it has removed itself. */ function captureCronJobSourceAuthority(e) { const t = getCurrentCronActiveJobMarker(e); const n = t?.standingGrantAuthority; if (!t || !n) return; return () => { if (getCurrentCronActiveJobMarker(e) !== t || t.jobRemoved && !isCronSelfRemovalCurrent(t) || t.cancellation?.kind === "requested") throw new Error("Cron occurrence source authority is no longer active"); n.assertCurrent(); return t.jobRemoved === true; }; } function captureCronJobStandingGrantAuthority(e) { const t = getCurrentCronActiveJobMarker(e.jobId); const n = t?.standingGrantAuthority; if (!t || !n) return; const { instanceId: r, runId: i } = e.operationalRunInstance; const { admittedJobRuns: a } = getCronActiveJobState(); let o; const assertCurrent = () => { const s = a.get(t); if (getCurrentCronActiveJobMarker(e.jobId) !== t || t.jobRemoved || t.cancellation?.kind === "requested" || !s || s.context.operationalRunInstance.instanceId !== r || s.context.operationalRunInstance.runId !== i || o !== void 0 && s !== o) throw new Error("Cron standing-grant occurrence is no longer active"); o ??= s; o.assertActive(); n.assertCurrent(); }; return { context: n.context, handle: { ...n.handle }, assertCurrent }; } /** Captures host-owned admission; neither a copied token nor a same-id run can redeem it. */ function bindCronSelfRemovalCommitGuard(e, t, n, r) { const { admittedJobRuns: i, selfRemovalOwners: a } = getCronActiveJobState(); const o = getCurrentCronActiveJobMarker(e); const s = o && i.get(o); const assertBinding = () => { if (!o || !s || s.context.operationalRunInstance.instanceId !== t.instanceId || s.context.operationalRunInstance.runId !== t.runId || getCurrentCronActiveJobMarker(e) !== o || i.get(o) !== s) throw new TypeError("Cron self-removal requires the exact live run; the job was not removed."); s.assertActive.assertScopeCurrent(); return s; }; let c = false; const selfRemovalGuard = () => { c = false; n(); r(); assertBinding().assertActive(); c = true; }; a.set(selfRemovalGuard, () => { try { if (!c) return; assertBinding(); return o; } catch { return; } }); return selfRemovalGuard; } function getCronActiveJobState() { const e = resolveGlobalSingleton(CRON_ACTIVE_JOB_STATE_KEY, () => ({ activeJobs: /* @__PURE__ */ new Map(), selfRemovalOwners: /* @__PURE__ */ new WeakMap(), admittedJobRuns: /* @__PURE__ */ new WeakMap(), generation: 0, nextToken: 1, emptyWaiters: /* @__PURE__ */ new Set() })); e.generation ??= 0; e.nextToken ??= 1; e.activeJobs ??= /* @__PURE__ */ new Map(); e.selfRemovalOwners ??= /* @__PURE__ */ new WeakMap(); e.admittedJobRuns ??= /* @__PURE__ */ new WeakMap(); e.emptyWaiters ??= /* @__PURE__ */ new Set(); return e; } function getActiveCronJobCountForGeneration(e) { let t = 0; for (const n of e.activeJobs.values()) if (isMarkerActiveInGeneration(n, e.generation)) t += 1; return t; } function isMarkerActiveInGeneration(e, t) { return e.generation === t || e.preserveAcrossGenerationAdvance === true; } function getCurrentCronActiveJobMarker(e) { if (!e) return; const t = getCronActiveJobState(); const n = t.activeJobs.get(e); return n && isMarkerActiveInGeneration(n, t.generation) ? n : void 0; } function notifyActiveCronJobWaitersIfEmpty(e) { if (getActiveCronJobCountForGeneration(e) > 0) return; for (const t of e.emptyWaiters) t(); e.emptyWaiters.clear(); } function notifyCronJobInactive(e) { if (e.inactiveNotified) return; e.inactiveNotified = true; for (const t of e.onInactive ?? []) t(); e.onInactive?.clear(); } /** Marks a cron job id as currently executing for duplicate-run suppression. */ function markCronJobActive(e, t) { if (!e) return; const n = getCronActiveJobState(); const r = n.nextToken; n.nextToken += 1; const i = { jobId: e, ...t?.agentId ? { agentId: t.agentId } : {}, ...t?.sessionKey ? { sessionKey: t.sessionKey } : {}, ...t?.stateIdentityKey ? { stateIdentityKey: t.stateIdentityKey } : {}, ...t?.isMessageActionAuthorityCurrent ? { isMessageActionAuthorityCurrent: t.isMessageActionAuthorityCurrent } : {}, ...t?.isMessageSourceAuthorityCurrent ? { isMessageSourceAuthorityCurrent: t.isMessageSourceAuthorityCurrent } : {}, generation: n.generation, token: r, ...t?.preserveAcrossGenerationAdvance ? { preserveAcrossGenerationAdvance: true } : {} }; n.activeJobs.set(e, i); notifyGatewayWorkMetricsChanged(); return i; } /** Clears the active marker when a cron run exits or is abandoned. */ function clearCronJobActive(e, t) { if (!e) return; const n = getCronActiveJobState(); const r = n.activeJobs.get(e); if (r && (!t || t.jobId === e && t.token === r.token)) { n.activeJobs.delete(e); notifyCronJobInactive(r); } else if (t?.jobId === e) notifyCronJobInactive(t); notifyActiveCronJobWaitersIfEmpty(n); notifyGatewayWorkMetricsChanged(); } /** Records a durable schedule edit against the exact run that was active for it. */ function noteActiveCronJobScheduleMutation(e) { const t = getCurrentCronActiveJobMarker(e); if (t) t.scheduleMutated = true; } /** Records a durable trigger edit against the exact run that evaluated it. */ function noteActiveCronJobTriggerMutation(e) { const t = getCurrentCronActiveJobMarker(e); if (t) t.triggerMutated = true; } /** A committed permission change cannot be undone by a retry or an A-to-B-to-A edit. */ function noteActiveCronJobMessageActionAuthorityMutation(e) { const t = getCurrentCronActiveJobMarker(e); if (t) t.messageActionAuthorityRevoked = true; } /** Revokes source-scoped reads and writes after their authenticated executable source changes. */ function noteActiveCronJobMessageSourceAuthorityMutation(e) { const t = getCurrentCronActiveJobMarker(e); if (t) t.messageSourceAuthorityRevoked = true; } /** Retires the admitted job identity after its deletion becomes durable. */ function noteActiveCronJobRemoval(e, t, n) { const r = getCurrentCronActiveJobMarker(e); if (!r) { n?.(void 0); return; } r.scheduleMutated = true; r.jobRemoved = true; try { if (!t || getCronActiveJobState().selfRemovalOwners.get(t)?.() !== r) requestCronActiveJobMarkerCancellation(r, "Cron job removed by operator."); else r.selfRemovalAccepted = true; } finally { n?.(r); } return r; } /** Completion retains its live receipt after self-removal; closed tools gain no new authority. */ function isCronSelfRemovalCurrent(e) { return e?.selfRemovalAccepted === true && e.cancellation?.kind !== "requested" && getCurrentCronActiveJobMarker(e.jobId) === e; } function requestCronActiveJobMarkerCancellation(e, t) { const n = e.cancellation; if (n?.kind === "requested") return; e.cancellation = { kind: "requested", reason: t }; n?.cancel(t); } /** Requests cancellation now or when the exact active run binds its controller. */ function requestActiveCronJobCancellation(e, t) { const n = getCurrentCronActiveJobMarker(e); if (n) requestCronActiveJobMarkerCancellation(n, t); } /** Capture deletion's exact owners; an outer rollback or later successor keeps its authority. */ function captureActiveCronJobAgentDeletion(e, t) { const n = getCronActiveJobState(); const r = [...n.activeJobs.values()].filter((r) => r.agentId === e && r.stateIdentityKey === t && isMarkerActiveInGeneration(r, n.generation)); return () => { for (const e of r) if (getCurrentCronActiveJobMarker(e.jobId) === e) requestCronActiveJobMarkerCancellation(e, "Cron job agent deletion began."); }; } /** Returns whether the given cron job id is currently executing in this process. */ function isCronJobActive(e) { return getCurrentCronActiveJobMarker(e) !== void 0; } /** Snapshot host-only activity before scheduling worker maintenance. */ function listActiveCronJobIds() { return [...getCronActiveJobState().activeJobs.keys()].filter(isCronJobActive); } /** Includes admitted runs that have not entered their executing core yet. */ function hasActiveCronJobsForAgent(e, t, n) { for (const r of getCronActiveJobState().activeJobs.values()) if (r.jobId !== t && !(n?.excludeIdleWaiters && r.idleAdmissionWait) && !r.inactiveNotified && (!r.agentId || r.agentId === e)) return true; return false; } /** Pending idle work remains drain-visible without making peer waiters block each other. */ function markCronJobWaitingForIdle(e, t) { if (!e || !isCronActiveJobMarkerCurrent(e)) throw new Error("Cron idle admission lost its active run marker"); const n = { replyOperation: t }; e.idleAdmissionWait = n; notifyGatewayWorkMetricsChanged(); return () => { if (e.idleAdmissionWait === n) { delete e.idleAdmissionWait; notifyGatewayWorkMetricsChanged(); } }; } /** Excludes only the captured reply owner, never a successor that reuses its session key. */ function isCronReplyOperationWaitingForIdle(e) { if (e.abortSignal.aborted || e.result) return false; for (const t of getCronActiveJobState().activeJobs.values()) if (t.idleAdmissionWait?.replyOperation === e && isCronActiveJobMarkerCurrent(t)) return true; return false; } /** Runs a callback when the exact cron job no longer has an active in-process run. */ function onCronJobInactive(e, t) { if (!e || e.inactiveNotified) { t(); return; } e.onInactive ??= /* @__PURE__ */ new Set(); e.onInactive.add(t); } function isCronActiveJobMarkerCurrent(e) { if (!e) return true; const t = getCronActiveJobState(); return t.activeJobs.get(e.jobId)?.token === e.token && isMarkerActiveInGeneration(e, t.generation); } /** Returns the number of active cron runs in this process. */ function getActiveCronJobCount() { return getActiveCronJobCountForGeneration(getCronActiveJobState()); } async function waitForActiveCronJobs(e) { const t = getCronActiveJobState(); if (getActiveCronJobCountForGeneration(t) === 0) return { drained: true, active: 0 }; await new Promise((n) => { const waiter = () => { clearTimeout(r); n(); }; const r = setTimeout(() => { t.emptyWaiters.delete(waiter); n(); }, Math.max(0, Math.floor(e))); t.emptyWaiters.add(waiter); }); const n = getActiveCronJobCountForGeneration(t); return { drained: n === 0, active: n }; } /** Starts a new process-lifecycle generation without clearing still-finalizing old runs. */ function advanceCronActiveJobGeneration() { const e = getCronActiveJobState(); e.generation += 1; for (const [t, n] of e.activeJobs) { if (n.preserveAcrossGenerationAdvance === true) continue; if (n.generation < e.generation - 1) { e.activeJobs.delete(t); notifyCronJobInactive(n); } } notifyActiveCronJobWaitersIfEmpty(e); notifyGatewayWorkMetricsChanged(); } /** Clears process-global cron active-job state at process-lifecycle boundaries. */ function resetCronActiveJobs() { const e = getCronActiveJobState(); e.generation += 1; for (const t of e.activeJobs.values()) notifyCronJobInactive(t); e.activeJobs.clear(); notifyActiveCronJobWaitersIfEmpty(e); notifyGatewayWorkMetricsChanged(); } //#endregion export { noteActiveCronJobTriggerMutation as C, waitForActiveCronJobs as D, resetCronActiveJobs as E, noteActiveCronJobScheduleMutation as S, requestActiveCronJobCancellation as T, markCronJobActive as _, captureCronJobMessageActionAuthority as a, noteActiveCronJobMessageSourceAuthorityMutation as b, captureCronJobStandingGrantAuthority as c, hasActiveCronJobsForAgent as d, isCronActiveJobMarkerCurrent as f, listActiveCronJobIds as g, isCronSelfRemovalCurrent as h, captureActiveCronJobAgentDeletion as i, clearCronJobActive as l, isCronReplyOperationWaitingForIdle as m, bindCronJobAdmittedRun as n, captureCronJobMessageSourceAuthority as o, isCronJobActive as p, bindCronSelfRemovalCommitGuard as r, captureCronJobSourceAuthority as s, advanceCronActiveJobGeneration as t, getActiveCronJobCount as u, markCronJobWaitingForIdle as v, onCronJobInactive as w, noteActiveCronJobRemoval as x, noteActiveCronJobMessageActionAuthorityMutation as y };