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