@tidegap/core 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/README.md +1 -1
  2. package/dist/agent-snippet.d.ts +30 -0
  3. package/dist/agent-snippet.js +120 -0
  4. package/dist/channels/commands.d.ts +137 -0
  5. package/dist/channels/commands.js +377 -0
  6. package/dist/channels/delivery-codes.d.ts +9 -0
  7. package/dist/channels/delivery-codes.js +53 -0
  8. package/dist/channels/digest.d.ts +102 -0
  9. package/dist/channels/digest.js +146 -0
  10. package/dist/channels/format.d.ts +138 -0
  11. package/dist/channels/format.js +425 -0
  12. package/dist/channels/index.d.ts +15 -0
  13. package/dist/channels/index.js +15 -0
  14. package/dist/channels/kinds/command.d.ts +13 -0
  15. package/dist/channels/kinds/command.js +65 -0
  16. package/dist/channels/kinds/discord.d.ts +16 -0
  17. package/dist/channels/kinds/discord.js +67 -0
  18. package/dist/channels/kinds/email.d.ts +20 -0
  19. package/dist/channels/kinds/email.js +162 -0
  20. package/dist/channels/kinds/index.d.ts +8 -0
  21. package/dist/channels/kinds/index.js +17 -0
  22. package/dist/channels/kinds/ntfy.d.ts +25 -0
  23. package/dist/channels/kinds/ntfy.js +163 -0
  24. package/dist/channels/kinds/pushover.d.ts +11 -0
  25. package/dist/channels/kinds/pushover.js +77 -0
  26. package/dist/channels/kinds/shared.d.ts +25 -0
  27. package/dist/channels/kinds/shared.js +39 -0
  28. package/dist/channels/kinds/shortcuts.d.ts +9 -0
  29. package/dist/channels/kinds/shortcuts.js +45 -0
  30. package/dist/channels/kinds/slack.d.ts +8 -0
  31. package/dist/channels/kinds/slack.js +57 -0
  32. package/dist/channels/kinds/telegram.d.ts +4 -0
  33. package/dist/channels/kinds/telegram.js +26 -0
  34. package/dist/channels/kinds/webhook.d.ts +30 -0
  35. package/dist/channels/kinds/webhook.js +177 -0
  36. package/dist/channels/payload.d.ts +36 -0
  37. package/dist/channels/payload.js +61 -0
  38. package/dist/channels/plan.d.ts +24 -0
  39. package/dist/channels/plan.js +66 -0
  40. package/dist/channels/registry.d.ts +191 -0
  41. package/dist/channels/registry.js +125 -0
  42. package/dist/channels/telegram.d.ts +110 -0
  43. package/dist/channels/telegram.js +168 -0
  44. package/dist/channels/types.d.ts +107 -0
  45. package/dist/channels/types.js +26 -0
  46. package/dist/claude-tools.d.ts +29 -0
  47. package/dist/claude-tools.js +49 -0
  48. package/dist/data/tables.generated.d.ts +6 -0
  49. package/dist/data/tables.generated.js +37 -0
  50. package/dist/energy.d.ts +84 -0
  51. package/dist/energy.js +138 -0
  52. package/dist/grid.d.ts +17 -2
  53. package/dist/grid.js +43 -4
  54. package/dist/handoff.d.ts +171 -0
  55. package/dist/handoff.js +482 -0
  56. package/dist/history.d.ts +17 -0
  57. package/dist/history.js +14 -1
  58. package/dist/index.d.ts +49 -15
  59. package/dist/index.js +36 -8
  60. package/dist/job-cadence.d.ts +76 -0
  61. package/dist/job-cadence.js +240 -0
  62. package/dist/jobs.d.ts +183 -0
  63. package/dist/jobs.js +917 -0
  64. package/dist/notify.d.ts +11 -0
  65. package/dist/notify.js +19 -4
  66. package/dist/postpone.d.ts +113 -0
  67. package/dist/postpone.js +185 -0
  68. package/dist/providers/anthropic.js +14 -8
  69. package/dist/providers/base.d.ts +145 -2
  70. package/dist/providers/base.js +41 -1
  71. package/dist/providers/budget.d.ts +25 -0
  72. package/dist/providers/budget.js +57 -0
  73. package/dist/providers/defaults.js +4 -0
  74. package/dist/providers/defer.d.ts +16 -0
  75. package/dist/providers/defer.js +31 -0
  76. package/dist/providers/gemini.d.ts +4 -0
  77. package/dist/providers/gemini.js +34 -24
  78. package/dist/providers/http.d.ts +40 -0
  79. package/dist/providers/http.js +82 -0
  80. package/dist/providers/index.d.ts +2 -2
  81. package/dist/providers/index.js +1 -1
  82. package/dist/providers/ollama.d.ts +4 -0
  83. package/dist/providers/ollama.js +32 -25
  84. package/dist/providers/openai.js +11 -9
  85. package/dist/providers/timeout.d.ts +36 -0
  86. package/dist/providers/timeout.js +71 -0
  87. package/dist/quota.d.ts +7 -2
  88. package/dist/quota.js +12 -27
  89. package/dist/readiness.d.ts +205 -0
  90. package/dist/readiness.js +326 -0
  91. package/dist/redact.d.ts +42 -0
  92. package/dist/redact.js +110 -0
  93. package/dist/region-host.d.ts +30 -0
  94. package/dist/region-host.js +69 -0
  95. package/dist/region.d.ts +102 -20
  96. package/dist/region.js +175 -23
  97. package/dist/run-limits.d.ts +268 -0
  98. package/dist/run-limits.js +572 -0
  99. package/dist/run-session.d.ts +36 -0
  100. package/dist/run-session.js +72 -0
  101. package/dist/schedule-job.d.ts +118 -0
  102. package/dist/schedule-job.js +243 -0
  103. package/dist/scheduler.d.ts +391 -18
  104. package/dist/scheduler.js +1341 -177
  105. package/dist/sign.d.ts +8 -1
  106. package/dist/sign.js +49 -3
  107. package/dist/storage/sqlite.d.ts +183 -5
  108. package/dist/storage/sqlite.js +720 -19
  109. package/dist/task-events.d.ts +117 -0
  110. package/dist/task-events.js +345 -0
  111. package/dist/tool-surface.d.ts +31 -2
  112. package/dist/tool-surface.js +390 -65
  113. package/dist/types.d.ts +267 -3
  114. package/dist/types.js +6 -1
  115. package/dist/zone-time.d.ts +22 -0
  116. package/dist/zone-time.js +76 -0
  117. package/package.json +13 -5
  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,13 @@
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";
23
+ import { type ResolvedRunLimits, type RunLimitSettings, type TaskRunLimitsView } from "./run-limits.js";
22
24
  import { type QuotaResetConfig } from "./quota.js";
