@tidegap/core 0.20.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 (45) hide show
  1. package/dist/channels/digest.js +3 -3
  2. package/dist/channels/format.d.ts +11 -0
  3. package/dist/channels/format.js +26 -8
  4. package/dist/energy.d.ts +7 -0
  5. package/dist/energy.js +7 -0
  6. package/dist/handoff.d.ts +22 -3
  7. package/dist/handoff.js +69 -17
  8. package/dist/history.d.ts +15 -0
  9. package/dist/history.js +11 -0
  10. package/dist/index.d.ts +17 -13
  11. package/dist/index.js +12 -10
  12. package/dist/jobs.d.ts +25 -15
  13. package/dist/jobs.js +186 -63
  14. package/dist/notify.d.ts +9 -0
  15. package/dist/notify.js +17 -3
  16. package/dist/providers/anthropic.js +8 -6
  17. package/dist/providers/base.d.ts +40 -9
  18. package/dist/providers/base.js +29 -4
  19. package/dist/providers/gemini.d.ts +3 -0
  20. package/dist/providers/gemini.js +9 -6
  21. package/dist/providers/http.d.ts +40 -0
  22. package/dist/providers/http.js +82 -0
  23. package/dist/providers/index.d.ts +1 -1
  24. package/dist/providers/index.js +1 -1
  25. package/dist/providers/ollama.d.ts +3 -0
  26. package/dist/providers/ollama.js +8 -5
  27. package/dist/providers/openai.js +7 -5
  28. package/dist/providers/timeout.d.ts +26 -8
  29. package/dist/providers/timeout.js +53 -15
  30. package/dist/readiness.d.ts +39 -3
  31. package/dist/readiness.js +73 -1
  32. package/dist/run-limits.d.ts +268 -0
  33. package/dist/run-limits.js +572 -0
  34. package/dist/schedule-job.d.ts +23 -0
  35. package/dist/schedule-job.js +48 -0
  36. package/dist/scheduler.d.ts +159 -17
  37. package/dist/scheduler.js +482 -128
  38. package/dist/storage/sqlite.d.ts +28 -2
  39. package/dist/storage/sqlite.js +65 -5
  40. package/dist/task-events.d.ts +19 -4
  41. package/dist/task-events.js +42 -5
  42. package/dist/tool-surface.js +38 -7
  43. package/dist/types.d.ts +31 -10
  44. package/dist/types.js +1 -3
  45. 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,10 @@
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";
31
+ import { BATCH_SUBMIT_INTERRUPTED_ERROR, deriveTitle } from "./history.js";
30
32
  import { isCalendarAnchored, JobScheduleError, nextOccurrence, validateJobSchedule } from "./job-cadence.js";
31
33
  import { sleptBetween } from "./readiness.js";
34
+ import { capValueError, classifyFailure, FAILURE_CLASSES, isRetryableFailure, isRunLimitCap, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsFromDetails, versionedCaps, } from "./run-limits.js";
32
35
  import { canonicalize } from "./sign.js";
33
36
  import { systemTimeZone } from "./zone-time.js";
34
37
  import { DEFAULT_JOB_CAPS, } from "./types.js";
@@ -50,6 +53,14 @@ export class JobActionError extends Error {
50
53
  this.name = "JobActionError";
51
54
  }
52
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
+ ]);
53
64
  /** Providers a prompt or summarize step may use (`command` is the shell step itself). */
54
65
  const LLM_PROVIDERS = new Set(["anthropic", "openai", "gemini", "ollama", "claude-code"]);
