@tidegap/core 0.20.0 → 0.22.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 (54) hide show
  1. package/dist/channels/digest.js +4 -4
  2. package/dist/channels/format.d.ts +30 -4
  3. package/dist/channels/format.js +125 -22
  4. package/dist/channels/payload.js +8 -6
  5. package/dist/channels/plan.js +3 -2
  6. package/dist/channels/types.d.ts +17 -1
  7. package/dist/energy.d.ts +7 -0
  8. package/dist/energy.js +7 -0
  9. package/dist/grid.d.ts +10 -2
  10. package/dist/grid.js +14 -5
  11. package/dist/handoff.d.ts +88 -6
  12. package/dist/handoff.js +177 -20
  13. package/dist/history.d.ts +19 -0
  14. package/dist/history.js +24 -1
  15. package/dist/index.d.ts +24 -18
  16. package/dist/index.js +16 -12
  17. package/dist/job-cadence.d.ts +10 -0
  18. package/dist/job-cadence.js +34 -0
  19. package/dist/job-wake.d.ts +55 -0
  20. package/dist/job-wake.js +91 -0
  21. package/dist/jobs.d.ts +74 -17
  22. package/dist/jobs.js +420 -75
  23. package/dist/notify.d.ts +9 -0
  24. package/dist/notify.js +17 -3
  25. package/dist/providers/anthropic.js +8 -6
  26. package/dist/providers/base.d.ts +47 -9
  27. package/dist/providers/base.js +29 -4
  28. package/dist/providers/gemini.d.ts +3 -0
  29. package/dist/providers/gemini.js +9 -6
  30. package/dist/providers/http.d.ts +40 -0
  31. package/dist/providers/http.js +82 -0
  32. package/dist/providers/index.d.ts +1 -1
  33. package/dist/providers/index.js +1 -1
  34. package/dist/providers/ollama.d.ts +3 -0
  35. package/dist/providers/ollama.js +8 -5
  36. package/dist/providers/openai.js +7 -5
  37. package/dist/providers/timeout.d.ts +26 -8
  38. package/dist/providers/timeout.js +53 -15
  39. package/dist/readiness.d.ts +39 -3
  40. package/dist/readiness.js +73 -1
  41. package/dist/run-limits.d.ts +268 -0
  42. package/dist/run-limits.js +572 -0
  43. package/dist/schedule-job.d.ts +41 -2
  44. package/dist/schedule-job.js +70 -2
  45. package/dist/scheduler.d.ts +161 -17
  46. package/dist/scheduler.js +485 -128
  47. package/dist/storage/sqlite.d.ts +52 -5
  48. package/dist/storage/sqlite.js +200 -33
  49. package/dist/task-events.d.ts +19 -4
  50. package/dist/task-events.js +51 -5
  51. package/dist/tool-surface.js +62 -7
  52. package/dist/types.d.ts +72 -11
  53. package/dist/types.js +1 -3
  54. package/package.json +5 -2
package/dist/jobs.js CHANGED
@@ -10,12 +10,14 @@
10
10
  * inside `prepareTick`, so every ticker gets it. For each job it reads the
11
11
  * tracked occurrence and:
12
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);
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);
16
17
  * - 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;
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;
19
21
  * - no occurrence on an active job: materializes one.
20
22
  *
21
23
  * Every job write is a compare-and-set on `revision`. Pause, edit and
@@ -26,9 +28,12 @@
26
28
  */
27
29
  import { randomBytes } from "node:crypto";
28
30
  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 { wakeError } from "./handoff.js";
32
+ import { BATCH_SUBMIT_INTERRUPTED_ERROR, deriveTitle, taskResultText } from "./history.js";
33
+ import { JOB_WAKE_FORMS, matchWake, wakePatternError } from "./job-wake.js";
34
+ import { isCalendarAnchored, JobScheduleError, nextOccurrence, untilBoundMs, untilText, validateJobSchedule } from "./job-cadence.js";
31
35
  import { sleptBetween } from "./readiness.js";
36
+ import { capValueError, classifyFailure, FAILURE_CLASSES, isRetryableFailure, isRunLimitCap, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsFromDetails, versionedCaps, } from "./run-limits.js";
32
37
  import { canonicalize } from "./sign.js";
33
38
  import { systemTimeZone } from "./zone-time.js";
34
39
  import { DEFAULT_JOB_CAPS, } from "./types.js";
@@ -50,6 +55,14 @@ export class JobActionError extends Error {
50
55
  this.name = "JobActionError";
51
56
  }
52
57
  }
58
+ /** Every caps key a caller may set. */
59
+ export const JOB_CAPS_KEYS = new Set([
60
+ "commandTimeoutMs",
61
+ "llmTimeoutMs",
62
+ "retries",
63
+ "retryDelayMs",
64
+ ...Object.keys(DEFAULT_JOB_CAPS),
65
+ ]);
53
66
  /** Providers a prompt or summarize step may use (`command` is the shell step itself). */
54
67
  const LLM_PROVIDERS = new Set(["anthropic", "openai", "gemini", "ollama", "claude-code"]);