23
25
  import { TaskStore } from "./storage/sqlite.js";
24
- import type { DeferOptions, DeferrableTask, GridFeed, GridForecastEntry, ProviderCallSpec, ProviderName, TaskRecord, TickResult, TickResultEntry } from "./types.js";
26
+ import { type TaskEvent, type TaskEventActor } from "./task-events.js";
27
+ import type { DeferOptions, DeferrableTask, GridFeed, JobCaps, GridForecastEntry, ProviderCallOrigin, ProviderCallSpec, ProviderName, TaskRecord, TaskStatus, TickResult, TickResultEntry } from "./types.js";
25
28
  /** Target of {@link Scheduler.rescheduleTask} (ui v2): exactly one shape. */
26
29
  export type RescheduleTarget =
27
30
  /** A new deadline; the window picker chooses the hour. */
@@ -36,6 +39,14 @@ export type RescheduleTarget =
36
39
  | {
37
40
  dayStart: string | Date;
38
41
  dayEnd: string | Date;
42
+ }
43
+ /**
44
+ * An earliest start (a usage-limit reset); the picker chooses an hour at
45
+ * or after it. The deadline rises to at least `notBefore + 2 h`.
46
+ */
47
+ | {
48
+ notBefore: string | Date;
49
+ deadline?: string | Date;
39
50
  };
40
51
  /** Options of {@link Scheduler.replyToTask} (ui v2). */
