@tidegap/core 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/channels/digest.js +3 -3
  2. package/dist/channels/format.d.ts +11 -0
  3. package/dist/channels/format.js +26 -8
  4. package/dist/energy.d.ts +7 -0
  5. package/dist/energy.js +7 -0
  6. package/dist/handoff.d.ts +22 -3
  7. package/dist/handoff.js +69 -17
  8. package/dist/history.d.ts +15 -0
  9. package/dist/history.js +11 -0
  10. package/dist/index.d.ts +17 -13
  11. package/dist/index.js +12 -10
  12. package/dist/jobs.d.ts +25 -15
  13. package/dist/jobs.js +186 -63
  14. package/dist/notify.d.ts +9 -0
  15. package/dist/notify.js +17 -3
  16. package/dist/providers/anthropic.js +8 -6
  17. package/dist/providers/base.d.ts +40 -9
  18. package/dist/providers/base.js +29 -4
  19. package/dist/providers/gemini.d.ts +3 -0
  20. package/dist/providers/gemini.js +9 -6
  21. package/dist/providers/http.d.ts +40 -0
  22. package/dist/providers/http.js +82 -0
  23. package/dist/providers/index.d.ts +1 -1
  24. package/dist/providers/index.js +1 -1
  25. package/dist/providers/ollama.d.ts +3 -0
  26. package/dist/providers/ollama.js +8 -5
  27. package/dist/providers/openai.js +7 -5
  28. package/dist/providers/timeout.d.ts +26 -8
  29. package/dist/providers/timeout.js +53 -15
  30. package/dist/readiness.d.ts +39 -3
  31. package/dist/readiness.js +73 -1
  32. package/dist/run-limits.d.ts +268 -0
  33. package/dist/run-limits.js +572 -0
  34. package/dist/schedule-job.d.ts +23 -0
  35. package/dist/schedule-job.js +48 -0
  36. package/dist/scheduler.d.ts +159 -17
  37. package/dist/scheduler.js +482 -128
  38. package/dist/storage/sqlite.d.ts +28 -2
  39. package/dist/storage/sqlite.js +65 -5
  40. package/dist/task-events.d.ts +19 -4
  41. package/dist/task-events.js +42 -5
  42. package/dist/tool-surface.js +38 -7
  43. package/dist/types.d.ts +31 -10
  44. package/dist/types.js +1 -3
  45. package/package.json +5 -2
@@ -20,6 +20,7 @@ import { type CarbonAlert, type CarbonBudgetConfig } from "./budget.js";
20
20
  import type { ProviderAdapter } from "./providers/base.js";
21
21
  import { type LimitResetSource, type PostponeOption, type PostponeTarget } from "./postpone.js";
22
22
  import { type RoutingPreview } from "./routing.js";
23
+ import { type ResolvedRunLimits, type RunLimitSettings, type TaskRunLimitsView } from "./run-limits.js";
23
24
  import { type QuotaResetConfig } from "./quota.js";
24
25
  import { TaskStore } from "./storage/sqlite.js";
25
26
  import { type TaskEvent, type TaskEventActor } from "./task-events.js";
@@ -195,11 +196,50 @@ export interface SchedulerOptions {
195
196
  boot_at: number;
196
197
  slept_ms: number;
197
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;
198
231
  }
199
232
  /** Per-call options of the task actions: who the change is recorded as. */
