@tidegap/core 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/channels/commands.d.ts +137 -0
  5. package/dist/channels/commands.js +377 -0
  6. package/dist/channels/delivery-codes.d.ts +9 -0
  7. package/dist/channels/delivery-codes.js +53 -0
  8. package/dist/channels/digest.d.ts +102 -0
  9. package/dist/channels/digest.js +146 -0
  10. package/dist/channels/format.d.ts +138 -0
  11. package/dist/channels/format.js +425 -0
  12. package/dist/channels/index.d.ts +15 -0
  13. package/dist/channels/index.js +15 -0
  14. package/dist/channels/kinds/command.d.ts +13 -0
  15. package/dist/channels/kinds/command.js +65 -0
  16. package/dist/channels/kinds/discord.d.ts +16 -0
  17. package/dist/channels/kinds/discord.js +67 -0
  18. package/dist/channels/kinds/email.d.ts +20 -0
  19. package/dist/channels/kinds/email.js +162 -0
  20. package/dist/channels/kinds/index.d.ts +8 -0
  21. package/dist/channels/kinds/index.js +17 -0
  22. package/dist/channels/kinds/ntfy.d.ts +25 -0
  23. package/dist/channels/kinds/ntfy.js +163 -0
  24. package/dist/channels/kinds/pushover.d.ts +11 -0
  25. package/dist/channels/kinds/pushover.js +77 -0
  26. package/dist/channels/kinds/shared.d.ts +25 -0
  27. package/dist/channels/kinds/shared.js +39 -0
  28. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  29. package/dist/channels/kinds/shortcuts.js +45 -0
  30. package/dist/channels/kinds/slack.d.ts +8 -0
  31. package/dist/channels/kinds/slack.js +57 -0
  32. package/dist/channels/kinds/telegram.d.ts +4 -0
  33. package/dist/channels/kinds/telegram.js +26 -0
  34. package/dist/channels/kinds/webhook.d.ts +30 -0
  35. package/dist/channels/kinds/webhook.js +177 -0
  36. package/dist/channels/payload.d.ts +36 -0
  37. package/dist/channels/payload.js +61 -0
  38. package/dist/channels/plan.d.ts +24 -0
  39. package/dist/channels/plan.js +66 -0
  40. package/dist/channels/registry.d.ts +191 -0
  41. package/dist/channels/registry.js +125 -0
  42. package/dist/channels/telegram.d.ts +110 -0
  43. package/dist/channels/telegram.js +168 -0
  44. package/dist/channels/types.d.ts +107 -0
  45. package/dist/channels/types.js +26 -0
  46. package/dist/claude-tools.d.ts +29 -0
  47. package/dist/claude-tools.js +49 -0
  48. package/dist/data/tables.generated.d.ts +6 -0
  49. package/dist/data/tables.generated.js +37 -0
  50. package/dist/energy.d.ts +84 -0
  51. package/dist/energy.js +138 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +171 -0
  55. package/dist/handoff.js +482 -0
  56. package/dist/history.d.ts +17 -0
  57. package/dist/history.js +14 -1
  58. package/dist/index.d.ts +49 -15
  59. package/dist/index.js +36 -8
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +183 -0
  63. package/dist/jobs.js +917 -0
  64. package/dist/notify.d.ts +11 -0
  65. package/dist/notify.js +19 -4
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +14 -8
  69. package/dist/providers/base.d.ts +145 -2
  70. package/dist/providers/base.js +41 -1
  71. package/dist/providers/budget.d.ts +25 -0
  72. package/dist/providers/budget.js +57 -0
  73. package/dist/providers/defaults.js +4 -0
  74. package/dist/providers/defer.d.ts +16 -0
  75. package/dist/providers/defer.js +31 -0
  76. package/dist/providers/gemini.d.ts +4 -0
  77. package/dist/providers/gemini.js +34 -24
  78. package/dist/providers/http.d.ts +40 -0
  79. package/dist/providers/http.js +82 -0
  80. package/dist/providers/index.d.ts +2 -2
  81. package/dist/providers/index.js +1 -1
  82. package/dist/providers/ollama.d.ts +4 -0
  83. package/dist/providers/ollama.js +32 -25
  84. package/dist/providers/openai.js +11 -9
  85. package/dist/providers/timeout.d.ts +36 -0
  86. package/dist/providers/timeout.js +71 -0
  87. package/dist/quota.d.ts +7 -2
  88. package/dist/quota.js +12 -27
  89. package/dist/readiness.d.ts +205 -0
  90. package/dist/readiness.js +326 -0
  91. package/dist/redact.d.ts +42 -0
  92. package/dist/redact.js +110 -0
  93. package/dist/region-host.d.ts +30 -0
  94. package/dist/region-host.js +69 -0
  95. package/dist/region.d.ts +102 -20
  96. package/dist/region.js +175 -23
  97. package/dist/run-limits.d.ts +268 -0
  98. package/dist/run-limits.js +572 -0
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +118 -0
  102. package/dist/schedule-job.js +243 -0
  103. package/dist/scheduler.d.ts +391 -18
  104. package/dist/scheduler.js +1341 -177
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +183 -5
  108. package/dist/storage/sqlite.js +720 -19
  109. package/dist/task-events.d.ts +117 -0
  110. package/dist/task-events.js +345 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +390 -65
  113. package/dist/types.d.ts +267 -3
  114. package/dist/types.js +6 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +13 -5
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
package/dist/jobs.js ADDED
@@ -0,0 +1,917 @@
1
+ /**
2
+ * Floating recurring jobs: the job store actions and the job sweep.
3
+ *
4
+ * A job ("at least once a day, check my mail") keeps exactly one live
5
+ * occurrence in the ledger: an ordinary provider-call task with `job_id`
6
+ * set, `repeat = none` and no series. The id is derived, `<job_id>~<seq>`
7
+ * (a retry is `<job_id>~<seq>r`), and inserted once (`insertIfAbsent`).
8
+ *
9
+ * {@link sweepJobs} owns every transition the daemon makes (KTD2). It runs
10
+ * inside `prepareTick`, so every ticker gets it. For each job it reads the
11
+ * tracked occurrence and:
12
+ *
13
+ * - live occurrence: nothing (R17), except a `running` one whose tick is
14
+ * gone or whose dispatch is older than its time limits allow, which
15
+ * fails as interrupted (a Batch row with a batch id goes back to
16
+ * `submitted` instead);
17
+ * - finished occurrence: records the outcome (KTD9: ok, a failure with
18
+ * the retries of the job's retry policy per slot and auto-pause after
19
+ * three failed slots, or a skip), then materializes the next
20
+ * occurrence;
21
+ * - no occurrence on an active job: materializes one.
22
+ *
23
+ * Every job write is a compare-and-set on `revision`. Pause, edit and
24
+ * remove write the job row first, then cancel the tracked occurrence; a
25
+ * sweep whose job write misses leaves its insert to the next pass, which
26
+ * adopts it on an active job and cancels it otherwise (the stop-flag-first
27
+ * rule). The sweep never throws.
28
+ */
29
+ import { randomBytes } from "node:crypto";
30
+ import { DEFAULT_MODEL_BY_PROVIDER } from "./providers/defaults.js";
31
+ import { BATCH_SUBMIT_INTERRUPTED_ERROR, deriveTitle } from "./history.js";
32
+ import { isCalendarAnchored, JobScheduleError, nextOccurrence, validateJobSchedule } from "./job-cadence.js";
33
+ import { sleptBetween } from "./readiness.js";
34
+ import { capValueError, classifyFailure, FAILURE_CLASSES, isRetryableFailure, isRunLimitCap, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsFromDetails, versionedCaps, } from "./run-limits.js";
35
+ import { canonicalize } from "./sign.js";
36
+ import { systemTimeZone } from "./zone-time.js";
37
+ import { DEFAULT_JOB_CAPS, } from "./types.js";
38
+ /** Why a job action was refused; `code` maps to an HTTP status in the hosts. */
39
+ export class JobActionError extends Error {
40
+ code;
41
+ reason;
42
+ constructor(message,
43
+ /** `invalid` = bad input (400), `not_found` (404), `conflict` = the state forbids it (409). */
44
+ code = "conflict",
45
+ /**
46
+ * A finer cause for a host that answers it: `stale_revision` = the caller
47
+ * holds an older revision than the stored job ({@link updateJob}).
48
+ */
49
+ reason) {
50
+ super(message);
51
+ this.code = code;
52
+ this.reason = reason;
53
+ this.name = "JobActionError";
54
+ }
55
+ }
56
+ /** Every caps key a caller may set. */
57
+ export const JOB_CAPS_KEYS = new Set([
58
+ "commandTimeoutMs",
59
+ "llmTimeoutMs",
60
+ "retries",
61
+ "retryDelayMs",
62
+ ...Object.keys(DEFAULT_JOB_CAPS),
63
+ ]);
64
+ /** Providers a prompt or summarize step may use (`command` is the shell step itself). */
65
+ const LLM_PROVIDERS = new Set(["anthropic", "openai", "gemini", "ollama", "claude-code"]);
66
+ const TOOLS = {
67
+ none: [],
68
+ files: ["Read", "Grep", "Glob"],
69
+ web: ["WebSearch", "WebFetch"],
70
+ };
71
+ const NOTIFY = new Set(["every_run", "failures", "summary"]);
72
+ const ORIGIN_HOSTS = new Set(["page", "cli", "mcp", "openclaw"]);
73
+ const TASK_ORIGIN_HOSTS = new Set(["cli", "mcp", "openclaw"]);
74
+ /** A job secret name: what the command sees as an environment variable. */
75
+ export const JOB_SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
76
+ const LIVE_STATUSES = ["queued", "scheduled", "running", "submitted"];
77
+ const PENDING_STATUSES = ["queued", "scheduled"];
78
+ const LIVE = new Set(LIVE_STATUSES);
79
+ const PENDING = new Set(PENDING_STATUSES);
80
+ /** Cancel reasons a job action writes; any other cancel of an occurrence is a skip. */
81
+ const ACTION_CANCEL_REASONS = new Set(["paused", "edited", "removed", "duplicate"]);
82
+ const MINUTE_MS = 60_000;
83
+ /** Failed slots in a row that pause a job. */
84
+ export const JOB_AUTO_PAUSE_FAILURES = 3;
85
+ /** How `pauseReason` starts when the third failed slot paused the job: `auto: <first error line>`. */
86
+ export const JOB_AUTO_PAUSE_PREFIX = "auto: ";
87
+ /** The error line of an auto-pause reason, or undefined when the job was not paused by its failures. */
88
+ export function jobAutoPauseReason(pauseReason) {
89
+ return pauseReason?.startsWith(JOB_AUTO_PAUSE_PREFIX) ? pauseReason.slice(JOB_AUTO_PAUSE_PREFIX.length).trim() : undefined;
90
+ }
91
+ /** Grace on top of the caps before a running occurrence counts as interrupted. */
92
+ const INTERRUPT_GRACE_MS = 5 * MINUTE_MS;
93
+ export const JOB_INTERRUPTED_ERROR = "interrupted: the tick stopped during the run";
94
+ // The Batch submit marker lives in history.ts (`taskActions` reads it), so history.ts imports nothing from this module.
95
+ export { BATCH_SUBMIT_INTERRUPTED_ERROR };
96
+ const CORRUPT = "corrupt template";
97
+ function ledgerOf(scheduler) {
98
+ const store = scheduler.ledger();
99
+ if (!store)
100
+ throw new JobActionError("jobs need a ledger (a scheduler with dbPath)", "invalid");
101
+ return store;
102
+ }
103
+ function nonEmpty(v, what) {
104
+ if (typeof v !== "string" || v.trim() === "")
105
+ throw new JobActionError(`${what} must be a non-empty string`, "invalid");
106
+ return v;
107
+ }
108
+ function optionalString(v, what) {
109
+ if (v === undefined)
110
+ return undefined;
111
+ return nonEmpty(v, what);
112
+ }
113
+ function llmProvider(v, what) {
114
+ if (typeof v !== "string" || !LLM_PROVIDERS.has(v)) {
115
+ throw new JobActionError(`${what} must be one of ${[...LLM_PROVIDERS].join(", ")}`, "invalid");
116
+ }
117
+ return v;
118
+ }
119
+ function validTemplate(t) {
120
+ if (t?.runner === "prompt") {
121
+ const tools = t.tools ?? "none";
122
+ if (!(tools in TOOLS))
123
+ throw new JobActionError("tools must be none, files or web", "invalid");
124
+ return {
125
+ runner: "prompt",
126
+ prompt: nonEmpty(t.prompt, "prompt"),
127
+ provider: llmProvider(t.provider, "provider"),
128
+ model: optionalString(t.model, "model"),
129
+ cwd: optionalString(t.cwd, "cwd"),
130
+ tools,
131
+ };
132
+ }
133
+ if (t?.runner === "command") {
134
+ const secrets = Array.isArray(t.secrets) ? t.secrets : [];
135
+ for (const name of secrets) {
136
+ if (typeof name !== "string" || !JOB_SECRET_NAME.test(name)) {
137
+ throw new JobActionError(`secret name ${JSON.stringify(name)} must match ${JOB_SECRET_NAME.source}`, "invalid");
138
+ }
139
+ }
140
+ const s = t.summarize;
141
+ return {
142
+ runner: "command",
143
+ command: nonEmpty(t.command, "command"),
144
+ cwd: optionalString(t.cwd, "cwd"),
145
+ secrets: [...new Set(secrets)],
146
+ summarize: s
147
+ ? { prompt: nonEmpty(s.prompt, "summarize prompt"), provider: llmProvider(s.provider, "summarize provider"), model: optionalString(s.model, "summarize model") }
148
+ : undefined,
149
+ };
150
+ }
151
+ throw new JobActionError('runner must be "prompt" or "command"', "invalid");
152
+ }
153
+ /**
154
+ * The caps to store: `base` with `patch` applied. The result holds only the
155
+ * time limits a caller set (old stored defaults dropped) and `capsVersion: 2`.
156
+ */
157
+ function validCaps(base, patch) {
158
+ const out = { ...DEFAULT_JOB_CAPS, ...versionedCaps(base) };
159
+ for (const [key, value] of Object.entries(patch ?? {})) {
160
+ if (!JOB_CAPS_KEYS.has(key))
161
+ throw new JobActionError(`unknown cap "${key}"`, "invalid");
162
+ if (value === undefined)
163
+ continue;
164
+ if (value === null) {
165
+ if (isRunLimitCap(key))
166
+ delete out[key];
167
+ else
168
+ out[key] = DEFAULT_JOB_CAPS[key];
169
+ continue;
170
+ }
171
+ const error = capValueError(key, value);
172
+ if (error)
173
+ throw new JobActionError(error, "invalid");
174
+ out[key] = value;
175
+ }
176
+ return out;
177
+ }
178
+ function validSchedule(s) {
179
+ try {
180
+ return validateJobSchedule(s);
181
+ }
182
+ catch (err) {
183
+ if (err instanceof JobScheduleError)
184
+ throw new JobActionError(err.message, "invalid");
185
+ throw err;
186
+ }
187
+ }
188
+ function validTitle(title) {
189
+ const text = nonEmpty(title, "title");
190
+ return deriveTitle(text) ?? text;
191
+ }
192
+ function validNotify(v) {
193
+ if (typeof v !== "string" || !NOTIFY.has(v))
194
+ throw new JobActionError("notify must be every_run, failures or summary", "invalid");
195
+ return v;
196
+ }
197
+ function newJobId(store) {
198
+ for (;;) {
199
+ const id = `job-${randomBytes(4).toString("hex")}`;
200
+ if (!store.getJob(id))
201
+ return id;
202
+ }
203
+ }
204
+ /** The occurrence body a job's template runs (Data shapes in the plan). */
205
+ function occurrenceBody(job) {
206
+ const t = job.template;
207
+ if (t.runner === "prompt") {
208
+ return {
209
+ type: "provider_call",
210
+ provider: t.provider,
211
+ model: t.model ?? DEFAULT_MODEL_BY_PROVIDER[t.provider],
212
+ prompt: t.prompt,
213
+ tools: TOOLS[t.tools],
214
+ caps: job.caps,
215
+ };
216
+ }
217
+ return {
218
+ type: "provider_call",
219
+ provider: "command",
220
+ model: t.summarize?.model ?? (t.summarize ? DEFAULT_MODEL_BY_PROVIDER[t.summarize.provider] : "none"),
221
+ prompt: t.summarize?.prompt ?? "",
222
+ command: { run: t.command, cwd: t.cwd, secrets: t.secrets },
223
+ summarize: t.summarize ? { provider: t.summarize.provider, model: t.summarize.model } : undefined,
224
+ caps: job.caps,
225
+ };
226
+ }
227
+ /**
228
+ * The time limits a run of `job` gets if it starts now, with their sources:
229
+ * the scheduler's settings reader, or without one the settings file.
230
+ */
231
+ export function jobRunLimits(job, scheduler) {
232
+ const body = occurrenceBody(job);
233
+ return scheduler ? scheduler.runLimitsFor(body) : resolveTaskRunLimits(body, loadRunLimitSettings());
234
+ }
235
+ function scheduleOf(job) {
236
+ return { cadence: job.cadence, window: job.window, timeZone: job.timeZone };
237
+ }
238
+ /** Sequence number of an occurrence id `<job>~<seq>`, or of a retry `<job>~<seq>r`, `<job>~<seq>r2`, ... */
239
+ function seqOf(taskId) {
240
+ const m = /~(\d+)(?:r\d*)?$/.exec(taskId);
241
+ return m ? Number(m[1]) : 0;
242
+ }
243
+ /** Which retry of its slot an occurrence id is: 0 for `<job>~<seq>`, 1 for `...r`, k for `...rk`. */
244
+ function retryOrdinal(taskId) {
245
+ const m = /~\d+r(\d*)$/.exec(taskId);
246
+ if (!m)
247
+ return 0;
248
+ return m[1] ? Number(m[1]) : 1;
249
+ }
250
+ /** The id of retry `k` of the slot of `taskId`: `<job>~<seq>r`, then `r2`, `r3`, ... */
251
+ function retryIdOf(taskId, k) {
252
+ const base = taskId.replace(/r\d*$/, "");
253
+ return k === 1 ? `${base}r` : `${base}r${k}`;
254
+ }
255
+ function firstLine(text, max = 200) {
256
+ return (text ?? "").split("\n")[0].slice(0, max);
257
+ }
258
+ /** The occurrence's last `dispatched` event. */
259
+ function dispatchedEvent(scheduler, taskId) {
260
+ const events = scheduler.listTaskEvents(taskId);
261
+ for (let i = events.length - 1; i >= 0; i--)
262
+ if (events[i].kind === "dispatched")
263
+ return events[i];
264
+ return undefined;
265
+ }
266
+ /**
267
+ * The failure class of a failed occurrence: the one its `failed` event
268
+ * records, or, for a row from before classes were recorded, the one its
269
+ * event's steps and its error give (a failure after the command step is
270
+ * `after_command`, the Batch submit marker `batch_submit_interrupted`,
271
+ * anything else `transient`, as those rows always got their one retry).
272
+ */
273
+ function failureClassOf(scheduler, row) {
274
+ const events = scheduler.listTaskEvents(row.taskId);
275
+ let details = {};
276
+ for (let i = events.length - 1; i >= 0; i--) {
277
+ if (events[i].kind !== "failed")
278
+ continue;
279
+ details = events[i].details ?? {};
280
+ break;
281
+ }
282
+ const recorded = details.failure_class;
283
+ if (typeof recorded === "string" && FAILURE_CLASSES.includes(recorded))
284
+ return recorded;
285
+ const steps = Array.isArray(details.steps) ? details.steps.filter((s) => typeof s === "string") : undefined;
286
+ return classifyFailure({
287
+ ...(steps?.includes("prompt") ? { steps } : {}),
288
+ ...(row.error === BATCH_SUBMIT_INTERRUPTED_ERROR ? { interrupted: "batch_submit" } : {}),
289
+ });
290
+ }
291
+ /**
292
+ * When the next retry of a failed occurrence's slot starts, or undefined
293
+ * for none: its class must allow a retry, the slot must have retries left
294
+ * by the job's retry policy (its own value, the settings, the default), and
295
+ * retry k starts the retry delay times 2^(k−1) after now, no later than the
296
+ * slot's deadline.
297
+ */
298
+ function jobRetryAt(scheduler, job, failed, nowMs) {
299
+ if (!isRetryableFailure(failureClassOf(scheduler, failed)))
300
+ return undefined;
301
+ const deadline = Date.parse(failed.deadline ?? "");
302
+ if (!Number.isFinite(deadline))
303
+ return undefined;
304
+ const plan = planRetry({
305
+ attempt: job.retryUsed + 1,
306
+ ...retryPolicyOf(jobRunLimits(job, scheduler)),
307
+ failedAt: nowMs,
308
+ deadline,
309
+ });
310
+ return "retryAt" in plan ? plan.retryAt : undefined;
311
+ }
312
+ /** The sleep counter a `dispatched` event stored (`details.sleep`), or null. */
313
+ function sleepAt(raw) {
314
+ const r = raw;
315
+ return r && Number.isFinite(r.boot_at) && Number.isFinite(r.slept_ms) ? { boot_at: r.boot_at, slept_ms: r.slept_ms } : null;
316
+ }
317
+ /** Reason on the occurrence's `cancelled` event (`paused`, `edited`, ... or none = a skip). */
318
+ function cancelReason(scheduler, taskId) {
319
+ const events = scheduler.listTaskEvents(taskId);
320
+ for (let i = events.length - 1; i >= 0; i--) {
321
+ if (events[i].kind === "cancelled") {
322
+ const reason = events[i].details.reason;
323
+ return typeof reason === "string" ? reason : undefined;
324
+ }
325
+ }
326
+ return undefined;
327
+ }
328
+ /**
329
+ * Cancel a pending occurrence with a job reason. Pending only: a row a tick
330
+ * claimed meanwhile runs to its end. Returns true when this call cancelled it.
331
+ */
332
+ function cancelOccurrence(scheduler, taskId, jobId, reason, actor) {
333
+ const row = scheduler.cancelTask(taskId, { actor, details: { job_id: jobId, reason }, expectedStatus: PENDING_STATUSES });
334
+ return row.status === "cancelled";
335
+ }
336
+ /** The run fields of an occurrence body: what an edit of the template changes (KTD2). */
337
+ function runFields(spec) {
338
+ const { provider, model, prompt, tools, caps, command, summarize } = spec;
339
+ return canonicalize({ provider, model, prompt, tools: tools ?? [], caps, command, summarize });
340
+ }
341
+ /** True when a stored occurrence runs what the job's current template gives. */
342
+ function runsCurrentTemplate(row, job) {
343
+ try {
344
+ return runFields(JSON.parse(row.bodyJson ?? "null")) === runFields(occurrenceBody(job));
345
+ }
346
+ catch {
347
+ return false;
348
+ }
349
+ }
350
+ function emptyResult() {
351
+ return { messages: [], materialized: [], retried: [], autoPaused: [], interrupted: [] };
352
+ }
353
+ /**
354
+ * One job's step of the sweep: record the tracked occurrence's outcome and
355
+ * keep one live occurrence. Retries a few times when another writer moved
356
+ * the job row meanwhile.
357
+ */
358
+ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
359
+ const store = ledgerOf(scheduler);
360
+ const nowMs = now.getTime();
361
+ /** Rows this call inserted: cleaned up when every job write misses. */
362
+ const inserted = [];
363
+ for (let attempt = 0; attempt < 3; attempt++) {
364
+ const job = store.getJob(jobId);
365
+ if (!job || job.pauseReason === CORRUPT)
366
+ return;
367
+ const tracked = pendingRow(store, job);
368
+ const orphans = store
369
+ .list({ jobId, status: LIVE_STATUSES })
370
+ .filter((t) => t.taskId !== job.pendingTaskId);
371
+ // An inactive job keeps no pending occurrence (stop-flag-first rule).
372
+ if (job.status !== "active") {
373
+ let cancelled = false;
374
+ for (const t of [...orphans, ...(tracked ? [tracked] : [])]) {
375
+ if (!PENDING.has(t.status))
376
+ continue;
377
+ cancelOccurrence(scheduler, t.taskId, jobId, job.status === "removed" ? "removed" : "paused", opts.actor);
378
+ cancelled = true;
379
+ }
380
+ if (cancelled)
381
+ continue;
382
+ }
383
+ if (tracked && LIVE.has(tracked.status)) {
384
+ // Exactly one live occurrence: a second pending one is a duplicate.
385
+ for (const t of orphans)
386
+ if (PENDING.has(t.status))
387
+ cancelOccurrence(scheduler, t.taskId, jobId, "duplicate");
388
+ if (tracked.status === "running" && opts.interruptCheck) {
389
+ const outcome = interrupted(scheduler, store, job, tracked, nowMs, opts.interruptCheck.sleepNow);
390
+ if (outcome === "failed") {
391
+ result.interrupted.push(tracked.taskId);
392
+ result.messages.push(`job ${jobId}: ${tracked.taskId} ${JOB_INTERRUPTED_ERROR}`);
393
+ continue;
394
+ }
395
+ if (outcome === "submitted") {
396
+ result.messages.push(`job ${jobId}: ${tracked.taskId} back to submitted: the tick stopped while it polled the batch`);
397
+ }
398
+ }
399
+ return;
400
+ }
401
+ if (!tracked && job.status !== "active")
402
+ return;
403
+ // The tracked occurrence ended (or there is none): record the outcome.
404
+ const next = { ...job, updatedAt: now.toISOString() };
405
+ let successor = job.status === "active" ? "next" : "none";
406
+ let skippedDeadline;
407
+ let retryAt;
408
+ if (tracked) {
409
+ next.pendingTaskId = undefined;
410
+ next.lastTaskId = tracked.taskId;
411
+ next.lastRunStartedAt = dispatchedEvent(scheduler, tracked.taskId)?.at ?? job.lastRunStartedAt;
412
+ if (tracked.status === "completed") {
413
+ next.lastOutcome = "ok";
414
+ next.consecutiveFailures = 0;
415
+ }
416
+ else if (tracked.status === "failed") {
417
+ next.lastOutcome = "failed";
418
+ // A run stopped during its Batch submit may have a batch at the
419
+ // provider, and a failed LLM step ran its command already: neither
420
+ // class retries, nor a permanent failure.
421
+ retryAt = successor === "next" ? jobRetryAt(scheduler, job, tracked, nowMs) : undefined;
422
+ if (retryAt !== undefined) {
423
+ successor = "retry";
424
+ }
425
+ else {
426
+ next.consecutiveFailures = job.consecutiveFailures + 1;
427
+ if (successor === "next" && next.consecutiveFailures >= JOB_AUTO_PAUSE_FAILURES) {
428
+ successor = "none";
429
+ next.status = "paused";
430
+ next.pauseReason = `${JOB_AUTO_PAUSE_PREFIX}${firstLine(tracked.error) || "failed"}`;
431
+ next.pausedAt = now.toISOString();
432
+ next.pauseNotifiedAt = undefined;
433
+ result.autoPaused.push(jobId);
434
+ }
435
+ }
436
+ }
437
+ else if (!ACTION_CANCEL_REASONS.has(cancelReason(scheduler, tracked.taskId) ?? "")) {
438
+ // A plain cancel of an occurrence is a skip: the counter stays.
439
+ next.lastOutcome = "skipped";
440
+ skippedDeadline = tracked.deadline;
441
+ }
442
+ }
443
+ // A live row nobody tracks (a crash between an insert and its job
444
+ // write): adopt it instead of inserting a second one (KTD4). A pending
445
+ // one made from a template an edit has since replaced never runs: it is
446
+ // cancelled as edited and a fresh one is made (follow-ups KTD2). The
447
+ // cancelled row keeps its id, so the fresh one takes a later sequence.
448
+ const adoptable = [];
449
+ const edited = [];
450
+ if (successor !== "none") {
451
+ for (const t of orphans) {
452
+ if (PENDING.has(t.status) && !runsCurrentTemplate(t, next) && cancelOccurrence(scheduler, t.taskId, jobId, "edited", opts.actor)) {
453
+ edited.push(t.taskId);
454
+ }
455
+ else {
456
+ adoptable.push(t);
457
+ }
458
+ }
459
+ }
460
+ const freeSeq = Math.max(job.nextSeq, ...edited.map((id) => seqOf(id) + 1));
461
+ const retryId = tracked && successor === "retry" ? retryIdOf(tracked.taskId, job.retryUsed + 1) : undefined;
462
+ // The edit replaced the template the retry would run: make a regular
463
+ // occurrence of the new template instead; the failure is not counted.
464
+ if (retryId && edited.includes(retryId))
465
+ successor = "next";
466
+ const adopt = adoptable[adoptable.length - 1];
467
+ let taskId;
468
+ if (adopt) {
469
+ taskId = adopt.taskId;
470
+ next.nextSeq = Math.max(freeSeq, seqOf(adopt.taskId) + 1);
471
+ next.retryUsed = retryOrdinal(adopt.taskId);
472
+ for (const t of adoptable) {
473
+ if (t !== adopt && PENDING.has(t.status))
474
+ cancelOccurrence(scheduler, t.taskId, jobId, "duplicate");
475
+ }
476
+ }
477
+ else if (successor === "retry" && retryId) {
478
+ taskId = retryId;
479
+ next.retryUsed = job.retryUsed + 1;
480
+ if (await materialize(scheduler, next, taskId, retryAt, Date.parse(tracked.deadline), "retry")) {
481
+ inserted.push(taskId);
482
+ result.retried.push(taskId);
483
+ result.materialized.push(taskId);
484
+ }
485
+ }
486
+ else if (successor === "next") {
487
+ const occ = firstOccurrence(next, tracked, nowMs, skippedDeadline, opts);
488
+ taskId = `${jobId}~${freeSeq}`;
489
+ next.nextSeq = freeSeq + 1;
490
+ next.retryUsed = 0;
491
+ if (await materialize(scheduler, next, taskId, occ.earliest, occ.deadline, occ.anchor)) {
492
+ inserted.push(taskId);
493
+ result.materialized.push(taskId);
494
+ }
495
+ }
496
+ next.pendingTaskId = taskId;
497
+ // A miss: another writer moved the job meanwhile. The next pass adopts
498
+ // the insert on an active job, or cancels it on an inactive one.
499
+ if (store.updateJobIf(next, job.revision))
500
+ return;
501
+ }
502
+ result.messages.push(`job ${jobId}: the job row kept changing; left for the next sweep`);
503
+ // No pass is left to cancel this call's insert on a job that stopped
504
+ // meanwhile (stop-flag-first rule), so cancel it here.
505
+ const latest = store.getJob(jobId);
506
+ if (latest?.status === "active")
507
+ return;
508
+ for (const id of inserted)
509
+ cancelOccurrence(scheduler, id, jobId, latest?.status === "paused" ? "paused" : "removed", opts.actor);
510
+ }
511
+ /** `[earliest, deadline]` of the next regular occurrence, in ms. */
512
+ function firstOccurrence(job, tracked, nowMs, skippedDeadline, opts) {
513
+ if (opts.firstDeadline !== undefined && !tracked) {
514
+ return { earliest: nowMs, deadline: opts.firstDeadline, anchor: "deadline" };
515
+ }
516
+ const schedule = scheduleOf(job);
517
+ const calendar = isCalendarAnchored(schedule);
518
+ // Resume counts from now only for a run-anchored job. A calendar job
519
+ // keeps its last run, so a slot it already ran in is not run again; no
520
+ // backfill follows anyway, as a slot must end after now.
521
+ const fromNow = opts.fromNow === true && !calendar;
522
+ let lastRunStart = fromNow ? undefined : job.lastRunStartedAt;
523
+ // A calendar slot is used once, run or not: an occurrence that finished
524
+ // without running (failed before dispatch) still moves on to the next
525
+ // slot. A job action's cancel (edit, pause) used nothing. Run now clears
526
+ // `notBefore`; the last minute before the deadline then marks the slot.
527
+ const used = tracked?.status === "completed" || tracked?.status === "failed";
528
+ const slotMark = tracked?.notBefore ?? (tracked?.deadline ? new Date(Date.parse(tracked.deadline) - MINUTE_MS).toISOString() : undefined);
529
+ if (calendar && used && slotMark && !fromNow) {
530
+ if (!lastRunStart || Date.parse(slotMark) > Date.parse(lastRunStart))
531
+ lastRunStart = slotMark;
532
+ }
533
+ const occ = nextOccurrence(schedule, { now: nowMs, lastRunStart, skippedDeadline });
534
+ return { earliest: Date.parse(occ.earliest), deadline: Date.parse(occ.deadline), anchor: occ.anchor };
535
+ }
536
+ async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
537
+ const t = job.template;
538
+ return scheduler.materializeOccurrence({
539
+ taskId,
540
+ jobId: job.jobId,
541
+ earliest: new Date(earliest).toISOString(),
542
+ deadline: new Date(deadline).toISOString(),
543
+ title: job.title,
544
+ bodyJson: JSON.stringify(occurrenceBody(job)),
545
+ originHost: job.originHost && TASK_ORIGIN_HOSTS.has(job.originHost) ? job.originHost : undefined,
546
+ originCwd: t.cwd,
547
+ }, { job_id: job.jobId, seq: seqOf(taskId), anchor });
548
+ }
549
+ /**
550
+ * How long a run may last before the time rule frees it: its time limits
551
+ * plus a grace period, so the limit is generous. The limits are the ones
552
+ * its `dispatched` event recorded; a run dispatched before they were
553
+ * recorded gets the ones it would get now. Undefined when a limit is
554
+ * `none`: such a run is freed only by the tick lock rule. A row with no
555
+ * usable `dispatched` event (a Batch row) counts from its deadline, and no
556
+ * LLM time limit applies to a Batch run, so there a `none` limit adds
557
+ * nothing instead.
558
+ */
559
+ function runTimeAllowance(scheduler, row, dispatched) {
560
+ let limits = runLimitsFromDetails(dispatched?.details);
561
+ if (!limits) {
562
+ let spec;
563
+ try {
564
+ spec = JSON.parse(row.bodyJson ?? "null");
565
+ }
566
+ catch {
567
+ spec = undefined;
568
+ }
569
+ if (!spec || typeof spec.provider !== "string")
570
+ return INTERRUPT_GRACE_MS;
571
+ limits = scheduler.runLimitsFor(spec);
572
+ }
573
+ let total = INTERRUPT_GRACE_MS;
574
+ for (const limit of [limits.command_timeout, limits.llm_timeout]) {
575
+ if (!limit)
576
+ continue;
577
+ if (limit.value === "none") {
578
+ if (dispatched)
579
+ return undefined;
580
+ continue;
581
+ }
582
+ total += limit.value;
583
+ }
584
+ return total;
585
+ }
586
+ /**
587
+ * The time rule of a running occurrence: its dispatch is older than its
588
+ * time limits plus a grace period ({@link runTimeAllowance}). A run with a
589
+ * `none` limit never counts as too old, unless its age counts from the
590
+ * deadline (below).
591
+ *
592
+ * The age counts from the last `dispatched` event. Two `running` rows have
593
+ * no usable one and count from the deadline instead: a Batch row being
594
+ * polled (its event is the submit, hours old) and a row whose tick died
595
+ * between the claim and the event (Batch submit). Neither can run past
596
+ * its deadline legitimately (Batch rows have a deadline over a day ahead).
597
+ */
598
+ function olderThanLimits(scheduler, row, nowMs, sleepNow) {
599
+ const dispatched = row.batchId ? undefined : dispatchedEvent(scheduler, row.taskId);
600
+ const started = Date.parse(dispatched?.at ?? row.deadline ?? "");
601
+ if (!Number.isFinite(started))
602
+ return false;
603
+ const limit = runTimeAllowance(scheduler, row, dispatched);
604
+ if (limit === undefined)
605
+ return false;
606
+ const wallAge = nowMs - started;
607
+ const sleepThen = sleepAt(dispatched?.details.sleep);
608
+ if (sleepThen && !sleepNow) {
609
+ // This host cannot read the sleep counter, but the run's ticker could:
610
+ // the run may have slept. Wait for its deadline plus the limits, so a
611
+ // host that reads the counter decides first, and a dead tick still
612
+ // frees the job at the latest then.
613
+ const deadline = Date.parse(row.deadline ?? "");
614
+ return nowMs - (Number.isFinite(deadline) ? Math.max(deadline, started) : started) > limit;
615
+ }
616
+ // Awake time only: a run the machine slept through is still running.
617
+ const slept = sleptBetween(sleepThen, sleepNow, wallAge);
618
+ return wallAge - slept > limit;
619
+ }
620
+ /**
621
+ * A running occurrence whose tick died. Fail it by compare-and-set from
622
+ * `running`; a completion that lands after this write is dropped. A row with
623
+ * a batch id was being polled: its batch is live at the provider, so it goes
624
+ * back to `submitted` (compare-and-set from `running`) and the next tick
625
+ * polls it again. Returns what this call wrote: "failed", "submitted", or
626
+ * undefined for nothing.
627
+ *
628
+ * Under the tick lock, a run whose dispatch carries tick details follows the
629
+ * tick lock rule ({@link Scheduler.deadTickRun}): it is freed as soon as the
630
+ * tick that ran it is gone, and never while that tick's process runs. Any
631
+ * other run, a run whose tick the host cannot judge included, is freed when
632
+ * it is older than its time limits plus a grace period ({@link olderThanLimits}).
633
+ */
634
+ function interrupted(scheduler, store, job, row, nowMs, sleepNow) {
635
+ const deadTick = scheduler.deadTickRun(row);
636
+ if (deadTick === false)
637
+ return undefined;
638
+ if (deadTick === undefined && !olderThanLimits(scheduler, row, nowMs, sleepNow))
639
+ return undefined;
640
+ if (row.batchId) {
641
+ return store.transitionIf({ ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]) ? "submitted" : undefined;
642
+ }
643
+ const failed = store.transitionIf({ ...row, status: "failed", completedAt: new Date(nowMs).toISOString(), error: JOB_INTERRUPTED_ERROR }, ["running"], undefined,
644
+ // A job run fails for good here; the sweep's next pass makes its slot's retry row by the retry policy.
645
+ { kind: "failed", actor: "system", details: { job_id: job.jobId, reason: "interrupted", attempts: 1, failure_class: "interrupted" } });
646
+ return failed ? "failed" : undefined;
647
+ }
648
+ /**
649
+ * The job sweep (KTD2): for every job, record the outcome of its finished
650
+ * occurrence and keep one live occurrence per active job. Never throws.
651
+ */
652
+ export async function sweepJobs(scheduler, now = new Date(), opts = {}) {
653
+ const result = emptyResult();
654
+ let jobs;
655
+ try {
656
+ const store = scheduler.ledger();
657
+ if (!store)
658
+ return result;
659
+ jobs = store.listJobs().filter((j) => j.status !== "removed" || j.pendingTaskId !== undefined);
660
+ }
661
+ catch (err) {
662
+ result.messages.push(`job sweep: cannot read the ledger: ${errMessage(err)}`);
663
+ return result;
664
+ }
665
+ for (const job of jobs) {
666
+ try {
667
+ await sweepJob(scheduler, job.jobId, now, result, { interruptCheck: { sleepNow: opts.sleepNow } });
668
+ }
669
+ catch (err) {
670
+ result.messages.push(`job sweep: ${job.jobId}: ${errMessage(err)}`);
671
+ }
672
+ }
673
+ for (const id of result.materialized)
674
+ result.messages.push(`materialized job occurrence ${id}`);
675
+ for (const id of result.autoPaused)
676
+ result.messages.push(`paused job ${id} after ${JOB_AUTO_PAUSE_FAILURES} failed runs`);
677
+ return result;
678
+ }
679
+ /** Create a job and its first occurrence. Throws {@link JobActionError} on bad input. */
680
+ export async function createJob(scheduler, input, opts = {}) {
681
+ const store = ledgerOf(scheduler);
682
+ const now = new Date();
683
+ const schedule = validSchedule({ cadence: input.cadence, window: input.window, timeZone: input.timeZone ?? systemTimeZone() });
684
+ let firstDeadline;
685
+ if (input.deadline !== undefined) {
686
+ firstDeadline = new Date(input.deadline).getTime();
687
+ if (!Number.isFinite(firstDeadline) || firstDeadline <= now.getTime()) {
688
+ throw new JobActionError("deadline must be a future instant", "invalid");
689
+ }
690
+ }
691
+ if (input.originHost !== undefined && !ORIGIN_HOSTS.has(input.originHost)) {
692
+ throw new JobActionError("originHost must be page, cli, mcp or openclaw", "invalid");
693
+ }
694
+ const job = {
695
+ jobId: newJobId(store),
696
+ title: validTitle(input.title),
697
+ status: "active",
698
+ cadence: schedule.cadence,
699
+ window: schedule.window,
700
+ timeZone: schedule.timeZone,
701
+ template: validTemplate(input.template),
702
+ caps: validCaps({}, input.caps),
703
+ notify: input.notify === undefined ? "every_run" : validNotify(input.notify),
704
+ originHost: input.originHost,
705
+ originCwd: input.originCwd,
706
+ createdBy: opts.actor,
707
+ createdAt: now.toISOString(),
708
+ updatedAt: now.toISOString(),
709
+ revision: 1,
710
+ nextSeq: 1,
711
+ consecutiveFailures: 0,
712
+ retryUsed: 0,
713
+ };
714
+ store.insertJob(job);
715
+ try {
716
+ await sweepJob(scheduler, job.jobId, now, emptyResult(), { firstDeadline, actor: opts.actor });
717
+ }
718
+ catch (err) {
719
+ // All or nothing (follow-ups KTD3): a create that reports failure
720
+ // leaves no job and no occurrence behind, so a retry makes one job.
721
+ abandonJob(scheduler, store, job.jobId, opts.actor);
722
+ throw err;
723
+ }
724
+ return store.getJob(job.jobId);
725
+ }
726
+ /** Undo a create whose first sweep threw: mark the job removed, cancel its pending rows. Best effort. */
727
+ function abandonJob(scheduler, store, jobId, actor) {
728
+ try {
729
+ writeJob(store, jobId, (job) => ({ ...job, status: "removed", pendingTaskId: undefined }));
730
+ }
731
+ catch {
732
+ // The rows below are still cancelled; a later sweep skips a removed job.
733
+ }
734
+ try {
735
+ for (const t of store.list({ jobId, status: PENDING_STATUSES }))
736
+ cancelOccurrence(scheduler, t.taskId, jobId, "removed", actor);
737
+ }
738
+ catch {
739
+ // Same ledger error as the sweep's: the sweep cancels these rows of a removed job.
740
+ }
741
+ }
742
+ function requireJob(store, jobId) {
743
+ const job = store.getJob(jobId);
744
+ if (!job)
745
+ throw new JobActionError(`job ${JSON.stringify(jobId)} not found`, "not_found");
746
+ return job;
747
+ }
748
+ /** The job's tracked occurrence row, if it has one. */
749
+ function pendingRow(store, job) {
750
+ return job.pendingTaskId ? store.get(job.pendingTaskId) : undefined;
751
+ }
752
+ /** Refuse every action but remove on a removed job or one whose stored template does not parse. */
753
+ function requireEditable(job) {
754
+ if (job.status === "removed")
755
+ throw new JobActionError("job was removed");
756
+ if (job.pauseReason === CORRUPT)
757
+ throw new JobActionError(`job ${job.jobId} has a corrupt template; remove it and create it again`);
758
+ }
759
+ /**
760
+ * Write `change(job)` with a compare-and-set, re-reading once on a miss.
761
+ * `change` throws {@link JobActionError} to refuse.
762
+ */
763
+ function writeJob(store, jobId, change) {
764
+ for (let attempt = 0; attempt < 2; attempt++) {
765
+ const before = requireJob(store, jobId);
766
+ const after = { ...change(before), updatedAt: new Date().toISOString() };
767
+ if (store.updateJobIf(after, before.revision))
768
+ return { before, after };
769
+ }
770
+ throw new JobActionError(`job ${jobId} changed meanwhile; try again`);
771
+ }
772
+ /** Cancel the job's pending occurrence, if it has one, with a job-action reason. */
773
+ function cancelPending(scheduler, store, job, reason, actor) {
774
+ const row = pendingRow(store, job);
775
+ if (row && PENDING.has(row.status))
776
+ cancelOccurrence(scheduler, row.taskId, job.jobId, reason, actor);
777
+ }
778
+ /**
779
+ * Change a job; the pending occurrence is replaced by one on the new rule (a
780
+ * running one keeps its template). With `expectedRevision`, a job another
781
+ * writer changed since is refused with reason `stale_revision`.
782
+ */
783
+ export async function updateJob(scheduler, jobId, patch, opts = {}) {
784
+ const store = ledgerOf(scheduler);
785
+ const { before } = writeJob(store, jobId, (job) => {
786
+ requireEditable(job);
787
+ if (opts.expectedRevision !== undefined && job.revision !== opts.expectedRevision) {
788
+ throw new JobActionError(`job changed meanwhile (revision ${job.revision}); reload it and try again`, "conflict", "stale_revision");
789
+ }
790
+ const schedule = validSchedule({
791
+ cadence: patch.cadence ?? job.cadence,
792
+ window: patch.window === null ? undefined : (patch.window ?? job.window),
793
+ timeZone: patch.timeZone ?? job.timeZone,
794
+ });
795
+ return {
796
+ ...job,
797
+ title: patch.title !== undefined ? validTitle(patch.title) : job.title,
798
+ cadence: schedule.cadence,
799
+ window: schedule.window,
800
+ timeZone: schedule.timeZone,
801
+ template: patch.template !== undefined ? validTemplate(patch.template) : job.template,
802
+ caps: validCaps(job.caps, patch.caps),
803
+ notify: patch.notify !== undefined ? validNotify(patch.notify) : job.notify,
804
+ };
805
+ });
806
+ cancelPending(scheduler, store, before, "edited", opts.actor);
807
+ await sweepJob(scheduler, jobId, new Date(), emptyResult(), { actor: opts.actor });
808
+ return store.getJob(jobId);
809
+ }
810
+ /** Pause an active job; its pending occurrence is cancelled, a running one finishes with no successor. */
811
+ export async function pauseJob(scheduler, jobId, opts = {}) {
812
+ const store = ledgerOf(scheduler);
813
+ const now = new Date();
814
+ const { after } = writeJob(store, jobId, (job) => {
815
+ requireEditable(job);
816
+ if (job.status === "paused")
817
+ throw new JobActionError("job is already paused");
818
+ return { ...job, status: "paused", pauseReason: "manual", pausedAt: now.toISOString(), pauseNotifiedAt: undefined };
819
+ });
820
+ cancelPending(scheduler, store, after, "paused", opts.actor);
821
+ await sweepJob(scheduler, jobId, now, emptyResult(), { actor: opts.actor });
822
+ return store.getJob(jobId);
823
+ }
824
+ /** Resume a paused job: counter reset, one occurrence from now, no backfill (R8). */
825
+ export async function resumeJob(scheduler, jobId, opts = {}) {
826
+ const store = ledgerOf(scheduler);
827
+ writeJob(store, jobId, (job) => {
828
+ requireEditable(job);
829
+ if (job.status === "active")
830
+ throw new JobActionError("job is not paused");
831
+ return {
832
+ ...job,
833
+ status: "active",
834
+ consecutiveFailures: 0,
835
+ retryUsed: 0,
836
+ pauseReason: undefined,
837
+ pausedAt: undefined,
838
+ pauseNotifiedAt: undefined,
839
+ };
840
+ });
841
+ await sweepJob(scheduler, jobId, new Date(), emptyResult(), { fromNow: true, actor: opts.actor });
842
+ return store.getJob(jobId);
843
+ }
844
+ /**
845
+ * Run a job at the next tick (AS10): its pending occurrence is expedited
846
+ * (no second row). Refused while an occurrence runs or the job is paused.
847
+ * Returns the expedited occurrence.
848
+ */
849
+ export async function runJobNow(scheduler, jobId, opts = {}) {
850
+ const store = ledgerOf(scheduler);
851
+ let job = requireJob(store, jobId);
852
+ requireEditable(job);
853
+ refuseIfPaused(job);
854
+ let row = pendingRow(store, job);
855
+ if (!row || !LIVE.has(row.status)) {
856
+ await sweepJob(scheduler, jobId, new Date(), emptyResult(), { actor: opts.actor });
857
+ job = requireJob(store, jobId);
858
+ // The sweep may have just auto-paused the job (its third failed slot).
859
+ refuseIfPaused(job);
860
+ row = pendingRow(store, job);
861
+ }
862
+ if (row && (row.status === "running" || row.status === "submitted")) {
863
+ throw new JobActionError("an occurrence is already running");
864
+ }
865
+ if (!row || !PENDING.has(row.status))
866
+ throw new JobActionError(`job ${jobId} has no occurrence to run`);
867
+ return scheduler.runNow(row.taskId, { actor: opts.actor });
868
+ }
869
+ /** Refuse run now on a paused job, naming the failure when the job paused itself. */
870
+ function refuseIfPaused(job) {
871
+ if (job.status !== "paused")
872
+ return;
873
+ const auto = jobAutoPauseReason(job.pauseReason);
874
+ throw new JobActionError(auto ? `job is paused after ${JOB_AUTO_PAUSE_FAILURES} failures: ${auto}` : "job is paused");
875
+ }
876
+ /** Remove a job: it stops and is hidden; its rows and history stay (AS11). */
877
+ export async function removeJob(scheduler, jobId, opts = {}) {
878
+ const store = ledgerOf(scheduler);
879
+ const { after } = writeJob(store, jobId, (job) => {
880
+ if (job.status === "removed")
881
+ throw new JobActionError("job was removed");
882
+ return { ...job, status: "removed" };
883
+ });
884
+ cancelPending(scheduler, store, after, "removed", opts.actor);
885
+ await sweepJob(scheduler, jobId, new Date(), emptyResult(), { actor: opts.actor });
886
+ return store.getJob(jobId);
887
+ }
888
+ /** One job, removed ones included; undefined when the id is unknown. */
889
+ export function getJob(scheduler, jobId) {
890
+ return ledgerOf(scheduler).getJob(jobId);
891
+ }
892
+ /** Jobs, oldest first; removed jobs are hidden unless asked for. */
893
+ export function listJobs(scheduler, opts = {}) {
894
+ return ledgerOf(scheduler).listJobs(opts.includeRemoved ? {} : { status: ["active", "paused"] });
895
+ }
896
+ /** A job's occurrences, newest first. */
897
+ export function jobHistory(scheduler, jobId, limit = 20) {
898
+ const store = ledgerOf(scheduler);
899
+ requireJob(store, jobId);
900
+ return store
901
+ .list({ jobId, newestFirst: true, limit: Math.max(0, limit) })
902
+ .map((t) => ({
903
+ taskId: t.taskId,
904
+ status: t.status,
905
+ enqueuedAt: t.enqueuedAt,
906
+ scheduledFor: t.scheduledFor,
907
+ deadline: t.deadline,
908
+ completedAt: t.completedAt,
909
+ hasReceipt: t.receipt !== undefined,
910
+ carbonG: t.receipt?.actualCarbonGCo2 ?? t.receipt?.estimatedCarbonGCo2 ?? t.estimatedCarbonGCo2,
911
+ error: t.status === "failed" ? firstLine(t.error) : undefined,
912
+ }));
913
+ }
914
+ function errMessage(err) {
915
+ return err instanceof Error ? err.message : String(err);
916
+ }
917
+ //# sourceMappingURL=jobs.js.map