41
52
  export interface ReplyOptions {
@@ -47,7 +58,16 @@ export interface ReplyOptions {
47
58
  originHost?: DeferOptions["originHost"];
48
59
  originCwd?: string;
49
60
  originSessionId?: string;
61
+ /**
62
+ * Keep the parent's origin session (`spec.origin`), so the reply runs in
63
+ * a copy of that session too. Default false: only a caller that is the
64
+ * user (the CLI, the page) or that session itself may resume it; any other
65
+ * caller's reply runs fresh.
66
+ */
67
+ keepOrigin?: boolean;
50
68
  }
69
+ export declare const PENDING_STATUSES: readonly TaskStatus[];
70
+ export declare const UNFINISHED_STATUSES: readonly TaskStatus[];
51
71
  /** Ledger meta key holding the ISO time a ticker last ran. */
52
72
  export declare const LAST_TICK_META_KEY = "last_tick_at";
53
73
  /**
@@ -57,6 +77,23 @@ export declare const LAST_TICK_META_KEY = "last_tick_at";
57
77
  * clear "no adapter configured" error rather than silently dropping it.
58
78
  */
59
79
  export type TickAdapters = Partial<Record<ProviderName, ProviderAdapter>>;
80
+ /** Options of {@link Scheduler.tick}. */
81
+ export interface TickOptions {
82
+ /**
83
+ * Leave a due row whose provider has no adapter (and no routing candidate
84
+ * with one) `scheduled` instead of failing it. For a host that serves no
85
+ * LLM provider at all, such as the CLI tick with only command jobs: the
86
+ * row waits for a host that can run it.
87
+ */
88
+ holdUnserved?: boolean;
89
+ /**
90
+ * Stop the tick cooperatively: once aborted, no further row is claimed,
91
+ * submitted, dispatched or polled. A dispatch already running finishes
92
+ * (its runner decides how a stop signal ends it); the tick returns what
93
+ * it did so far. Rows it did not reach stay as they were.
94
+ */
95
+ signal?: AbortSignal;
96
+ }
60
97
  /** Thrown when no candidate window meets the user-supplied carbon budget. */
61
98
  export declare class CarbonBudgetExceededError extends Error {
62
99
  readonly minimumGCo2: number;
@@ -70,8 +107,12 @@ export declare class InvalidDeadlineError extends Error {
70
107
  }
71
108
  export interface SchedulerOptions {
72
109
  feed?: GridFeed;
73
- /** Default region to use when DeferOptions does not name one. */
74
- defaultRegion?: string;
110
+ /**
111
+ * Default region to use when DeferOptions does not name one. A getter is
112
+ * called on every schedule, so a host can follow a changed setting
113
+ * without a restart.
114
+ */
115
+ defaultRegion?: string | (() => string);
75
116
  /** If true (default), background loop ticks immediately on `defer`. */
76
117
  eager?: boolean;
77
118
  /**
@@ -133,22 +174,107 @@ export interface SchedulerOptions {
133
174
  * sees config edits.
134
175
  */
135
176
  quotaConfig?: () => QuotaResetConfig;
177
+ /**
178
+ * The plugged-in limit-reset source for "Later → after limit reset"
179
+ * (coherence KTD5), for example the CLI usage module's Claude reset.
180
+ * A caller-given reset wins over it; a stored hint is the fallback.
181
+ */
182
+ limitReset?: LimitResetSource;
183
+ /**
184
+ * Who this scheduler's writes are recorded as in `task_events` (for
185
+ * example `cli`, `tick`, `agent:mcp`). Default `system`. A mutation
186
+ * method's own `{ actor }` wins.
187
+ */
188
+ actor?: TaskEventActor;
189
+ /**
190
+ * The machine's sleep counter (`boot_at`, `slept_ms`), read by the host
191
+ * (the CLI tick). Stored on each `dispatched` event as `sleep`, so the job
192
+ * sweep counts a run's age on awake time: a run the machine slept
193
+ * through is not interrupted (`sleep-gap-is-not-a-dead-daemon.md`).
194
+ */
195
+ sleepCounter?: () => {
196
+ boot_at: number;
197
+ slept_ms: number;
198
+ } | null;
199
+ /**
200
+ * The locked tick this scheduler runs under: the CLI tick, which holds
201
+ * `<ledger>.tick.lock`. Its details go on each `dispatched` event as
202
+ * `tick`, and `tick()` first frees the one-off rows another tick left
203
+ * `running` once that tick's process is gone; the job sweep frees job
204
+ * rows by the same rule ({@link Scheduler.deadTickRun}). A host that does
205
+ * not hold the lock leaves it out.
206
+ */
207
+ lockedTick?: LockedTick;
208
+ /**
209
+ * The run-limit settings of `~/.tidegap/config`, read at each run start, so
210
+ * a change applies to the next run without a restart. Default: the core
211
+ * reader of that file. A host passes its own to read another path.
212
+ */
213
+ runLimits?: () => RunLimitSettings;
214
+ }
215
+ /** The `tick` details of a `dispatched` event: the locked tick that ran the row. */
216
+ export interface TickDetails {
217
+ /** Random, one per locked tick. */
218
+ id: string;
219
+ pid: number;
220
+ /** ISO-8601 start of the tick's process, when the host could read it. */
221
+ started_at?: string;
222
+ }
223
+ /** A locked tick: its details, and how to tell whether another tick's process still runs. */
224
+ export interface LockedTick {
225
+ tick: TickDetails;
226
+ /**
227
+ * Whether the process `tick` names still runs: its pid, with the same start
228
+ * time. Undefined when the host cannot tell (no start time to compare).
229
+ */
230
+ isRunning(tick: TickDetails): boolean | undefined;
136
231
  }
232
+ /** Per-call options of the task actions: who the change is recorded as. */
233
+ export interface ActorOptions {
234
+ actor?: TaskEventActor;
235
+ }
236
+ /** What {@link Scheduler.retryTask} did: the run's result, or the task due now for the next tick. */
237
+ export type RetryResult = TickResultEntry | {
238
+ taskId: string;
239
+ status: "scheduled";
240
+ scheduledFor: string;
241
+ error?: undefined;
242
+ };
137
243
  export declare class Scheduler {
138
244
  private readonly feed;
139
- private readonly defaultRegion;
245
+ private readonly defaultRegionOption;
140
246
  private readonly rng;
141
247
  private readonly tasks;
142
248
  private readonly pendingTimers;
143
249
  private readonly resolvers;
144
250
  private readonly bodies;
251
+ /** Rows a tick moved to `running` whose dispatch has not settled (KTD12), and what each is doing. */
252
+ private readonly held;
253
+ /** Failed attempts per task without a ledger, where no `attempt_failed` event is stored to count. */
254
+ private readonly attemptsWithoutLedger;
145
255
  private readonly store;
146
256
  private signingConfig;
147
257
  private signingKey;
148
258
  private readonly carbonBudget;
149
259
  private readonly onCarbonAlert;
150
260
  private readonly quotaConfig;
261
+ private readonly limitReset;
262
+ private readonly actor;
263
+ private readonly sleepCounter;
264
+ private readonly lockedTick;
265
+ private readonly runLimitSettings;
266
+ private defaultRegion;
151
267
  constructor(opts?: SchedulerOptions);
268
+ /**
269
+ * The time limits a run of `spec` gets if it starts now: the stored
270
+ * values, then the settings, then the defaults. A settings read that
271
+ * throws gives the stored values and the defaults.
272
+ */
273
+ runLimitsFor(spec: Pick<ProviderCallSpec, "provider" | "caps" | "summarize">): ResolvedRunLimits;
274
+ /** A task's time limits as views show them: the ones its newest run recorded, else the ones a run now gets. */
275
+ taskRunLimits(record: TaskRecord<unknown>, events?: readonly TaskEvent[]): TaskRunLimitsView;
276
+ /** The run-limit settings now; a reader that throws gives none (the stored values and the defaults apply). */
277
+ private settingsNow;
152
278
  /**
153
279
  * Compute the current aggregate carbon-budget status (ROADMAP item 4)
154
280
  * over this scheduler's ledger, or `undefined` when no budget is
@@ -190,10 +316,38 @@ export declare class Scheduler {
190
316
  markTaskRead(taskId: string, at?: Date): boolean;
191
317
  /** Clear a task's read marker (v0.17). Returns true iff it was set. */
192
318
  markTaskUnread(taskId: string): boolean;
319
+ /** A task's events from the ledger, oldest first; [] without a store. */
320
+ listTaskEvents(taskId: string, opts?: {
321
+ limit?: number;
322
+ }): TaskEvent[];
193
323
  /** Record that a ticker ran at `at` (ledger meta `last_tick_at`). No-op without a store. */
194
324
  recordTickRun(at?: Date): void;
195
325
  /** When a ticker (`tidegap tick` or the OpenClaw loop) last ran, if ever recorded. */
196
326
  lastTickAt(): string | undefined;
327
+ /** The ledger this scheduler writes through to, if any. Jobs live there too. */
328
+ ledger(): TaskStore | undefined;
329
+ /**
330
+ * Insert one job occurrence and plan it (floating recurring jobs, KTD4).
331
+ * The row is built here, not through `enqueueProviderCall` (which refuses
332
+ * `provider: "command"`): `scheduled`, `notBefore = earliest`,
333
+ * `scheduledFor = earliest + 1 min` (never equal to `notBefore`, which
334
+ * would read as an exact pin), the slot deadline with no widening,
335
+ * `repeat = none` and no series, so `rollSeries` never touches it. The
336
+ * insert is `insertIfAbsent` on the derived id; returns false, writing
337
+ * nothing, when the row exists. Planning picks the cleanest forecast hour
338
+ * inside `[earliest, deadline]`, or leaves the row unplanned for
339
+ * `replanSweep` when the forecast does not reach it (or fails).
340
+ */
341
+ materializeOccurrence(occ: {
342
+ taskId: string;
343
+ jobId: string;
344
+ earliest: string;
345
+ deadline: string;
346
+ title: string;
347
+ bodyJson: string;
348
+ originHost?: TaskRecord["originHost"];
349
+ originCwd?: string;
350
+ }, details: Record<string, unknown>): Promise<boolean>;
197
351
  /**
198
352
  * Defer a task. Returns a promise that resolves with the task's eventual
199
353
  * result when Tidegap dispatches it.
@@ -219,13 +373,37 @@ export declare class Scheduler {
219
373
  * later cron-tick) can pick them up.
220
374
  */
221
375
  enqueueProviderCall(spec: ProviderCallSpec, opts?: DeferOptions): Promise<TaskRecord<unknown>>;
376
+ /**
377
+ * Queue a one-off shell command (`tidegap queue add --runner command`):
378
+ * the row of a command job run (`provider: "command"`, `model: "none"`,
379
+ * an empty prompt) with `command.origin: "cli"` and no job id, planned
380
+ * like any provider call. Only the CLI tick's command adapter runs it.
381
+ * Checks: a command of 1 to 32,000 characters, an existing absolute
382
+ * folder, valid caps, and the result path rules. Only the caps the caller
383
+ * set are stored; the time limits not set come from the settings when the
384
+ * run starts. `enqueueProviderCall` keeps refusing `command`, and
385
+ * `retryTask` refuses these rows: running a shell command again is the
386
+ * user's call.
387
+ */
388
+ enqueueCommandTask(task: {
389
+ run: string;
390
+ cwd: string;
391
+ caps?: Partial<JobCaps>;
392
+ resultPath?: string;
393
+ /** The checked agent session that queued it, for its notice. */
394
+ origin?: ProviderCallOrigin;
395
+ /** Wake that session when the task finishes; needs `origin` and `opts.originSessionId`. */
396
+ wake?: boolean;
397
+ }, opts?: DeferOptions): Promise<TaskRecord<unknown>>;
398
+ /** Insert a checked provider-call row with its `created` event, then plan its window. */
399
+ private insertProviderCall;
222
400
  /**
223
401
  * Drain due provider-call tasks against the supplied adapters. Returns a
224
402
  * `TickResult` summarising what happened. Closure-based tasks
225
403
  * (`enqueue` / `defer`) are NOT touched by this method — only this
226
404
  * process can run those.
227
405
  */
228
- tick(adapters: TickAdapters): Promise<TickResult>;
406
+ tick(adapters: TickAdapters, opts?: TickOptions): Promise<TickResult>;
229
407
  /**
230
408
  * Collect scheduled provider-call tasks that should be routed through a
231
409
  * Batch API this tick: preferBatch !== false, an adapter with a
@@ -248,6 +426,19 @@ export declare class Scheduler {
248
426
  private reloadClaimed;
249
427
  /** Undo a claim on a row that turned out not to be ready: back to `scheduled`. */
250
428
  private releaseClaim;
429
+ /**
430
+ * The head of the Batch-poll sweep (batch 27 KTD9): a plain row that a
431
+ * killed tick left `running` with its batch id goes back to `submitted`
432
+ * once its deadline plus `STRANDED_POLL_GRACE_MS` has passed, and the sweep
433
+ * then polls it. The batch id proves a live batch. A row goes to a Batch
434
+ * API only with a deadline over a day ahead, and the providers end every
435
+ * batch within 24 h, so a row past its deadline has a finished batch: the
436
+ * step rarely meets a live poll in another process, and compare-and-set
437
+ * still lands one completion if it does. Job rows are the job sweep's;
438
+ * rows this scheduler's tick holds are live. No event, as in
439
+ * `failHeldRuns`.
440
+ */
441
+ private freeStrandedPolls;
251
442
  /**
252
443
  * Collect every "submitted" provider-call task awaiting batch results.
253
444
  * `exclude` skips tasks submitted earlier in the same tick — submit and
@@ -273,6 +464,18 @@ export declare class Scheduler {
273
464
  private clearPendingTimer;
274
465
  /** Merge a stored row into the cache, keeping the cached object identity. */
275
466
  private cacheRow;
467
+ /**
468
+ * The progress callback of one run: the lines an adapter reports become
469
+ * `progress` events (actor `tick`) within the core caps. None without a
470
+ * ledger. Each write waits at most `PROGRESS_BUSY_MS` for a busy ledger.
471
+ * A failed write costs its line, never the run; the first failure of a
472
+ * task logs one warning that says later failed lines are dropped too.
473
+ */
474
+ private progressFor;
475
+ /** `{ tick }` for a `dispatched` event under the tick lock; else nothing. */
476
+ private tickDetails;
477
+ /** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
478
+ private sleepDetails;
276
479
  /**
277
480
  * Compare-and-set write: store `next` only while the row's status is in
278
481
  * `expected`; on success copy it onto the cached record. On a miss the
@@ -280,6 +483,12 @@ export declare class Scheduler {
280
483
  * store the write always succeeds.
281
484
  */
282
485
  private writeIf;
486
+ /**
487
+ * The `task_events` row for a write from `prev` to `next`: the given kind,
488
+ * or a terminal kind the status change implies; undefined = no event.
489
+ * `spec.details` are extra keys on top of {@link eventDetails}.
490
+ */
491
+ private eventFor;
283
492
  /**
284
493
  * Series rollover (ui v2, KTD6). Called when an occurrence with a repeat
285
494
  * rule finishes (completed, failed, or cancelled as a skip), BEFORE its
@@ -314,11 +523,16 @@ export declare class Scheduler {
314
523
  * claimed the row first, the cancel lands on the `running` row; the
315
524
  * dispatcher re-checks the status before finalizing and drops the late
316
525
  * result. `opts.series` also ends the series (`repeat = none`) in the
317
- * same write ("stop series").
526
+ * same write ("stop series"); on a finished occurrence it ends the
527
+ * series at its live occurrence. `opts.expectedStatus` cancels only a row in
528
+ * one of those states and returns any other row unchanged: the job code
529
+ * passes the pending states, so a row a tick claimed runs to its end.
318
530
  */
319
531
  cancelTask(taskId: string, opts?: {
320
532
  series?: boolean;
321
- }): TaskRecord<unknown>;
533
+ details?: Record<string, unknown>;
534
+ expectedStatus?: readonly TaskStatus[];
535
+ } & ActorOptions): TaskRecord<unknown>;
322
536
  /**
323
537
  * Run a pending provider-call task at the next tick (ui v2). A write
324
538
  * only: no dispatch happens here, so a process without adapters (the
@@ -327,7 +541,7 @@ export declare class Scheduler {
327
541
  * survives onto the completed row. Throws when the task's state does not
328
542
  * allow it (see `taskActions`).
329
543
  */
330
- runNow(taskId: string): TaskRecord<unknown>;
544
+ runNow(taskId: string, opts?: ActorOptions): TaskRecord<unknown>;
331
545
  /**
332
546
  * Move a queued or scheduled provider-call task (ui v2). `{deadline}`
333
547
  * re-runs the window picker up to the new deadline; `{at}` pins the exact
@@ -338,7 +552,24 @@ export declare class Scheduler {
338
552
  * compare-and-set on the pending statuses; throws when the task is not
339
553
  * movable.
340
554
  */
341
- rescheduleTask(taskId: string, target: RescheduleTarget): Promise<TaskRecord<unknown>>;
555
+ rescheduleTask(taskId: string, target: RescheduleTarget, opts?: ActorOptions): Promise<TaskRecord<unknown>>;
556
+ /** `rescheduleTask` with the event to record (`rescheduled` or `postponed`). */
557
+ private moveTask;
558
+ /**
559
+ * "Later" (coherence KTD4): move a queued or scheduled provider-call task
560
+ * so it never runs earlier than its planned start. Resolves the target
561
+ * with {@link resolvePostpone} and writes it through `rescheduleTask`, so
562
+ * the write is the same compare-and-set on the pending statuses. An
563
+ * `after_limit_reset` target uses its own `resetAt` (stored as the hint),
564
+ * else the plugged-in `limitReset` source, else a still-future hint.
565
+ * Throws `TaskActionError` with the refusal reason.
566
+ */
567
+ postponeTask(taskId: string, target: PostponeTarget, opts?: ActorOptions): Promise<TaskRecord<unknown>>;
568
+ /**
569
+ * The Later presets of a task with their resolved times (KTD6), using
570
+ * the plugged-in reset source and the stored hint.
571
+ */
572
+ postponeOptionsFor(task: string | TaskRecord<unknown>, now?: Date): Promise<PostponeOption[]>;
342
573
  /**
343
574
  * Reply to a completed provider-call task (ui v2, brainstorm R16/R17):
344
575
  * enqueue a child with the parent's conversation as history, the reply as
@@ -346,14 +577,14 @@ export declare class Scheduler {
346
577
  * child runs through the normal window picker (default deadline one hour
347
578
  * ahead) and never repeats. Refuses failed and cancelled parents (AE4).
348
579
  */
349
- replyToTask(parentId: string, text: string, opts?: ReplyOptions): Promise<TaskRecord<unknown>>;
580
+ replyToTask(parentId: string, text: string, opts?: ReplyOptions & ActorOptions): Promise<TaskRecord<unknown>>;
350
581
  /**
351
582
  * Dispatch a queued/scheduled provider-call task immediately,
352
583
  * bypassing the scheduler's chosen window. Receipt records
353
584
  * `intensitySource: "expedited"`. Closure-based tasks (from
354
585
  * `defer`) are not expediteable; we throw a clear error.
355
586
  */
356
- expediteTask(taskId: string, adapters: TickAdapters): Promise<TickResultEntry>;
587
+ expediteTask(taskId: string, adapters: TickAdapters, opts?: ActorOptions): Promise<TickResultEntry>;
357
588
  /**
358
589
  * Re-score and reschedule a queued/scheduled task against a new
359
590
  * deadline. Throws if the task is already running or terminal, or
@@ -365,7 +596,7 @@ export declare class Scheduler {
365
596
  */
366
597
  updateDeadline(taskId: string, newDeadline: string | Date, opts?: {
367
598
  deadlineKind?: "absolute";
368
- }): Promise<TaskRecord<unknown>>;
599
+ } & ActorOptions): Promise<TaskRecord<unknown>>;
369
600
  /**
370
601
  * The quota sweep's reschedule (`sweepQuotaDeadlines`). Same window
371
602
  * selection as `updateDeadline`, but the ledger write is conditional on
@@ -376,12 +607,27 @@ export declare class Scheduler {
376
607
  */