55
68
  const TOOLS = {
@@ -62,15 +75,28 @@ const ORIGIN_HOSTS = new Set(["page", "cli", "mcp", "openclaw"]);
62
75
  const TASK_ORIGIN_HOSTS = new Set(["cli", "mcp", "openclaw"]);
63
76
  /** A job secret name: what the command sees as an environment variable. */
64
77
  export const JOB_SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
78
+ /**
79
+ * The prompt `tidegap jobs add --summarize` stores when the user gives none.
80
+ * It is stored as text on the job, so a later change here leaves existing
81
+ * jobs as they are.
82
+ */
83
+ export const DEFAULT_SUMMARIZE_PROMPT = [
84
+ "You write the message a person reads on their phone when this scheduled job finishes. The job title and the command output follow.",
85
+ "Line 1: the verdict in one short sentence: all fine, or what needs attention.",
86
+ "Then a blank line and one to three short sentences: only what changed or what to do next. Give a number only when it changed or crossed a limit. Name a metric only when the reader needs the name to act.",
87
+ "Plain text only: no headings, lists, tables, markdown or code. Do not repeat the output.",
88
+ "Write in the language of the job title.",
89
+ "If the output is empty or you cannot tell what it means, say so on line 1.",
90
+ ].join("\n");
65
91
  const LIVE_STATUSES = ["queued", "scheduled", "running", "submitted"];
66
92
  const PENDING_STATUSES = ["queued", "scheduled"];
67
93
  const LIVE = new Set(LIVE_STATUSES);
68
94
  const PENDING = new Set(PENDING_STATUSES);
69
95
  /** 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"]);
96
+ const ACTION_CANCEL_REASONS = new Set(["paused", "edited", "removed", "duplicate", "ended"]);
71
97
  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;
98
+ /** The most runs a job's `count` may ask for. */
99
+ export const JOB_MAX_COUNT = 1000;
74
100
  /** Failed slots in a row that pause a job. */
75
101
  export const JOB_AUTO_PAUSE_FAILURES = 3;
76
102
  /** How `pauseReason` starts when the third failed slot paused the job: `auto: <first error line>`. */
@@ -82,14 +108,8 @@ export function jobAutoPauseReason(pauseReason) {
82
108
  /** Grace on top of the caps before a running occurrence counts as interrupted. */
83
109
  const INTERRUPT_GRACE_MS = 5 * MINUTE_MS;
84
110
  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";
111
+ // The Batch submit marker lives in history.ts (`taskActions` reads it), so history.ts imports nothing from this module.
112
+ export { BATCH_SUBMIT_INTERRUPTED_ERROR };
93
113
  const CORRUPT = "corrupt template";
94
114
  function ledgerOf(scheduler) {
95
115
  const store = scheduler.ledger();
@@ -147,14 +167,27 @@ function validTemplate(t) {
147
167
  }
148
168
  throw new JobActionError('runner must be "prompt" or "command"', "invalid");
149
169
  }
170
+ /**
171
+ * The caps to store: `base` with `patch` applied. The result holds only the
172
+ * time limits a caller set (old stored defaults dropped) and `capsVersion: 2`.
173
+ */
150
174
  function validCaps(base, patch) {
151
- const out = { ...base };
175
+ const out = { ...DEFAULT_JOB_CAPS, ...versionedCaps(base) };
152
176
  for (const [key, value] of Object.entries(patch ?? {})) {
153
- if (!(key in DEFAULT_JOB_CAPS))
177
+ if (!JOB_CAPS_KEYS.has(key))
154
178
  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");
179
+ if (value === undefined)
180
+ continue;
181
+ if (value === null) {
182
+ if (isRunLimitCap(key))
183
+ delete out[key];
184
+ else
185
+ out[key] = DEFAULT_JOB_CAPS[key];
186
+ continue;
157
187
  }
188
+ const error = capValueError(key, value);
189
+ if (error)
190
+ throw new JobActionError(error, "invalid");
158
191
  out[key] = value;
159
192
  }
160
193
  return out;
@@ -178,6 +211,75 @@ function validNotify(v) {
178
211
  throw new JobActionError("notify must be every_run, failures or summary", "invalid");
179
212
  return v;
180
213
  }
214
+ /** A valid `until` for a job in `timeZone`, or undefined for none; a bound already past is refused. */
215
+ function validUntil(v, timeZone, nowMs) {
216
+ if (v === undefined || v === null)
217
+ return undefined;
218
+ if (typeof v !== "string")
219
+ throw new JobActionError("until must be a day YYYY-MM-DD or an ISO instant", "invalid");
220
+ const text = v.trim();
221
+ let bound;
222
+ try {
223
+ bound = untilBoundMs(text, timeZone);
224
+ }
225
+ catch (err) {
226
+ if (err instanceof JobScheduleError)
227
+ throw new JobActionError(err.message, "invalid");
228
+ throw err;
229
+ }
230
+ if (bound <= nowMs)
231
+ throw new JobActionError(`until "${text}" has passed; give a later day or instant`, "invalid");
232
+ return text;
233
+ }
234
+ /** A valid `count`, or undefined for none. */
235
+ function validCount(v) {
236
+ if (v === undefined || v === null)
237
+ return undefined;
238
+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > JOB_MAX_COUNT) {
239
+ throw new JobActionError(`count must be a whole number from 1 to ${JOB_MAX_COUNT}`, "invalid");
240
+ }
241
+ return v;
242
+ }
243
+ /** What an end reason says: `its end date (<until>) passed` or `its runs are done`. */
244
+ export function jobEndText(reason, until) {
245
+ return reason === "until" ? `its end date${until ? ` (${until})` : ""} passed` : "its runs are done";
246
+ }
247
+ /**
248
+ * A job's end condition in words, or undefined for a job with none:
249
+ * `ends after 2026-11-17 (Europe/Berlin)`, `3 runs left`, or both joined by `; `.
250
+ */
251
+ export function jobEndsText(job) {
252
+ const parts = [];
253
+ if (job.until !== undefined)
254
+ parts.push(`ends ${untilText(job.until, job.timeZone)}`);
255
+ if (job.runsLeft !== undefined)
256
+ parts.push(`${job.runsLeft} ${job.runsLeft === 1 ? "run" : "runs"} left`);
257
+ return parts.length > 0 ? parts.join("; ") : undefined;
258
+ }
259
+ /**
260
+ * The binding a wake input gives, checked: `never` clears both fields; a
261
+ * rule needs a Claude Code session ({@link wakeError}) and, for `match`, a
262
+ * pattern {@link wakePatternError} accepts. `boundAt` is `now`.
263
+ */
264
+ function validWake(input, now) {
265
+ if (input.on === "never")
266
+ return { wake: undefined, originSessionId: undefined };
267
+ if (input.on !== "failures" && input.on !== "match")
268
+ throw new JobActionError(`wake must be ${JOB_WAKE_FORMS}`, "invalid");
269
+ const refused = wakeError(true, { agent: input.agent }, input.sessionId);
270
+ if (refused)
271
+ throw new JobActionError(refused, "invalid");
272
+ if (input.on === "failures")
273
+ return { wake: { on: "failures", boundAt: now.toISOString() }, originSessionId: input.sessionId };
274
+ const patternError = wakePatternError(input.pattern);
275
+ if (patternError)
276
+ throw new JobActionError(patternError, "invalid");
277
+ return { wake: { on: "match", pattern: input.pattern, boundAt: now.toISOString() }, originSessionId: input.sessionId };
278
+ }
279
+ /** The session a job wakes, or undefined when it is not bound. */
280
+ export function jobWakeSession(job) {
281
+ return job.wake && job.originSessionId ? job.originSessionId : undefined;
282
+ }
181
283
  function newJobId(store) {
182
284
  for (;;) {
183
285
  const id = `job-${randomBytes(4).toString("hex")}`;
@@ -188,6 +290,9 @@ function newJobId(store) {
188
290
  /** The occurrence body a job's template runs (Data shapes in the plan). */
189
291
  function occurrenceBody(job) {
190
292
  const t = job.template;
293
+ const session = jobWakeSession(job);
294
+ // A bound job's runs carry the rule and the session, never `origin` (KTD7).
295
+ const jobWake = session ? { jobWake: { on: job.wake.on, session } } : {};
191
296
  if (t.runner === "prompt") {
192
297
  return {
193
298
  type: "provider_call",
@@ -196,6 +301,7 @@ function occurrenceBody(job) {
196
301
  prompt: t.prompt,
197
302
  tools: TOOLS[t.tools],
198
303
  caps: job.caps,
304
+ ...jobWake,
199
305
  };
200
306
  }
201
307
  return {
@@ -206,16 +312,37 @@ function occurrenceBody(job) {
206
312
  command: { run: t.command, cwd: t.cwd, secrets: t.secrets },
207
313
  summarize: t.summarize ? { provider: t.summarize.provider, model: t.summarize.model } : undefined,
208
314
  caps: job.caps,
315
+ ...jobWake,
209
316
  };
210
317
  }
318
+ /**
319
+ * The time limits a run of `job` gets if it starts now, with their sources:
320
+ * the scheduler's settings reader, or without one the settings file.
321
+ */
322
+ export function jobRunLimits(job, scheduler) {
323
+ const body = occurrenceBody(job);
324
+ return scheduler ? scheduler.runLimitsFor(body) : resolveTaskRunLimits(body, loadRunLimitSettings());
325
+ }
211
326
  function scheduleOf(job) {
212
327
  return { cadence: job.cadence, window: job.window, timeZone: job.timeZone };
213
328
  }
214
- /** Sequence number of an occurrence id `<job>~<seq>` or `<job>~<seq>r`. */
329
+ /** Sequence number of an occurrence id `<job>~<seq>`, or of a retry `<job>~<seq>r`, `<job>~<seq>r2`, ... */
215
330
  function seqOf(taskId) {
216
- const m = /~(\d+)r?$/.exec(taskId);
331
+ const m = /~(\d+)(?:r\d*)?$/.exec(taskId);
217
332
  return m ? Number(m[1]) : 0;
218
333
  }
334
+ /** Which retry of its slot an occurrence id is: 0 for `<job>~<seq>`, 1 for `...r`, k for `...rk`. */
335
+ function retryOrdinal(taskId) {
336
+ const m = /~\d+r(\d*)$/.exec(taskId);
337
+ if (!m)
338
+ return 0;
339
+ return m[1] ? Number(m[1]) : 1;
340
+ }
341
+ /** The id of retry `k` of the slot of `taskId`: `<job>~<seq>r`, then `r2`, `r3`, ... */
342
+ function retryIdOf(taskId, k) {
343
+ const base = taskId.replace(/r\d*$/, "");
344
+ return k === 1 ? `${base}r` : `${base}r${k}`;
345
+ }
219
346
  function firstLine(text, max = 200) {
220
347
  return (text ?? "").split("\n")[0].slice(0, max);
221
348
  }
@@ -228,19 +355,50 @@ function dispatchedEvent(scheduler, taskId) {
228
355
  return undefined;
229
356
  }
230
357
  /**
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.
358
+ * The failure class of a failed occurrence: the one its `failed` event
359
+ * records, or, for a row from before classes were recorded, the one its
360
+ * event's steps and its error give (a failure after the command step is
361
+ * `after_command`, the Batch submit marker `batch_submit_interrupted`,
362
+ * anything else `transient`, as those rows always got their one retry).
234
363
  */
235
- function failedAfterCommand(scheduler, taskId) {
236
- const events = scheduler.listTaskEvents(taskId);
364
+ function failureClassOf(scheduler, row) {
365
+ const events = scheduler.listTaskEvents(row.taskId);
366
+ let details = {};
237
367
  for (let i = events.length - 1; i >= 0; i--) {
238
368
  if (events[i].kind !== "failed")
239
369
  continue;
240
- const steps = events[i].details?.steps;
241
- return Array.isArray(steps) && steps.includes("prompt");
370
+ details = events[i].details ?? {};
371
+ break;
242
372
  }
243
- return false;
373
+ const recorded = details.failure_class;
374
+ if (typeof recorded === "string" && FAILURE_CLASSES.includes(recorded))
375
+ return recorded;
376
+ const steps = Array.isArray(details.steps) ? details.steps.filter((s) => typeof s === "string") : undefined;
377
+ return classifyFailure({
378
+ ...(steps?.includes("prompt") ? { steps } : {}),
379
+ ...(row.error === BATCH_SUBMIT_INTERRUPTED_ERROR ? { interrupted: "batch_submit" } : {}),
380
+ });
381
+ }
382
+ /**
383
+ * When the next retry of a failed occurrence's slot starts, or undefined
384
+ * for none: its class must allow a retry, the slot must have retries left
385
+ * by the job's retry policy (its own value, the settings, the default), and
386
+ * retry k starts the retry delay times 2^(k−1) after now, no later than the
387
+ * slot's deadline.
388
+ */
389
+ function jobRetryAt(scheduler, job, failed, nowMs) {
390
+ if (!isRetryableFailure(failureClassOf(scheduler, failed)))
391
+ return undefined;
392
+ const deadline = Date.parse(failed.deadline ?? "");
393
+ if (!Number.isFinite(deadline))
394
+ return undefined;
395
+ const plan = planRetry({
396
+ attempt: job.retryUsed + 1,
397
+ ...retryPolicyOf(jobRunLimits(job, scheduler)),
398
+ failedAt: nowMs,
399
+ deadline,
400
+ });
401
+ return "retryAt" in plan ? plan.retryAt : undefined;
244
402
  }
245
403
  /** The sleep counter a `dispatched` event stored (`details.sleep`), or null. */
246
404
  function sleepAt(raw) {
@@ -266,10 +424,10 @@ function cancelOccurrence(scheduler, taskId, jobId, reason, actor) {
266
424
  const row = scheduler.cancelTask(taskId, { actor, details: { job_id: jobId, reason }, expectedStatus: PENDING_STATUSES });
267
425
  return row.status === "cancelled";
268
426
  }
269
- /** The run fields of an occurrence body: what an edit of the template changes (KTD2). */
427
+ /** The run fields of an occurrence body: what an edit of the template or the wake binding changes (KTD2, KTD7). */
270
428
  function runFields(spec) {
271
- const { provider, model, prompt, tools, caps, command, summarize } = spec;
272
- return canonicalize({ provider, model, prompt, tools: tools ?? [], caps, command, summarize });
429
+ const { provider, model, prompt, tools, caps, command, summarize, jobWake } = spec;
430
+ return canonicalize({ provider, model, prompt, tools: tools ?? [], caps, command, summarize, jobWake });
273
431
  }
274
432
  /** True when a stored occurrence runs what the job's current template gives. */
275
433
  function runsCurrentTemplate(row, job) {
@@ -281,7 +439,7 @@ function runsCurrentTemplate(row, job) {
281
439
  }
282
440
  }
283
441
  function emptyResult() {
284
- return { messages: [], materialized: [], retried: [], autoPaused: [], interrupted: [] };
442
+ return { messages: [], materialized: [], retried: [], autoPaused: [], interrupted: [], ended: [], sessionNotices: [] };
285
443
  }
286
444
  /**
287
445
  * One job's step of the sweep: record the tracked occurrence's outcome and
@@ -293,6 +451,8 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
293
451
  const nowMs = now.getTime();
294
452
  /** Rows this call inserted: cleaned up when every job write misses. */
295
453
  const inserted = [];
454
+ /** Runs whose notice this call decided: a second attempt does not match the pattern again. */
455
+ const notices = new Set();
296
456
  for (let attempt = 0; attempt < 3; attempt++) {
297
457
  const job = store.getJob(jobId);
298
458
  if (!job || job.pauseReason === CORRUPT)
@@ -331,12 +491,15 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
331
491
  }
332
492
  return;
333
493
  }
334
- if (!tracked && job.status !== "active")
494
+ if (!tracked && job.status !== "active" && !(job.status === "paused" && pausedEndReason(job, nowMs)))
335
495
  return;
336
496
  // The tracked occurrence ended (or there is none): record the outcome.
337
497
  const next = { ...job, updatedAt: now.toISOString() };
338
498
  let successor = job.status === "active" ? "next" : "none";
339
499
  let skippedDeadline;
500
+ let retryAt;
501
+ /** The tracked slot ended for good: completed, or failed with no retry left. */
502
+ let slotEnded = false;
340
503
  if (tracked) {
341
504
  next.pendingTaskId = undefined;
342
505
  next.lastTaskId = tracked.taskId;
@@ -344,17 +507,19 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
344
507
  if (tracked.status === "completed") {
345
508
  next.lastOutcome = "ok";
346
509
  next.consecutiveFailures = 0;
510
+ slotEnded = true;
347
511
  }
348
512
  else if (tracked.status === "failed") {
349
513
  next.lastOutcome = "failed";
350
- const left = tracked.deadline ? Date.parse(tracked.deadline) - nowMs : 0;
351
514
  // 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) {
515
+ // provider, and a failed LLM step ran its command already: neither
516
+ // class retries, nor a permanent failure.
517
+ retryAt = successor === "next" ? jobRetryAt(scheduler, job, tracked, nowMs) : undefined;
518
+ if (retryAt !== undefined) {
355
519
  successor = "retry";
356
520
  }
357
521
  else {
522
+ slotEnded = true;
358
523
  next.consecutiveFailures = job.consecutiveFailures + 1;
359
524
  if (successor === "next" && next.consecutiveFailures >= JOB_AUTO_PAUSE_FAILURES) {
360
525
  successor = "none";
@@ -390,17 +555,34 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
390
555
  }
391
556
  }
392
557
  const freeSeq = Math.max(job.nextSeq, ...edited.map((id) => seqOf(id) + 1));
393
- const retryId = tracked && successor === "retry" ? `${tracked.taskId.replace(/r$/, "")}r` : undefined;
558
+ const retryId = tracked && successor === "retry" ? retryIdOf(tracked.taskId, job.retryUsed + 1) : undefined;
394
559
  // The edit replaced the template the retry would run: make a regular
395
560
  // occurrence of the new template instead; the failure is not counted.
396
561
  if (retryId && edited.includes(retryId))
397
562
  successor = "next";
398
- const adopt = adoptable[adoptable.length - 1];
563
+ if (slotEnded && next.runsLeft !== undefined)
564
+ next.runsLeft = Math.max(0, next.runsLeft - 1);
565
+ // The end wins over the auto-pause: a last slot that also paused the job ends it.
566
+ const endReason = successor === "retry" ? undefined : jobEndReason(next, job.status, tracked, nowMs, skippedDeadline, opts);
567
+ if (endReason) {
568
+ successor = "none";
569
+ if (next.status === "paused" && job.status === "active") {
570
+ result.autoPaused = result.autoPaused.filter((id) => id !== jobId);
571
+ next.pauseReason = job.pauseReason;
572
+ next.pausedAt = job.pausedAt;
573
+ next.pauseNotifiedAt = job.pauseNotifiedAt;
574
+ }
575
+ next.status = "ended";
576
+ next.endedAt = now.toISOString();
577
+ next.endReason = endReason;
578
+ next.endNotifiedAt = undefined;
579
+ }
580
+ const adopt = endReason ? undefined : adoptable[adoptable.length - 1];
399
581
  let taskId;
400
582
  if (adopt) {
401
583
  taskId = adopt.taskId;
402
584
  next.nextSeq = Math.max(freeSeq, seqOf(adopt.taskId) + 1);
403
- next.retryUsed = adopt.taskId.endsWith("r");
585
+ next.retryUsed = retryOrdinal(adopt.taskId);
404
586
  for (const t of adoptable) {
405
587
  if (t !== adopt && PENDING.has(t.status))
406
588
  cancelOccurrence(scheduler, t.taskId, jobId, "duplicate");
@@ -408,8 +590,8 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
408
590
  }
409
591
  else if (successor === "retry" && retryId) {
410
592
  taskId = retryId;
411
- next.retryUsed = true;
412
- if (await materialize(scheduler, next, taskId, nowMs + JOB_RETRY_DELAY_MS, Date.parse(tracked.deadline), "retry")) {
593
+ next.retryUsed = job.retryUsed + 1;
594
+ if (await materialize(scheduler, next, taskId, retryAt, Date.parse(tracked.deadline), "retry")) {
413
595
  inserted.push(taskId);
414
596
  result.retried.push(taskId);
415
597
  result.materialized.push(taskId);
@@ -419,17 +601,29 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
419
601
  const occ = firstOccurrence(next, tracked, nowMs, skippedDeadline, opts);
420
602
  taskId = `${jobId}~${freeSeq}`;
421
603
  next.nextSeq = freeSeq + 1;
422
- next.retryUsed = false;
604
+ next.retryUsed = 0;
423
605
  if (await materialize(scheduler, next, taskId, occ.earliest, occ.deadline, occ.anchor)) {
424
606
  inserted.push(taskId);
425
607
  result.materialized.push(taskId);
426
608
  }
427
609
  }
428
610
  next.pendingTaskId = taskId;
611
+ // The run's session notice goes in before the job write, so a reader
612
+ // never sees the job ended (or moved on) without it (KTD9).
613
+ if (tracked && successor !== "retry")
614
+ recordJobNotice(store, job, tracked, slotEnded, endReason !== undefined, result, notices);
429
615
  // A miss: another writer moved the job meanwhile. The next pass adopts
430
616
  // the insert on an active job, or cancels it on an inactive one.
431
- if (store.updateJobIf(next, job.revision))
617
+ if (store.updateJobIf(next, job.revision)) {
618
+ if (endReason) {
619
+ result.ended.push(jobId);
620
+ // The sweep skips an ended job, so no later pass cancels a stray pending row.
621
+ for (const t of orphans)
622
+ if (PENDING.has(t.status))
623
+ cancelOccurrence(scheduler, t.taskId, jobId, "ended", opts.actor);
624
+ }
432
625
  return;
626
+ }
433
627
  }
434
628
  result.messages.push(`job ${jobId}: the job row kept changing; left for the next sweep`);
435
629
  // No pass is left to cancel this call's insert on a job that stopped
@@ -440,6 +634,78 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
440
634
  for (const id of inserted)
441
635
  cancelOccurrence(scheduler, id, jobId, latest?.status === "paused" ? "paused" : "removed", opts.actor);
442
636
  }
637
+ /**
638
+ * The session notice of a finished run of a bound job (KTD9), written as a
639
+ * `session_notice` event when the run has a reason: `failed` when its slot
640
+ * failed for good, `matched` when the job is under `match`, the run
641
+ * completed and its result text matches, `ended` when this outcome ends the
642
+ * job. It wakes the session for `failed` under `failures` and for
643
+ * `matched`, while the job is active. A run of another session (made before a rebind), or of a job
644
+ * no longer bound, gets nothing.
645
+ */
646
+ function recordJobNotice(store, job, run, slotEnded, ended, result, decided) {
647
+ const session = jobWakeSession(job);
648
+ if (!session || run.originSessionId !== session || decided.has(run.taskId) || !run.completedAt)
649
+ return;
650
+ decided.add(run.taskId);
651
+ const reasons = [];
652
+ const failed = run.status === "failed" && slotEnded;
653
+ if (failed)
654
+ reasons.push("failed");
655
+ if (job.wake.on === "match" && run.status === "completed") {
656
+ const m = matchWake(job.wake.pattern ?? "", taskResultText(run) ?? "");
657
+ if (m.timedOut)
658
+ result.messages.push(`job ${job.jobId}: ${run.taskId}: the wake pattern timed out; counted as matched`);
659
+ if (m.broken)
660
+ result.messages.push(`job ${job.jobId}: ${run.taskId}: the wake pattern does not compile; counted as matched`);
661
+ if (m.matched)
662
+ reasons.push("matched");
663
+ }
664
+ if (ended)
665
+ reasons.push("ended");
666
+ if (reasons.length === 0)
667
+ return;
668
+ // A run that finished after someone paused or removed its job is a notice for the next prompt, not a wake.
669
+ const wake = job.status === "active" && ((failed && job.wake.on === "failures") || reasons.includes("matched"));
670
+ if (store.recordSessionNotice(run.taskId, { reasons, wake }))
671
+ result.sessionNotices.push(run.taskId);
672
+ }
673
+ /** The `until` bound of a job in ms, or undefined when it has none or the stored text does not parse. */
674
+ function untilBound(job) {
675
+ if (job.until === undefined)
676
+ return undefined;
677
+ try {
678
+ return untilBoundMs(job.until, job.timeZone);
679
+ }
680
+ catch {
681
+ return undefined;
682
+ }
683
+ }
684
+ /** Why a paused job ends with no run: its runs are done, or its end date passed. */
685
+ function pausedEndReason(job, nowMs) {
686
+ if (job.runsLeft !== undefined && job.runsLeft <= 0)
687
+ return "count";
688
+ const bound = untilBound(job);
689
+ return bound !== undefined && bound <= nowMs ? "until" : undefined;
690
+ }
691
+ /**
692
+ * Why `next` ends instead of getting its next occurrence, or undefined. An
693
+ * active job ends when its runs are done or its next regular occurrence
694
+ * would start at or after the `until` bound; a paused one when its runs are
695
+ * done or the bound passed. `status` is the job's status before this pass.
696
+ */
697
+ function jobEndReason(next, status, tracked, nowMs, skippedDeadline, opts) {
698
+ if (status === "paused")
699
+ return pausedEndReason(next, nowMs);
700
+ if (status !== "active")
701
+ return undefined;
702
+ if (next.runsLeft !== undefined && next.runsLeft <= 0)
703
+ return "count";
704
+ const bound = untilBound(next);
705
+ if (bound === undefined)
706
+ return undefined;
707
+ return firstOccurrence(next, tracked, nowMs, skippedDeadline, opts).earliest >= bound ? "until" : undefined;
708
+ }
443
709
  /** `[earliest, deadline]` of the next regular occurrence, in ms. */
444
710
  function firstOccurrence(job, tracked, nowMs, skippedDeadline, opts) {
445
711
  if (opts.firstDeadline !== undefined && !tracked) {
@@ -476,16 +742,51 @@ async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
476
742
  bodyJson: JSON.stringify(occurrenceBody(job)),
477
743
  originHost: job.originHost && TASK_ORIGIN_HOSTS.has(job.originHost) ? job.originHost : undefined,
478
744
  originCwd: t.cwd,
745
+ originSessionId: jobWakeSession(job),
479
746
  }, { job_id: job.jobId, seq: seqOf(taskId), anchor });
480
747
  }
481
748
  /**
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.
749
+ * How long a run may last before the time rule frees it: its time limits
750
+ * plus a grace period, so the limit is generous. The limits are the ones
751
+ * its `dispatched` event recorded; a run dispatched before they were
752
+ * recorded gets the ones it would get now. Undefined when a limit is
753
+ * `none`: such a run is freed only by the tick lock rule. A row with no
754
+ * usable `dispatched` event (a Batch row) counts from its deadline, and no
755
+ * LLM time limit applies to a Batch run, so there a `none` limit adds
756
+ * nothing instead.
757
+ */
758
+ function runTimeAllowance(scheduler, row, dispatched) {
759
+ let limits = runLimitsFromDetails(dispatched?.details);
760
+ if (!limits) {
761
+ let spec;
762
+ try {
763
+ spec = JSON.parse(row.bodyJson ?? "null");
764
+ }
765
+ catch {
766
+ spec = undefined;
767
+ }
768
+ if (!spec || typeof spec.provider !== "string")
769
+ return INTERRUPT_GRACE_MS;
770
+ limits = scheduler.runLimitsFor(spec);
771
+ }
772
+ let total = INTERRUPT_GRACE_MS;
773
+ for (const limit of [limits.command_timeout, limits.llm_timeout]) {
774
+ if (!limit)
775
+ continue;
776
+ if (limit.value === "none") {
777
+ if (dispatched)
778
+ return undefined;
779
+ continue;
780
+ }
781
+ total += limit.value;
782
+ }
783
+ return total;
784
+ }
785
+ /**
786
+ * The time rule of a running occurrence: its dispatch is older than its
787
+ * time limits plus a grace period ({@link runTimeAllowance}). A run with a
788
+ * `none` limit never counts as too old, unless its age counts from the
789
+ * deadline (below).
489
790
  *
490
791
  * The age counts from the last `dispatched` event. Two `running` rows have
491
792
  * no usable one and count from the deadline instead: a Batch row being
@@ -493,33 +794,54 @@ async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
493
794
  * between the claim and the event (Batch submit). Neither can run past
494
795
  * its deadline legitimately (Batch rows have a deadline over a day ahead).
495
796
  */
496
- function interrupted(scheduler, store, job, row, nowMs, sleepNow) {
797
+ function olderThanLimits(scheduler, row, nowMs, sleepNow) {
497
798
  const dispatched = row.batchId ? undefined : dispatchedEvent(scheduler, row.taskId);
498
799
  const started = Date.parse(dispatched?.at ?? row.deadline ?? "");
499
800
  if (!Number.isFinite(started))
500
- return undefined;
501
- const limit = job.caps.commandTimeoutMs + job.caps.llmTimeoutMs + INTERRUPT_GRACE_MS;
801
+ return false;
802
+ const limit = runTimeAllowance(scheduler, row, dispatched);
803
+ if (limit === undefined)
804
+ return false;
502
805
  const wallAge = nowMs - started;
503
806
  const sleepThen = sleepAt(dispatched?.details.sleep);
504
807
  if (sleepThen && !sleepNow) {
505
808
  // 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
809
+ // the run may have slept. Wait for its deadline plus the limits, so a
507
810
  // host that reads the counter decides first, and a dead tick still
508
811
  // frees the job at the latest then.
509
812
  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;
813
+ return nowMs - (Number.isFinite(deadline) ? Math.max(deadline, started) : started) > limit;
518
814
  }
815
+ // Awake time only: a run the machine slept through is still running.
816
+ const slept = sleptBetween(sleepThen, sleepNow, wallAge);
817
+ return wallAge - slept > limit;
818
+ }
819
+ /**
820
+ * A running occurrence whose tick died. Fail it by compare-and-set from
821
+ * `running`; a completion that lands after this write is dropped. A row with
822
+ * a batch id was being polled: its batch is live at the provider, so it goes
823
+ * back to `submitted` (compare-and-set from `running`) and the next tick
824
+ * polls it again. Returns what this call wrote: "failed", "submitted", or
825
+ * undefined for nothing.
826
+ *
827
+ * Under the tick lock, a run whose dispatch carries tick details follows the
828
+ * tick lock rule ({@link Scheduler.deadTickRun}): it is freed as soon as the
829
+ * tick that ran it is gone, and never while that tick's process runs. Any
830
+ * other run, a run whose tick the host cannot judge included, is freed when
831
+ * it is older than its time limits plus a grace period ({@link olderThanLimits}).
832
+ */
833
+ function interrupted(scheduler, store, job, row, nowMs, sleepNow) {
834
+ const deadTick = scheduler.deadTickRun(row);
835
+ if (deadTick === false)
836
+ return undefined;
837
+ if (deadTick === undefined && !olderThanLimits(scheduler, row, nowMs, sleepNow))
838
+ return undefined;
519
839
  if (row.batchId) {
520
840
  return store.transitionIf({ ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]) ? "submitted" : undefined;
521
841
  }
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" } });
842
+ const failed = store.transitionIf({ ...row, status: "failed", completedAt: new Date(nowMs).toISOString(), error: JOB_INTERRUPTED_ERROR }, ["running"], undefined,
843
+ // A job run fails for good here; the sweep's next pass makes its slot's retry row by the retry policy.
844
+ { kind: "failed", actor: "system", details: { job_id: job.jobId, reason: "interrupted", attempts: 1, failure_class: "interrupted" } });
523
845
  return failed ? "failed" : undefined;
524
846
  }
525
847
  /**
@@ -533,7 +855,7 @@ export async function sweepJobs(scheduler, now = new Date(), opts = {}) {
533
855
  const store = scheduler.ledger();
534
856
  if (!store)
535
857
  return result;
536
- jobs = store.listJobs().filter((j) => j.status !== "removed" || j.pendingTaskId !== undefined);
858
+ jobs = store.listJobs({ status: ["active", "paused", "removed"] }).filter((j) => j.status !== "removed" || j.pendingTaskId !== undefined);
537
859
  }
538
860
  catch (err) {
539
861
  result.messages.push(`job sweep: cannot read the ledger: ${errMessage(err)}`);
@@ -551,6 +873,8 @@ export async function sweepJobs(scheduler, now = new Date(), opts = {}) {
551
873
  result.messages.push(`materialized job occurrence ${id}`);
552
874
  for (const id of result.autoPaused)
553
875
  result.messages.push(`paused job ${id} after ${JOB_AUTO_PAUSE_FAILURES} failed runs`);
876
+ for (const id of result.ended)
877
+ result.messages.push(`ended job ${id}`);
554
878
  return result;
555
879
  }
556
880
  /** Create a job and its first occurrence. Throws {@link JobActionError} on bad input. */
@@ -576,7 +900,7 @@ export async function createJob(scheduler, input, opts = {}) {
576
900
  window: schedule.window,
577
901
  timeZone: schedule.timeZone,
578
902
  template: validTemplate(input.template),
579
- caps: validCaps(DEFAULT_JOB_CAPS, input.caps),
903
+ caps: validCaps({}, input.caps),
580
904
  notify: input.notify === undefined ? "every_run" : validNotify(input.notify),
581
905
  originHost: input.originHost,
582
906
  originCwd: input.originCwd,
@@ -586,8 +910,19 @@ export async function createJob(scheduler, input, opts = {}) {
586
910
  revision: 1,
587
911
  nextSeq: 1,
588
912
  consecutiveFailures: 0,
589
- retryUsed: false,
913
+ retryUsed: 0,
914
+ until: validUntil(input.until, schedule.timeZone, now.getTime()),
915
+ runsLeft: validCount(input.count),
916
+ ...(input.wake ? validWake(input.wake, now) : {}),
590
917
  };
918
+ // A job that would end before its first run is a mistake, not a job.
919
+ const bound = untilBound(job);
920
+ if (bound !== undefined) {
921
+ const first = firstOccurrence(job, undefined, now.getTime(), undefined, { firstDeadline }).earliest;
922
+ if (first >= bound) {
923
+ throw new JobActionError(`until "${job.until}" comes before the first run (${new Date(first).toISOString()}); give a later day or instant`, "invalid");
924
+ }
925
+ }
591
926
  store.insertJob(job);
592
927
  try {
593
928
  await sweepJob(scheduler, job.jobId, now, emptyResult(), { firstDeadline, actor: opts.actor });
@@ -626,10 +961,12 @@ function requireJob(store, jobId) {
626
961
  function pendingRow(store, job) {
627
962
  return job.pendingTaskId ? store.get(job.pendingTaskId) : undefined;
628
963
  }
629
- /** Refuse every action but remove on a removed job or one whose stored template does not parse. */
964
+ /** Refuse every action but remove on a removed or ended job, or one whose stored template does not parse. */
630
965
  function requireEditable(job) {
631
966
  if (job.status === "removed")
632
967
  throw new JobActionError("job was removed");
968
+ if (job.status === "ended")
969
+ throw new JobActionError(`job ended (${jobEndText(job.endReason, job.until)}); add a new job`);
633
970
  if (job.pauseReason === CORRUPT)
634
971
  throw new JobActionError(`job ${job.jobId} has a corrupt template; remove it and create it again`);
635
972
  }
@@ -678,6 +1015,13 @@ export async function updateJob(scheduler, jobId, patch, opts = {}) {
678
1015
  template: patch.template !== undefined ? validTemplate(patch.template) : job.template,
679
1016
  caps: validCaps(job.caps, patch.caps),
680
1017
  notify: patch.notify !== undefined ? validNotify(patch.notify) : job.notify,
1018
+ // A new zone moves a day bound, so the kept `until` is checked again.
1019
+ until: patch.until !== undefined || schedule.timeZone !== job.timeZone
1020
+ ? validUntil(patch.until !== undefined ? patch.until : job.until, schedule.timeZone, Date.now())
1021
+ : job.until,
1022
+ runsLeft: patch.count !== undefined ? validCount(patch.count) : job.runsLeft,
1023
+ // A wake edit rebinds the job to the session that makes it; a page edit keeps the binding.
1024
+ ...(patch.wake !== undefined ? validWake(patch.wake, new Date()) : {}),
681
1025
  };
682
1026
  });
683
1027
  cancelPending(scheduler, store, before, "edited", opts.actor);
@@ -709,7 +1053,7 @@ export async function resumeJob(scheduler, jobId, opts = {}) {
709
1053
  ...job,
710
1054
  status: "active",
711
1055
  consecutiveFailures: 0,
712
- retryUsed: false,
1056
+ retryUsed: 0,
713
1057
  pauseReason: undefined,
714
1058
  pausedAt: undefined,
715
1059
  pauseNotifiedAt: undefined,
@@ -732,7 +1076,8 @@ export async function runJobNow(scheduler, jobId, opts = {}) {
732
1076
  if (!row || !LIVE.has(row.status)) {
733
1077
  await sweepJob(scheduler, jobId, new Date(), emptyResult(), { actor: opts.actor });
734
1078
  job = requireJob(store, jobId);
735
- // The sweep may have just auto-paused the job (its third failed slot).
1079
+ // The sweep may have just ended the job or auto-paused it (its third failed slot).
1080
+ requireEditable(job);
736
1081
  refuseIfPaused(job);
737
1082
  row = pendingRow(store, job);
738
1083
  }
@@ -766,7 +1111,7 @@ export async function removeJob(scheduler, jobId, opts = {}) {
766
1111
  export function getJob(scheduler, jobId) {
767
1112
  return ledgerOf(scheduler).getJob(jobId);
768
1113
  }
769
- /** Jobs, oldest first; removed jobs are hidden unless asked for. */
1114
+ /** Jobs, oldest first; removed and ended jobs are hidden unless asked for. */
770
1115
  export function listJobs(scheduler, opts = {}) {
771
1116
  return ledgerOf(scheduler).listJobs(opts.includeRemoved ? {} : { status: ["active", "paused"] });
772
1117
  }