@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
@@ -18,10 +18,12 @@
18
18
  */
19
19
  import { type CarbonAlert, type CarbonBudgetConfig } from "./budget.js";
20
20
  import type { ProviderAdapter } from "./providers/base.js";
21
+ import { type LimitResetSource, type PostponeOption, type PostponeTarget } from "./postpone.js";
21
22
  import { type RoutingPreview } from "./routing.js";
22
23
  import { type QuotaResetConfig } from "./quota.js";
23
24
  import { TaskStore } from "./storage/sqlite.js";
24
- import type { DeferOptions, DeferrableTask, GridFeed, GridForecastEntry, ProviderCallSpec, ProviderName, TaskRecord, TickResult, TickResultEntry } from "./types.js";
25
+ import { type TaskEvent, type TaskEventActor } from "./task-events.js";
26
+ import type { DeferOptions, DeferrableTask, GridFeed, JobCaps, GridForecastEntry, ProviderCallOrigin, ProviderCallSpec, ProviderName, TaskRecord, TaskStatus, TickResult, TickResultEntry } from "./types.js";
25
27
  /** Target of {@link Scheduler.rescheduleTask} (ui v2): exactly one shape. */
26
28
  export type RescheduleTarget =
27
29
  /** A new deadline; the window picker chooses the hour. */
@@ -36,6 +38,14 @@ export type RescheduleTarget =
36
38
  | {
37
39
  dayStart: string | Date;
38
40
  dayEnd: string | Date;
41
+ }
42
+ /**
43
+ * An earliest start (a usage-limit reset); the picker chooses an hour at
44
+ * or after it. The deadline rises to at least `notBefore + 2 h`.
45
+ */
46
+ | {
47
+ notBefore: string | Date;
48
+ deadline?: string | Date;
39
49
  };
40
50
  /** Options of {@link Scheduler.replyToTask} (ui v2). */