377
608
  rescheduleIfPending(taskId: string, newDeadline: Date): Promise<boolean>;
378
609
  /**
379
- * Re-dispatch a failed task. Useful when the original failure was a
380
- * transient provider error (rate-limit, 5xx) and the underlying
381
- * spec is still valid. Only `failed` tasks are eligible; throws
382
- * otherwise.
610
+ * Retry a failed task by hand, starting a new attempt count. With a ready
611
+ * adapter for the task's provider in `adapters`, the call runs now and
612
+ * its result comes back. Otherwise, and always for a `command` or
613
+ * `claude-code` task, which only the tidegap tick runs, the task is due
614
+ * now ({@link retryLater}) and the next tick runs it. A manual retry
615
+ * ignores the deadline: the user asked for it. Throws for a task that is
616
+ * not failed, stopped during its Batch submit, closure-based or a run of
617
+ * a job.
618
+ */
619
+ retryTask(taskId: string, adapters: TickAdapters, opts?: ActorOptions): Promise<RetryResult>;
620
+ /**
621
+ * Retry a failed task on the next tick: `failed → scheduled`, due now, its
622
+ * earliest start, error and completion time cleared, with a `rescheduled`
623
+ * event (`reason: retry`), which starts a new attempt count. A write
624
+ * only, for a process that does not dispatch (the CLI, the page's server)
625
+ * or holds no adapter for the task. A manual retry ignores the deadline.
626
+ * Throws {@link TaskActionError} for a task that is not failed, stopped
627
+ * during its Batch submit, closure-based or a run of a job, and when
628
+ * another process moved the row first.
383
629
  */
