@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/scheduler.js CHANGED
@@ -26,14 +26,15 @@ import { deferRetryAt } from "./providers/defer.js";
26
26
  import { postponeOptions, resolveLimitReset, resolvePostpone, taskProvider, writeLimitResetHint, } from "./postpone.js";
27
27
  import { candidateId, parseCandidates, previewRouting, scoreCandidates, } from "./routing.js";
28
28
  import { capHistory, deriveTitle, displayTitle, isRepeating, taskActions, taskHistory } from "./history.js";
29
- import { BATCH_SUBMIT_INTERRUPTED_ERROR, JOB_INTERRUPTED_ERROR } from "./jobs.js";
30
- import { DEFAULT_JOB_CAPS } from "./types.js";
29
+ import { BATCH_SUBMIT_INTERRUPTED_ERROR, JOB_CAPS_KEYS, JOB_INTERRUPTED_ERROR } from "./jobs.js";
30
+ import { attemptNumber, CAPS_VERSION, capValueError, classifyFailure, failureFactsOf, finalFailureError, isRetryableFailure, loadRunLimitSettings, planRetry, resolveTaskRunLimits, retryPolicyOf, runLimitsDetails, taskRunLimitsView, } from "./run-limits.js";
31
31
  import { resolveQuotaDeadline } from "./quota.js";
32
+ import { tickDispatch } from "./readiness.js";
32
33
  import { redactBodyJson, redactPrompt } from "./redact.js";
33
34
  import { selectWindow } from "./select-window.js";
34
35
  import { loadOrCreateSigningKey, signReceipt, } from "./sign.js";
35
36
  import { TaskStore } from "./storage/sqlite.js";
36
- import { createProgressRecorder, eventDetails, impliedEventKind, } from "./task-events.js";
37
+ import { PROGRESS_BUSY_MS, createProgressRecorder, eventDetails, impliedEventKind, } from "./task-events.js";
37
38
  export const PENDING_STATUSES = ["queued", "scheduled"];
38
39
  export const UNFINISHED_STATUSES = ["queued", "scheduled", "submitted", "running"];
39
40
  const TERMINAL = new Set(["completed", "failed", "cancelled"]);
@@ -70,6 +71,10 @@ export class InvalidDeadlineError extends Error {
70
71
  this.name = "InvalidDeadlineError";
71
72
  }
72
73
  }