41
51
  export interface ReplyOptions {
@@ -47,7 +57,16 @@ export interface ReplyOptions {
47
57
  originHost?: DeferOptions["originHost"];
48
58
  originCwd?: string;
49
59
  originSessionId?: string;
60
+ /**
61
+ * Keep the parent's origin session (`spec.origin`), so the reply runs in
62
+ * a copy of that session too. Default false: only a caller that is the
63
+ * user (the CLI, the page) or that session itself may resume it; any other
64
+ * caller's reply runs fresh.
65
+ */
66
+ keepOrigin?: boolean;
50
67
  }
68
+ export declare const PENDING_STATUSES: readonly TaskStatus[];
69
+ export declare const UNFINISHED_STATUSES: readonly TaskStatus[];
51
70
  /** Ledger meta key holding the ISO time a ticker last ran. */
52
71
  export declare const LAST_TICK_META_KEY = "last_tick_at";
53
72
  /**
@@ -57,6 +76,23 @@ export declare const LAST_TICK_META_KEY = "last_tick_at";
57
76
  * clear "no adapter configured" error rather than silently dropping it.
58
77
  */
59
78
  export type TickAdapters = Partial<Record<ProviderName, ProviderAdapter>>;
79
+ /** Options of {@link Scheduler.tick}. */
80
+ export interface TickOptions {
81
+ /**
82
+ * Leave a due row whose provider has no adapter (and no routing candidate
83
+ * with one) `scheduled` instead of failing it. For a host that serves no
84
+ * LLM provider at all, such as the CLI tick with only command jobs: the
85
+ * row waits for a host that can run it.
86
+ */
87
+ holdUnserved?: boolean;
88
+ /**
89
+ * Stop the tick cooperatively: once aborted, no further row is claimed,
90
+ * submitted, dispatched or polled. A dispatch already running finishes
91
+ * (its runner decides how a stop signal ends it); the tick returns what
92
+ * it did so far. Rows it did not reach stay as they were.
93
+ */
94
+ signal?: AbortSignal;
95
+ }
60
96
  /** Thrown when no candidate window meets the user-supplied carbon budget. */
61
97
  export declare class CarbonBudgetExceededError extends Error {
62
98
  readonly minimumGCo2: number;
@@ -70,8 +106,12 @@ export declare class InvalidDeadlineError extends Error {
70
106
  }
71
107
  export interface SchedulerOptions {
72
108
  feed?: GridFeed;
73
- /** Default region to use when DeferOptions does not name one. */
74
- defaultRegion?: string;
109
+ /**
110
+ * Default region to use when DeferOptions does not name one. A getter is
111
+ * called on every schedule, so a host can follow a changed setting
112
+ * without a restart.
113
+ */
114
+ defaultRegion?: string | (() => string);
75
115
  /** If true (default), background loop ticks immediately on `defer`. */
76
116
  eager?: boolean;
77
117
  /**
@@ -133,21 +173,53 @@ export interface SchedulerOptions {
133
173
  * sees config edits.
134
174
  */
135
175
  quotaConfig?: () => QuotaResetConfig;
176
+ /**
177
+ * The plugged-in limit-reset source for "Later → after limit reset"
178
+ * (coherence KTD5), for example the CLI usage module's Claude reset.
179
+ * A caller-given reset wins over it; a stored hint is the fallback.
180
+ */
181
+ limitReset?: LimitResetSource;
182
+ /**
183
+ * Who this scheduler's writes are recorded as in `task_events` (for
184
+ * example `cli`, `tick`, `agent:mcp`). Default `system`. A mutation
185
+ * method's own `{ actor }` wins.
186
+ */
187
+ actor?: TaskEventActor;
188
+ /**
189
+ * The machine's sleep counter (`boot_at`, `slept_ms`), read by the host
190
+ * (the CLI tick). Stored on each `dispatched` event as `sleep`, so the job
191
+ * sweep counts a run's age on awake time: a run the machine slept
192
+ * through is not interrupted (`sleep-gap-is-not-a-dead-daemon.md`).
193
+ */
194
+ sleepCounter?: () => {
195
+ boot_at: number;
196
+ slept_ms: number;
197
+ } | null;
198
+ }
199
+ /** Per-call options of the task actions: who the change is recorded as. */
200
+ export interface ActorOptions {
201
+ actor?: TaskEventActor;
136
202
  }
137
203
  export declare class Scheduler {
138
204
  private readonly feed;
139
- private readonly defaultRegion;
205
+ private readonly defaultRegionOption;
140
206
  private readonly rng;
141
207
  private readonly tasks;
142
208
  private readonly pendingTimers;
143
209
  private readonly resolvers;
144
210
  private readonly bodies;
211
+ /** Rows a tick moved to `running` whose dispatch has not settled (KTD12), and what each is doing. */
212
+ private readonly held;
145
213
  private readonly store;
146
214
  private signingConfig;
147
215
  private signingKey;
148
216
  private readonly carbonBudget;
149
217
  private readonly onCarbonAlert;
150
218
  private readonly quotaConfig;
219
+ private readonly limitReset;
220
+ private readonly actor;
221
+ private readonly sleepCounter;
222
+ private defaultRegion;
151
223
  constructor(opts?: SchedulerOptions);
152
224
  /**
153
225
  * Compute the current aggregate carbon-budget status (ROADMAP item 4)
@@ -190,10 +262,38 @@ export declare class Scheduler {
190
262
  markTaskRead(taskId: string, at?: Date): boolean;
191
263
  /** Clear a task's read marker (v0.17). Returns true iff it was set. */
192
264
  markTaskUnread(taskId: string): boolean;
265
+ /** A task's events from the ledger, oldest first; [] without a store. */
266
+ listTaskEvents(taskId: string, opts?: {
267
+ limit?: number;
268
+ }): TaskEvent[];
193
269
  /** Record that a ticker ran at `at` (ledger meta `last_tick_at`). No-op without a store. */
194
270
  recordTickRun(at?: Date): void;
195
271
  /** When a ticker (`tidegap tick` or the OpenClaw loop) last ran, if ever recorded. */
196
272
  lastTickAt(): string | undefined;
273
+ /** The ledger this scheduler writes through to, if any. Jobs live there too. */
274
+ ledger(): TaskStore | undefined;
275
+ /**
276
+ * Insert one job occurrence and plan it (floating recurring jobs, KTD4).
277
+ * The row is built here, not through `enqueueProviderCall` (which refuses
278
+ * `provider: "command"`): `scheduled`, `notBefore = earliest`,
279
+ * `scheduledFor = earliest + 1 min` (never equal to `notBefore`, which
280
+ * would read as an exact pin), the slot deadline with no widening,
281
+ * `repeat = none` and no series, so `rollSeries` never touches it. The
282
+ * insert is `insertIfAbsent` on the derived id; returns false, writing
283
+ * nothing, when the row exists. Planning picks the cleanest forecast hour
284
+ * inside `[earliest, deadline]`, or leaves the row unplanned for
285
+ * `replanSweep` when the forecast does not reach it (or fails).
286
+ */
287
+ materializeOccurrence(occ: {
288
+ taskId: string;
289
+ jobId: string;
290
+ earliest: string;
291
+ deadline: string;
292
+ title: string;
293
+ bodyJson: string;
294
+ originHost?: TaskRecord["originHost"];
295
+ originCwd?: string;
296
+ }, details: Record<string, unknown>): Promise<boolean>;
197
297
  /**
198
298
  * Defer a task. Returns a promise that resolves with the task's eventual
199
299
  * result when Tidegap dispatches it.
@@ -219,13 +319,35 @@ export declare class Scheduler {
219
319
  * later cron-tick) can pick them up.
220
320
  */
221
321
  enqueueProviderCall(spec: ProviderCallSpec, opts?: DeferOptions): Promise<TaskRecord<unknown>>;
322
+ /**
323
+ * Queue a one-off shell command (`tidegap queue add --runner command`):
324
+ * the row of a command job run (`provider: "command"`, `model: "none"`,
325
+ * an empty prompt) with `command.origin: "cli"` and no job id, planned
326
+ * like any provider call. Only the CLI tick's command adapter runs it.
327
+ * Checks: a command of 1 to 32,000 characters, an existing absolute
328
+ * folder, positive caps, and the result path rules. `enqueueProviderCall`
329
+ * keeps refusing `command`, and `retryTask` refuses these rows: running a
330
+ * shell command again is the user's call.
331
+ */
332
+ enqueueCommandTask(task: {
333
+ run: string;
334
+ cwd: string;
335
+ caps?: Partial<JobCaps>;
336
+ resultPath?: string;
337
+ /** The checked agent session that queued it, for its notice. */
338
+ origin?: ProviderCallOrigin;
339
+ /** Wake that session when the task finishes; needs `origin` and `opts.originSessionId`. */
340
+ wake?: boolean;
341
+ }, opts?: DeferOptions): Promise<TaskRecord<unknown>>;
342
+ /** Insert a checked provider-call row with its `created` event, then plan its window. */
343
+ private insertProviderCall;
222
344
  /**
223
345
  * Drain due provider-call tasks against the supplied adapters. Returns a
224
346
  * `TickResult` summarising what happened. Closure-based tasks
225
347
  * (`enqueue` / `defer`) are NOT touched by this method — only this
226
348
  * process can run those.
227
349
  */
228
- tick(adapters: TickAdapters): Promise<TickResult>;
350
+ tick(adapters: TickAdapters, opts?: TickOptions): Promise<TickResult>;
229
351
  /**
230
352
  * Collect scheduled provider-call tasks that should be routed through a
231
353
  * Batch API this tick: preferBatch !== false, an adapter with a
@@ -248,6 +370,19 @@ export declare class Scheduler {
248
370
  private reloadClaimed;
249
371
  /** Undo a claim on a row that turned out not to be ready: back to `scheduled`. */
250
372
  private releaseClaim;
373
+ /**
374
+ * The head of the Batch-poll sweep (batch 27 KTD9): a plain row that a
375
+ * killed tick left `running` with its batch id goes back to `submitted`
376
+ * once its deadline plus `STRANDED_POLL_GRACE_MS` has passed, and the sweep
377
+ * then polls it. The batch id proves a live batch. A row goes to a Batch
378
+ * API only with a deadline over a day ahead, and the providers end every
379
+ * batch within 24 h, so a row past its deadline has a finished batch: the
380
+ * step rarely meets a live poll in another process, and compare-and-set
381
+ * still lands one completion if it does. Job rows are the job sweep's;
382
+ * rows this scheduler's tick holds are live. No event, as in
383
+ * `failHeldRuns`.
384
+ */
385
+ private freeStrandedPolls;
251
386
  /**
252
387
  * Collect every "submitted" provider-call task awaiting batch results.
253
388
  * `exclude` skips tasks submitted earlier in the same tick — submit and
@@ -273,6 +408,14 @@ export declare class Scheduler {
273
408
  private clearPendingTimer;
274
409
  /** Merge a stored row into the cache, keeping the cached object identity. */
275
410
  private cacheRow;
411
+ /**
412
+ * The progress callback of one run: the lines an adapter reports become
413
+ * `progress` events (actor `tick`) within the core caps. None without a
414
+ * ledger. A failed write costs its line and one warning, never the run.
415
+ */
416
+ private progressFor;
417
+ /** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
418
+ private sleepDetails;
276
419
  /**
277
420
  * Compare-and-set write: store `next` only while the row's status is in
278
421
  * `expected`; on success copy it onto the cached record. On a miss the
@@ -280,6 +423,12 @@ export declare class Scheduler {
280
423
  * store the write always succeeds.
281
424
  */
282
425
  private writeIf;
426
+ /**
427
+ * The `task_events` row for a write from `prev` to `next`: the given kind,
428
+ * or a terminal kind the status change implies; undefined = no event.
429
+ * `spec.details` are extra keys on top of {@link eventDetails}.
430
+ */
431
+ private eventFor;
283
432
  /**
284
433
  * Series rollover (ui v2, KTD6). Called when an occurrence with a repeat
285
434
  * rule finishes (completed, failed, or cancelled as a skip), BEFORE its
@@ -314,11 +463,16 @@ export declare class Scheduler {
314
463
  * claimed the row first, the cancel lands on the `running` row; the
315
464
  * dispatcher re-checks the status before finalizing and drops the late
316
465
  * result. `opts.series` also ends the series (`repeat = none`) in the
317
- * same write ("stop series").
466
+ * same write ("stop series"); on a finished occurrence it ends the
467
+ * series at its live occurrence. `opts.expectedStatus` cancels only a row in
468
+ * one of those states and returns any other row unchanged: the job code
469
+ * passes the pending states, so a row a tick claimed runs to its end.
318
470
  */
319
471
  cancelTask(taskId: string, opts?: {
320
472
  series?: boolean;
321
- }): TaskRecord<unknown>;
473
+ details?: Record<string, unknown>;
474
+ expectedStatus?: readonly TaskStatus[];
475
+ } & ActorOptions): TaskRecord<unknown>;
322
476
  /**
323
477
  * Run a pending provider-call task at the next tick (ui v2). A write
324
478
  * only: no dispatch happens here, so a process without adapters (the
@@ -327,7 +481,7 @@ export declare class Scheduler {
327
481
  * survives onto the completed row. Throws when the task's state does not
328
482
  * allow it (see `taskActions`).
329
483
  */
330
- runNow(taskId: string): TaskRecord<unknown>;
484
+ runNow(taskId: string, opts?: ActorOptions): TaskRecord<unknown>;
331
485
  /**
332
486
  * Move a queued or scheduled provider-call task (ui v2). `{deadline}`
333
487
  * re-runs the window picker up to the new deadline; `{at}` pins the exact
@@ -338,7 +492,24 @@ export declare class Scheduler {
338
492
  * compare-and-set on the pending statuses; throws when the task is not
339
493
  * movable.
340
494
  */
341
- rescheduleTask(taskId: string, target: RescheduleTarget): Promise<TaskRecord<unknown>>;
495
+ rescheduleTask(taskId: string, target: RescheduleTarget, opts?: ActorOptions): Promise<TaskRecord<unknown>>;
496
+ /** `rescheduleTask` with the event to record (`rescheduled` or `postponed`). */
497
+ private moveTask;
498
+ /**
499
+ * "Later" (coherence KTD4): move a queued or scheduled provider-call task
500
+ * so it never runs earlier than its planned start. Resolves the target
501
+ * with {@link resolvePostpone} and writes it through `rescheduleTask`, so
502
+ * the write is the same compare-and-set on the pending statuses. An
503
+ * `after_limit_reset` target uses its own `resetAt` (stored as the hint),
504
+ * else the plugged-in `limitReset` source, else a still-future hint.
505
+ * Throws `TaskActionError` with the refusal reason.
506
+ */
507
+ postponeTask(taskId: string, target: PostponeTarget, opts?: ActorOptions): Promise<TaskRecord<unknown>>;
508
+ /**
509
+ * The Later presets of a task with their resolved times (KTD6), using
510
+ * the plugged-in reset source and the stored hint.
511
+ */
512
+ postponeOptionsFor(task: string | TaskRecord<unknown>, now?: Date): Promise<PostponeOption[]>;
342
513
  /**
343
514
  * Reply to a completed provider-call task (ui v2, brainstorm R16/R17):
344
515
  * enqueue a child with the parent's conversation as history, the reply as
@@ -346,14 +517,14 @@ export declare class Scheduler {
346
517
  * child runs through the normal window picker (default deadline one hour
347
518
  * ahead) and never repeats. Refuses failed and cancelled parents (AE4).
348
519
  */
349
- replyToTask(parentId: string, text: string, opts?: ReplyOptions): Promise<TaskRecord<unknown>>;
520
+ replyToTask(parentId: string, text: string, opts?: ReplyOptions & ActorOptions): Promise<TaskRecord<unknown>>;
350
521
  /**
351
522
  * Dispatch a queued/scheduled provider-call task immediately,
352
523
  * bypassing the scheduler's chosen window. Receipt records
353
524
  * `intensitySource: "expedited"`. Closure-based tasks (from
354
525
  * `defer`) are not expediteable; we throw a clear error.
355
526
  */
356
- expediteTask(taskId: string, adapters: TickAdapters): Promise<TickResultEntry>;
527
+ expediteTask(taskId: string, adapters: TickAdapters, opts?: ActorOptions): Promise<TickResultEntry>;
357
528
  /**
358
529
  * Re-score and reschedule a queued/scheduled task against a new
359
530
  * deadline. Throws if the task is already running or terminal, or
@@ -365,7 +536,7 @@ export declare class Scheduler {
365
536
  */
366
537
  updateDeadline(taskId: string, newDeadline: string | Date, opts?: {
367
538
  deadlineKind?: "absolute";
368
- }): Promise<TaskRecord<unknown>>;
539
+ } & ActorOptions): Promise<TaskRecord<unknown>>;
369
540
  /**
370
541
  * The quota sweep's reschedule (`sweepQuotaDeadlines`). Same window
371
542
  * selection as `updateDeadline`, but the ledger write is conditional on
@@ -381,7 +552,7 @@ export declare class Scheduler {
381
552
  * spec is still valid. Only `failed` tasks are eligible; throws
382
553
  * otherwise.
383
554
  */