384
- retryTask(taskId: string, adapters: TickAdapters): Promise<TickResultEntry>;
630
+ retryLater(taskId: string, opts?: ActorOptions): TaskRecord<unknown>;
385
631
  /**
386
632
  * Pure read-only planning helper: compute the scheduled window and
387
633
  * carbon receipt that the same call to `enqueueProviderCall` would
@@ -395,6 +641,8 @@ export declare class Scheduler {
395
641
  band: GridForecastEntry["band"];
396
642
  batchEligible: boolean;
397
643
  region: string;
644
+ /** The deadline the commit would store (raised by a `notBefore`). */
645
+ deadline: string;
398
646
  /**
399
647
  * How many near-equal low-carbon windows sat in the cleanest-tolerance
400
648
  * band the shared `selectWindow` chose from (§2.1). A committed
@@ -414,12 +662,99 @@ export declare class Scheduler {
414
662
  }>;
415
663
  /** Snapshot the queue (immutable copy). */
416
664
  listTasks(): ReadonlyArray<TaskRecord<unknown>>;
665
+ /** Runs the dispatch of a row the tick moved to `running`, holding the row until it settles. */
666
+ private holding;
667
+ /**
668
+ * Watch a held row while its run is in flight: read its status every
669
+ * {@link RUN_STATUS_CHECK_MS} and abort the returned signal once another
670
+ * writer moved it off `running` (a cancel, or a `failed` written
671
+ * elsewhere), so a retry can never overlap the run; `end` stops the watch
672
+ * when the run settles.
673
+ */
674
+ private cancelWatch;
675
+ /**
676
+ * A run the watch stopped because its row left `running`. A cancel keeps
677
+ * the row, and its event gains `stopped_run: true`; any other move (a row
678
+ * failed elsewhere) keeps what that writer wrote. Nothing else is written,
679
+ * as for a late result; the writer that moved the row settled its series.
680
+ */
681
+ private stoppedRun;
682
+ /**
683
+ * The retry funnel: every provider-call run that fails ends here. A
684
+ * one-off row whose failure class may retry, with retries left and a next
685
+ * start that fits before its deadline, goes back to `scheduled`
686
+ * (compare-and-set on `expected`, `running` by default) with an
687
+ * `attempt_failed` event: `notBefore` is the next start, the fallback time
688
+ * one minute later, the deadline unchanged, the estimate, the run-now mark
689
+ * and any batch id cleared. Anything else fails for good: `failed`, with
690
+ * `attempts` and `failure_class` on the event and `(after N attempts)` on
691
+ * the error when more than one ran. A job row always fails for good (the
692
+ * job sweep makes its retry row). The series rolls on a final failure
693
+ * only. Synchronous; an async caller then plans the next attempt's window
694
+ * ({@link planRetryWindow}).
695
+ */
696
+ private failRun;
697
+ /** {@link failRun} for a thrown error: its facts, and its run details (`steps`, `stopped_by`, `truncated`) for the event. */
698
+ private failRunWith;
699
+ /**
700
+ * After {@link failRun} queued another attempt: plan it at the cleanest
701
+ * hour between its earliest start and its deadline. Best effort: without
702
+ * a deadline, or when the forecast fails, the row keeps its fallback time
703
+ * and `replanSweep` plans it before a later tick.
704
+ */
705
+ private planRetryWindow;
706
+ /**
707
+ * The tick-lock rule for a `running` row, shared by the head of a locked
708
+ * tick and the job sweep: true when the run was dispatched under another
709
+ * locked tick whose process is gone, false when that tick is this one or
710
+ * its process still runs. Undefined when this scheduler holds no lock, the
711
+ * row's newest event (progress lines aside) is not a dispatch with tick
712
+ * details (no locked tick ran it, or the row moved on since), or the host
713
+ * cannot tell whether that tick's process runs: the run may be live.
714
+ */
715
+ deadTickRun(row: TaskRecord<unknown>): boolean | undefined;
716
+ /**
717
+ * The head of a locked tick, before any sweep claims a row: a one-off
718
+ * `running` row whose run a dead tick dispatched ({@link deadTickRun})
719
+ * fails as interrupted through the retry funnel (another attempt when the
720
+ * policy allows it), and a Batch row with its batch id goes back to
721
+ * `submitted` for the poll sweep. Compare-and-set from `running`. Job rows
722
+ * are the job sweep's; rows this scheduler holds are live. Returns the
723
+ * entries of the rows it failed or queued again.
724
+ */
725
+ private freeDeadTickRuns;
726
+ /**
727
+ * A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
728
+ * scheduler moved to `running` in a tick whose dispatch has not settled,
729
+ * by what the row was doing:
730
+ * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`)
731
+ * through the retry funnel: a one-off row with retries left is
732
+ * queued again, its window planned before a later tick;
733
+ * - a Batch poll goes back to `submitted` with its `batchId`: the batch
734
+ * is live at the provider, and the next tick polls it again;
735
+ * - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
736
+ * provider may have accepted the batch, so no retry path runs it again.
737
+ * Compare-and-set from `running`, so a row another writer finished first
738
+ * keeps its status; rows another process holds, or a crashed tick
739
+ * stranded, are not touched (the job sweep frees job runs, and the next
740
+ * tick a Batch poll past its deadline: `freeStrandedPolls`). Synchronous, for
741
+ * a process about to exit. Returns the ids it failed or queued again; a
742
+ * second call changes nothing.
743
+ */
744
+ failHeldRuns(): string[];
417
745
  /** Cancel and clean up timers. Mostly for tests. */