200
233
  export interface ActorOptions {
201
234
  actor?: TaskEventActor;
202
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
+ };
203
243
  export declare class Scheduler {
204
244
  private readonly feed;
205
245
  private readonly defaultRegionOption;
@@ -210,6 +250,8 @@ export declare class Scheduler {
210
250
  private readonly bodies;
211
251
  /** Rows a tick moved to `running` whose dispatch has not settled (KTD12), and what each is doing. */
212
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;
213
255
  private readonly store;
214
256
  private signingConfig;
215
257
  private signingKey;
@@ -219,8 +261,20 @@ export declare class Scheduler {
219
261
  private readonly limitReset;
220
262
  private readonly actor;
221
263
  private readonly sleepCounter;
264
+ private readonly lockedTick;
265
+ private readonly runLimitSettings;
222
266
  private defaultRegion;
223
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;
224
278
  /**
225
279
  * Compute the current aggregate carbon-budget status (ROADMAP item 4)
226
280
  * over this scheduler's ledger, or `undefined` when no budget is
@@ -325,9 +379,11 @@ export declare class Scheduler {
325
379
  * an empty prompt) with `command.origin: "cli"` and no job id, planned
326
380
  * like any provider call. Only the CLI tick's command adapter runs it.
327
381
  * 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.
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.
331
387
  */
332
388
  enqueueCommandTask(task: {
333
389
  run: string;
@@ -411,9 +467,13 @@ export declare class Scheduler {
411
467
  /**
412
468
  * The progress callback of one run: the lines an adapter reports become
413
469
  * `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.
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.
415
473
  */
416
474
  private progressFor;
475
+ /** `{ tick }` for a `dispatched` event under the tick lock; else nothing. */
476
+ private tickDetails;
417
477
  /** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
418
478
  private sleepDetails;
419
479
  /**
@@ -547,12 +607,27 @@ export declare class Scheduler {
547
607
  */
548
608
  rescheduleIfPending(taskId: string, newDeadline: Date): Promise<boolean>;
549
609
  /**
550
- * Re-dispatch a failed task. Useful when the original failure was a
551
- * transient provider error (rate-limit, 5xx) and the underlying
552
- * spec is still valid. Only `failed` tasks are eligible; throws
553
- * 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.
554
618
  */
555
- retryTask(taskId: string, adapters: TickAdapters, opts?: ActorOptions): Promise<TickResultEntry>;
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.
629
+ */
630
+ retryLater(taskId: string, opts?: ActorOptions): TaskRecord<unknown>;
556
631
  /**
557
632
  * Pure read-only planning helper: compute the scheduled window and
558
633
  * carbon receipt that the same call to `enqueueProviderCall` would
@@ -589,11 +664,72 @@ export declare class Scheduler {
589
664
  listTasks(): ReadonlyArray<TaskRecord<unknown>>;
590
665
  /** Runs the dispatch of a row the tick moved to `running`, holding the row until it settles. */
591
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;
592
726
  /**
593
727
  * A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
594
728
  * scheduler moved to `running` in a tick whose dispatch has not settled,
595
729
  * by what the row was doing:
596
- * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`);
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;
597
733
  * - a Batch poll goes back to `submitted` with its `batchId`: the batch
598
734
  * is live at the provider, and the next tick polls it again;
599
735
  * - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
@@ -602,8 +738,8 @@ export declare class Scheduler {
602
738
  * keeps its status; rows another process holds, or a crashed tick
603
739
  * stranded, are not touched (the job sweep frees job runs, and the next
604
740
  * 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.
741
+ * a process about to exit. Returns the ids it failed or queued again; a
742
+ * second call changes nothing.
607
743
  */
608
744
  failHeldRuns(): string[];
609
745
  /** Cancel and clean up timers. Mostly for tests. */
@@ -726,11 +862,17 @@ export declare function pickBestWindow(entries: GridForecastEntry[], deadline: D
726
862
  * errors raised *before* the request could reach the provider
727
863
  * (ECONNREFUSED / ENOTFOUND / EAI_AGAIN). Ambiguous mid-flight errors
728
864
  * (ETIMEDOUT, ECONNRESET) are NOT retried — the provider may already
729
- * have accepted and billed the call. Other 4xx bubble up immediately.
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.
730
872
  *
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.
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.
734
876
  */
735
- export declare function retryWithBackoff<T>(fn: () => Promise<T>): Promise<T>;
877
+ export declare function retryWithBackoff<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T>;
736
878
  //# sourceMappingURL=scheduler.d.ts.map