384
- retryTask(taskId: string, adapters: TickAdapters): Promise<TickResultEntry>;
555
+ retryTask(taskId: string, adapters: TickAdapters, opts?: ActorOptions): Promise<TickResultEntry>;
385
556
  /**
386
557
  * Pure read-only planning helper: compute the scheduled window and
387
558
  * carbon receipt that the same call to `enqueueProviderCall` would
@@ -395,6 +566,8 @@ export declare class Scheduler {
395
566
  band: GridForecastEntry["band"];
396
567
  batchEligible: boolean;
397
568
  region: string;
569
+ /** The deadline the commit would store (raised by a `notBefore`). */
570
+ deadline: string;
398
571
  /**
399
572
  * How many near-equal low-carbon windows sat in the cleanest-tolerance
400
573
  * band the shared `selectWindow` chose from (§2.1). A committed
@@ -414,12 +587,38 @@ export declare class Scheduler {
414
587
  }>;
415
588
  /** Snapshot the queue (immutable copy). */
416
589
  listTasks(): ReadonlyArray<TaskRecord<unknown>>;
590
+ /** Runs the dispatch of a row the tick moved to `running`, holding the row until it settles. */
591
+ private holding;
592
+ /**
593
+ * A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
594
+ * scheduler moved to `running` in a tick whose dispatch has not settled,
595
+ * by what the row was doing:
596
+ * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`);
597
+ * - a Batch poll goes back to `submitted` with its `batchId`: the batch
598
+ * is live at the provider, and the next tick polls it again;
599
+ * - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
600
+ * provider may have accepted the batch, so no retry path runs it again.
601
+ * Compare-and-set from `running`, so a row another writer finished first
602
+ * keeps its status; rows another process holds, or a crashed tick
603
+ * stranded, are not touched (the job sweep frees job runs, and the next
604
+ * tick a Batch poll past its deadline: `freeStrandedPolls`). Synchronous, for
605
+ * a process about to exit. Returns the ids it failed; a second call
606
+ * changes nothing.
607
+ */
608
+ failHeldRuns(): string[];
417
609
  /** Cancel and clean up timers. Mostly for tests. */