74
+ /** How often a held run's row is read for a cancel, or any other move off `running`, by another writer. */
75
+ const RUN_STATUS_CHECK_MS = 10_000;
76
+ /** The tick result of a run stopped because its task was cancelled. */
77
+ const STOPPED_RUN_ERROR = "task was cancelled while running; its run was stopped";
73
78
  export class Scheduler {
74
79
  feed;
75
80
  defaultRegionOption;
@@ -80,6 +85,8 @@ export class Scheduler {
80
85
  bodies = new Map();
81
86
  /** Rows a tick moved to `running` whose dispatch has not settled (KTD12), and what each is doing. */
82
87
  held = new Map();
88
+ /** Failed attempts per task without a ledger, where no `attempt_failed` event is stored to count. */
89
+ attemptsWithoutLedger = new Map();
83
90
  store;
84
91
  // Mutable: a single load failure disables signing for the rest of
85
92
  // this scheduler instance (see `getSigningKey`).
@@ -91,6 +98,8 @@ export class Scheduler {
91
98
  limitReset;
92
99
  actor;
93
100
  sleepCounter;
101
+ lockedTick;
102
+ runLimitSettings;
94
103
  defaultRegion() {
95
104
  const option = this.defaultRegionOption;
96
105
  return typeof option === "function" ? option() : option;
@@ -111,7 +120,30 @@ export class Scheduler {
111
120
  this.quotaConfig = opts.quotaConfig;
112
121
  this.limitReset = opts.limitReset;
113
122
  this.actor = opts.actor ?? "system";
123
+ this.lockedTick = opts.lockedTick;
114
124
  this.sleepCounter = opts.sleepCounter;
125
+ this.runLimitSettings = opts.runLimits ?? (() => loadRunLimitSettings());
126
+ }
127
+ /**
128
+ * The time limits a run of `spec` gets if it starts now: the stored
129
+ * values, then the settings, then the defaults. A settings read that
130
+ * throws gives the stored values and the defaults.
131
+ */
132
+ runLimitsFor(spec) {
133
+ return resolveTaskRunLimits(spec, this.settingsNow());
134
+ }
135
+ /** A task's time limits as views show them: the ones its newest run recorded, else the ones a run now gets. */
136
+ taskRunLimits(record, events = this.listTaskEvents(record.taskId)) {
137
+ return taskRunLimitsView(record.bodyJson, events, this.settingsNow());
138
+ }
139
+ /** The run-limit settings now; a reader that throws gives none (the stored values and the defaults apply). */
140
+ settingsNow() {
141
+ try {
142
+ return this.runLimitSettings();
143
+ }
144
+ catch {
145
+ return { values: {}, ignored: [] };
146
+ }
115
147
  }
116
148
  /**
117
149
  * Compute the current aggregate carbon-budget status (ROADMAP item 4)
@@ -438,6 +470,9 @@ export class Scheduler {
438
470
  if (typeof spec.prompt !== "string" || spec.prompt.length === 0) {
439
471
  throw new Error("enqueueProviderCall: spec.prompt must be a non-empty string");
440
472
  }
473
+ if (spec.caps !== undefined) {
474
+ spec = { ...spec, caps: checkedCaps(spec.caps, MODEL_CALL_CAPS_KEYS, "enqueueProviderCall") };
475
+ }
441
476
  const checked = checkedHandoff(spec, opts, "enqueueProviderCall");
442
477
  if (checked.tools !== undefined) {
443
478
  const toolsError = claudeCodeToolsError(checked.tools);
@@ -456,9 +491,11 @@ export class Scheduler {
456
491
  * an empty prompt) with `command.origin: "cli"` and no job id, planned
457
492
  * like any provider call. Only the CLI tick's command adapter runs it.
458
493
  * Checks: a command of 1 to 32,000 characters, an existing absolute
459
- * folder, positive caps, and the result path rules. `enqueueProviderCall`
460
- * keeps refusing `command`, and `retryTask` refuses these rows: running a
461
- * shell command again is the user's call.
494
+ * folder, valid caps, and the result path rules. Only the caps the caller
495
+ * set are stored; the time limits not set come from the settings when the
496
+ * run starts. `enqueueProviderCall` keeps refusing `command`, and
497
+ * `retryTask` refuses these rows: running a shell command again is the
498
+ * user's call.
462
499
  */
463
500
  async enqueueCommandTask(task, opts = {}) {
464
501
  if (typeof task.run !== "string" || task.run.trim() === "") {
@@ -470,15 +507,7 @@ export class Scheduler {
470
507
  const cwdError = handoffCwdError(task.cwd, "command");
471
508
  if (cwdError)
472
509
  throw new Error(`enqueueCommandTask: ${cwdError}`);
473
- const caps = { ...DEFAULT_JOB_CAPS };
474
- for (const [key, value] of Object.entries(task.caps ?? {})) {
475
- if (!(key in DEFAULT_JOB_CAPS))
476
- throw new Error(`enqueueCommandTask: unknown cap "${key}"`);
477
- if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
478
- throw new Error(`enqueueCommandTask: cap ${key} must be a positive number`);
479
- }
480
- caps[key] = value;
481
- }
510
+ const caps = checkedCaps(task.caps, JOB_CAPS_KEYS, "enqueueCommandTask");
482
511
  if (task.resultPath !== undefined) {
483
512
  const pathError = resultPathError(task.resultPath, { cwd: task.cwd, originCwd: opts.originCwd });
484
513
  if (pathError)
@@ -583,6 +612,7 @@ export class Scheduler {
583
612
  let dispatched = 0;
584
613
  let failed = 0;
585
614
  let deferred = 0;
615
+ let retrying = 0;
586
616
  let inspected = 0;
587
617
  // Provider and model → retryAt after its first defer this tick: later due
588
618
  // tasks on that provider and model defer to the same time without a
@@ -594,9 +624,16 @@ export class Scheduler {
594
624
  dispatched++;
595
625
  else if (entry.status === "deferred")
596
626
  deferred++;
627
+ else if (entry.status === "retrying")
628
+ retrying++;
597
629
  else
598
630
  failed++;
599
631
  };
632
+ // ---- (0) Rows a dead tick left running, under the tick lock only ----
633
+ for (const entry of this.freeDeadTickRuns()) {
634
+ results.push(await this.planRetryWindow(entry));
635
+ count(entry);
636
+ }
600
637
  // ---- (1) Batch-submit sweep, BEFORE the due sweep ----
601
638
  // A batch-eligible task's deferral mechanism IS the Batch API: the
602
639
  // provider runs it within its own 24h SLA and picks the execution
@@ -657,10 +694,8 @@ export class Scheduler {
657
694
  batchSubmitted++;
658
695
  submittedThisTick.add(record.taskId);
659
696
  }
660
- else if (entry.status === "completed")
661
- dispatched++;
662
697
  else
663
- failed++;
698
+ count(entry);
664
699
  }
665
700
  // ---- (2) Due sweep (sync provider calls) ----
666
701
  const now = Date.now();
@@ -755,12 +790,10 @@ export class Scheduler {
755
790
  inspected++;
756
791
  const entry = await this.holding(record, "batch_poll", () => this.pollBatch(record, adapters));
757
792
  results.push(entry);
758
- if (entry.status === "completed")
759
- dispatched++;
760
- else if (entry.status === "submitted")
793
+ if (entry.status === "submitted")
761
794
  batchPolled++;
762
795
  else
763
- failed++;
796
+ count(entry);
764
797
  }
765
798
  // ---- (4) Aggregate carbon-budget alert (ROADMAP item 4) ----
766
799
  // After every receipt this tick wrote (sync due-sweep + batch poll),
@@ -781,6 +814,7 @@ export class Scheduler {
781
814
  batchSubmitted,
782
815
  batchPolled,
783
816
  deferred,
817
+ retrying,
784
818
  };
785
819
  }
786
820
  /**
@@ -983,7 +1017,9 @@ export class Scheduler {
983
1017
  /**
984
1018
  * The progress callback of one run: the lines an adapter reports become
985
1019
  * `progress` events (actor `tick`) within the core caps. None without a
986
- * ledger. A failed write costs its line and one warning, never the run.
1020
+ * ledger. Each write waits at most `PROGRESS_BUSY_MS` for a busy ledger.
1021
+ * A failed write costs its line, never the run; the first failure of a
1022
+ * task logs one warning that says later failed lines are dropped too.
987
1023
  */
988
1024
  progressFor(taskId) {
989
1025
  const store = this.store;
@@ -992,16 +1028,20 @@ export class Scheduler {
992
1028
  let warned = false;
993
1029
  return createProgressRecorder((details) => {
994
1030
  try {
995
- store.recordEvent(taskId, { kind: "progress", actor: "tick", details });
1031
+ store.recordEvent(taskId, { kind: "progress", actor: "tick", details }, { busyMs: PROGRESS_BUSY_MS });
996
1032
  }
997
1033
  catch (err) {
998
1034
  if (warned)
999
1035
  return;
1000
1036
  warned = true;
1001
1037
  // eslint-disable-next-line no-console
1002
- console.warn(`[tidegap/scheduler] task ${taskId}: could not record a progress event: ${describeErr(err)}`);
1038
+ console.warn(`[tidegap/scheduler] task ${taskId}: could not record a progress event (this and later failed lines are dropped): ${describeErr(err)}`);
1003
1039
  }
1004
- }, { existing: () => store.listTaskEvents(taskId).filter((e) => e.kind === "progress").length });
1040
+ }, { existing: () => store.countTaskEvents(taskId, "progress") });
1041
+ }
1042
+ /** `{ tick }` for a `dispatched` event under the tick lock; else nothing. */
1043
+ tickDetails() {
1044
+ return this.lockedTick ? { tick: this.lockedTick.tick } : {};
1005
1045
  }
1006
1046
  /** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
1007
1047
  sleepDetails() {
@@ -1582,56 +1622,57 @@ export class Scheduler {
1582
1622
  });
1583
1623
  }
1584
1624
  /**
1585
- * Re-dispatch a failed task. Useful when the original failure was a
1586
- * transient provider error (rate-limit, 5xx) and the underlying
1587
- * spec is still valid. Only `failed` tasks are eligible; throws
1588
- * otherwise.
1625
+ * Retry a failed task by hand, starting a new attempt count. With a ready
1626
+ * adapter for the task's provider in `adapters`, the call runs now and
1627
+ * its result comes back. Otherwise, and always for a `command` or
1628
+ * `claude-code` task, which only the tidegap tick runs, the task is due
1629
+ * now ({@link retryLater}) and the next tick runs it. A manual retry
1630
+ * ignores the deadline: the user asked for it. Throws for a task that is
1631
+ * not failed, stopped during its Batch submit, closure-based or a run of
1632
+ * a job.
1589
1633
  */
1590
1634
  async retryTask(taskId, adapters, opts = {}) {
1591
1635
  const record = this.refreshTask(taskId);
1592
1636
  if (!record) {
1593
- throw new Error(`retryTask: task ${JSON.stringify(taskId)} not found`);
1594
- }
1595
- if (record.status !== "failed") {
1596
- throw new Error(`retryTask: task ${taskId} has status ${record.status}; retry is only valid on failed tasks`);
1637
+ throw new TaskActionError(`retryTask: task ${JSON.stringify(taskId)} not found`);
1597
1638
  }
1598
- if (record.error === BATCH_SUBMIT_INTERRUPTED_ERROR) {
1599
- // Before the job-run refusal: the job does not retry this run either.
1600
- throw new TaskActionError(`retryTask: task ${taskId} stopped during its Batch submit, and the provider may have accepted the batch; ` +
1601
- "a retry could run and bill it twice, so check the provider's batch list and enqueue the task again only if no batch exists");
1639
+ retryRefusal("retryTask", record);
1640
+ const provider = taskProvider(record);
1641
+ const adapter = provider ? adapters[provider] : undefined;
1642
+ if (provider === "command" || provider === "claude-code" || !adapter?.ready) {
1643
+ const queued = this.retryLater(taskId, opts);
1644
+ return { taskId, status: "scheduled", scheduledFor: queued.scheduledFor };
1602
1645
  }
1603
- if (!record.bodyJson) {
1604
- throw new Error(`retryTask: task ${taskId} is closure-based; only provider-call tasks can be retried`);
1605
- }
1606
- if (record.jobId) {
1607
- // The job sweep already recorded this failure and queued a retry or
1608
- // the next run; a second run of the same slot would go unrecorded.
1609
- throw new TaskActionError(`retryTask: task ${taskId} is a run of job ${record.jobId}, which retries failed runs itself; use run now on the job`);
1610
- }
1611
- if (taskProvider(record) === "command") {
1612
- // A one-off shell command: running it again is the user's call.
1613
- throw new TaskActionError(`retryTask: task ${taskId} ran a shell command, which is never run again by a retry; ` +
1614
- "queue it again with tidegap queue add --runner command");
1615
- }
1616
- const next = {
1617
- ...record,
1618
- status: "scheduled",
1619
- scheduledFor: new Date().toISOString(),
1620
- completedAt: undefined,
1621
- error: undefined,
1622
- // A retry re-dispatches synchronously via the due path below — clear
1623
- // any stale batchId from a prior batch attempt so the completed row
1624
- // no longer points at a dead/failed batch.
1625
- batchId: undefined,
1626
- };
1627
1646
  // Row-level claim: don't double-dispatch if a concurrent tick in
1628
1647
  // another process grabbed the freshly re-scheduled row first.
1629
- if (!this.writeIf(record, next, ["failed"], { kind: "rescheduled", actor: opts.actor, details: { reason: "retry" } }) ||
1630
- (this.store && !this.store.claimScheduled(taskId))) {
1631
- throw new Error(`task ${taskId} was just claimed by another process (racing tick?)`);
1648
+ if (!this.writeIf(record, retryWrite(record), ["failed"], retryEvent(opts)) || (this.store && !this.store.claimScheduled(taskId))) {
1649
+ throw new TaskActionError(`retryTask: task ${taskId} was just claimed by another process (racing tick?)`);
1632
1650
  }
1651
+ this.attemptsWithoutLedger.delete(taskId);
1633
1652
  return await this.dispatchProviderCall(record, adapters);
1634
1653
  }
1654
+ /**
1655
+ * Retry a failed task on the next tick: `failed → scheduled`, due now, its
1656
+ * earliest start, error and completion time cleared, with a `rescheduled`
1657
+ * event (`reason: retry`), which starts a new attempt count. A write
1658
+ * only, for a process that does not dispatch (the CLI, the page's server)
1659
+ * or holds no adapter for the task. A manual retry ignores the deadline.
1660
+ * Throws {@link TaskActionError} for a task that is not failed, stopped
1661
+ * during its Batch submit, closure-based or a run of a job, and when
1662
+ * another process moved the row first.
1663
+ */
1664
+ retryLater(taskId, opts = {}) {
1665
+ const record = this.refreshTask(taskId);
1666
+ if (!record)
1667
+ throw new TaskActionError(`retryLater: task ${JSON.stringify(taskId)} not found`);
1668
+ retryRefusal("retryLater", record);
1669
+ this.clearPendingTimer(taskId);
1670
+ if (!this.writeIf(record, retryWrite(record), ["failed"], retryEvent(opts))) {
1671
+ throw new TaskActionError(`retryLater: task ${taskId} was just claimed by another process (racing tick?)`);
1672
+ }
1673
+ this.attemptsWithoutLedger.delete(taskId);
1674
+ return record;
1675
+ }
1635
1676
  /**
1636
1677
  * Pure read-only planning helper: compute the scheduled window and
1637
1678
  * carbon receipt that the same call to `enqueueProviderCall` would
@@ -1743,11 +1784,239 @@ export class Scheduler {
1743
1784
  this.held.delete(record.taskId);
1744
1785
  }
1745
1786
  }
1787
+ /**
1788
+ * Watch a held row while its run is in flight: read its status every
1789
+ * {@link RUN_STATUS_CHECK_MS} and abort the returned signal once another
1790
+ * writer moved it off `running` (a cancel, or a `failed` written
1791
+ * elsewhere), so a retry can never overlap the run; `end` stops the watch
1792
+ * when the run settles.
1793
+ */
1794
+ cancelWatch(taskId) {
1795
+ const controller = new AbortController();
1796
+ const timer = setInterval(() => {
1797
+ let status;
1798
+ try {
1799
+ status = (this.store?.get(taskId) ?? this.tasks.get(taskId))?.status;
1800
+ }
1801
+ catch {
1802
+ return; // a busy ledger: the next check reads it again
1803
+ }
1804
+ if (status === undefined || status === "running")
1805
+ return;
1806
+ clearInterval(timer);
1807
+ controller.abort();
1808
+ }, RUN_STATUS_CHECK_MS);
1809
+ timer.unref?.();
1810
+ return { signal: controller.signal, end: () => clearInterval(timer) };
1811
+ }
1812
+ /**
1813
+ * A run the watch stopped because its row left `running`. A cancel keeps
1814
+ * the row, and its event gains `stopped_run: true`; any other move (a row
1815
+ * failed elsewhere) keeps what that writer wrote. Nothing else is written,
1816
+ * as for a late result; the writer that moved the row settled its series.
1817
+ */
1818
+ stoppedRun(record) {
1819
+ let status = "cancelled";
1820
+ try {
1821
+ status = this.store?.get(record.taskId)?.status ?? record.status;
1822
+ }
1823
+ catch {
1824
+ // A busy ledger: report it as the cancel the watch most likely saw.
1825
+ }
1826
+ record.status = status;
1827
+ if (status !== "cancelled") {
1828
+ // eslint-disable-next-line no-console
1829
+ console.warn(`[tidegap/scheduler] task ${record.taskId} was ${status} while running; its run was stopped`);
1830
+ return { taskId: record.taskId, status: "failed", error: `task was ${status} while running; its run was stopped` };
1831
+ }
1832
+ try {
1833
+ this.store?.annotateEvent(record.taskId, "cancelled", { stopped_run: true });
1834
+ }
1835
+ catch (err) {
1836
+ // eslint-disable-next-line no-console
1837
+ console.warn(`[tidegap/scheduler] task ${record.taskId}: could not note the stopped run: ${describeErr(err)}`);
1838
+ }
1839
+ // eslint-disable-next-line no-console
1840
+ console.warn(`[tidegap/scheduler] task ${record.taskId} was cancelled while running; its run was stopped`);
1841
+ return { taskId: record.taskId, status: "failed", error: STOPPED_RUN_ERROR };
1842
+ }
1843
+ /**
1844
+ * The retry funnel: every provider-call run that fails ends here. A
1845
+ * one-off row whose failure class may retry, with retries left and a next
1846
+ * start that fits before its deadline, goes back to `scheduled`
1847
+ * (compare-and-set on `expected`, `running` by default) with an
1848
+ * `attempt_failed` event: `notBefore` is the next start, the fallback time
1849
+ * one minute later, the deadline unchanged, the estimate, the run-now mark
1850
+ * and any batch id cleared. Anything else fails for good: `failed`, with
1851
+ * `attempts` and `failure_class` on the event and `(after N attempts)` on
1852
+ * the error when more than one ran. A job row always fails for good (the
1853
+ * job sweep makes its retry row). The series rolls on a final failure
1854
+ * only. Synchronous; an async caller then plans the next attempt's window
1855
+ * ({@link planRetryWindow}).
1856
+ */
1857
+ failRun(record, failure, expected = ["running"]) {
1858
+ const now = Date.now();
1859
+ const failureClass = classifyFailure(failure.facts);
1860
+ const attempt = this.store ? attemptNumber(this.listTaskEvents(record.taskId)) : (this.attemptsWithoutLedger.get(record.taskId) ?? 0) + 1;
1861
+ let spec;
1862
+ try {
1863
+ spec = JSON.parse(record.bodyJson ?? "null");
1864
+ }
1865
+ catch {
1866
+ spec = undefined;
1867
+ }
1868
+ const deadlineMs = record.deadline ? Date.parse(record.deadline) : Number.NaN;
1869
+ const notBeforeMs = record.notBefore ? Date.parse(record.notBefore) : Number.NaN;
1870
+ let plan;
1871
+ if (!record.jobId && typeof spec?.provider === "string" && isRetryableFailure(failureClass)) {
1872
+ plan = planRetry({
1873
+ attempt,
1874
+ ...retryPolicyOf(this.runLimitsFor(spec)),
1875
+ failedAt: now,
1876
+ ...(Number.isFinite(deadlineMs) ? { deadline: deadlineMs } : {}),
1877
+ ...(Number.isFinite(notBeforeMs) ? { notBefore: notBeforeMs } : {}),
1878
+ });
1879
+ }
1880
+ const firstLine = failure.error.split("\n")[0].slice(0, 300);
1881
+ if (plan && "retryAt" in plan) {
1882
+ const retryAt = new Date(plan.retryAt).toISOString();
1883
+ const fallback = Number.isFinite(deadlineMs) ? Math.min(plan.retryAt + MINUTE_MS, deadlineMs) : plan.retryAt + MINUTE_MS;
1884
+ const next = {
1885
+ ...record,
1886
+ status: "scheduled",
1887
+ notBefore: retryAt,
1888
+ scheduledFor: new Date(fallback).toISOString(),
1889
+ estimatedCarbonGCo2: undefined,
1890
+ intensitySource: undefined,
1891
+ batchId: undefined,
1892
+ completedAt: undefined,
1893
+ error: undefined,
1894
+ };
1895
+ const event = {
1896
+ kind: "attempt_failed",
1897
+ details: { ...failure.details, attempt, failure_class: failureClass, error: firstLine, retry_at: retryAt },
1898
+ };
1899
+ if (!this.writeIf(record, next, expected, event)) {
1900
+ return { taskId: record.taskId, status: "failed", error: `task was ${record.status} while running; retry dropped` };
1901
+ }
1902
+ if (!this.store)
1903
+ this.attemptsWithoutLedger.set(record.taskId, attempt);
1904
+ return { taskId: record.taskId, status: "retrying", retryAt, error: failure.error };
1905
+ }
1906
+ // The Batch submit marker stays exact: retry refusals compare the error with it.
1907
+ const error = failureClass === "batch_submit_interrupted" ? failure.error : finalFailureError(failure.error, attempt, plan && "final" in plan ? plan.final : undefined);
1908
+ if (!failure.keepSeries)
1909
+ this.rollSeries(record);
1910
+ this.attemptsWithoutLedger.delete(record.taskId);
1911
+ this.writeIf(record, { ...record, status: "failed", completedAt: new Date(now).toISOString(), error }, expected, {
1912
+ kind: "failed",
1913
+ details: { ...failure.details, attempts: attempt, failure_class: failureClass },
1914
+ });
1915
+ return { taskId: record.taskId, status: "failed", error };
1916
+ }
1917
+ /** {@link failRun} for a thrown error: its facts, and its run details (`steps`, `stopped_by`, `truncated`) for the event. */
1918
+ failRunWith(record, err) {
1919
+ const details = runDetails(err?.details);
1920
+ return this.failRun(record, { error: err instanceof Error ? err.message : String(err), facts: failureFactsOf(err), details });
1921
+ }
1922
+ /**
1923
+ * After {@link failRun} queued another attempt: plan it at the cleanest
1924
+ * hour between its earliest start and its deadline. Best effort: without
1925
+ * a deadline, or when the forecast fails, the row keeps its fallback time
1926
+ * and `replanSweep` plans it before a later tick.
1927
+ */
1928
+ async planRetryWindow(entry) {
1929
+ if (entry.status !== "retrying")
1930
+ return entry;
1931
+ const record = this.tasks.get(entry.taskId);
1932
+ if (!record?.deadline)
1933
+ return entry;
1934
+ try {
1935
+ await this.scheduleProviderCall(entry.taskId, new Date(record.deadline));
1936
+ }
1937
+ catch (err) {
1938
+ // eslint-disable-next-line no-console
1939
+ console.warn(`[tidegap/scheduler] could not plan the next attempt of ${entry.taskId}: ${describeErr(err)}; replanSweep plans it later`);
1940
+ }
1941
+ return entry;
1942
+ }
1943
+ /**
1944
+ * The tick-lock rule for a `running` row, shared by the head of a locked
1945
+ * tick and the job sweep: true when the run was dispatched under another
1946
+ * locked tick whose process is gone, false when that tick is this one or
1947
+ * its process still runs. Undefined when this scheduler holds no lock, the
1948
+ * row's newest event (progress lines aside) is not a dispatch with tick
1949
+ * details (no locked tick ran it, or the row moved on since), or the host
1950
+ * cannot tell whether that tick's process runs: the run may be live.
1951
+ */
1952
+ deadTickRun(row) {
1953
+ const locked = this.lockedTick;
1954
+ if (!locked)
1955
+ return undefined;
1956
+ const tick = tickDispatch(this.listTaskEvents(row.taskId))?.tick;
1957
+ if (!tick)
1958
+ return undefined;
1959
+ if (tick.id === locked.tick.id)
1960
+ return false;
1961
+ try {
1962
+ const running = locked.isRunning(tick);
1963
+ return running === undefined ? undefined : !running;
1964
+ }
1965
+ catch {
1966
+ return undefined;
1967
+ }
1968
+ }
1969
+ /**
1970
+ * The head of a locked tick, before any sweep claims a row: a one-off
1971
+ * `running` row whose run a dead tick dispatched ({@link deadTickRun})
1972
+ * fails as interrupted through the retry funnel (another attempt when the
1973
+ * policy allows it), and a Batch row with its batch id goes back to
1974
+ * `submitted` for the poll sweep. Compare-and-set from `running`. Job rows
1975
+ * are the job sweep's; rows this scheduler holds are live. Returns the
1976
+ * entries of the rows it failed or queued again.
1977
+ */
1978
+ freeDeadTickRuns() {
1979
+ if (!this.lockedTick || !this.store)
1980
+ return [];
1981
+ let rows;
1982
+ try {
1983
+ rows = this.store.list({ status: "running" });
1984
+ }
1985
+ catch (err) {
1986
+ // eslint-disable-next-line no-console
1987
+ console.warn(`[tidegap/scheduler] tick: could not read running rows: ${describeErr(err)}; no dead tick's row freed this round`);
1988
+ return [];
1989
+ }
1990
+ const out = [];
1991
+ for (const row of rows) {
1992
+ if (row.jobId || this.held.has(row.taskId))
1993
+ continue;
1994
+ try {
1995
+ if (this.deadTickRun(row) !== true)
1996
+ continue;
1997
+ const record = this.cacheRow(row);
1998
+ if (row.batchId) {
1999
+ this.writeIf(record, { ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
2000
+ continue;
2001
+ }
2002
+ const entry = this.failRun(record, { error: JOB_INTERRUPTED_ERROR, facts: { interrupted: "run" }, details: { reason: "interrupted" } });
2003
+ if (entry.status === "retrying" || record.status === "failed")
2004
+ out.push(entry);
2005
+ }
2006
+ catch (err) {
2007
+ // eslint-disable-next-line no-console
2008
+ console.warn(`[tidegap/scheduler] tick: could not free ${row.taskId} of a dead tick: ${describeErr(err)}; skipping this round`);
2009
+ }
2010
+ }
2011
+ return out;
2012
+ }
1746
2013
  /**
1747
2014
  * A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
1748
2015
  * scheduler moved to `running` in a tick whose dispatch has not settled,
1749
2016
  * by what the row was doing:
1750
- * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`);
2017
+ * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`)
2018
+ * through the retry funnel: a one-off row with retries left is
2019
+ * queued again, its window planned before a later tick;
1751
2020
  * - a Batch poll goes back to `submitted` with its `batchId`: the batch
1752
2021
  * is live at the provider, and the next tick polls it again;
1753
2022
  * - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
@@ -1756,8 +2025,8 @@ export class Scheduler {
1756
2025
  * keeps its status; rows another process holds, or a crashed tick
1757
2026
  * stranded, are not touched (the job sweep frees job runs, and the next
1758
2027
  * tick a Batch poll past its deadline: `freeStrandedPolls`). Synchronous, for
1759
- * a process about to exit. Returns the ids it failed; a second call
1760
- * changes nothing.
2028
+ * a process about to exit. Returns the ids it failed or queued again; a
2029
+ * second call changes nothing.
1761
2030
  */
1762
2031
  failHeldRuns() {
1763
2032
  const failed = [];
@@ -1766,12 +2035,12 @@ export class Scheduler {
1766
2035
  this.writeIf(record, { ...record, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
1767
2036
  continue;
1768
2037
  }
1769
- this.rollSeries(record);
1770
2038
  const submit = phase === "batch_submit";
1771
2039
  const details = { reason: "interrupted", ...(submit ? { phase } : {}), ...(record.jobId ? { job_id: record.jobId } : {}) };
1772
2040
  const error = submit ? BATCH_SUBMIT_INTERRUPTED_ERROR : JOB_INTERRUPTED_ERROR;
1773
- const next = { ...record, status: "failed", completedAt: new Date().toISOString(), error };
1774
- if (this.writeIf(record, next, ["running"], { kind: "failed", details }))
2041
+ // The next attempt keeps its fallback time; replanSweep plans it before a later tick.
2042
+ const entry = this.failRun(record, { error, facts: { interrupted: submit ? "batch_submit" : "run" }, details });
2043
+ if (entry.status === "retrying" || record.status === "failed")
1775
2044
  failed.push(record.taskId);
1776
2045
  }
1777
2046
  this.held.clear();
@@ -2185,13 +2454,10 @@ export class Scheduler {
2185
2454
  }
2186
2455
  catch (err) {
2187
2456
  const msg = err instanceof Error ? err.message : String(err);
2188
- this.failTask(record.taskId, new Error(`tick: corrupt body_json: ${msg}`));
2189
- return { taskId: record.taskId, status: "failed", error: msg };
2457
+ return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2190
2458
  }
2191
2459
  if (!spec || spec.type !== "provider_call") {
2192
- const msg = `tick: body is not a provider_call spec`;
2193
- this.failTask(record.taskId, new Error(msg));
2194
- return { taskId: record.taskId, status: "failed", error: msg };
2460
+ return this.failRun(record, { error: "tick: body is not a provider_call spec", facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2195
2461
  }
2196
2462
  // Cross-provider routing fallback (ROADMAP item 1): when a routing
2197
2463
  // decision is attached, dispatch the highest-scoring candidate whose
@@ -2209,9 +2475,7 @@ export class Scheduler {
2209
2475
  if (!picked) {
2210
2476
  const msg = `tick: no configured/ready adapter for any routing candidate ` +
2211
2477
  `(${routing.considered.map((c) => candidateId(c)).join(", ")})`;
2212
- this.rollSeries(record);
2213
- this.failTask(record.taskId, new Error(msg));
2214
- return { taskId: record.taskId, status: "failed", error: msg };
2478
+ return this.failRun(record, { error: msg, facts: { permanent: true } }, UNFINISHED_STATUSES);
2215
2479
  }
2216
2480
  const pickedId = candidateId(picked);
2217
2481
  if (pickedId !== routing.chosen) {
@@ -2231,21 +2495,27 @@ export class Scheduler {
2231
2495
  // No rollover: a missing adapter is a skip (OpenClaw restores the row
2232
2496
  // to `scheduled`), and a successor would run beside the occurrence.
2233
2497
  // A retry that completes rolls the series then.
2234
- this.failTask(record.taskId, new Error(msg));
2235
- return { taskId: record.taskId, status: "failed", error: msg };
2498
+ return this.failRun(record, { error: msg, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2236
2499
  }
2237
2500
  const deferKey = deferKeyOf(spec);
2238
2501
  const earlier = deferrals?.get(deferKey);
2239
2502
  if (earlier) {
2240
2503
  return this.deferTask(record, earlier, `${spec.provider}: deferred with an earlier task this tick until ${earlier.toISOString()}`);
2241
2504
  }
2505
+ const limits = this.runLimitsFor(spec);
2242
2506
  let stillOurs = true;
2243
2507
  try {
2244
2508
  // The row was claimed (`running`) or, without a store, is ours. A
2245
2509
  // cancel that landed after the claim wins: do not make the call.
2246
2510
  stillOurs = this.writeIf(record, { ...record, status: "running" }, ["running", "scheduled"], {
2247
2511
  kind: "dispatched",
2248
- details: { provider: spec.provider, model: spec.model, ...this.sleepDetails() },
2512
+ details: {
2513
+ provider: spec.provider,
2514
+ model: spec.model,
2515
+ limits: runLimitsDetails(limits),
2516
+ ...this.sleepDetails(),
2517
+ ...this.tickDetails(),
2518
+ },
2249
2519
  });
2250
2520
  }
2251
2521
  catch (err) {
@@ -2270,6 +2540,7 @@ export class Scheduler {
2270
2540
  // Lines the run reports while it runs (the command adapter's output);
2271
2541
  // nothing is written once the call settled.
2272
2542
  const progress = this.progressFor(record.taskId);
2543
+ const watch = this.cancelWatch(record.taskId);
2273
2544
  try {
2274
2545
  // Batch routing (deadline > 24h) is handled by the dedicated
2275
2546
  // submit/poll sweeps in tick(); by the time a task reaches this
@@ -2281,21 +2552,24 @@ export class Scheduler {
2281
2552
  messages: spec.messages,
2282
2553
  ...(spec.tools !== undefined ? { tools: spec.tools } : {}),
2283
2554
  ...dispatchOrigin(record, spec),
2284
- ...jobDispatchOptions(record, spec),
2555
+ ...jobDispatchOptions(record, spec, limits),
2285
2556
  ...(progress ? { onProgress: (line) => progress.onLine(line), onProgressEnd: () => progress.close() } : {}),
2286
- })).finally(() => progress?.close());
2557
+ signal: watch.signal,
2558
+ }), watch.signal).finally(() => progress?.close());
2287
2559
  }
2288
2560
  catch (err) {
2561
+ if (watch.signal.aborted)
2562
+ return this.stoppedRun(record);
2289
2563
  const msg = err instanceof Error ? err.message : String(err);
2290
2564
  const retryAt = deferRetryAt(err);
2291
2565
  if (retryAt) {
2292
2566
  deferrals?.set(deferKey, retryAt);
2293
2567
  return this.deferTask(record, retryAt, msg);
2294
2568
  }
2295
- this.rollSeries(record);
2296
- const details = runDetails(err?.details);
2297
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"], details ? { kind: "failed", details } : undefined);
2298
- return { taskId: record.taskId, status: "failed", error: msg };
2569
+ return this.planRetryWindow(this.failRunWith(record, err));
2570
+ }
2571
+ finally {
2572
+ watch.end();
2299
2573
  }
2300
2574
  const durationMs = Date.now() - start;
2301
2575
  // The task may have been cancelled while the provider call was in
@@ -2461,10 +2735,8 @@ export class Scheduler {
2461
2735
  const retryMs = retryAt.getTime();
2462
2736
  const capMs = Date.parse(record.enqueuedAt) + DEFER_CAP_MS;
2463
2737
  if (retryMs + NOT_BEFORE_SPAN_MS > capMs) {
2464
- const error = `${message}; limit did not reset before the 8-day cap`;
2465
- this.rollSeries(record);
2466
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error }, ["running"]);
2467
- return { taskId: record.taskId, status: "failed", error };
2738
+ // A later attempt would meet the same cap: permanent.
2739
+ return this.failRun(record, { error: `${message}; limit did not reset before the 8-day cap`, facts: { permanent: true } });
2468
2740
  }
2469
2741
  const next = {
2470
2742
  ...record,
@@ -2502,8 +2774,7 @@ export class Scheduler {
2502
2774
  }
2503
2775
  catch (err) {
2504
2776
  const msg = err instanceof Error ? err.message : String(err);
2505
- this.failTask(record.taskId, new Error(`tick: corrupt body_json: ${msg}`));
2506
- return { taskId: record.taskId, status: "failed", error: msg };
2777
+ return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2507
2778
  }
2508
2779
  const adapter = adapters[spec.provider];
2509
2780
  const dispatchBatch = adapter?.dispatchBatch;
@@ -2511,8 +2782,7 @@ export class Scheduler {
2511
2782
  // Should not happen — collectBatchSubmitCandidates already filtered
2512
2783
  // — but stay defensive: fall back to a clear failure.
2513
2784
  const msg = `tick: batch submit selected but adapter/dispatchBatch missing for ${spec.provider}`;
2514
- this.failTask(record.taskId, new Error(msg));
2515
- return { taskId: record.taskId, status: "failed", error: msg };
2785
+ return this.failRun(record, { error: msg, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2516
2786
  }
2517
2787
  try {
2518
2788
  const handle = await retryWithBackoff(() => dispatchBatch.call(adapter, spec.model, [spec.prompt], {
@@ -2522,7 +2792,7 @@ export class Scheduler {
2522
2792
  messages: spec.messages,
2523
2793
  }));
2524
2794
  try {
2525
- if (!this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"], { kind: "dispatched", details: { batch_id: handle.batchId } })) {
2795
+ if (!this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"], { kind: "dispatched", details: { batch_id: handle.batchId, ...this.tickDetails() } })) {
2526
2796
  // Another writer moved the row (a cancel) during the submit: it
2527
2797
  // keeps its status, and the live batch is reported, not stored.
2528
2798
  const error = `task was ${record.status} while its batch was submitted; batch ${handle.batchId} is not stored, and the provider may still run and bill it`;
@@ -2559,9 +2829,8 @@ export class Scheduler {
2559
2829
  held.phase = "provider_call";
2560
2830
  return this.dispatchProviderCall(record, adapters);
2561
2831
  }
2562
- this.rollSeries(record);
2563
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
2564
- return { taskId: record.taskId, status: "failed", error: msg };
2832
+ // The submit failed, so no batch exists: a later attempt may submit again.
2833
+ return this.planRetryWindow(this.failRunWith(record, err));
2565
2834
  }
2566
2835
  }
2567
2836
  /**
@@ -2581,8 +2850,7 @@ export class Scheduler {
2581
2850
  }
2582
2851
  catch (err) {
2583
2852
  const msg = err instanceof Error ? err.message : String(err);
2584
- this.failTask(record.taskId, new Error(`tick: corrupt body_json: ${msg}`));
2585
- return { taskId: record.taskId, status: "failed", error: msg };
2853
+ return this.failRun(record, { error: `tick: corrupt body_json: ${msg}`, facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2586
2854
  }
2587
2855
  const adapter = adapters[spec.provider];
2588
2856
  if (!adapter || typeof adapter.retrieveBatch !== "function") {
@@ -2596,9 +2864,7 @@ export class Scheduler {
2596
2864
  }
2597
2865
  const batchId = record.batchId;
2598
2866
  if (!batchId) {
2599
- const msg = "tick: submitted task has no batchId";
2600
- this.failTask(record.taskId, new Error(msg));
2601
- return { taskId: record.taskId, status: "failed", error: msg };
2867
+ return this.failRun(record, { error: "tick: submitted task has no batchId", facts: { permanent: true }, keepSeries: true }, UNFINISHED_STATUSES);
2602
2868
  }
2603
2869
  const ranAt = new Date();
2604
2870
  let poll;
@@ -2618,18 +2884,13 @@ export class Scheduler {
2618
2884
  return { taskId: record.taskId, status: "submitted" };
2619
2885
  }
2620
2886
  if (poll.status === "failed" || poll.status === "expired") {
2621
- const msg = poll.error ?? `batch ${poll.status}`;
2622
- this.rollSeries(record);
2623
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
2624
- return { taskId: record.taskId, status: "failed", error: msg };
2887
+ // The batch is over at the provider: a later attempt submits the task again.
2888
+ return this.planRetryWindow(this.failRun(record, { error: poll.error ?? `batch ${poll.status}`, facts: {} }));
2625
2889
  }
2626
2890
  // completed — take the first (single-prompt) result.
2627
2891
  const first = poll.results?.[0];
2628
2892
  if (!first) {
2629
- const msg = "batch completed with no results";
2630
- this.rollSeries(record);
2631
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
2632
- return { taskId: record.taskId, status: "failed", error: msg };
2893
+ return this.planRetryWindow(this.failRun(record, { error: "batch completed with no results", facts: {} }));
2633
2894
  }
2634
2895
  // Shape a DispatchResult-like object so the receipt path is identical
2635
2896
  // to the sync dispatch.
@@ -2753,18 +3014,46 @@ export class Scheduler {
2753
3014
  };
2754
3015
  }
2755
3016
  }
3017
+ /** The caps keys a one-off model call takes: its LLM time limit and its retry policy. */
3018
+ const MODEL_CALL_CAPS_KEYS = new Set(["llmTimeoutMs", "retries", "retryDelayMs"]);
3019
+ /**
3020
+ * The caps a one-off row stores: only the keys the caller set, each checked
3021
+ * (a time limit from 1 s to 7 days or `"none"`, retries from 0 to 10, a
3022
+ * retry delay from 1 s to 7 days, any other cap a positive number), with
3023
+ * `capsVersion: 2`. Throws on an unknown key or a bad value.
3024
+ */
3025
+ function checkedCaps(caps, keys, what) {
3026
+ if (caps === undefined)
3027
+ return { capsVersion: CAPS_VERSION };
3028
+ if (!caps || typeof caps !== "object" || Array.isArray(caps))
3029
+ throw new Error(`${what}: caps must be an object`);
3030
+ const out = {};
3031
+ for (const [key, value] of Object.entries(caps)) {
3032
+ if (key === "capsVersion" || value === undefined)
3033
+ continue;
3034
+ if (!keys.has(key))
3035
+ throw new Error(`${what}: unknown cap "${key}"`);
3036
+ const error = capValueError(key, value);
3037
+ if (error)
3038
+ throw new Error(`${what}: ${error}`);
3039
+ out[key] = value;
3040
+ }
3041
+ return { ...out, capsVersion: CAPS_VERSION };
3042
+ }
2756
3043
  /**
2757
- * Dispatch options of a job occurrence (KTD8): the caps as a per-call time
2758
- * limit and budget, and for a row with `job_id` its working directory and
2759
- * job id. A `claude-code` row without a job gets its handoff folder. A
2760
- * `command` body also hands over its shell and summarize steps.
3044
+ * Dispatch options of a run: its resolved time limits, the caps' budget,
3045
+ * and for a row with `job_id` its working directory and job id. A
3046
+ * `claude-code` row without a job gets its handoff folder. A `command` body
3047
+ * also hands over its shell and summarize steps.
2761
3048
  */
2762
- function jobDispatchOptions(record, spec) {
3049
+ function jobDispatchOptions(record, spec, limits) {
2763
3050
  const out = {};
2764
- if (spec.caps) {
2765
- out.timeoutMs = spec.caps.llmTimeoutMs;
3051
+ if (limits.llm_timeout)
3052
+ out.timeoutMs = limits.llm_timeout.value;
3053
+ if (limits.command_timeout)
3054
+ out.commandTimeoutMs = limits.command_timeout.value;
3055
+ if (spec.caps?.maxBudgetUsd !== undefined)
2766
3056
  out.maxBudgetUsd = spec.caps.maxBudgetUsd;
2767
- }
2768
3057
  if (record.jobId) {
2769
3058
  out.jobId = record.jobId;
2770
3059
  if (record.originCwd)
@@ -3070,6 +3359,51 @@ function refusal(action, record, allowed) {
3070
3359
  const what = record.bodyJson ? record.status : `${record.status} (closure-based)`;
3071
3360
  return `${action}: task ${record.taskId} is ${what}; ${allowed}`;
3072
3361
  }
3362
+ /**
3363
+ * Throws the refusal of a manual retry, or returns for a task that can be
3364
+ * retried: a failed provider-call one-off that did not stop during its
3365
+ * Batch submit.
3366
+ */
3367
+ function retryRefusal(action, record) {
3368
+ const taskId = record.taskId;
3369
+ if (record.status !== "failed") {
3370
+ throw new TaskActionError(`${action}: task ${taskId} has status ${record.status}; retry is only valid on failed tasks`);
3371
+ }
3372
+ if (record.error === BATCH_SUBMIT_INTERRUPTED_ERROR) {
3373
+ // Before the job-run refusal: the job does not retry this run either.
3374
+ throw new TaskActionError(`${action}: task ${taskId} stopped during its Batch submit, and the provider may have accepted the batch; ` +
3375
+ "a retry could run and bill it twice, so check the provider's batch list and enqueue the task again only if no batch exists");
3376
+ }
3377
+ if (!record.bodyJson) {
3378
+ throw new TaskActionError(`${action}: task ${taskId} is closure-based; only provider-call tasks can be retried`);
3379
+ }
3380
+ if (record.jobId) {
3381
+ // The job sweep already recorded this failure and queued a retry or
3382
+ // the next run; a second run of the same slot would go unrecorded.
3383
+ throw new TaskActionError(`${action}: task ${taskId} is a run of job ${record.jobId}, which retries failed runs itself; use run now on the job`);
3384
+ }
3385
+ }
3386
+ /**
3387
+ * A failed row retried by hand: due now with no earliest start, error and
3388
+ * completion time cleared, and no stale batch id (the retry dispatches
3389
+ * synchronously). The run-now mark keeps it off the Batch API.
3390
+ */
3391
+ function retryWrite(record) {
3392
+ return {
3393
+ ...record,
3394
+ status: "scheduled",
3395
+ scheduledFor: new Date().toISOString(),
3396
+ notBefore: undefined,
3397
+ completedAt: undefined,
3398
+ error: undefined,
3399
+ batchId: undefined,
3400
+ intensitySource: "expedited",
3401
+ };
3402
+ }
3403
+ /** The event of a manual retry; its reason starts a new attempt count. */
3404
+ function retryEvent(opts) {
3405
+ return { kind: "rescheduled", actor: opts.actor, details: { reason: "retry" } };
3406
+ }
3073
3407
  /** Classify a reschedule target; exactly one shape must be given. */
3074
3408
  function rescheduleShape(target) {
3075
3409
  const t = (target ?? {});
@@ -3157,13 +3491,19 @@ export function pickBestWindow(entries, deadline) {
3157
3491
  * errors raised *before* the request could reach the provider
3158
3492
  * (ECONNREFUSED / ENOTFOUND / EAI_AGAIN). Ambiguous mid-flight errors
3159
3493
  * (ETIMEDOUT, ECONNRESET) are NOT retried — the provider may already
3160
- * have accepted and billed the call. Other 4xx bubble up immediately.
3494
+ * have accepted and billed the call. Other 4xx bubble up immediately;
3495
+ * a 408 or 425 then gets the task retry (`isPermanentStatus` in run-limits).
3161
3496
  *
3162
- * This is the single retry policy for Tidegap: provider adapters
3163
- * construct their SDK clients with `maxRetries: 0` so vendor-side
3164
- * retries cannot multiply with this one.
3497
+ * This is the in-call resend for Tidegap: provider adapters construct
3498
+ * their SDK clients with `maxRetries: 0` so vendor-side retries cannot
3499
+ * multiply with this one. The task's retry policy (a later attempt) is a
3500
+ * separate layer, in the scheduler's retry funnel.
3501
+ *
3502
+ * `signal` (the task's cancel watch) ends the waits: once it aborts, no
3503
+ * further call is made, even when the adapter ignored the signal, and the
3504
+ * last error is thrown.
3165
3505
  */
3166
- export async function retryWithBackoff(fn) {
3506
+ export async function retryWithBackoff(fn, signal) {
3167
3507
  const waits = [1_000, 4_000, 16_000];
3168
3508
  let lastErr;
3169
3509
  for (let attempt = 0; attempt <= waits.length; attempt++) {
@@ -3172,16 +3512,30 @@ export async function retryWithBackoff(fn) {
3172
3512
  }
3173
3513
  catch (err) {
3174
3514
  lastErr = err;
3175
- if (!isRetryable(err) || attempt === waits.length) {
3515
+ if (!isRetryable(err) || attempt === waits.length || signal?.aborted) {
3176
3516
  throw err;
3177
3517
  }
3178
3518
  // eslint-disable-next-line no-console
3179
3519
  console.warn(`[tidegap/scheduler] dispatch attempt ${attempt + 1} failed (${describeErr(err)}); retrying in ${waits[attempt] / 1000}s`);
3180
- await new Promise((r) => setTimeout(r, waits[attempt]));
3520
+ await waitUnlessAborted(waits[attempt], signal);
3521
+ if (signal?.aborted)
3522
+ throw err;
3181
3523
  }
3182
3524
  }
3183
3525
  throw lastErr;
3184
3526
  }
3527
+ /** Wait `ms`, or less when `signal` aborts first. */
3528
+ function waitUnlessAborted(ms, signal) {
3529
+ return new Promise((resolve) => {
3530
+ const done = () => {
3531
+ clearTimeout(timer);
3532
+ signal?.removeEventListener("abort", done);
3533
+ resolve();
3534
+ };
3535
+ const timer = setTimeout(done, ms);
3536
+ signal?.addEventListener("abort", done, { once: true });
3537
+ });
3538
+ }
3185
3539
  function isRetryable(err) {
3186
3540
  if (!err || typeof err !== "object")
3187
3541
  return false;