418
746
  shutdown(): void;
419
747
  private schedule;
420
748
  /** Fire-and-forget wrapper around `dispatch` that routes any unexpected
421
749
  * rejection to `failTask` instead of an unhandledRejection. */
422
750
  private dispatchSafe;
751
+ /**
752
+ * A closure task's write missed: another process cancelled, claimed or
753
+ * finished its row. Reject the awaiter with the status the ledger now
754
+ * holds and drop the body, so `defer()` never waits forever. A no-op for
755
+ * a provider call, which has no awaiter.
756
+ */
757
+ private rejectMissedClosure;
423
758
  private failTask;
424
759
  private dispatch;
425
760
  /**
@@ -454,6 +789,15 @@ export declare class Scheduler {
454
789
  */
455
790
  private applyRoutingIfNeeded;
456
791
  private dispatchProviderCall;
792
+ /**
793
+ * Put a running task back in the queue until `retryAt` (KTD7): `scheduled`,
794
+ * `notBefore = retryAt`, one minute later as the fallback time, the
795
+ * deadline raised to at least `retryAt + 2 h`, the estimate cleared so
796
+ * `replanSweep` moves it to the cleanest hour once the forecast covers it.
797
+ * Compare-and-set on `running`: a cancel during the run wins. Past the
798
+ * 8-day cap from `enqueuedAt` the task fails with `message` instead.
799
+ */
800
+ private deferTask;
457
801
  /**
458
802
  * Submit a batch-eligible task to the provider's Batch API. The row was
459
803
  * already claimed (scheduled → running) by the caller. On success the
@@ -483,7 +827,16 @@ export declare class Scheduler {
483
827
  private fetchCurrentIntensity;
484
828
  }
485
829
  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>`. */
