@tidegap/core 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +3 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/budget.d.ts +0 -12
  5. package/dist/budget.js +2 -24
  6. package/dist/channels/commands.d.ts +137 -0
  7. package/dist/channels/commands.js +377 -0
  8. package/dist/channels/delivery-codes.d.ts +9 -0
  9. package/dist/channels/delivery-codes.js +53 -0
  10. package/dist/channels/digest.d.ts +102 -0
  11. package/dist/channels/digest.js +146 -0
  12. package/dist/channels/format.d.ts +127 -0
  13. package/dist/channels/format.js +407 -0
  14. package/dist/channels/index.d.ts +15 -0
  15. package/dist/channels/index.js +15 -0
  16. package/dist/channels/kinds/command.d.ts +13 -0
  17. package/dist/channels/kinds/command.js +65 -0
  18. package/dist/channels/kinds/discord.d.ts +16 -0
  19. package/dist/channels/kinds/discord.js +67 -0
  20. package/dist/channels/kinds/email.d.ts +20 -0
  21. package/dist/channels/kinds/email.js +162 -0
  22. package/dist/channels/kinds/index.d.ts +8 -0
  23. package/dist/channels/kinds/index.js +17 -0
  24. package/dist/channels/kinds/ntfy.d.ts +25 -0
  25. package/dist/channels/kinds/ntfy.js +163 -0
  26. package/dist/channels/kinds/pushover.d.ts +11 -0
  27. package/dist/channels/kinds/pushover.js +77 -0
  28. package/dist/channels/kinds/shared.d.ts +25 -0
  29. package/dist/channels/kinds/shared.js +39 -0
  30. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  31. package/dist/channels/kinds/shortcuts.js +45 -0
  32. package/dist/channels/kinds/slack.d.ts +8 -0
  33. package/dist/channels/kinds/slack.js +57 -0
  34. package/dist/channels/kinds/telegram.d.ts +4 -0
  35. package/dist/channels/kinds/telegram.js +26 -0
  36. package/dist/channels/kinds/webhook.d.ts +30 -0
  37. package/dist/channels/kinds/webhook.js +177 -0
  38. package/dist/channels/payload.d.ts +36 -0
  39. package/dist/channels/payload.js +61 -0
  40. package/dist/channels/plan.d.ts +24 -0
  41. package/dist/channels/plan.js +66 -0
  42. package/dist/channels/registry.d.ts +191 -0
  43. package/dist/channels/registry.js +125 -0
  44. package/dist/channels/telegram.d.ts +110 -0
  45. package/dist/channels/telegram.js +168 -0
  46. package/dist/channels/types.d.ts +107 -0
  47. package/dist/channels/types.js +26 -0
  48. package/dist/claude-tools.d.ts +29 -0
  49. package/dist/claude-tools.js +49 -0
  50. package/dist/data/tables.generated.d.ts +6 -0
  51. package/dist/data/tables.generated.js +37 -0
  52. package/dist/energy.d.ts +77 -0
  53. package/dist/energy.js +131 -0
  54. package/dist/grid.d.ts +19 -2
  55. package/dist/grid.js +84 -28
  56. package/dist/handoff.d.ts +152 -0
  57. package/dist/handoff.js +430 -0
  58. package/dist/history.d.ts +2 -0
  59. package/dist/history.js +3 -1
  60. package/dist/index.d.ts +46 -16
  61. package/dist/index.js +34 -8
  62. package/dist/job-cadence.d.ts +76 -0
  63. package/dist/job-cadence.js +240 -0
  64. package/dist/jobs.d.ts +173 -0
  65. package/dist/jobs.js +794 -0
  66. package/dist/notify.d.ts +2 -0
  67. package/dist/notify.js +2 -1
  68. package/dist/paths.d.ts +13 -46
  69. package/dist/paths.js +51 -219
  70. package/dist/postpone.d.ts +113 -0
  71. package/dist/postpone.js +185 -0
  72. package/dist/providers/anthropic.js +7 -3
  73. package/dist/providers/base.d.ts +113 -1
  74. package/dist/providers/base.js +15 -0
  75. package/dist/providers/budget.d.ts +25 -0
  76. package/dist/providers/budget.js +57 -0
  77. package/dist/providers/defaults.js +4 -0
  78. package/dist/providers/defer.d.ts +16 -0
  79. package/dist/providers/defer.js +31 -0
  80. package/dist/providers/gemini.d.ts +1 -0
  81. package/dist/providers/gemini.js +27 -20
  82. package/dist/providers/index.d.ts +2 -2
  83. package/dist/providers/index.js +1 -1
  84. package/dist/providers/ollama.d.ts +1 -0
  85. package/dist/providers/ollama.js +26 -22
  86. package/dist/providers/openai.js +5 -5
  87. package/dist/providers/timeout.d.ts +18 -0
  88. package/dist/providers/timeout.js +33 -0
  89. package/dist/quota.d.ts +7 -2
  90. package/dist/quota.js +13 -29
  91. package/dist/readiness.d.ts +169 -0
  92. package/dist/readiness.js +254 -0
  93. package/dist/redact.d.ts +42 -0
  94. package/dist/redact.js +110 -0
  95. package/dist/region-host.d.ts +30 -0
  96. package/dist/region-host.js +69 -0
  97. package/dist/region.d.ts +102 -20
  98. package/dist/region.js +175 -23
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +95 -0
  102. package/dist/schedule-job.js +195 -0
  103. package/dist/scheduler.d.ts +245 -14
  104. package/dist/scheduler.js +925 -110
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +157 -5
  108. package/dist/storage/sqlite.js +661 -20
  109. package/dist/task-events.d.ts +102 -0
  110. package/dist/task-events.js +308 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +359 -65
  113. package/dist/types.d.ts +246 -3
  114. package/dist/types.js +8 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +11 -6
  118. package/dist/aggregator.d.ts.map +0 -1
  119. package/dist/aggregator.js.map +0 -1
  120. package/dist/budget.d.ts.map +0 -1
  121. package/dist/budget.js.map +0 -1
  122. package/dist/data/tables.generated.d.ts.map +0 -1
  123. package/dist/data/tables.generated.js.map +0 -1
  124. package/dist/energy.d.ts.map +0 -1
  125. package/dist/energy.js.map +0 -1
  126. package/dist/grid.d.ts.map +0 -1
  127. package/dist/grid.js.map +0 -1
  128. package/dist/history.d.ts.map +0 -1
  129. package/dist/history.js.map +0 -1
  130. package/dist/index.d.ts.map +0 -1
  131. package/dist/index.js.map +0 -1
  132. package/dist/notify.d.ts.map +0 -1
  133. package/dist/notify.js.map +0 -1
  134. package/dist/paths.d.ts.map +0 -1
  135. package/dist/paths.js.map +0 -1
  136. package/dist/providers/anthropic.d.ts.map +0 -1
  137. package/dist/providers/anthropic.js.map +0 -1
  138. package/dist/providers/base.d.ts.map +0 -1
  139. package/dist/providers/base.js.map +0 -1
  140. package/dist/providers/defaults.d.ts.map +0 -1
  141. package/dist/providers/defaults.js.map +0 -1
  142. package/dist/providers/gemini.d.ts.map +0 -1
  143. package/dist/providers/gemini.js.map +0 -1
  144. package/dist/providers/index.d.ts.map +0 -1
  145. package/dist/providers/index.js.map +0 -1
  146. package/dist/providers/ollama.d.ts.map +0 -1
  147. package/dist/providers/ollama.js.map +0 -1
  148. package/dist/providers/openai.d.ts.map +0 -1
  149. package/dist/providers/openai.js.map +0 -1
  150. package/dist/quota.d.ts.map +0 -1
  151. package/dist/quota.js.map +0 -1
  152. package/dist/recommend.d.ts.map +0 -1
  153. package/dist/recommend.js.map +0 -1
  154. package/dist/redact.d.ts.map +0 -1
  155. package/dist/redact.js.map +0 -1
  156. package/dist/region.d.ts.map +0 -1
  157. package/dist/region.js.map +0 -1
  158. package/dist/routing.d.ts.map +0 -1
  159. package/dist/routing.js.map +0 -1
  160. package/dist/scheduler.d.ts.map +0 -1
  161. package/dist/scheduler.js.map +0 -1
  162. package/dist/select-window.d.ts.map +0 -1
  163. package/dist/select-window.js.map +0 -1
  164. package/dist/sign.d.ts.map +0 -1
  165. package/dist/sign.js.map +0 -1
  166. package/dist/storage/sqlite.d.ts.map +0 -1
  167. package/dist/storage/sqlite.js.map +0 -1
  168. package/dist/tool-surface.d.ts.map +0 -1
  169. package/dist/tool-surface.js.map +0 -1
  170. package/dist/types.d.ts.map +0 -1
  171. package/dist/types.js.map +0 -1
package/dist/scheduler.js CHANGED
@@ -18,17 +18,24 @@
18
18
  */
19
19
  import { randomUUID } from "node:crypto";
20
20
  import { carbonBudgetUsage, receiptCarbonG, windowBounds, } from "./budget.js";
21
- import { gramsForIntensity, resolveModelEnergy } from "./energy.js";
21
+ import { billModelUsage, gramsForIntensity, resolveModelEnergy, singleModelCounts } from "./energy.js";
22
+ import { claudeCodeToolsError } from "./claude-tools.js";
23
+ import { handoffCwdError, outputPathError, profileTools, resultPathError, sameTools, wakeError } from "./handoff.js";
22
24
  import { mockGridFeed } from "./grid.js";
25
+ import { deferRetryAt } from "./providers/defer.js";
26
+ import { postponeOptions, resolveLimitReset, resolvePostpone, taskProvider, writeLimitResetHint, } from "./postpone.js";
23
27
  import { candidateId, parseCandidates, previewRouting, scoreCandidates, } from "./routing.js";
24
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";
25
31
  import { resolveQuotaDeadline } from "./quota.js";
26
32
  import { redactBodyJson, redactPrompt } from "./redact.js";
27
33
  import { selectWindow } from "./select-window.js";
28
34
  import { loadOrCreateSigningKey, signReceipt, } from "./sign.js";
29
35
  import { TaskStore } from "./storage/sqlite.js";
30
- const PENDING_STATUSES = ["queued", "scheduled"];
31
- const UNFINISHED_STATUSES = ["queued", "scheduled", "submitted", "running"];
36
+ import { createProgressRecorder, eventDetails, impliedEventKind, } from "./task-events.js";
37
+ export const PENDING_STATUSES = ["queued", "scheduled"];
38
+ export const UNFINISHED_STATUSES = ["queued", "scheduled", "submitted", "running"];
32
39
  const TERMINAL = new Set(["completed", "failed", "cancelled"]);
33
40
  const DEFAULT_REGION = "US-CAL-CISO";
34
41
  const MAX_HORIZON_HOURS = 72;
@@ -40,6 +47,7 @@ const SUPPORTED_PROVIDERS = new Set([
40
47
  "openai",
41
48
  "gemini",
42
49
  "ollama",
50
+ "claude-code",
43
51
  ]);
44
52
  /** Thrown when no candidate window meets the user-supplied carbon budget. */