418
610
  shutdown(): void;
419
611
  private schedule;
420
612
  /** Fire-and-forget wrapper around `dispatch` that routes any unexpected
421
613
  * rejection to `failTask` instead of an unhandledRejection. */
422
614
  private dispatchSafe;
615
+ /**
616
+ * A closure task's write missed: another process cancelled, claimed or
617
+ * finished its row. Reject the awaiter with the status the ledger now
618
+ * holds and drop the body, so `defer()` never waits forever. A no-op for
619
+ * a provider call, which has no awaiter.
620
+ */
621
+ private rejectMissedClosure;
423
622
  private failTask;
424
623
  private dispatch;
425
624
  /**
@@ -454,6 +653,15 @@ export declare class Scheduler {
454
653
  */
455
654
  private applyRoutingIfNeeded;
456
655
  private dispatchProviderCall;
656
+ /**
657
+ * Put a running task back in the queue until `retryAt` (KTD7): `scheduled`,
658
+ * `notBefore = retryAt`, one minute later as the fallback time, the
659
+ * deadline raised to at least `retryAt + 2 h`, the estimate cleared so
660
+ * `replanSweep` moves it to the cleanest hour once the forecast covers it.
661
+ * Compare-and-set on `running`: a cancel during the run wins. Past the
662
+ * 8-day cap from `enqueuedAt` the task fails with `message` instead.
663
+ */
664
+ private deferTask;
457
665
  /**
458
666
  * Submit a batch-eligible task to the provider's Batch API. The row was
459
667
  * already claimed (scheduled → running) by the caller. On success the
@@ -483,7 +691,16 @@ export declare class Scheduler {
483
691
  private fetchCurrentIntensity;
484
692
  }
485
693
  export declare function defer<T>(task: DeferrableTask<T>, opts?: DeferOptions): Promise<T>;
486
- /** One-line refusal in the shared style: `<action>: task <id> is <status>; <allowed>`. */
694
+ /** Longest one-off shell command `enqueueCommandTask` accepts. */
695
+ export declare const COMMAND_MAX_CHARS = 32000;
696
+ /**
697
+ * A plain Batch row that a killed tick left `running` goes back to
698
+ * `submitted` once its deadline plus this grace has passed (batch 27 KTD9),
699
+ * the job sweep's limit for a job's Batch row. Wall-clock time: a provider
700
+ * ends a batch whether or not this machine slept.
701
+ * `test/fixtures/stranded-batch-polls.json` holds it for both cores.
702
+ */
703
+ export declare const STRANDED_POLL_GRACE_MS: number;
487
704
  /**
488
705
  * A task action refused by the task's state or by its input (ui v2): the
489
706
  * message is a one-line rule safe to show a user. Any other error from an
@@ -502,4 +719,18 @@ export declare class TaskActionError extends Error {
502
719
  * (cheapest) entry in the sorted band. Prefer `selectWindow` for new code.
503
720
  */
504
721
  export declare function pickBestWindow(entries: GridForecastEntry[], deadline: Date): GridForecastEntry | undefined;
722
+ /**
723
+ * Retry an async function with exponential backoff: up to 4 attempts
724
+ * total (1 initial + 3 retries at 1s, 4s, 16s waits). Retries only on
725
+ * errors that are safe to re-send: 429 rate-limits, 5xx, and network
726
+ * errors raised *before* the request could reach the provider
727
+ * (ECONNREFUSED / ENOTFOUND / EAI_AGAIN). Ambiguous mid-flight errors
728
+ * (ETIMEDOUT, ECONNRESET) are NOT retried — the provider may already
729
+ * have accepted and billed the call. Other 4xx bubble up immediately.
730
+ *
731
+ * This is the single retry policy for Tidegap: provider adapters
732
+ * construct their SDK clients with `maxRetries: 0` so vendor-side
733
+ * retries cannot multiply with this one.
734
+ */
735
+ export declare function retryWithBackoff<T>(fn: () => Promise<T>): Promise<T>;
505
736
  //# sourceMappingURL=scheduler.d.ts.map