55
66
  const TOOLS = {
@@ -69,8 +80,6 @@ const PENDING = new Set(PENDING_STATUSES);
69
80
  /** Cancel reasons a job action writes; any other cancel of an occurrence is a skip. */
70
81
  const ACTION_CANCEL_REASONS = new Set(["paused", "edited", "removed", "duplicate"]);
71
82
  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
83
  /** Failed slots in a row that pause a job. */
75
84
  export const JOB_AUTO_PAUSE_FAILURES = 3;
76
85
  /** How `pauseReason` starts when the third failed slot paused the job: `auto: <first error line>`. */
@@ -82,14 +91,8 @@ export function jobAutoPauseReason(pauseReason) {
82
91
  /** Grace on top of the caps before a running occurrence counts as interrupted. */
83
92
  const INTERRUPT_GRACE_MS = 5 * MINUTE_MS;
84
93
  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";
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 };
93
96
  const CORRUPT = "corrupt template";
94
97
  function ledgerOf(scheduler) {
95
98
  const store = scheduler.ledger();
@@ -147,14 +150,27 @@ function validTemplate(t) {
147
150
  }
148
151
  throw new JobActionError('runner must be "prompt" or "command"', "invalid");
149
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
+ */
150
157
  function validCaps(base, patch) {
151
- const out = { ...base };
158
+ const out = { ...DEFAULT_JOB_CAPS, ...versionedCaps(base) };
152
159
  for (const [key, value] of Object.entries(patch ?? {})) {
153
- if (!(key in DEFAULT_JOB_CAPS))
160
+ if (!JOB_CAPS_KEYS.has(key))
154
161
  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");
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;
157
170
  }
171
+ const error = capValueError(key, value);
172
+ if (error)
173
+ throw new JobActionError(error, "invalid");
158
174
  out[key] = value;
159
175
  }
160
176
  return out;
@@ -208,14 +224,34 @@ function occurrenceBody(job) {
208
224
  caps: job.caps,
209
225
  };
210
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
+ }
211
235
  function scheduleOf(job) {
212
236
  return { cadence: job.cadence, window: job.window, timeZone: job.timeZone };
213
237
  }
214
- /** Sequence number of an occurrence id `<job>~<seq>` or `<job>~<seq>r`. */
238
+ /** Sequence number of an occurrence id `<job>~<seq>`, or of a retry `<job>~<seq>r`, `<job>~<seq>r2`, ... */
215
239
  function seqOf(taskId) {
216
- const m = /~(\d+)r?$/.exec(taskId);
240
+ const m = /~(\d+)(?:r\d*)?$/.exec(taskId);
217
241
  return m ? Number(m[1]) : 0;
218
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
+ }
219
255
  function firstLine(text, max = 200) {
220
256
  return (text ?? "").split("\n")[0].slice(0, max);
221
257
  }
@@ -228,19 +264,50 @@ function dispatchedEvent(scheduler, taskId) {
228
264
  return undefined;
229
265
  }
230
266
  /**
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.
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).
234
272
  */
235
- function failedAfterCommand(scheduler, taskId) {
236
- const events = scheduler.listTaskEvents(taskId);
273
+ function failureClassOf(scheduler, row) {
274
+ const events = scheduler.listTaskEvents(row.taskId);
275
+ let details = {};
237
276
  for (let i = events.length - 1; i >= 0; i--) {
238
277
  if (events[i].kind !== "failed")
239
278
  continue;
240
- const steps = events[i].details?.steps;
241
- return Array.isArray(steps) && steps.includes("prompt");
242
- }
243
- return false;
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;
244
311
  }
245
312
  /** The sleep counter a `dispatched` event stored (`details.sleep`), or null. */
246
313
  function sleepAt(raw) {
@@ -337,6 +404,7 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
337
404
  const next = { ...job, updatedAt: now.toISOString() };
338
405
  let successor = job.status === "active" ? "next" : "none";
339
406
  let skippedDeadline;
407
+ let retryAt;
340
408
  if (tracked) {
341
409
  next.pendingTaskId = undefined;
342
410
  next.lastTaskId = tracked.taskId;
@@ -347,11 +415,11 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
347
415
  }
348
416
  else if (tracked.status === "failed") {
349
417
  next.lastOutcome = "failed";
350
- const left = tracked.deadline ? Date.parse(tracked.deadline) - nowMs : 0;
351
418
  // 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) {
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) {
355
423
  successor = "retry";
356
424
  }
357
425
  else {
@@ -390,7 +458,7 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
390
458
  }
391
459
  }
392
460
  const freeSeq = Math.max(job.nextSeq, ...edited.map((id) => seqOf(id) + 1));
393
- const retryId = tracked && successor === "retry" ? `${tracked.taskId.replace(/r$/, "")}r` : undefined;
461
+ const retryId = tracked && successor === "retry" ? retryIdOf(tracked.taskId, job.retryUsed + 1) : undefined;
394
462
  // The edit replaced the template the retry would run: make a regular
395
463
  // occurrence of the new template instead; the failure is not counted.
396
464
  if (retryId && edited.includes(retryId))
@@ -400,7 +468,7 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
400
468
  if (adopt) {
401
469
  taskId = adopt.taskId;
402
470
  next.nextSeq = Math.max(freeSeq, seqOf(adopt.taskId) + 1);
403
- next.retryUsed = adopt.taskId.endsWith("r");
471
+ next.retryUsed = retryOrdinal(adopt.taskId);
404
472
  for (const t of adoptable) {
405
473
  if (t !== adopt && PENDING.has(t.status))
406
474
  cancelOccurrence(scheduler, t.taskId, jobId, "duplicate");
@@ -408,8 +476,8 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
408
476
  }
409
477
  else if (successor === "retry" && retryId) {
410
478
  taskId = retryId;
411
- next.retryUsed = true;
412
- if (await materialize(scheduler, next, taskId, nowMs + JOB_RETRY_DELAY_MS, Date.parse(tracked.deadline), "retry")) {
479
+ next.retryUsed = job.retryUsed + 1;
480
+ if (await materialize(scheduler, next, taskId, retryAt, Date.parse(tracked.deadline), "retry")) {
413
481
  inserted.push(taskId);
414
482
  result.retried.push(taskId);
415
483
  result.materialized.push(taskId);
@@ -419,7 +487,7 @@ async function sweepJob(scheduler, jobId, now, result, opts = {}) {
419
487
  const occ = firstOccurrence(next, tracked, nowMs, skippedDeadline, opts);
420
488
  taskId = `${jobId}~${freeSeq}`;
421
489
  next.nextSeq = freeSeq + 1;
422
- next.retryUsed = false;
490
+ next.retryUsed = 0;
423
491
  if (await materialize(scheduler, next, taskId, occ.earliest, occ.deadline, occ.anchor)) {
424
492
  inserted.push(taskId);
425
493
  result.materialized.push(taskId);
@@ -479,13 +547,47 @@ async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
479
547
  }, { job_id: job.jobId, seq: seqOf(taskId), anchor });
480
548
  }
481
549
  /**
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.
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).
489
591
  *
490
592
  * The age counts from the last `dispatched` event. Two `running` rows have
491
593
  * no usable one and count from the deadline instead: a Batch row being
@@ -493,33 +595,54 @@ async function materialize(scheduler, job, taskId, earliest, deadline, anchor) {
493
595
  * between the claim and the event (Batch submit). Neither can run past
494
596
  * its deadline legitimately (Batch rows have a deadline over a day ahead).
495
597
  */
496
- function interrupted(scheduler, store, job, row, nowMs, sleepNow) {
598
+ function olderThanLimits(scheduler, row, nowMs, sleepNow) {
497
599
  const dispatched = row.batchId ? undefined : dispatchedEvent(scheduler, row.taskId);
498
600
  const started = Date.parse(dispatched?.at ?? row.deadline ?? "");
499
601
  if (!Number.isFinite(started))
500
- return undefined;
501
- const limit = job.caps.commandTimeoutMs + job.caps.llmTimeoutMs + INTERRUPT_GRACE_MS;
602
+ return false;
603
+ const limit = runTimeAllowance(scheduler, row, dispatched);
604
+ if (limit === undefined)
605
+ return false;
502
606
  const wallAge = nowMs - started;
503
607
  const sleepThen = sleepAt(dispatched?.details.sleep);
504
608
  if (sleepThen && !sleepNow) {
505
609
  // 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
610
+ // the run may have slept. Wait for its deadline plus the limits, so a
507
611
  // host that reads the counter decides first, and a dead tick still
508
612
  // frees the job at the latest then.
509
613
  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;
614
+ return nowMs - (Number.isFinite(deadline) ? Math.max(deadline, started) : started) > limit;
518
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;
519
640
  if (row.batchId) {
520
641
  return store.transitionIf({ ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]) ? "submitted" : undefined;
521
642
  }
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" } });
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" } });
523
646
  return failed ? "failed" : undefined;
524
647
  }
525
648
  /**
@@ -576,7 +699,7 @@ export async function createJob(scheduler, input, opts = {}) {
576
699
  window: schedule.window,
577
700
  timeZone: schedule.timeZone,
578
701
  template: validTemplate(input.template),
579
- caps: validCaps(DEFAULT_JOB_CAPS, input.caps),
702
+ caps: validCaps({}, input.caps),
580
703
  notify: input.notify === undefined ? "every_run" : validNotify(input.notify),
581
704
  originHost: input.originHost,
582
705
  originCwd: input.originCwd,
@@ -586,7 +709,7 @@ export async function createJob(scheduler, input, opts = {}) {
586
709
  revision: 1,
587
710
  nextSeq: 1,
588
711
  consecutiveFailures: 0,
589
- retryUsed: false,
712
+ retryUsed: 0,
590
713
  };
591
714
  store.insertJob(job);
592
715
  try {
@@ -709,7 +832,7 @@ export async function resumeJob(scheduler, jobId, opts = {}) {
709
832
  ...job,
710
833
  status: "active",
711
834
  consecutiveFailures: 0,
712
- retryUsed: false,
835
+ retryUsed: 0,
713
836
  pauseReason: undefined,
714
837
  pausedAt: undefined,
715
838
  pauseNotifiedAt: undefined,
package/dist/notify.d.ts CHANGED
@@ -39,8 +39,17 @@ export interface OsNotifyOptions {
39
39
  export declare function osNotifyCommand(platform: NodeJS.Platform, title: string, body: string, opts?: OsNotifyOptions): OsNotifyCommand | null;
40
40
  /** Characters of result text shown in a notification body. */
41
41
  export declare const NOTIFY_PREVIEW_CHARS = 140;
42
+ /** `text` default-redacted, control characters removed, whitespace runs joined, trimmed. */
43
+ export declare function oneLine(text: string): string;
42
44
  /** `text` cut to `max` characters (code points) plus an ellipsis. */
43
45
  export declare function clip(text: string, max: number): string;
46
+ /**
47
+ * The first line of a task's error that has visible text once redacted,
48
+ * stripped of control characters and made one line, cut to `max`
49
+ * characters: the line every failure notice and channel message shows.
50
+ * Undefined when no line has visible text.
51
+ */
52
+ export declare function firstErrorLine(error: string | undefined, max?: number): string | undefined;
44
53
  /**
45
54
  * Notification title and body for a finished task: the task title (or id),
46
55
  * a redacted one-line preview of the result (completed) or the first line
package/dist/notify.js CHANGED
@@ -72,7 +72,8 @@ export function osNotifyCommand(platform, title, body, opts = {}) {
72
72
  }
73
73
  /** Characters of result text shown in a notification body. */
74
74
  export const NOTIFY_PREVIEW_CHARS = 140;
75
- function oneLine(text) {
75
+ /** `text` default-redacted, control characters removed, whitespace runs joined, trimmed. */
76
+ export function oneLine(text) {
76
77
  return stripControlChars(redactPrompt(text, undefined))
77
78
  .replace(/\s+/g, " ")
78
79
  .trim();
@@ -82,6 +83,20 @@ export function clip(text, max) {
82
83
  const chars = Array.from(text);
83
84
  return chars.length > max ? `${chars.slice(0, max).join("")}…` : text;
84
85
  }
86
+ /**
87
+ * The first line of a task's error that has visible text once redacted,
88
+ * stripped of control characters and made one line, cut to `max`
89
+ * characters: the line every failure notice and channel message shows.
90
+ * Undefined when no line has visible text.
91
+ */
92
+ export function firstErrorLine(error, max = NOTIFY_PREVIEW_CHARS) {
93
+ for (const line of (error ?? "").split(/\r?\n/)) {
94
+ const text = oneLine(line);
95
+ if (text)
96
+ return clip(text, max);
97
+ }
98
+ return undefined;
99
+ }
85
100
  function grams(receipt) {
86
101
  if (receipt && typeof receipt.actualCarbonGCo2 === "number") {
87
102
  return `${receipt.actualCarbonGCo2} gCO2e`;
@@ -100,10 +115,9 @@ export function taskNotificationContent(record) {
100
115
  const name = clip(oneLine(record.title ?? "") || record.taskId, 80);
101
116
  const show = `tidegap queue show ${record.taskId}`;
102
117
  if (record.status === "failed") {
103
- const firstErr = (record.error ?? "").split(/\r?\n/).find((l) => l.trim()) ?? "unknown error";
104
118
  return {
105
119
  title: `Tidegap: failed: ${name}`,
106
- body: `${clip(oneLine(firstErr), NOTIFY_PREVIEW_CHARS)}\n${show}`,
120
+ body: `${firstErrorLine(record.error) ?? "unknown error"}\n${show}`,
107
121
  };
108
122
  }
109
123
  const r = record.result;
@@ -10,8 +10,9 @@
10
10
  * - messages.batches.create — Batch API (50% off, 24h SLA)
11
11
  */
12
12
  import { normalizeModelName } from "../energy.js";
13
- import { conversation, ProviderRefusalError } from "./base.js";
13
+ import { conversation, permanentError, ProviderRefusalError } from "./base.js";
14
14
  import { budgetMaxTokens } from "./budget.js";
15
+ import { sdkFetch } from "./http.js";
15
16
  import { withLlmTimeout } from "./timeout.js";
16
17
  /**
17
18
  * Output ceiling when the caller sets none. The `claude-api` skill's
@@ -69,7 +70,7 @@ export class AnthropicAdapter {
69
70
  ...requestParams(model, prompt, { ...options, maxTokens }),
70
71
  metadata: options.metadata ? { user_id: undefined, ...options.metadata } : undefined,
71
72
  };
72
- const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => request ? client.messages.create(req, request) : client.messages.create(req)));
73
+ const res = (await withLlmTimeout(this.provider, options.timeoutMs, (request) => (request ? client.messages.create(req, request) : client.messages.create(req)), options.signal));
73
74
  assertNotRefused(res, model);
74
75
  return {
75
76
  text: messageText(res),
@@ -172,7 +173,7 @@ export class AnthropicAdapter {
172
173
  if (this.client)
173
174
  return this.client;
174
175
  if (!this.apiKey) {
175
- throw new Error("AnthropicAdapter: no API key. Set ANTHROPIC_API_KEY or pass { apiKey } to the constructor.");
176
+ throw permanentError("AnthropicAdapter: no API key. Set ANTHROPIC_API_KEY or pass { apiKey } to the constructor.");
176
177
  }
177
178
  let Anthropic;
178
179
  try {
@@ -183,12 +184,13 @@ export class AnthropicAdapter {
183
184
  : mod.Anthropic;
184
185
  }
185
186
  catch (err) {
186
- throw new Error("AnthropicAdapter: @anthropic-ai/sdk is not installed. Run `pnpm add @anthropic-ai/sdk`.");
187
+ throw permanentError("AnthropicAdapter: @anthropic-ai/sdk is not installed. Run `pnpm add @anthropic-ai/sdk`.");
187
188
  }
188
189
  // maxRetries: 0 — Tidegap's scheduler owns the retry policy
189
190
  // (retryWithBackoff); letting the SDK retry too multiplies attempts
190
- // and can double-bill ambiguous network errors.
191
- this.client = new Anthropic({ apiKey: this.apiKey, maxRetries: 0 });
191
+ // and can double-bill ambiguous network errors. The undici fetch takes
192
+ // the dispatcher of each call's time limit (http.ts).
193
+ this.client = new Anthropic({ apiKey: this.apiKey, maxRetries: 0, fetch: sdkFetch });
192
194
  return this.client;
193
195
  }
194
196
  }
@@ -56,10 +56,21 @@ export interface DispatchOptions {
56
56
  */
57
57
  origin?: DispatchOrigin;
58
58
  /**
59
- * Per-call time limit in ms (a job's `llmTimeoutMs`). Overrides the
60
- * adapter's own limit; adapters without one ignore it.
59
+ * The LLM time limit of this call in ms, or `"none"` for no limit (the
60
+ * scheduler resolves it when the run starts). Absent, the adapter applies
61
+ * its own default. For the `command` adapter it is the summarize step's
62
+ * limit.
61
63
  */
62
- timeoutMs?: number;
64
+ timeoutMs?: number | "none";
65
+ /** The command time limit of the shell step in ms, or `"none"` (`command` adapter only). */
66
+ commandTimeoutMs?: number | "none";
67
+ /**
68
+ * Aborted when the task is cancelled while it runs (the scheduler checks
69
+ * the row's status while it holds the run). The `command` and
70
+ * `claude-code` adapters stop the process group as at their time limit;
71
+ * the API adapters abort the request. The dispatch then rejects.
72
+ */
73
+ signal?: AbortSignal;
63
74
  /**
64
75
  * Per-call budget in USD (a job's `maxBudgetUsd`). `claude-code` passes it
65
76
  * as `--max-budget-usd`; API adapters cap `maxTokens` with it and refuse a
@@ -77,8 +88,8 @@ export interface DispatchOptions {
77
88
  command?: ProviderCallSpec["command"];
78
89
  /** The tool-less summarize step after the shell step (`command` adapter only). */
79
90
  summarize?: ProviderCallSpec["summarize"];
80
- /** The job's caps (`command` adapter only; other adapters get `timeoutMs` and `maxBudgetUsd`). */
81
- caps?: JobCaps;
91
+ /** The job's output and budget caps (`command` adapter only; other adapters get `timeoutMs` and `maxBudgetUsd`). */
92
+ caps?: Partial<JobCaps>;
82
93
  /**
83
94
  * A line the run printed while it runs, already scrubbed of secrets (the
84
95
  * `command` adapter calls it). The scheduler records it as a `progress`
@@ -164,22 +175,42 @@ export interface DispatchResult {
164
175
  details?: RunDetails;
165
176
  }
166
177
  /**
167
- * An error the scheduler must not retry: the call may have done work that
168
- * must not run twice (a job's shell step), or retrying cannot help (a
178
+ * An error the call must not resend at once (`retryWithBackoff`): the call
179
+ * may have done work (a shell step that ran), or resending cannot help (a
169
180
  * budget the input alone exceeds). `details` go on the `failed` event.
181
+ * `permanent` is for the retry policy of the task: a retry cannot fix it (a
182
+ * refusal, missing setup, a request the provider rejects), so the task
183
+ * fails at once instead of trying again later.
170
184
  */
171
185
  export declare class NonRetryableError extends Error {
172
186
  readonly nonRetryable = true;
173
187
  readonly details?: RunDetails;
174
- constructor(message: string, details?: RunDetails);
188
+ readonly permanent: boolean;
189
+ /** Set when a tick's stop ended the run (`run`) or its Batch submit (`batch_submit`); `classifyFailure` reads it. */
190
+ readonly interrupted?: "run" | "batch_submit";
191
+ constructor(message: string, details?: RunDetails, opts?: {
192
+ permanent?: boolean;
193
+ interrupted?: "run" | "batch_submit";
194
+ });
175
195
  }
196
+ /** A {@link NonRetryableError} that a retry of the task cannot fix: missing setup, a refusal, a rejected request. */
197
+ export declare function permanentError(message: string, details?: RunDetails): NonRetryableError;
198
+ /**
199
+ * The error of an HTTP answer that is not OK, for an adapter that calls
200
+ * `fetch` itself: a request the provider rejects ({@link isPermanentStatus})
201
+ * is permanent; anything else is a plain error, which the retry policy reads
202
+ * as transient. No status rides on it, so the call is not resent at once.
203
+ */
204
+ export declare function httpError(message: string, status: number): Error;
176
205
  /**
177
206
  * Thrown when the provider declined the request (Anthropic
178
207
  * `stop_reason: "refusal"`). The call returned HTTP 200, but its content
179
208
  * is not an answer, so it must not be recorded as a completed task.
180
- * Carries no HTTP status, so the scheduler does not retry it.
209
+ * Carries no HTTP status, so the scheduler does not resend it, and it is
210
+ * permanent: a later attempt would be declined too.
181
211
  */
182
212
  export declare class ProviderRefusalError extends Error {
213
+ readonly permanent = true;
183
214
  readonly provider: string;
184
215
  readonly model: string;
185
216
  /** Refusal category from `stop_details.category` ("cyber", "bio", ...), or null. */