45
53
  export class CarbonBudgetExceededError extends Error {
@@ -64,12 +72,14 @@ export class InvalidDeadlineError extends Error {
64
72
  }
65
73
  export class Scheduler {
66
74
  feed;
67
- defaultRegion;
75
+ defaultRegionOption;
68
76
  rng;
69
77
  tasks = new Map();
70
78
  pendingTimers = new Map();
71
79
  resolvers = new Map();
72
80
  bodies = new Map();
81
+ /** Rows a tick moved to `running` whose dispatch has not settled (KTD12), and what each is doing. */
82
+ held = new Map();
73
83
  store;
74
84
  // Mutable: a single load failure disables signing for the rest of
75
85
  // this scheduler instance (see `getSigningKey`).
@@ -78,9 +88,16 @@ export class Scheduler {
78
88
  carbonBudget;
79
89
  onCarbonAlert;
80
90
  quotaConfig;
91
+ limitReset;
92
+ actor;
93
+ sleepCounter;
94
+ defaultRegion() {
95
+ const option = this.defaultRegionOption;
96
+ return typeof option === "function" ? option() : option;
97
+ }
81
98
  constructor(opts = {}) {
82
99
  this.feed = opts.feed ?? mockGridFeed();
83
- this.defaultRegion = opts.defaultRegion ?? DEFAULT_REGION;
100
+ this.defaultRegionOption = opts.defaultRegion ?? DEFAULT_REGION;
84
101
  this.rng = opts.rng ?? Math.random;
85
102
  if (opts.store) {
86
103
  this.store = opts.store;
@@ -92,6 +109,9 @@ export class Scheduler {
92
109
  this.carbonBudget = opts.carbonBudget;
93
110
  this.onCarbonAlert = opts.onCarbonAlert;
94
111
  this.quotaConfig = opts.quotaConfig;
112
+ this.limitReset = opts.limitReset;
113
+ this.actor = opts.actor ?? "system";
114
+ this.sleepCounter = opts.sleepCounter;
95
115
  }
96
116
  /**
97
117
  * Compute the current aggregate carbon-budget status (ROADMAP item 4)
@@ -274,6 +294,10 @@ export class Scheduler {
274
294
  cached.readAt = undefined;
275
295
  return changed;
276
296
  }
297
+ /** A task's events from the ledger, oldest first; [] without a store. */
298
+ listTaskEvents(taskId, opts = {}) {
299
+ return this.store?.listTaskEvents(taskId, opts) ?? [];
300
+ }
277
301
  /** Record that a ticker ran at `at` (ledger meta `last_tick_at`). No-op without a store. */
278
302
  recordTickRun(at = new Date()) {
279
303
  this.store?.setMeta(LAST_TICK_META_KEY, at.toISOString());
@@ -282,6 +306,55 @@ export class Scheduler {
282
306
  lastTickAt() {
283
307
  return this.store?.getMeta(LAST_TICK_META_KEY);
284
308
  }
309
+ /** The ledger this scheduler writes through to, if any. Jobs live there too. */
310
+ ledger() {
311
+ return this.store;
312
+ }
313
+ /**
314
+ * Insert one job occurrence and plan it (floating recurring jobs, KTD4).
315
+ * The row is built here, not through `enqueueProviderCall` (which refuses
316
+ * `provider: "command"`): `scheduled`, `notBefore = earliest`,
317
+ * `scheduledFor = earliest + 1 min` (never equal to `notBefore`, which
318
+ * would read as an exact pin), the slot deadline with no widening,
319
+ * `repeat = none` and no series, so `rollSeries` never touches it. The
320
+ * insert is `insertIfAbsent` on the derived id; returns false, writing
321
+ * nothing, when the row exists. Planning picks the cleanest forecast hour
322
+ * inside `[earliest, deadline]`, or leaves the row unplanned for
323
+ * `replanSweep` when the forecast does not reach it (or fails).
324
+ */
325
+ async materializeOccurrence(occ, details) {
326
+ if (!this.store)
327
+ throw new Error("materializeOccurrence: jobs need a ledger (dbPath)");
328
+ const earliestMs = Date.parse(occ.earliest);
329
+ const deadlineMs = Date.parse(occ.deadline);
330
+ const record = {
331
+ taskId: occ.taskId,
332
+ status: "scheduled",
333
+ enqueuedAt: new Date().toISOString(),
334
+ region: this.defaultRegion(),
335
+ bodyJson: occ.bodyJson,
336
+ deadline: new Date(deadlineMs).toISOString(),
337
+ notBefore: new Date(earliestMs).toISOString(),
338
+ scheduledFor: new Date(Math.min(earliestMs + MINUTE_MS, deadlineMs)).toISOString(),
339
+ title: occ.title,
340
+ originHost: occ.originHost,
341
+ originCwd: occ.originCwd,
342
+ repeat: "none",
343
+ jobId: occ.jobId,
344
+ };
345
+ const created = this.eventFor(undefined, record, { kind: "created", actor: "system", details });
346
+ if (!this.store.insertIfAbsent(record, created))
347
+ return false;
348
+ this.cacheRow(record);
349
+ try {
350
+ await this.scheduleProviderCall(record.taskId, new Date(deadlineMs));
351
+ }
352
+ catch (err) {
353
+ // eslint-disable-next-line no-console
354
+ console.warn(`[tidegap/scheduler] could not plan job occurrence ${record.taskId}: ${describeErr(err)}; replanSweep plans it later`);
355
+ }
356
+ return true;
357
+ }
285
358
  /**
286
359
  * Defer a task. Returns a promise that resolves with the task's eventual
287
360
  * result when Tidegap dispatches it.
@@ -320,7 +393,7 @@ export class Scheduler {
320
393
  throw new Error(`repeat ${JSON.stringify(opts.repeat)} needs a provider-call task; closure tasks cannot repeat`);
321
394
  }
322
395
  const taskId = opts.taskId ?? `t-${randomUUID()}`;
323
- const region = opts.region ?? this.defaultRegion;
396
+ const region = opts.region ?? this.defaultRegion();
324
397
  const record = {
325
398
  taskId,
326
399
  status: "queued",
@@ -332,7 +405,7 @@ export class Scheduler {
332
405
  };
333
406
  this.tasks.set(taskId, record);
334
407
  this.bodies.set(taskId, task);
335
- this.store?.upsert(record);
408
+ this.store?.upsert(record, this.eventFor(undefined, record, { kind: "created", actor: opts.actor }));
336
409
  // Fire-and-forget, but never unhandled: a rejecting grid feed (or any
337
410
  // scheduling error) must fail the task — rejecting the defer() promise
338
411
  // — instead of crashing the process with an unhandledRejection.
@@ -365,7 +438,77 @@ export class Scheduler {
365
438
  if (typeof spec.prompt !== "string" || spec.prompt.length === 0) {
366
439
  throw new Error("enqueueProviderCall: spec.prompt must be a non-empty string");
367
440
  }
368
- const deadline = normalizeDeadline(opts.deadline);
441
+ const checked = checkedHandoff(spec, opts, "enqueueProviderCall");
442
+ if (checked.tools !== undefined) {
443
+ const toolsError = claudeCodeToolsError(checked.tools);
444
+ if (toolsError)
445
+ throw new Error(`enqueueProviderCall: ${toolsError}`);
446
+ }
447
+ // The title is never rewritten at terminal transitions, so it is stored
448
+ // redacted from the start (same patterns as the receipt prompt).
449
+ const title = deriveTitle(opts.title ?? spec.prompt, spec.redactInReceipt) ??
450
+ (opts.title !== undefined ? deriveTitle(spec.prompt, spec.redactInReceipt) : undefined);
451
+ return this.insertProviderCall(checked, opts, title);
452
+ }
453
+ /**
454
+ * Queue a one-off shell command (`tidegap queue add --runner command`):
455
+ * the row of a command job run (`provider: "command"`, `model: "none"`,
456
+ * an empty prompt) with `command.origin: "cli"` and no job id, planned
457
+ * like any provider call. Only the CLI tick's command adapter runs it.
458
+ * 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.
462
+ */
463
+ async enqueueCommandTask(task, opts = {}) {
464
+ if (typeof task.run !== "string" || task.run.trim() === "") {
465
+ throw new Error("enqueueCommandTask: the command must be a non-empty string");
466
+ }
467
+ if (task.run.length > COMMAND_MAX_CHARS) {
468
+ throw new Error(`enqueueCommandTask: the command is longer than ${COMMAND_MAX_CHARS} characters`);
469
+ }
470
+ const cwdError = handoffCwdError(task.cwd, "command");
471
+ if (cwdError)
472
+ 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
+ }
482
+ if (task.resultPath !== undefined) {
483
+ const pathError = resultPathError(task.resultPath, { cwd: task.cwd, originCwd: opts.originCwd });
484
+ if (pathError)
485
+ throw new Error(`enqueueCommandTask: ${pathError}`);
486
+ }
487
+ const wakeRefused = wakeError(task.wake, task.origin, opts.originSessionId);
488
+ if (wakeRefused)
489
+ throw new Error(`enqueueCommandTask: ${wakeRefused}`);
490
+ const handoff = {
491
+ ...(task.resultPath !== undefined ? { resultPath: task.resultPath } : {}),
492
+ ...(task.wake === true ? { wake: true } : {}),
493
+ };
494
+ const spec = {
495
+ type: "provider_call",
496
+ provider: "command",
497
+ model: "none",
498
+ prompt: "",
499
+ command: { run: task.run, cwd: task.cwd, secrets: [], origin: "cli" },
500
+ caps,
501
+ ...(Object.keys(handoff).length > 0 ? { handoff } : {}),
502
+ ...(task.origin ? { origin: task.origin } : {}),
503
+ };
504
+ return this.insertProviderCall(spec, opts, deriveTitle(opts.title ?? task.run));
505
+ }
506
+ /** Insert a checked provider-call row with its `created` event, then plan its window. */
507
+ async insertProviderCall(spec, opts, title) {
508
+ const requested = normalizeDeadline(opts.deadline);
509
+ const notBefore = earliestStart(opts.notBefore);
510
+ const start = notBefore ? startFields(notBefore.getTime(), requested.getTime()) : undefined;
511
+ const deadline = start ? new Date(start.deadline) : requested;
369
512
  if (opts.taskId !== undefined) {
370
513
  if (typeof opts.taskId !== "string" || opts.taskId.length === 0) {
371
514
  throw new Error(`Invalid taskId: must be a non-empty string`);
@@ -382,11 +525,7 @@ export class Scheduler {
382
525
  throw new Error(`repeat "quota_reset" needs deadlineKind "quota_reset" and a quotaProvider label`);
383
526
  }
384
527
  const taskId = opts.taskId ?? `t-${randomUUID()}`;
385
- const region = opts.region ?? this.defaultRegion;
386
- // The title is never rewritten at terminal transitions, so it is stored
387
- // redacted from the start (same patterns as the receipt prompt).
388
- const title = deriveTitle(opts.title ?? spec.prompt, spec.redactInReceipt) ??
389
- (opts.title !== undefined ? deriveTitle(spec.prompt, spec.redactInReceipt) : undefined);
528
+ const region = opts.region ?? this.defaultRegion();
390
529
  const record = {
391
530
  taskId,
392
531
  status: "queued",
@@ -397,8 +536,26 @@ export class Scheduler {
397
536
  deadline: deadline.toISOString(),
398
537
  ...identityFields(taskId, opts, title),
399
538
  };
539
+ if (start) {
540
+ record.notBefore = start.notBefore;
541
+ record.scheduledFor = start.scheduledFor;
542
+ }
400
543
  this.tasks.set(taskId, record);
401
- this.store?.upsert(record);
544
+ // Insert once: another process that enqueued the same id since the
545
+ // check above keeps its row.
546
+ const created = this.eventFor(undefined, record, {
547
+ kind: "created",
548
+ actor: opts.actor,
549
+ details: opts.parentTaskId ? { parent_task_id: opts.parentTaskId } : {},
550
+ });
551
+ if (this.store && !this.store.insertIfAbsent(record, created)) {
552
+ this.tasks.delete(taskId);
553
+ throw new Error(`Task id "${taskId}" is already in the queue`);
554
+ }
555
+ // A task from a session counts for that session's notices even when the
556
+ // first notice query runs only after it finished.
557
+ if (record.originSessionId)
558
+ this.store?.startSessionNotices(new Date(record.enqueuedAt));
402
559
  // Schedule a carbon window but DO NOT register an in-process timer that
403
560
  // calls `dispatch` — provider-call tasks are driven exclusively by
404
561
  // `Scheduler.tick`. We still write `scheduled` + `scheduledFor` so the
@@ -421,11 +578,25 @@ export class Scheduler {
421
578
  * (`enqueue` / `defer`) are NOT touched by this method — only this
422
579
  * process can run those.
423
580
  */
424
- async tick(adapters) {
581
+ async tick(adapters, opts = {}) {
425
582
  const results = [];
426
583
  let dispatched = 0;
427
584
  let failed = 0;
585
+ let deferred = 0;
428
586
  let inspected = 0;
587
+ // Provider and model → retryAt after its first defer this tick: later due
588
+ // tasks on that provider and model defer to the same time without a
589
+ // dispatch (KTD7.4). Keyed by model too: a spent per-model window (for
590
+ // example a weekly "Fable" limit) must not hold back the other models.
591
+ const deferrals = new Map();
592
+ const count = (entry) => {
593
+ if (entry.status === "completed")
594
+ dispatched++;
595
+ else if (entry.status === "deferred")
596
+ deferred++;
597
+ else
598
+ failed++;
599
+ };
429
600
  // ---- (1) Batch-submit sweep, BEFORE the due sweep ----
430
601
  // A batch-eligible task's deferral mechanism IS the Batch API: the
431
602
  // provider runs it within its own 24h SLA and picks the execution
@@ -439,6 +610,8 @@ export class Scheduler {
439
610
  // time to start the batch).
440
611
  const submittedThisTick = new Set();
441
612
  for (const record of this.collectBatchSubmitCandidates(adapters)) {
613
+ if (opts.signal?.aborted)
614
+ break;
442
615
  // Reuse the scheduled→running claim so a racing tick can't submit
443
616
  // the same row twice (double-billed batch). In-memory-only mode
444
617
  // has no cross-process race, so claim only when a store exists.
@@ -465,12 +638,9 @@ export class Scheduler {
465
638
  continue;
466
639
  }
467
640
  inspected++;
468
- const entry = await this.dispatchProviderCall(record, adapters);
641
+ const entry = await this.holding(record, "provider_call", () => this.dispatchProviderCall(record, adapters, deferrals));
469
642
  results.push(entry);
470
- if (entry.status === "completed")
471
- dispatched++;
472
- else
473
- failed++;
643
+ count(entry);
474
644
  continue;
475
645
  }
476
646
  }
@@ -481,7 +651,7 @@ export class Scheduler {
481
651
  record.status = "running";
482
652
  }
483
653
  inspected++;
484
- const entry = await this.submitBatch(record, adapters);
654
+ const entry = await this.holding(record, "batch_submit", () => this.submitBatch(record, adapters));
485
655
  results.push(entry);
486
656
  if (entry.status === "submitted") {
487
657
  batchSubmitted++;
@@ -511,10 +681,20 @@ export class Scheduler {
511
681
  continue;
512
682
  if (!this.isDue(record, now))
513
683
  continue;
684
+ // A command job's shell step runs only where a `command` adapter
685
+ // exists (the CLI tick). Elsewhere the row stays `scheduled`: no
686
+ // claim, no failure. With `holdUnserved`, so does any row this host
687
+ // has no adapter for.
688
+ if (unservedCommand(record, adapters))
689
+ continue;
690
+ if (opts.holdUnserved && unserved(record, adapters))
691
+ continue;
514
692
  candidates.push(record);
515
693
  seen.add(record.taskId);
516
694
  }
517
695
  for (const record of candidates) {
696
+ if (opts.signal?.aborted)
697
+ break;
518
698
  // Row-level claim: only one tick gets to dispatch this task. If
519
699
  // the store is configured, the claim is also visible to other
520
700
  // processes pointing at the same SQLite file (e.g. an
@@ -543,16 +723,16 @@ export class Scheduler {
543
723
  }
544
724
  }
545
725
  inspected++;
546
- const entry = await this.dispatchProviderCall(record, adapters);
726
+ const entry = await this.holding(record, "provider_call", () => this.dispatchProviderCall(record, adapters, deferrals));
547
727
  results.push(entry);
548
- if (entry.status === "completed")
549
- dispatched++;
550
- else
551
- failed++;
728
+ count(entry);
552
729
  }
553
730
  // ---- (3) Batch-poll sweep, AFTER the due sweep ----
731
+ this.freeStrandedPolls(Date.now());
554
732
  let batchPolled = 0;
555
733
  for (const record of this.collectSubmittedCandidates(submittedThisTick)) {
734
+ if (opts.signal?.aborted)
735
+ break;
556
736
  // Claim submitted→running so two racing ticks can't double-complete.
557
737
  if (this.store) {
558
738
  let claimed = false;
@@ -573,7 +753,7 @@ export class Scheduler {
573
753
  record.status = "running";
574
754
  }
575
755
  inspected++;
576
- const entry = await this.pollBatch(record, adapters);
756
+ const entry = await this.holding(record, "batch_poll", () => this.pollBatch(record, adapters));
577
757
  results.push(entry);
578
758
  if (entry.status === "completed")
579
759
  dispatched++;
@@ -600,6 +780,7 @@ export class Scheduler {
600
780
  results,
601
781
  batchSubmitted,
602
782
  batchPolled,
783
+ deferred,
603
784
  };
604
785
  }
605
786
  /**
@@ -680,6 +861,47 @@ export class Scheduler {
680
861
  releaseClaim(record) {
681
862
  this.writeIf(record, { ...record, status: "scheduled" }, ["running"]);
682
863
  }
864
+ /**
865
+ * The head of the Batch-poll sweep (batch 27 KTD9): a plain row that a
866
+ * killed tick left `running` with its batch id goes back to `submitted`
867
+ * once its deadline plus `STRANDED_POLL_GRACE_MS` has passed, and the sweep
868
+ * then polls it. The batch id proves a live batch. A row goes to a Batch
869
+ * API only with a deadline over a day ahead, and the providers end every
870
+ * batch within 24 h, so a row past its deadline has a finished batch: the
871
+ * step rarely meets a live poll in another process, and compare-and-set
872
+ * still lands one completion if it does. Job rows are the job sweep's;
873
+ * rows this scheduler's tick holds are live. No event, as in
874
+ * `failHeldRuns`.
875
+ */
876
+ freeStrandedPolls(now) {
877
+ if (!this.store)
878
+ return;
879
+ let rows;
880
+ try {
881
+ rows = this.store.list({ status: "running" });
882
+ }
883
+ catch (err) {
884
+ // eslint-disable-next-line no-console
885
+ console.warn(`[tidegap/scheduler] tick: could not read running rows: ${describeErr(err)}; no stranded Batch poll freed this round`);
886
+ return;
887
+ }
888
+ for (const row of rows) {
889
+ if (!row.batchId || row.jobId || this.held.has(row.taskId))
890
+ continue;
891
+ const deadline = Date.parse(row.deadline ?? "");
892
+ if (!Number.isFinite(deadline) || now - deadline <= STRANDED_POLL_GRACE_MS)
893
+ continue;
894
+ const record = this.tasks.get(row.taskId) ?? row;
895
+ try {
896
+ this.writeIf(record, { ...row, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
897
+ this.tasks.set(row.taskId, record);
898
+ }
899
+ catch (err) {
900
+ // eslint-disable-next-line no-console
901
+ console.warn(`[tidegap/scheduler] tick: could not free stranded Batch poll ${row.taskId}: ${describeErr(err)}; skipping this round`);
902
+ }
903
+ }
904
+ }
683
905
  /**
684
906
  * Collect every "submitted" provider-call task awaiting batch results.
685
907
  * `exclude` skips tasks submitted earlier in the same tick — submit and
@@ -758,14 +980,47 @@ export class Scheduler {
758
980
  Object.assign(cached, row);
759
981
  return cached;
760
982
  }
983
+ /**
984
+ * The progress callback of one run: the lines an adapter reports become
985
+ * `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.
987
+ */
988
+ progressFor(taskId) {
989
+ const store = this.store;
990
+ if (!store)
991
+ return undefined;
992
+ let warned = false;
993
+ return createProgressRecorder((details) => {
994
+ try {
995
+ store.recordEvent(taskId, { kind: "progress", actor: "tick", details });
996
+ }
997
+ catch (err) {
998
+ if (warned)
999
+ return;
1000
+ warned = true;
1001
+ // eslint-disable-next-line no-console
1002
+ console.warn(`[tidegap/scheduler] task ${taskId}: could not record a progress event: ${describeErr(err)}`);
1003
+ }
1004
+ }, { existing: () => store.listTaskEvents(taskId).filter((e) => e.kind === "progress").length });
1005
+ }
1006
+ /** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
1007
+ sleepDetails() {
1008
+ try {
1009
+ const r = this.sleepCounter?.();
1010
+ return r && Number.isFinite(r.boot_at) && Number.isFinite(r.slept_ms) ? { sleep: { boot_at: r.boot_at, slept_ms: r.slept_ms } } : {};
1011
+ }
1012
+ catch {
1013
+ return {};
1014
+ }
1015
+ }
761
1016
  /**
762
1017
  * Compare-and-set write: store `next` only while the row's status is in
763
1018
  * `expected`; on success copy it onto the cached record. On a miss the
764
1019
  * cache is reloaded from the ledger and false is returned. Without a
765
1020
  * store the write always succeeds.
766
1021
  */
767
- writeIf(record, next, expected) {
768
- if (this.store && !this.store.transitionIf(next, expected)) {
1022
+ writeIf(record, next, expected, event) {
1023
+ if (this.store && !this.store.transitionIf(next, expected, undefined, this.eventFor(record, next, event))) {
769
1024
  const current = this.store.get(record.taskId);
770
1025
  if (current)
771
1026
  Object.assign(record, current);
@@ -774,6 +1029,17 @@ export class Scheduler {
774
1029
  Object.assign(record, next);
775
1030
  return true;
776
1031
  }
1032
+ /**
1033
+ * The `task_events` row for a write from `prev` to `next`: the given kind,
1034
+ * or a terminal kind the status change implies; undefined = no event.
1035
+ * `spec.details` are extra keys on top of {@link eventDetails}.
1036
+ */
1037
+ eventFor(prev, next, spec) {
1038
+ const kind = spec?.kind ?? (prev ? impliedEventKind(prev.status, next.status) : undefined);
1039
+ if (!kind)
1040
+ return undefined;
1041
+ return { kind, actor: spec?.actor ?? this.actor, details: eventDetails(kind, prev, next, spec?.details) };
1042
+ }
777
1043
  /**
778
1044
  * Series rollover (ui v2, KTD6). Called when an occurrence with a repeat
779
1045
  * rule finishes (completed, failed, or cancelled as a skip), BEFORE its
@@ -832,7 +1098,12 @@ export class Scheduler {
832
1098
  quotaProvider: deadlineKind === "quota_reset" ? quotaProvider : undefined,
833
1099
  };
834
1100
  if (this.store) {
835
- if (this.store.insertIfAbsent(successor)) {
1101
+ const created = this.eventFor(undefined, successor, {
1102
+ kind: "created",
1103
+ actor: "system",
1104
+ details: { series_id: record.seriesId, previous_task_id: record.taskId },
1105
+ });
1106
+ if (this.store.insertIfAbsent(successor, created)) {
836
1107
  this.cacheRow(successor);
837
1108
  // A stop written between the read above and the insert: end the
838
1109
  // successor too. `cancelTask(..., {series})` also cancels pending
@@ -855,7 +1126,7 @@ export class Scheduler {
855
1126
  * `record` itself, with `repeat = none` (stop series). Compare-and-set per
856
1127
  * row; a row another process claimed meanwhile is left to the dispatcher.
857
1128
  */
858
- endSeriesOccurrences(record) {
1129
+ endSeriesOccurrences(record, actor) {
859
1130
  if (!this.store || !record.seriesId)
860
1131
  return;
861
1132
  for (const row of this.store.list({ seriesId: record.seriesId })) {
@@ -871,7 +1142,7 @@ export class Scheduler {
871
1142
  completedAt: new Date().toISOString(),
872
1143
  bodyJson: redactBodyJson(row.bodyJson),
873
1144
  repeat: "none",
874
- }, ["queued", "scheduled"]);
1145
+ }, ["queued", "scheduled"], { kind: "cancelled", actor, details: { series: true } });
875
1146
  }
876
1147
  }
877
1148
  /** The newest quota label stored on any occurrence of the record's series. */
@@ -898,7 +1169,10 @@ export class Scheduler {
898
1169
  * claimed the row first, the cancel lands on the `running` row; the
899
1170
  * dispatcher re-checks the status before finalizing and drops the late
900
1171
  * result. `opts.series` also ends the series (`repeat = none`) in the
901
- * same write ("stop series").
1172
+ * same write ("stop series"); on a finished occurrence it ends the
1173
+ * series at its live occurrence. `opts.expectedStatus` cancels only a row in
1174
+ * one of those states and returns any other row unchanged: the job code
1175
+ * passes the pending states, so a row a tick claimed runs to its end.
902
1176
  */
903
1177
  cancelTask(taskId, opts = {}) {
904
1178
  for (let attempt = 0; attempt < 2; attempt++) {
@@ -906,7 +1180,17 @@ export class Scheduler {
906
1180
  if (!record) {
907
1181
  throw new TaskActionError(`cancelTask: task ${JSON.stringify(taskId)} not found`);
908
1182
  }
909
- if (TERMINAL.has(record.status))
1183
+ if (TERMINAL.has(record.status)) {
1184
+ // "Stop series" from a finished occurrence ends the series at its
1185
+ // live occurrence, so a later run does not roll it on.
1186
+ if (opts.series && record.seriesId) {
1187
+ const live = this.store?.list({ seriesId: record.seriesId }).find((r) => !TERMINAL.has(r.status));
1188
+ if (live)
1189
+ this.cancelTask(live.taskId, { series: true, actor: opts.actor });
1190
+ }
1191
+ return record;
1192
+ }
1193
+ if (opts.expectedStatus && !opts.expectedStatus.includes(record.status))
910
1194
  return record;
911
1195
  this.clearPendingTimer(taskId);
912
1196
  if (record.status === "submitted") {
@@ -931,10 +1215,15 @@ export class Scheduler {
931
1215
  this.rollSeries(record);
932
1216
  // A miss means another process moved the row (claimed or finished it)
933
1217
  // between our read and this write: re-read and try once more.
934
- if (!this.writeIf(record, next, [record.status]))
1218
+ const event = {
1219
+ kind: "cancelled",
1220
+ actor: opts.actor,
1221
+ details: { ...opts.details, ...(opts.series ? { series: true } : {}) },
1222
+ };
1223
+ if (!this.writeIf(record, next, [record.status], event))
935
1224
  continue;
936
1225
  if (opts.series)
937
- this.endSeriesOccurrences(record);
1226
+ this.endSeriesOccurrences(record, opts.actor);
938
1227
  const resolver = this.resolvers.get(taskId);
939
1228
  resolver?.reject(new Error(`task ${taskId} cancelled`));
940
1229
  this.bodies.delete(taskId);
@@ -951,7 +1240,7 @@ export class Scheduler {
951
1240
  * survives onto the completed row. Throws when the task's state does not
952
1241
  * allow it (see `taskActions`).
953
1242
  */
954
- runNow(taskId) {
1243
+ runNow(taskId, opts = {}) {
955
1244
  const record = this.refreshTask(taskId);
956
1245
  if (!record)
957
1246
  throw new TaskActionError(`runNow: task ${JSON.stringify(taskId)} not found`);
@@ -966,7 +1255,7 @@ export class Scheduler {
966
1255
  intensitySource: "expedited",
967
1256
  notBefore: undefined,
968
1257
  };
969
- if (!this.writeIf(record, next, PENDING_STATUSES)) {
1258
+ if (!this.writeIf(record, next, PENDING_STATUSES, { kind: "expedited", actor: opts.actor })) {
970
1259
  throw new TaskActionError(refusal("runNow", record, "only queued or scheduled provider-call tasks can run now"));
971
1260
  }
972
1261
  return record;
@@ -981,7 +1270,11 @@ export class Scheduler {
981
1270
  * compare-and-set on the pending statuses; throws when the task is not
982
1271
  * movable.
983
1272
  */
984
- async rescheduleTask(taskId, target) {
1273
+ async rescheduleTask(taskId, target, opts = {}) {
1274
+ return this.moveTask(taskId, target, { kind: "rescheduled", actor: opts.actor });
1275
+ }
1276
+ /** `rescheduleTask` with the event to record (`rescheduled` or `postponed`). */
1277
+ async moveTask(taskId, target, event) {
985
1278
  const why = "only queued or scheduled provider-call tasks can be rescheduled";
986
1279
  const shape = rescheduleShape(target);
987
1280
  const record = this.refreshTask(taskId);
@@ -1008,13 +1301,22 @@ export class Scheduler {
1008
1301
  deadline: new Date(deadlineMs).toISOString(),
1009
1302
  estimatedCarbonGCo2: undefined,
1010
1303
  };
1011
- if (!this.writeIf(record, next, PENDING_STATUSES)) {
1304
+ if (!this.writeIf(record, next, PENDING_STATUSES, event)) {
1012
1305
  throw new TaskActionError(refusal("reschedule", record, why));
1013
1306
  }
1014
1307
  return record;
1015
1308
  }
1016
1309
  let deadline;
1017
- if (shape.kind === "deadline") {
1310
+ if (shape.kind === "notBefore") {
1311
+ const start = parseInstant(shape.notBefore, "notBefore");
1312
+ const startMs = Math.max(start.getTime(), Date.now());
1313
+ const given = shape.deadline !== undefined ? normalizeDeadline(shape.deadline).getTime() : 0;
1314
+ const current = record.deadline ? Date.parse(record.deadline) : 0;
1315
+ const fields = startFields(startMs, given || current);
1316
+ deadline = new Date(fields.deadline);
1317
+ Object.assign(record, absolute, fields, { estimatedCarbonGCo2: undefined });
1318
+ }
1319
+ else if (shape.kind === "deadline") {
1018
1320
  deadline = normalizeDeadline(shape.deadline);
1019
1321
  Object.assign(record, absolute, { notBefore: undefined, deadline: deadline.toISOString() });
1020
1322
  }
@@ -1032,13 +1334,17 @@ export class Scheduler {
1032
1334
  const offset = Number.isFinite(current)
1033
1335
  ? (((current - dayStart.getTime()) % DAY_MS) + DAY_MS) % DAY_MS
1034
1336
  : 12 * HOUR_MS;
1337
+ // `scheduledFor === notBefore` marks an exact-time pin, which
1338
+ // `replanSweep` and the batch sweep skip. A fallback on the day's
1339
+ // first instant (a task now scheduled at that time of day) would read
1340
+ // as one and never be planned, so it moves one minute into the day.
1035
1341
  Object.assign(record, absolute, {
1036
1342
  notBefore: dayStart.toISOString(),
1037
1343
  deadline: deadline.toISOString(),
1038
- scheduledFor: new Date(dayStart.getTime() + offset).toISOString(),
1344
+ scheduledFor: new Date(dayStart.getTime() + Math.max(offset, MINUTE_MS)).toISOString(),
1039
1345
  });
1040
1346
  }
1041
- if (!(await this.scheduleProviderCall(taskId, deadline))) {
1347
+ if (!(await this.scheduleProviderCall(taskId, deadline, event))) {
1042
1348
  throw new TaskActionError(refusal("reschedule", record, why));
1043
1349
  }
1044
1350
  // Planning can fail the task (no hour under its carbon budget): report
@@ -1048,6 +1354,53 @@ export class Scheduler {
1048
1354
  }
1049
1355
  return record;
1050
1356
  }
1357
+ /**
1358
+ * "Later" (coherence KTD4): move a queued or scheduled provider-call task
1359
+ * so it never runs earlier than its planned start. Resolves the target
1360
+ * with {@link resolvePostpone} and writes it through `rescheduleTask`, so
1361
+ * the write is the same compare-and-set on the pending statuses. An
1362
+ * `after_limit_reset` target uses its own `resetAt` (stored as the hint),
1363
+ * else the plugged-in `limitReset` source, else a still-future hint.
1364
+ * Throws `TaskActionError` with the refusal reason.
1365
+ */
1366
+ async postponeTask(taskId, target, opts = {}) {
1367
+ const record = this.refreshTask(taskId);
1368
+ if (!record)
1369
+ throw new TaskActionError(`later: task ${JSON.stringify(taskId)} not found`);
1370
+ const now = new Date();
1371
+ const afterReset = "preset" in target && target.preset === "after_limit_reset";
1372
+ const givenReset = afterReset ? target.resetAt : undefined;
1373
+ const reset = afterReset && givenReset === undefined ? await resolveLimitReset(record, now, this.limitReset, this.store) : null;
1374
+ // Resolve against the row as it is after the wait: another process may
1375
+ // have moved it meanwhile, and "later" is measured from its current plan.
1376
+ const current = this.refreshTask(taskId);
1377
+ if (!current)
1378
+ throw new TaskActionError(`later: task ${JSON.stringify(taskId)} not found`);
1379
+ const resolved = resolvePostpone(current, target, now, reset);
1380
+ if (!resolved.ok)
1381
+ throw new TaskActionError(`later: task ${taskId}: ${resolved.reason}`);
1382
+ const moved = await this.moveTask(taskId, resolved.reschedule, {
1383
+ kind: "postponed",
1384
+ actor: opts.actor,
1385
+ details: "preset" in target ? { preset: target.preset } : {},
1386
+ });
1387
+ if (givenReset !== undefined)
1388
+ writeLimitResetHint(this.store, new Date(givenReset), taskProvider(record));
1389
+ return moved;
1390
+ }
1391
+ /**
1392
+ * The Later presets of a task with their resolved times (KTD6), using
1393
+ * the plugged-in reset source and the stored hint.
1394
+ */
1395
+ async postponeOptionsFor(task, now = new Date()) {
1396
+ const record = typeof task === "string" ? this.refreshTask(task) : task;
1397
+ if (!record)
1398
+ throw new TaskActionError(`later: task ${JSON.stringify(task)} not found`);
1399
+ const reset = taskActions(record).later
1400
+ ? await resolveLimitReset(record, now, this.limitReset, this.store)
1401
+ : null;
1402
+ return postponeOptions(record, now, reset);
1403
+ }
1051
1404
  /**
1052
1405
  * Reply to a completed provider-call task (ui v2, brainstorm R16/R17):
1053
1406
  * enqueue a child with the parent's conversation as history, the reply as
@@ -1066,6 +1419,7 @@ export class Scheduler {
1066
1419
  throw new TaskActionError("reply: text must be a non-empty string");
1067
1420
  }
1068
1421
  const spec = JSON.parse(parent.bodyJson);
1422
+ const handoff = replyHandoff(spec);
1069
1423
  const child = {
1070
1424
  type: "provider_call",
1071
1425
  provider: spec.provider,
@@ -1077,8 +1431,16 @@ export class Scheduler {
1077
1431
  ...(spec.maxTokens !== undefined ? { maxTokens: spec.maxTokens } : {}),
1078
1432
  ...(spec.temperature !== undefined ? { temperature: spec.temperature } : {}),
1079
1433
  ...(spec.redactInReceipt !== undefined ? { redactInReceipt: spec.redactInReceipt } : {}),
1434
+ ...(spec.tools !== undefined ? { tools: spec.tools } : {}),
1435
+ // The reply works in the parent's folder with its profile (checked
1436
+ // again at enqueue); it writes no result file of its own.
1437
+ ...(handoff ? { handoff } : {}),
1438
+ // With keepOrigin, the reply runs in the parent's origin session too
1439
+ // (with the parent's turns as history), so it keeps the facts the run needs.
1440
+ ...(opts.keepOrigin === true && spec.origin !== undefined ? { origin: spec.origin } : {}),
1080
1441
  };
1081
- return this.enqueueProviderCall(child, {
1442
+ const created = await this.enqueueProviderCall(child, {
1443
+ actor: opts.actor,
1082
1444
  deadline: opts.deadline ?? new Date(Date.now() + HOUR_MS),
1083
1445
  region: parent.region,
1084
1446
  parentTaskId: parent.taskId,
@@ -1087,6 +1449,20 @@ export class Scheduler {
1087
1449
  originCwd: opts.originCwd ?? parent.originCwd,
1088
1450
  originSessionId: opts.originSessionId ?? parent.originSessionId,
1089
1451
  });
1452
+ // The child is already committed (with its own `created` event): a
1453
+ // failed audit write on the parent must not fail the reply.
1454
+ try {
1455
+ this.store?.recordEvent(parent.taskId, {
1456
+ kind: "replied",
1457
+ actor: opts.actor ?? this.actor,
1458
+ details: { child_task_id: created.taskId },
1459
+ });
1460
+ }
1461
+ catch (err) {
1462
+ // eslint-disable-next-line no-console
1463
+ console.warn(`[tidegap/scheduler] task ${parent.taskId}: could not record the replied event: ${String(err)}`);
1464
+ }
1465
+ return created;
1090
1466
  }
1091
1467
  /**
1092
1468
  * Dispatch a queued/scheduled provider-call task immediately,
@@ -1094,7 +1470,7 @@ export class Scheduler {
1094
1470
  * `intensitySource: "expedited"`. Closure-based tasks (from
1095
1471
  * `defer`) are not expediteable; we throw a clear error.
1096
1472
  */
1097
- async expediteTask(taskId, adapters) {
1473
+ async expediteTask(taskId, adapters, opts = {}) {
1098
1474
  const record = this.refreshTask(taskId);
1099
1475
  if (!record) {
1100
1476
  throw new Error(`expediteTask: task ${JSON.stringify(taskId)} not found`);
@@ -1113,6 +1489,9 @@ export class Scheduler {
1113
1489
  if (!record.bodyJson) {
1114
1490
  throw new Error(`expediteTask: task ${taskId} is a closure-based task; only provider-call tasks can be expedited`);
1115
1491
  }
1492
+ if (unservedCommand(record, adapters)) {
1493
+ throw new Error(`expediteTask: task ${taskId} runs a shell command, which only the tidegap tick runs; use run now instead`);
1494
+ }
1116
1495
  this.clearPendingTimer(taskId);
1117
1496
  const next = {
1118
1497
  ...record,
@@ -1124,7 +1503,7 @@ export class Scheduler {
1124
1503
  // Same row-level claim `tick` uses: if a concurrent process (e.g. the
1125
1504
  // cron tick) grabbed the row between our read and here, do NOT
1126
1505
  // dispatch a second (double-billed) provider call.
1127
- if (!this.writeIf(record, next, PENDING_STATUSES) ||
1506
+ if (!this.writeIf(record, next, PENDING_STATUSES, { kind: "expedited", actor: opts.actor }) ||
1128
1507
  (this.store && !this.store.claimScheduled(taskId))) {
1129
1508
  throw new Error(`task ${taskId} was just claimed by another process (racing tick?)`);
1130
1509
  }
@@ -1160,7 +1539,8 @@ export class Scheduler {
1160
1539
  if (record.bodyJson) {
1161
1540
  // A new deadline replaces any pinned earliest start.
1162
1541
  record.notBefore = undefined;
1163
- if (!(await this.scheduleProviderCall(taskId, parsedDeadline))) {
1542
+ const event = { kind: "rescheduled", actor: opts.actor, details: { reason: "deadline" } };
1543
+ if (!(await this.scheduleProviderCall(taskId, parsedDeadline, event))) {
1164
1544
  throw new Error(`updateDeadline: task ${taskId} is ${record.status}; can only update queued/scheduled tasks`);
1165
1545
  }
1166
1546
  }
@@ -1195,7 +1575,11 @@ export class Scheduler {
1195
1575
  return false;
1196
1576
  record.deadline = newDeadline.toISOString();
1197
1577
  this.clearPendingTimer(taskId);
1198
- return this.scheduleProviderCall(taskId, newDeadline);
1578
+ return this.scheduleProviderCall(taskId, newDeadline, {
1579
+ kind: "rescheduled",
1580
+ actor: "system",
1581
+ details: { reason: "quota_sweep" },
1582
+ });
1199
1583
  }
1200
1584
  /**
1201
1585
  * Re-dispatch a failed task. Useful when the original failure was a
@@ -1203,7 +1587,7 @@ export class Scheduler {
1203
1587
  * spec is still valid. Only `failed` tasks are eligible; throws
1204
1588
  * otherwise.
1205
1589
  */
1206
- async retryTask(taskId, adapters) {
1590
+ async retryTask(taskId, adapters, opts = {}) {
1207
1591
  const record = this.refreshTask(taskId);
1208
1592
  if (!record) {
1209
1593
  throw new Error(`retryTask: task ${JSON.stringify(taskId)} not found`);
@@ -1211,9 +1595,24 @@ export class Scheduler {
1211
1595
  if (record.status !== "failed") {
1212
1596
  throw new Error(`retryTask: task ${taskId} has status ${record.status}; retry is only valid on failed tasks`);
1213
1597
  }
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");
1602
+ }
1214
1603
  if (!record.bodyJson) {
1215
1604
  throw new Error(`retryTask: task ${taskId} is closure-based; only provider-call tasks can be retried`);
1216
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
+ }
1217
1616
  const next = {
1218
1617
  ...record,
1219
1618
  status: "scheduled",
@@ -1227,7 +1626,7 @@ export class Scheduler {
1227
1626
  };
1228
1627
  // Row-level claim: don't double-dispatch if a concurrent tick in
1229
1628
  // another process grabbed the freshly re-scheduled row first.
1230
- if (!this.writeIf(record, next, ["failed"]) ||
1629
+ if (!this.writeIf(record, next, ["failed"], { kind: "rescheduled", actor: opts.actor, details: { reason: "retry" } }) ||
1231
1630
  (this.store && !this.store.claimScheduled(taskId))) {
1232
1631
  throw new Error(`task ${taskId} was just claimed by another process (racing tick?)`);
1233
1632
  }
@@ -1240,14 +1639,26 @@ export class Scheduler {
1240
1639
  * with `dry_run: true`.
1241
1640
  */
1242
1641
  async previewProviderCall(spec, opts = {}) {
1243
- const deadline = normalizeDeadline(opts.deadline);
1244
- const region = opts.region ?? this.defaultRegion;
1642
+ // The same refusals as the commit path, so a preview never shows a task
1643
+ // the real enqueue would refuse.
1644
+ checkedHandoff(spec, opts, "previewProviderCall");
1645
+ const requested = normalizeDeadline(opts.deadline);
1646
+ // An earliest start (after_limit_reset): same rule as the commit path.
1647
+ const notBefore = earliestStart(opts.notBefore);
1648
+ const deadline = notBefore
1649
+ ? new Date(startFields(notBefore.getTime(), requested.getTime()).deadline)
1650
+ : requested;
1651
+ const earliestMs = notBefore ? notBefore.getTime() + MINUTE_MS : 0;
1652
+ const region = opts.region ?? this.defaultRegion();
1245
1653
  const horizonH = Math.max(1, Math.min(MAX_HORIZON_HOURS, Math.ceil((deadline.getTime() - Date.now()) / (60 * 60 * 1000))));
1246
1654
  const forecast = await this.feed.fetchForecast(region, horizonH);
1655
+ const entries = notBefore
1656
+ ? forecast.entries.filter((e) => Date.parse(e.datetime) + HOUR_MS > notBefore.getTime())
1657
+ : forecast.entries;
1247
1658
  const budgetG = opts.carbonBudgetG;
1248
1659
  const survivors = budgetG !== undefined
1249
- ? forecast.entries.filter((e) => intensityToGrams(e.carbonIntensityGCo2PerKwh, spec.model) <= budgetG)
1250
- : forecast.entries;
1660
+ ? entries.filter((e) => intensityToGrams(e.carbonIntensityGCo2PerKwh, spec.model) <= budgetG)
1661
+ : entries;
1251
1662
  // Shared selection (§2.1): preview and the eventual commit both run
1252
1663
  // `selectWindow` over the same budget survivors, so they agree on the
1253
1664
  // candidate band even though each makes its own random pick within it.
@@ -1268,7 +1679,7 @@ export class Scheduler {
1268
1679
  // No usable window inside the deadline. Mirror what the commit path
1269
1680
  // (`scheduleProviderCall`) does — schedule for "now" — instead of
1270
1681
  // throwing, so dry_run and the real call cannot diverge.
1271
- const head = forecast.entries[0];
1682
+ const head = entries[0] ?? forecast.entries[0];
1272
1683
  if (!head) {
1273
1684
  throw new Error("previewProviderCall: forecast returned no entries");
1274
1685
  }
@@ -1282,12 +1693,13 @@ export class Scheduler {
1282
1693
  rng: this.rng,
1283
1694
  });
1284
1695
  return {
1285
- scheduledFor: new Date().toISOString(),
1696
+ scheduledFor: new Date(Math.max(Date.now(), earliestMs)).toISOString(),
1286
1697
  estimatedCarbonGCo2: Math.round(intensityToGrams(head.carbonIntensityGCo2PerKwh, spec.model) * 10) / 10,
1287
1698
  intensityGCo2PerKwh: head.carbonIntensityGCo2PerKwh,
1288
1699
  band: head.band,
1289
1700
  batchEligible,
1290
1701
  region,
1702
+ deadline: deadline.toISOString(),
1291
1703
  ...(routingPreviewNow ? { routingPreview: routingPreviewNow } : {}),
1292
1704
  };
1293
1705
  }
@@ -1302,14 +1714,17 @@ export class Scheduler {
1302
1714
  return {
1303
1715
  // A candidate whose hour started in the past is the *current* hour —
1304
1716
  // the commit path dispatches now, so the preview says "now" too.
1305
- scheduledFor: new Date(candidate.datetime).getTime() <= Date.now()
1306
- ? new Date().toISOString()
1307
- : candidate.datetime,
1717
+ scheduledFor: earliestMs > new Date(candidate.datetime).getTime()
1718
+ ? new Date(earliestMs).toISOString()
1719
+ : new Date(candidate.datetime).getTime() <= Date.now()
1720
+ ? new Date().toISOString()
1721
+ : candidate.datetime,
1308
1722
  estimatedCarbonGCo2: Math.round(intensityToGrams(candidate.carbonIntensityGCo2PerKwh, spec.model) * 10) / 10,
1309
1723
  intensityGCo2PerKwh: candidate.carbonIntensityGCo2PerKwh,
1310
1724
  band: candidate.band,
1311
1725
  batchEligible,
1312
1726
  region,
1727
+ deadline: deadline.toISOString(),
1313
1728
  cleanBandSize: selection.band.length,
1314
1729
  ...(routingPreview ? { routingPreview } : {}),
1315
1730
  };
@@ -1318,6 +1733,50 @@ export class Scheduler {
1318
1733
  listTasks() {
1319
1734
  return Array.from(this.tasks.values());
1320
1735
  }
1736
+ /** Runs the dispatch of a row the tick moved to `running`, holding the row until it settles. */
1737
+ async holding(record, phase, dispatch) {
1738
+ this.held.set(record.taskId, { record, phase });
1739
+ try {
1740
+ return await dispatch();
1741
+ }
1742
+ finally {
1743
+ this.held.delete(record.taskId);
1744
+ }
1745
+ }
1746
+ /**
1747
+ * A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
1748
+ * scheduler moved to `running` in a tick whose dispatch has not settled,
1749
+ * by what the row was doing:
1750
+ * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`);
1751
+ * - a Batch poll goes back to `submitted` with its `batchId`: the batch
1752
+ * is live at the provider, and the next tick polls it again;
1753
+ * - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
1754
+ * provider may have accepted the batch, so no retry path runs it again.
1755
+ * Compare-and-set from `running`, so a row another writer finished first
1756
+ * keeps its status; rows another process holds, or a crashed tick
1757
+ * stranded, are not touched (the job sweep frees job runs, and the next
1758
+ * 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.
1761
+ */
1762
+ failHeldRuns() {
1763
+ const failed = [];
1764
+ for (const { record, phase } of this.held.values()) {
1765
+ if (phase === "batch_poll") {
1766
+ this.writeIf(record, { ...record, status: "submitted", completedAt: undefined, error: undefined }, ["running"]);
1767
+ continue;
1768
+ }
1769
+ this.rollSeries(record);
1770
+ const submit = phase === "batch_submit";
1771
+ const details = { reason: "interrupted", ...(submit ? { phase } : {}), ...(record.jobId ? { job_id: record.jobId } : {}) };
1772
+ 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 }))
1775
+ failed.push(record.taskId);
1776
+ }
1777
+ this.held.clear();
1778
+ return failed;
1779
+ }
1321
1780
  /** Cancel and clean up timers. Mostly for tests. */
1322
1781
  shutdown() {
1323
1782
  for (const timer of this.pendingTimers.values()) {
@@ -1364,7 +1823,9 @@ export class Scheduler {
1364
1823
  return;
1365
1824
  }
1366
1825
  if (!this.writeIf(record, { ...record, status: "scheduled", scheduledFor: candidate.datetime }, PENDING_STATUSES)) {
1367
- return; // cancelled from another process meanwhile
1826
+ // Cancelled from another process during the forecast fetch.
1827
+ this.rejectMissedClosure(taskId, record);
1828
+ return;
1368
1829
  }
1369
1830
  const wait = Math.max(0, new Date(candidate.datetime).getTime() - Date.now());
1370
1831
  // Node's setTimeout overflows the signed-32-bit ms range (~24.85 days).
@@ -1393,6 +1854,17 @@ export class Scheduler {
1393
1854
  this.failTask(taskId, err instanceof Error ? err : new Error(String(err)));
1394
1855
  });
1395
1856
  }
1857
+ /**
1858
+ * A closure task's write missed: another process cancelled, claimed or
1859
+ * finished its row. Reject the awaiter with the status the ledger now
1860
+ * holds and drop the body, so `defer()` never waits forever. A no-op for
1861
+ * a provider call, which has no awaiter.
1862
+ */
1863
+ rejectMissedClosure(taskId, record) {
1864
+ this.resolvers.get(taskId)?.reject(new Error(`task ${taskId} ${record.status}`));
1865
+ this.bodies.delete(taskId);
1866
+ this.resolvers.delete(taskId);
1867
+ }
1396
1868
  failTask(taskId, err, onlyIfPending = false) {
1397
1869
  const record = this.tasks.get(taskId);
1398
1870
  if (!record)
@@ -1413,6 +1885,7 @@ export class Scheduler {
1413
1885
  // Compare-and-set: never overwrite a row another process finished or
1414
1886
  // cancelled meanwhile.
1415
1887
  if (!this.writeIf(record, next, onlyIfPending ? PENDING_STATUSES : UNFINISHED_STATUSES)) {
1888
+ this.rejectMissedClosure(taskId, record);
1416
1889
  return false;
1417
1890
  }
1418
1891
  const resolver = this.resolvers.get(taskId);
@@ -1427,11 +1900,9 @@ export class Scheduler {
1427
1900
  const resolver = this.resolvers.get(taskId);
1428
1901
  if (!record || !body)
1429
1902
  return;
1430
- if (!this.writeIf(record, { ...record, status: "running" }, PENDING_STATUSES)) {
1903
+ if (!this.writeIf(record, { ...record, status: "running" }, PENDING_STATUSES, { kind: "dispatched" })) {
1431
1904
  // Cancelled (possibly from another process) before the window came.
1432
- resolver?.reject(new Error(`task ${taskId} ${record.status}`));
1433
- this.bodies.delete(taskId);
1434
- this.resolvers.delete(taskId);
1905
+ this.rejectMissedClosure(taskId, record);
1435
1906
  return;
1436
1907
  }
1437
1908
  const start = Date.now();
@@ -1558,7 +2029,7 @@ export class Scheduler {
1558
2029
  * [notBefore, deadline] with no estimate ("unplanned"); `replanSweep`
1559
2030
  * re-scores it once the forecast covers it.
1560
2031
  */
1561
- async scheduleProviderCall(taskId, deadline) {
2032
+ async scheduleProviderCall(taskId, deadline, event) {
1562
2033
  const record = this.tasks.get(taskId);
1563
2034
  if (!record)
1564
2035
  return false;
@@ -1602,10 +2073,12 @@ export class Scheduler {
1602
2073
  record.status = "scheduled";
1603
2074
  record.scheduledFor = clampIso(record.scheduledFor, notBeforeMs, deadline.getTime());
1604
2075
  record.estimatedCarbonGCo2 = undefined;
1605
- return this.persist(record, before);
2076
+ return this.persist(record, before, event);
1606
2077
  }
1607
2078
  }
1608
- const earliest = pinned ? notBeforeMs : Date.now();
2079
+ // One minute past a pinned start: a picked hour that contains it would
2080
+ // otherwise give `scheduledFor === notBefore`, which reads as an exact pin.
2081
+ const earliest = pinned ? notBeforeMs + MINUTE_MS : Date.now();
1609
2082
  const budgetG = record.carbonBudgetG;
1610
2083
  const survivors = budgetG !== undefined
1611
2084
  ? entries.filter((e) => intensityToGrams(e.carbonIntensityGCo2PerKwh, specModel) <= budgetG)
@@ -1634,7 +2107,7 @@ export class Scheduler {
1634
2107
  record.estimatedCarbonGCo2 =
1635
2108
  Math.round(intensityToGrams(nowIntensity, routedModelNow) * 10) / 10;
1636
2109
  }
1637
- return this.persist(record, before);
2110
+ return this.persist(record, before, event);
1638
2111
  }
1639
2112
  record.status = "scheduled";
1640
2113
  // A candidate whose hour started in the past is the *current* hour —
@@ -1649,7 +2122,7 @@ export class Scheduler {
1649
2122
  const routedModel = this.applyRoutingIfNeeded(record, spec, candidate.carbonIntensityGCo2PerKwh);
1650
2123
  record.estimatedCarbonGCo2 =
1651
2124
  Math.round(intensityToGrams(candidate.carbonIntensityGCo2PerKwh, routedModel) * 10) / 10;
1652
- return this.persist(record, before);
2125
+ return this.persist(record, before, event);
1653
2126
  }
1654
2127
  /**
1655
2128
  * Write a scheduling result with a compare-and-set on the pending
@@ -1658,10 +2131,11 @@ export class Scheduler {
1658
2131
  * written, the cached record is reloaded from the ledger, and false is
1659
2132
  * returned.
1660
2133
  */
1661
- persist(record, before) {
2134
+ persist(record, before, event) {
1662
2135
  if (!this.store)
1663
2136
  return true;
1664
- if (this.store.transitionIf(record, PENDING_STATUSES, before))
2137
+ const ev = event ? this.eventFor(before, record, event) : undefined;
2138
+ if (this.store.transitionIf(record, PENDING_STATUSES, before, ev))
1665
2139
  return true;
1666
2140
  const current = this.store.get(record.taskId);
1667
2141
  if (current)
@@ -1704,7 +2178,7 @@ export class Scheduler {
1704
2178
  record.routingDecision = decision;
1705
2179
  return chosen?.model ?? spec.model;
1706
2180
  }
1707
- async dispatchProviderCall(record, adapters) {
2181
+ async dispatchProviderCall(record, adapters, deferrals) {
1708
2182
  let spec;
1709
2183
  try {
1710
2184
  spec = JSON.parse(record.bodyJson ?? "null");
@@ -1760,11 +2234,19 @@ export class Scheduler {
1760
2234
  this.failTask(record.taskId, new Error(msg));
1761
2235
  return { taskId: record.taskId, status: "failed", error: msg };
1762
2236
  }
2237
+ const deferKey = deferKeyOf(spec);
2238
+ const earlier = deferrals?.get(deferKey);
2239
+ if (earlier) {
2240
+ return this.deferTask(record, earlier, `${spec.provider}: deferred with an earlier task this tick until ${earlier.toISOString()}`);
2241
+ }
1763
2242
  let stillOurs = true;
1764
2243
  try {
1765
2244
  // The row was claimed (`running`) or, without a store, is ours. A
1766
2245
  // cancel that landed after the claim wins: do not make the call.
1767
- stillOurs = this.writeIf(record, { ...record, status: "running" }, ["running", "scheduled"]);
2246
+ stillOurs = this.writeIf(record, { ...record, status: "running" }, ["running", "scheduled"], {
2247
+ kind: "dispatched",
2248
+ details: { provider: spec.provider, model: spec.model, ...this.sleepDetails() },
2249
+ });
1768
2250
  }
1769
2251
  catch (err) {
1770
2252
  // eslint-disable-next-line no-console
@@ -1785,6 +2267,9 @@ export class Scheduler {
1785
2267
  // dispatch must NEVER be re-labelled "failed" (a retry would bill the
1786
2268
  // provider a second time).
1787
2269
  let result;
2270
+ // Lines the run reports while it runs (the command adapter's output);
2271
+ // nothing is written once the call settled.
2272
+ const progress = this.progressFor(record.taskId);
1788
2273
  try {
1789
2274
  // Batch routing (deadline > 24h) is handled by the dedicated
1790
2275
  // submit/poll sweeps in tick(); by the time a task reaches this
@@ -1794,12 +2279,22 @@ export class Scheduler {
1794
2279
  maxTokens: spec.maxTokens,
1795
2280
  system: spec.systemPrompt,
1796
2281
  messages: spec.messages,
1797
- }));
2282
+ ...(spec.tools !== undefined ? { tools: spec.tools } : {}),
2283
+ ...dispatchOrigin(record, spec),
2284
+ ...jobDispatchOptions(record, spec),
2285
+ ...(progress ? { onProgress: (line) => progress.onLine(line), onProgressEnd: () => progress.close() } : {}),
2286
+ })).finally(() => progress?.close());
1798
2287
  }
1799
2288
  catch (err) {
1800
2289
  const msg = err instanceof Error ? err.message : String(err);
2290
+ const retryAt = deferRetryAt(err);
2291
+ if (retryAt) {
2292
+ deferrals?.set(deferKey, retryAt);
2293
+ return this.deferTask(record, retryAt, msg);
2294
+ }
1801
2295
  this.rollSeries(record);
1802
- this.writeIf(record, { ...record, status: "failed", completedAt: new Date().toISOString(), error: msg }, ["running"]);
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);
1803
2298
  return { taskId: record.taskId, status: "failed", error: msg };
1804
2299
  }
1805
2300
  const durationMs = Date.now() - start;
@@ -1846,19 +2341,26 @@ export class Scheduler {
1846
2341
  // we re-estimate energy with the real token counts the provider
1847
2342
  // reported (when available) — that turns the receipt from "typical
1848
2343
  // task at this model" into "this specific call at this model".
1849
- const usage = result.usage;
1850
- const inputTokens = typeof usage?.inputTokens === "number" ? usage.inputTokens : undefined;
1851
- const outputTokens = typeof usage?.outputTokens === "number" ? usage.outputTokens : undefined;
1852
- const actualModel = result.model ?? spec.model;
1853
- const totalTokens = typeof usage?.totalTokens === "number" ? usage.totalTokens : undefined;
2344
+ // A count that is absent, not a number, negative or not finite is
2345
+ // unreported: billed at the typical count and left out (KTD2).
2346
+ const counts = singleModelCounts(result.usage);
2347
+ const modelUsage = result.modelUsage;
1854
2348
  let receipt;
1855
2349
  try {
2350
+ // A run that used two or more models is billed model by model (KTD7);
2351
+ // the totals, the dominant model and the weakest tiers come from the
2352
+ // bill. Otherwise `usage` is billed under one model, as before.
2353
+ const bill = Array.isArray(modelUsage) ? billModelUsage(intensityG, modelUsage) : undefined;
2354
+ const actualModel = bill?.model ?? result.model ?? spec.model;
2355
+ const totalTokens = bill ? bill.totalTokens : counts.totalTokens;
2356
+ const tokenCounts = bill ? bill.tokenCounts : counts.tokenCounts;
1856
2357
  const actualCarbonGCo2 = intensityG !== undefined
1857
- ? Math.round(gramsForIntensity(intensityG, {
1858
- model: actualModel,
1859
- inputTokens,
1860
- outputTokens,
1861
- }) * 10) / 10
2358
+ ? Math.round((bill?.carbonGCo2 ??
2359
+ gramsForIntensity(intensityG, {
2360
+ model: actualModel,
2361
+ inputTokens: counts.inputTokens,
2362
+ outputTokens: counts.outputTokens,
2363
+ })) * 10) / 10
1862
2364
  : (record.estimatedCarbonGCo2 ?? 0);
1863
2365
  const estimatedCarbonGCo2 = record.estimatedCarbonGCo2 ?? actualCarbonGCo2;
1864
2366
  const deltaPct = estimatedCarbonGCo2 > 0
@@ -1875,7 +2377,7 @@ export class Scheduler {
1875
2377
  // what was requested — the OpenClaw runtime bridge may run a
1876
2378
  // different model than spec.model. The batch path has no model.
1877
2379
  provider: result.provider ?? spec.provider,
1878
- model: result.model ?? spec.model,
2380
+ model: actualModel,
1879
2381
  durationMs,
1880
2382
  prompt: redactPrompt(spec.prompt, spec.redactInReceipt),
1881
2383
  totalTokens,
@@ -1887,12 +2389,20 @@ export class Scheduler {
1887
2389
  intensityGCo2PerKwh: intensityG,
1888
2390
  gridSource,
1889
2391
  signalType,
1890
- energySource: resolveModelEnergy(actualModel).coeffs.source,
1891
- energyResolution: resolveModelEnergy(actualModel).tier,
2392
+ energySource: bill?.energySource ?? resolveModelEnergy(actualModel).coeffs.source,
2393
+ energyResolution: bill?.energyResolution ?? resolveModelEnergy(actualModel).tier,
1892
2394
  // Cross-provider routing provenance (ROADMAP item 1): the scored
1893
2395
  // candidate list, weights, chosen id (+ any dispatch fallbackFrom).
1894
2396
  // Inside the signed payload; omitted when routing was not used.
1895
2397
  routing: record.routingDecision,
2398
+ tools: result.tools,
2399
+ session: result.session,
2400
+ // Per-model breakdown (KTD5): inside the signed payload; absent for
2401
+ // a single-model run, whose receipt is unchanged.
2402
+ models: bill?.models,
2403
+ // Signed; written only when a count was not reported in full, so a
2404
+ // fully reported receipt keeps its canonical bytes (KTD1).
2405
+ ...(tokenCounts !== undefined ? { tokenCounts } : {}),
1896
2406
  });
1897
2407
  }
1898
2408
  catch (err) {
@@ -1915,8 +2425,9 @@ export class Scheduler {
1915
2425
  bodyJson: redactBodyJson(record.bodyJson),
1916
2426
  };
1917
2427
  this.rollSeries(record);
2428
+ const completedDetails = runDetails(result.details);
1918
2429
  try {
1919
- if (!this.writeIf(record, completed, ["running"])) {
2430
+ if (!this.writeIf(record, completed, ["running"], completedDetails ? { kind: "completed", details: completedDetails } : undefined)) {
1920
2431
  // eslint-disable-next-line no-console
1921
2432
  console.warn(`[tidegap/scheduler] task ${record.taskId} was ${record.status} while running; dropping its late result`);
1922
2433
  return {
@@ -1931,10 +2442,50 @@ export class Scheduler {
1931
2442
  console.warn(`[tidegap/scheduler] failed to persist completed task ${record.taskId}: ${describeErr(err)}`);
1932
2443
  }
1933
2444
  if (spec.outputPath && receipt) {
1934
- await writeOutputFile(spec.outputPath, record.taskId, result, receipt);
2445
+ await writeOutputFile(spec.outputPath, record.taskId, result, receipt, {
2446
+ cwd: spec.handoff?.cwd,
2447
+ originCwd: record.originCwd,
2448
+ });
1935
2449
  }
1936
2450
  return { taskId: record.taskId, status: "completed" };
1937
2451
  }
2452
+ /**
2453
+ * Put a running task back in the queue until `retryAt` (KTD7): `scheduled`,
2454
+ * `notBefore = retryAt`, one minute later as the fallback time, the
2455
+ * deadline raised to at least `retryAt + 2 h`, the estimate cleared so
2456
+ * `replanSweep` moves it to the cleanest hour once the forecast covers it.
2457
+ * Compare-and-set on `running`: a cancel during the run wins. Past the
2458
+ * 8-day cap from `enqueuedAt` the task fails with `message` instead.
2459
+ */
2460
+ deferTask(record, retryAt, message) {
2461
+ const retryMs = retryAt.getTime();
2462
+ const capMs = Date.parse(record.enqueuedAt) + DEFER_CAP_MS;
2463
+ 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 };
2468
+ }
2469
+ const next = {
2470
+ ...record,
2471
+ status: "scheduled",
2472
+ ...startFields(retryMs, record.deadline ? Date.parse(record.deadline) : 0),
2473
+ estimatedCarbonGCo2: undefined,
2474
+ intensitySource: undefined,
2475
+ };
2476
+ const event = {
2477
+ kind: "deferred",
2478
+ details: { retry_at: retryAt.toISOString(), reason: message.split("\n")[0].slice(0, 300) },
2479
+ };
2480
+ if (!this.writeIf(record, next, ["running"], event)) {
2481
+ return {
2482
+ taskId: record.taskId,
2483
+ status: "failed",
2484
+ error: `task was ${record.status} while running; deferral dropped`,
2485
+ };
2486
+ }
2487
+ return { taskId: record.taskId, status: "deferred", retryAt: retryAt.toISOString(), error: message };
2488
+ }
1938
2489
  /**
1939
2490
  * Submit a batch-eligible task to the provider's Batch API. The row was
1940
2491
  * already claimed (scheduled → running) by the caller. On success the
@@ -1971,7 +2522,14 @@ export class Scheduler {
1971
2522
  messages: spec.messages,
1972
2523
  }));
1973
2524
  try {
1974
- this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"]);
2525
+ if (!this.writeIf(record, { ...record, status: "submitted", batchId: handle.batchId }, ["running"], { kind: "dispatched", details: { batch_id: handle.batchId } })) {
2526
+ // Another writer moved the row (a cancel) during the submit: it
2527
+ // keeps its status, and the live batch is reported, not stored.
2528
+ 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`;
2529
+ // eslint-disable-next-line no-console
2530
+ console.warn(`[tidegap/scheduler] ${record.taskId}: ${error}`);
2531
+ return { taskId: record.taskId, status: "failed", error };
2532
+ }
1975
2533
  }
1976
2534
  catch (err) {
1977
2535
  // eslint-disable-next-line no-console
@@ -1994,6 +2552,11 @@ export class Scheduler {
1994
2552
  record.status = "scheduled";
1995
2553
  record.batchId = undefined;
1996
2554
  record.error = undefined;
2555
+ // The submit failed, so no batch exists: a forced stop from here on
2556
+ // interrupts a provider call.
2557
+ const held = this.held.get(record.taskId);
2558
+ if (held)
2559
+ held.phase = "provider_call";
1997
2560
  return this.dispatchProviderCall(record, adapters);
1998
2561
  }
1999
2562
  this.rollSeries(record);
@@ -2091,18 +2654,16 @@ export class Scheduler {
2091
2654
  // eslint-disable-next-line no-console
2092
2655
  console.warn(`[tidegap/scheduler] intensity fetch for the receipt failed (${describeErr(err)}); receipt falls back to the schedule-time estimate`);
2093
2656
  }
2094
- const usage = result.usage;
2095
- const inputTokens = typeof usage?.inputTokens === "number" ? usage.inputTokens : undefined;
2096
- const outputTokens = typeof usage?.outputTokens === "number" ? usage.outputTokens : undefined;
2657
+ // The count rule of the sync path (KTD2).
2658
+ const counts = singleModelCounts(result.usage);
2097
2659
  const actualModel = result.model;
2098
- const totalTokens = typeof usage?.totalTokens === "number" ? usage.totalTokens : undefined;
2099
2660
  let receipt;
2100
2661
  try {
2101
2662
  const actualCarbonGCo2 = intensityG !== undefined
2102
2663
  ? Math.round(gramsForIntensity(intensityG, {
2103
2664
  model: actualModel,
2104
- inputTokens,
2105
- outputTokens,
2665
+ inputTokens: counts.inputTokens,
2666
+ outputTokens: counts.outputTokens,
2106
2667
  }) * 10) / 10
2107
2668
  : (record.estimatedCarbonGCo2 ?? 0);
2108
2669
  const estimatedCarbonGCo2 = record.estimatedCarbonGCo2 ?? actualCarbonGCo2;
@@ -2119,7 +2680,7 @@ export class Scheduler {
2119
2680
  provider: result.provider ?? spec.provider,
2120
2681
  model: actualModel,
2121
2682
  prompt: redactPrompt(spec.prompt, spec.redactInReceipt),
2122
- totalTokens,
2683
+ totalTokens: counts.totalTokens,
2123
2684
  intensityGCo2PerKwh: intensityG,
2124
2685
  gridSource,
2125
2686
  signalType,
@@ -2128,6 +2689,7 @@ export class Scheduler {
2128
2689
  // Cross-provider routing provenance (ROADMAP item 1) — see the sync
2129
2690
  // dispatch path. Present only when the task carried >= 2 candidates.
2130
2691
  routing: record.routingDecision,
2692
+ ...(counts.tokenCounts !== undefined ? { tokenCounts: counts.tokenCounts } : {}),
2131
2693
  });
2132
2694
  }
2133
2695
  catch (err) {
@@ -2158,7 +2720,10 @@ export class Scheduler {
2158
2720
  console.warn(`[tidegap/scheduler] failed to persist completed task ${record.taskId}: ${describeErr(err)}`);
2159
2721
  }
2160
2722
  if (spec.outputPath && receipt) {
2161
- await writeOutputFile(spec.outputPath, record.taskId, result, receipt);
2723
+ await writeOutputFile(spec.outputPath, record.taskId, result, receipt, {
2724
+ cwd: spec.handoff?.cwd,
2725
+ originCwd: record.originCwd,
2726
+ });
2162
2727
  }
2163
2728
  return { taskId: record.taskId, status: "completed" };
2164
2729
  }
@@ -2188,6 +2753,108 @@ export class Scheduler {
2188
2753
  };
2189
2754
  }
2190
2755
  }
2756
+ /**
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.
2761
+ */
2762
+ function jobDispatchOptions(record, spec) {
2763
+ const out = {};
2764
+ if (spec.caps) {
2765
+ out.timeoutMs = spec.caps.llmTimeoutMs;
2766
+ out.maxBudgetUsd = spec.caps.maxBudgetUsd;
2767
+ }
2768
+ if (record.jobId) {
2769
+ out.jobId = record.jobId;
2770
+ if (record.originCwd)
2771
+ out.cwd = record.originCwd;
2772
+ }
2773
+ else if (spec.provider === "claude-code" && typeof spec.handoff?.cwd === "string") {
2774
+ // A handed-off folder: the adapter forks the origin session when it is
2775
+ // the session's project folder, else runs fresh there.
2776
+ out.cwd = spec.handoff.cwd;
2777
+ }
2778
+ if (spec.provider === "command") {
2779
+ if (spec.command)
2780
+ out.command = spec.command;
2781
+ if (spec.summarize)
2782
+ out.summarize = spec.summarize;
2783
+ if (spec.caps)
2784
+ out.caps = spec.caps;
2785
+ }
2786
+ return out;
2787
+ }
2788
+ /**
2789
+ * The usage limit a dispatch can hit: its provider and model. A command
2790
+ * job's limit is its summarize step's, so a limit hit there defers the
2791
+ * other calls to that provider this tick, not every command job.
2792
+ */
2793
+ function deferKeyOf(spec) {
2794
+ if (spec.provider === "command" && spec.summarize) {
2795
+ return `${spec.summarize.provider}\u0000${spec.summarize.model ?? spec.model}`;
2796
+ }
2797
+ return `${spec.provider}\u0000${spec.model}`;
2798
+ }
2799
+ /** The known {@link RunDetails} keys of an adapter result or error, or undefined when none is set. */
2800
+ function runDetails(raw) {
2801
+ if (!raw || typeof raw !== "object")
2802
+ return undefined;
2803
+ const d = raw;
2804
+ const out = {};
2805
+ if (Array.isArray(d.steps))
2806
+ out.steps = d.steps.filter((x) => typeof x === "string");
2807
+ if (typeof d.stopped_by === "string")
2808
+ out.stopped_by = d.stopped_by;
2809
+ if (d.truncated === true)
2810
+ out.truncated = true;
2811
+ return Object.keys(out).length > 0 ? out : undefined;
2812
+ }
2813
+ /** True for a command-job row when `adapters` has no `command` adapter to run it. */
2814
+ function unservedCommand(record, adapters) {
2815
+ if (adapters.command || !record.bodyJson)
2816
+ return false;
2817
+ try {
2818
+ return JSON.parse(record.bodyJson).provider === "command";
2819
+ }
2820
+ catch {
2821
+ return false;
2822
+ }
2823
+ }
2824
+ /** True when no adapter serves the row: none for its provider and none for a routing candidate. */
2825
+ function unserved(record, adapters) {
2826
+ let provider;
2827
+ try {
2828
+ provider = JSON.parse(record.bodyJson ?? "null")?.provider;
2829
+ }
2830
+ catch {
2831
+ return false; // a corrupt body fails with its own error
2832
+ }
2833
+ if (typeof provider === "string" && adapters[provider])
2834
+ return false;
2835
+ return !record.routingDecision?.considered.some((c) => adapters[c.provider] !== undefined);
2836
+ }
2837
+ /**
2838
+ * The `origin` dispatch option (KTD13): only for a `claude-code` task whose
2839
+ * record names a session and a directory and whose spec names the agent.
2840
+ * The adapter registered as `anthropic` may be the Claude Code adapter, so
2841
+ * the check is on the task's provider, not on the adapter.
2842
+ */
2843
+ function dispatchOrigin(record, spec) {
2844
+ // A job occurrence never resumes or forks a session (KD8).
2845
+ if (spec.provider !== "claude-code" || !spec.origin || record.jobId)
2846
+ return {};
2847
+ if (!record.originSessionId || !record.originCwd)
2848
+ return {};
2849
+ return {
2850
+ origin: {
2851
+ sessionId: record.originSessionId,
2852
+ cwd: record.originCwd,
2853
+ agent: spec.origin.agent,
2854
+ ...(spec.origin.transcriptPath ? { transcriptPath: spec.origin.transcriptPath } : {}),
2855
+ },
2856
+ };
2857
+ }
2191
2858
  function intensityToGrams(gCo2PerKwh, model) {
2192
2859
  return gramsForIntensity(gCo2PerKwh, { model });
2193
2860
  }
@@ -2254,8 +2921,123 @@ function identityFields(taskId, opts, title) {
2254
2921
  originSessionId: opts.originSessionId,
2255
2922
  };
2256
2923
  }
2924
+ /** Longest one-off shell command `enqueueCommandTask` accepts. */
2925
+ export const COMMAND_MAX_CHARS = 32_000;
2926
+ /**
2927
+ * The spec with its handoff fields checked and its profile turned into
2928
+ * tools; throws on a refusal. `cwd` and a profile apply to `claude-code`
2929
+ * only (a cwd alone means profile `read`); a stored tool list must equal the
2930
+ * profile's. A result path follows the create-only rules and an
2931
+ * `outputPath` the location rules, both against the task's folder, the
2932
+ * session's project folder (`originCwd`) and the temp folders. A result
2933
+ * path needs a one-off task: each run of a series would write the same new
2934
+ * file. A wake needs a checked session origin.
2935
+ */
2936
+ function checkedHandoff(spec, opts, where) {
2937
+ const { originCwd, repeat } = opts;
2938
+ let out = spec;
2939
+ const h = spec.handoff;
2940
+ if (h !== undefined) {
2941
+ if (!h || typeof h !== "object" || Array.isArray(h))
2942
+ throw new Error(`${where}: handoff must be an object`);
2943
+ const handoff = h;
2944
+ const { cwd, profile, resultPath } = handoff;
2945
+ const wakeRefused = wakeError(handoff.wake, spec.origin, opts.originSessionId);
2946
+ if (wakeRefused)
2947
+ throw new Error(`${where}: ${wakeRefused}`);
2948
+ if (cwd !== undefined || profile !== undefined) {
2949
+ if (spec.provider !== "claude-code") {
2950
+ throw new Error(`${where}: cwd and a tool profile apply to the claude-code runner only, not ${spec.provider}`);
2951
+ }
2952
+ if (Array.isArray(spec.candidates) && spec.candidates.length > 1) {
2953
+ throw new Error(`${where}: cwd and a tool profile cannot be combined with routing candidates`);
2954
+ }
2955
+ }
2956
+ if (cwd !== undefined) {
2957
+ const cwdError = handoffCwdError(cwd, "claude-code");
2958
+ if (cwdError)
2959
+ throw new Error(`${where}: ${cwdError}`);
2960
+ }
2961
+ const choice = profileTools(profile, cwd);
2962
+ if (choice.error)
2963
+ throw new Error(`${where}: ${choice.error}`);
2964
+ let tools = spec.tools;
2965
+ if (choice.tools) {
2966
+ if (tools !== undefined && !(Array.isArray(tools) && sameTools(tools, choice.tools))) {
2967
+ throw new Error(`${where}: tools ${JSON.stringify(tools)} differ from profile ${choice.profile} (${choice.tools.join(", ") || "no tools"}); pass one of them`);
2968
+ }
2969
+ tools = choice.tools;
2970
+ }
2971
+ if (resultPath !== undefined) {
2972
+ if (repeat !== undefined && repeat !== "none") {
2973
+ throw new Error(`${where}: a result path needs a one-off task: each run of a series would write the same new file; omit repeat or the result path`);
2974
+ }
2975
+ const pathError = resultPathError(resultPath, { cwd, originCwd });
2976
+ if (pathError)
2977
+ throw new Error(`${where}: ${pathError}`);
2978
+ }
2979
+ out = {
2980
+ ...spec,
2981
+ ...(tools !== undefined ? { tools } : {}),
2982
+ handoff: { ...handoff, ...(choice.profile ? { profile: choice.profile } : {}) },
2983
+ };
2984
+ }
2985
+ if (spec.outputPath !== undefined) {
2986
+ const pathError = outputPathError(spec.outputPath, { cwd: out.handoff?.cwd, originCwd });
2987
+ if (pathError)
2988
+ throw new Error(`${where}: ${pathError}`);
2989
+ }
2990
+ return out;
2991
+ }
2992
+ /** The handoff a reply keeps from its parent: the folder and the profile, never the result path. */
2993
+ function replyHandoff(spec) {
2994
+ const h = spec.handoff;
2995
+ if (!h || typeof h !== "object")
2996
+ return undefined;
2997
+ const out = {
2998
+ ...(h.cwd !== undefined ? { cwd: h.cwd } : {}),
2999
+ ...(h.profile !== undefined ? { profile: h.profile } : {}),
3000
+ };
3001
+ return Object.keys(out).length > 0 ? out : undefined;
3002
+ }
3003
+ const MINUTE_MS = 60_000;
2257
3004
  const HOUR_MS = 3_600_000;
2258
3005
  const DAY_MS = 24 * HOUR_MS;
3006
+ /**
3007
+ * A plain Batch row that a killed tick left `running` goes back to
3008
+ * `submitted` once its deadline plus this grace has passed (batch 27 KTD9),
3009
+ * the job sweep's limit for a job's Batch row. Wall-clock time: a provider
3010
+ * ends a batch whether or not this machine slept.
3011
+ * `test/fixtures/stranded-batch-polls.json` holds it for both cores.
3012
+ */
3013
+ export const STRANDED_POLL_GRACE_MS = 5 * MINUTE_MS;
3014
+ /** Minimum span between an earliest start and the deadline. */
3015
+ const NOT_BEFORE_SPAN_MS = 2 * HOUR_MS;
3016
+ /** A deferred task never moves past `enqueuedAt` plus this. */
3017
+ const DEFER_CAP_MS = 8 * DAY_MS;
3018
+ /**
3019
+ * The timing columns of a task with an earliest start at `startMs`: the
3020
+ * deadline raised to at least `startMs + 2 h`, and the fallback time one
3021
+ * minute past the start, because `scheduledFor === notBefore` reads as an
3022
+ * exact-time pin, which `replanSweep` and the batch sweep skip.
3023
+ */
3024
+ function startFields(startMs, deadlineMs) {
3025
+ return {
3026
+ notBefore: new Date(startMs).toISOString(),
3027
+ scheduledFor: new Date(startMs + MINUTE_MS).toISOString(),
3028
+ deadline: new Date(Math.max(deadlineMs, startMs + NOT_BEFORE_SPAN_MS)).toISOString(),
3029
+ };
3030
+ }
3031
+ /** A future earliest start, or undefined (absent or past). */
3032
+ function earliestStart(v) {
3033
+ if (v === undefined || v === null)
3034
+ return undefined;
3035
+ const d = v instanceof Date ? v : new Date(v);
3036
+ if (Number.isNaN(d.getTime())) {
3037
+ throw new Error(`notBefore is not an ISO-8601 instant: ${JSON.stringify(v)}`);
3038
+ }
3039
+ return d.getTime() > Date.now() ? d : undefined;
3040
+ }
2259
3041
  /**
2260
3042
  * The next deadline of a period series: `prevMs` plus whole periods until
2261
3043
  * it is at least one hour ahead of `now`.
@@ -2275,7 +3057,6 @@ function occurrenceNumber(record) {
2275
3057
  const n = Number.parseInt(record.taskId.slice(prefix.length), 10);
2276
3058
  return Number.isFinite(n) && n > 0 ? n : 1;
2277
3059
  }
2278
- /** One-line refusal in the shared style: `<action>: task <id> is <status>; <allowed>`. */
2279
3060
  /**
2280
3061
  * A task action refused by the task's state or by its input (ui v2): the
2281
3062
  * message is a one-line rule safe to show a user. Any other error from an
@@ -2284,6 +3065,7 @@ function occurrenceNumber(record) {
2284
3065
  export class TaskActionError extends Error {
2285
3066
  name = "TaskActionError";
2286
3067
  }
3068
+ /** One-line refusal in the shared style: `<action>: task <id> is <status>; <allowed>`. */
2287
3069
  function refusal(action, record, allowed) {
2288
3070
  const what = record.bodyJson ? record.status : `${record.status} (closure-based)`;
2289
3071
  return `${action}: task ${record.taskId} is ${what}; ${allowed}`;
@@ -2292,9 +3074,19 @@ function refusal(action, record, allowed) {
2292
3074
  function rescheduleShape(target) {
2293
3075
  const t = (target ?? {});
2294
3076
  const has = (k) => t[k] !== undefined && t[k] !== null;
3077
+ if (has("notBefore")) {
3078
+ if (has("at") || has("dayStart") || has("dayEnd")) {
3079
+ throw new TaskActionError("reschedule: {notBefore} takes only an optional deadline");
3080
+ }
3081
+ return {
3082
+ kind: "notBefore",
3083
+ notBefore: t.notBefore,
3084
+ deadline: has("deadline") ? t.deadline : undefined,
3085
+ };
3086
+ }
2295
3087
  const shapes = [has("deadline"), has("at"), has("dayStart") || has("dayEnd")].filter(Boolean);
2296
3088
  if (shapes.length !== 1) {
2297
- throw new TaskActionError("reschedule: pass exactly one of {deadline}, {at} or {dayStart, dayEnd}");
3089
+ throw new TaskActionError("reschedule: pass exactly one of {deadline}, {at}, {dayStart, dayEnd} or {notBefore}");
2298
3090
  }
2299
3091
  if (has("deadline"))
2300
3092
  return { kind: "deadline", deadline: t.deadline };
@@ -2371,7 +3163,7 @@ export function pickBestWindow(entries, deadline) {
2371
3163
  * construct their SDK clients with `maxRetries: 0` so vendor-side
2372
3164
  * retries cannot multiply with this one.
2373
3165
  */
2374
- async function retryWithBackoff(fn) {
3166
+ export async function retryWithBackoff(fn) {
2375
3167
  const waits = [1_000, 4_000, 16_000];
2376
3168
  let lastErr;
2377
3169
  for (let attempt = 0; attempt <= waits.length; attempt++) {
@@ -2393,6 +3185,9 @@ async function retryWithBackoff(fn) {
2393
3185
  function isRetryable(err) {
2394
3186
  if (!err || typeof err !== "object")
2395
3187
  return false;
3188
+ // A job's shell step, or a call retrying cannot help (NonRetryableError).
3189
+ if (err.nonRetryable === true)
3190
+ return false;
2396
3191
  const e = err;
2397
3192
  const status = e.status ?? e.statusCode;
2398
3193
  if (typeof status === "number") {
@@ -2434,16 +3229,36 @@ function describeErr(err) {
2434
3229
  return String(err);
2435
3230
  }
2436
3231
  /**
2437
- * Write { taskId, result, receipt } as JSON to the spec's
2438
- * `outputPath`. Failures are logged but do not fail the task — the
2439
- * SQLite ledger is the source of truth, the file is a convenience.
3232
+ * Write { taskId, result, receipt } as JSON to the spec's `outputPath`,
3233
+ * after the location rules pass again (the folder must exist; a file there
3234
+ * must be a regular file this user owns, which is replaced; a link at the
3235
+ * path is never followed). Failures are logged but do not fail the task —
3236
+ * the SQLite ledger is the source of truth, the file is a convenience.
2440
3237
  */
2441
- async function writeOutputFile(path, taskId, result, receipt) {
3238
+ async function writeOutputFile(path, taskId, result, receipt, roots) {
2442
3239
  try {
2443
- const { mkdir, writeFile } = await import("node:fs/promises");
2444
- const { dirname } = await import("node:path");
2445
- await mkdir(dirname(path), { recursive: true });
2446
- await writeFile(path, JSON.stringify({ taskId, result, receipt }, null, 2));
3240
+ const refused = outputPathError(path, roots);
3241
+ if (refused)
3242
+ throw new Error(refused);
3243
+ const { open } = await import("node:fs/promises");
3244
+ const { constants } = await import("node:fs");
3245
+ // Never through a link, never into a pipe (O_NONBLOCK fails at once with
3246
+ // no reader), and no truncation before the opened file is checked.
3247
+ const flags = constants.O_WRONLY | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
3248
+ const file = await open(path, flags, 0o666);
3249
+ try {
3250
+ const st = await file.stat();
3251
+ const uid = process.getuid?.();
3252
+ // A second name (a hard link) could sit outside the allowed folders.
3253
+ if (!st.isFile() || st.nlink !== 1 || (uid !== undefined && st.uid !== uid)) {
3254
+ throw new Error("the file there is not a regular file you own with one name");
3255
+ }
3256
+ await file.truncate(0);
3257
+ await file.writeFile(JSON.stringify({ taskId, result, receipt }, null, 2));
3258
+ }
3259
+ finally {
3260
+ await file.close();
3261
+ }
2447
3262
  }
2448
3263
  catch (err) {
2449
3264
  // eslint-disable-next-line no-console