830
+ /** Longest one-off shell command `enqueueCommandTask` accepts. */
831
+ export declare const COMMAND_MAX_CHARS = 32000;
832
+ /**
833
+ * A plain Batch row that a killed tick left `running` goes back to
834
+ * `submitted` once its deadline plus this grace has passed (batch 27 KTD9),
835
+ * the job sweep's limit for a job's Batch row. Wall-clock time: a provider
836
+ * ends a batch whether or not this machine slept.
837
+ * `test/fixtures/stranded-batch-polls.json` holds it for both cores.
838
+ */
839
+ export declare const STRANDED_POLL_GRACE_MS: number;
487
840
  /**
488
841
  * A task action refused by the task's state or by its input (ui v2): the
489
842
  * message is a one-line rule safe to show a user. Any other error from an
@@ -502,4 +855,24 @@ export declare class TaskActionError extends Error {
502
855
  * (cheapest) entry in the sorted band. Prefer `selectWindow` for new code.
503
856
  */
504
857
  export declare function pickBestWindow(entries: GridForecastEntry[], deadline: Date): GridForecastEntry | undefined;
858
+ /**
859
+ * Retry an async function with exponential backoff: up to 4 attempts
860
+ * total (1 initial + 3 retries at 1s, 4s, 16s waits). Retries only on
861
+ * errors that are safe to re-send: 429 rate-limits, 5xx, and network
862
+ * errors raised *before* the request could reach the provider
863
+ * (ECONNREFUSED / ENOTFOUND / EAI_AGAIN). Ambiguous mid-flight errors
864
+ * (ETIMEDOUT, ECONNRESET) are NOT retried — the provider may already
865
+ * have accepted and billed the call. Other 4xx bubble up immediately;
866
+ * a 408 or 425 then gets the task retry (`isPermanentStatus` in run-limits).
867
+ *
868
+ * This is the in-call resend for Tidegap: provider adapters construct
869
+ * their SDK clients with `maxRetries: 0` so vendor-side retries cannot
870
+ * multiply with this one. The task's retry policy (a later attempt) is a
871
+ * separate layer, in the scheduler's retry funnel.
872
+ *
873
+ * `signal` (the task's cancel watch) ends the waits: once it aborts, no
874
+ * further call is made, even when the adapter ignored the signal, and the
875
+ * last error is thrown.
876
+ */
877
+ export declare function retryWithBackoff<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T>;
505
878
  //# sourceMappingURL=scheduler.d.ts.map