@tidegap/core 0.20.0 → 0.22.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 (54) hide show
  1. package/dist/channels/digest.js +4 -4
  2. package/dist/channels/format.d.ts +30 -4
  3. package/dist/channels/format.js +125 -22
  4. package/dist/channels/payload.js +8 -6
  5. package/dist/channels/plan.js +3 -2
  6. package/dist/channels/types.d.ts +17 -1
  7. package/dist/energy.d.ts +7 -0
  8. package/dist/energy.js +7 -0
  9. package/dist/grid.d.ts +10 -2
  10. package/dist/grid.js +14 -5
  11. package/dist/handoff.d.ts +88 -6
  12. package/dist/handoff.js +177 -20
  13. package/dist/history.d.ts +19 -0
  14. package/dist/history.js +24 -1
  15. package/dist/index.d.ts +24 -18
  16. package/dist/index.js +16 -12
  17. package/dist/job-cadence.d.ts +10 -0
  18. package/dist/job-cadence.js +34 -0
  19. package/dist/job-wake.d.ts +55 -0
  20. package/dist/job-wake.js +91 -0
  21. package/dist/jobs.d.ts +74 -17
  22. package/dist/jobs.js +420 -75
  23. package/dist/notify.d.ts +9 -0
  24. package/dist/notify.js +17 -3
  25. package/dist/providers/anthropic.js +8 -6
  26. package/dist/providers/base.d.ts +47 -9
  27. package/dist/providers/base.js +29 -4
  28. package/dist/providers/gemini.d.ts +3 -0
  29. package/dist/providers/gemini.js +9 -6
  30. package/dist/providers/http.d.ts +40 -0
  31. package/dist/providers/http.js +82 -0
  32. package/dist/providers/index.d.ts +1 -1
  33. package/dist/providers/index.js +1 -1
  34. package/dist/providers/ollama.d.ts +3 -0
  35. package/dist/providers/ollama.js +8 -5
  36. package/dist/providers/openai.js +7 -5
  37. package/dist/providers/timeout.d.ts +26 -8
  38. package/dist/providers/timeout.js +53 -15
  39. package/dist/readiness.d.ts +39 -3
  40. package/dist/readiness.js +73 -1
  41. package/dist/run-limits.d.ts +268 -0
  42. package/dist/run-limits.js +572 -0
  43. package/dist/schedule-job.d.ts +41 -2
  44. package/dist/schedule-job.js +70 -2
  45. package/dist/scheduler.d.ts +161 -17
  46. package/dist/scheduler.js +485 -128
  47. package/dist/storage/sqlite.d.ts +52 -5
  48. package/dist/storage/sqlite.js +200 -33
  49. package/dist/task-events.d.ts +19 -4
  50. package/dist/task-events.js +51 -5
  51. package/dist/tool-surface.js +62 -7
  52. package/dist/types.d.ts +72 -11
  53. package/dist/types.js +1 -3
  54. package/package.json +5 -2
@@ -10,7 +10,9 @@
10
10
  */
11
11
  import { includesFileTool, includesWebTool } from "./claude-tools.js";
12
12
  import { guaranteeText, parseWindow, validateJobSchedule } from "./job-cadence.js";
13
+ import { wakePatternError } from "./job-wake.js";
13
14
  import { getJob, removeJob } from "./jobs.js";
15
+ import { DURATION_FORM_ERROR, parseDuration, parseRetryDelay, RETRY_DELAY_ERROR, runLimitValueError, } from "./run-limits.js";
14
16
  import { systemTimeZone } from "./zone-time.js";
15
17
  /** The `repeat` values that create a job. */
16
18
  export const JOB_REPEATS = ["daily", "weekdays", "weekly", "every_n_hours"];
@@ -19,7 +21,7 @@ export function isJobRepeat(repeat) {
19
21
  return typeof repeat === "string" && JOB_REPEATS.includes(repeat);
20
22
  }
21
23
  /** Parameters that only mean something with a job repeat. */
22
- export const JOB_ONLY_PARAMS = ["every_hours", "days", "window", "time_zone"];
24
+ export const JOB_ONLY_PARAMS = ["every_hours", "days", "window", "time_zone", "until", "count", "wake_match"];
23
25
  /** Argument names that would make the run execute a shell command. */
24
26
  const SHELL_KEYS = ["command", "cmd", "shell", "script"];
25
27
  /** The CLI line that queues a one-off shell command task, which only the user runs. */
@@ -76,7 +78,6 @@ const JOB_UNSUPPORTED_PARAMS = [
76
78
  "cwd",
77
79
  "permission_profile",
78
80
  "result_path",
79
- "wake_session",
80
81
  "redact_in_receipt",
81
82
  "quota_provider",
82
83
  "deliver",
@@ -109,6 +110,64 @@ export function jobToolsFor(tools) {
109
110
  return "web";
110
111
  return "none";
111
112
  }
113
+ /**
114
+ * The wake rule of a `schedule_task` job call (KTD8), or undefined for
115
+ * none: `wake_session: true` wakes on a failed run, `wake_match` on a run
116
+ * whose output matches (with `wake_session` omitted or true). Throws an
117
+ * Error with a plain message.
118
+ */
119
+ export function jobWakeArgs(args) {
120
+ if (args.wake_match === undefined)
121
+ return args.wake_session === true ? { on: "failures" } : undefined;
122
+ if (args.wake_session === false) {
123
+ throw new Error("wake_match wakes the session on a matching run: omit wake_session or set it to true, or drop wake_match");
124
+ }
125
+ const error = wakePatternError(args.wake_match);
126
+ if (error)
127
+ throw new Error(`wake_match: ${error}`);
128
+ return { on: "match", pattern: args.wake_match };
129
+ }
130
+ /**
131
+ * The `llm_timeout` tool argument in ms or `"none"`, or undefined when it
132
+ * is absent. Throws an Error whose message names the grammar and `none`.
133
+ */
134
+ export function llmTimeoutArg(value) {
135
+ if (value === undefined)
136
+ return undefined;
137
+ if (typeof value !== "string")
138
+ throw new Error(`llm_timeout: ${DURATION_FORM_ERROR}`);
139
+ try {
140
+ return parseDuration(value);
141
+ }
142
+ catch (err) {
143
+ throw new Error(`llm_timeout: ${err.message}`);
144
+ }
145
+ }
146
+ /**
147
+ * The `retries` and `retry_delay` tool arguments as caps (`retries`,
148
+ * `retryDelayMs`), each only when given. Throws an Error whose message names
149
+ * the parameter and its rule.
150
+ */
151
+ export function retryCapsArgs(args) {
152
+ const out = {};
153
+ if (args.retries !== undefined) {
154
+ const error = runLimitValueError("retries", args.retries);
155
+ if (error)
156
+ throw new Error(`retries: ${error}`);
157
+ out.retries = args.retries;
158
+ }
159
+ if (args.retry_delay !== undefined) {
160
+ if (typeof args.retry_delay !== "string")
161
+ throw new Error(`retry_delay: ${RETRY_DELAY_ERROR}`);
162
+ try {
163
+ out.retryDelayMs = parseRetryDelay(args.retry_delay);
164
+ }
165
+ catch (err) {
166
+ throw new Error(`retry_delay: ${err.message}`);
167
+ }
168
+ }
169
+ return out;
170
+ }
112
171
  /** Today's weekday in `timeZone` (a `weekly` job with no days, KTD16). */
113
172
  function weekdayIn(timeZone, now) {
114
173
  return new Intl.DateTimeFormat("en-US", { weekday: "short", timeZone }).format(now).toLowerCase().slice(0, 3);
@@ -142,6 +201,11 @@ export function scheduleJobInput(args, now = new Date()) {
142
201
  const cadence = cadenceOf(args, timeZone, now);
143
202
  const window = args.window !== undefined ? parseWindow(args.window) : undefined;
144
203
  const schedule = validateJobSchedule({ cadence, window, timeZone });
204
+ const caps = {
205
+ ...(args.llmTimeoutMs !== undefined ? { llmTimeoutMs: args.llmTimeoutMs } : {}),
206
+ ...(args.retries !== undefined ? { retries: args.retries } : {}),
207
+ ...(args.retryDelayMs !== undefined ? { retryDelayMs: args.retryDelayMs } : {}),
208
+ };
145
209
  return {
146
210
  title: args.title?.trim() ? args.title : args.prompt,
147
211
  cadence: schedule.cadence,
@@ -157,7 +221,11 @@ export function scheduleJobInput(args, now = new Date()) {
157
221
  },
158
222
  originHost: args.host,
159
223
  originCwd: args.cwd,
224
+ ...(caps && Object.keys(caps).length > 0 ? { caps } : {}),
160
225
  ...(args.deadline !== undefined ? { deadline: args.deadline } : {}),
226
+ ...(args.until !== undefined ? { until: args.until } : {}),
227
+ ...(args.count !== undefined ? { count: args.count } : {}),
228
+ ...(args.wake !== undefined ? { wake: args.wake } : {}),
161
229
  };
162
230
  }
163
231
  const LIVE = new Set(["queued", "scheduled", "running", "submitted"]);
@@ -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
@@ -293,6 +347,8 @@ export declare class Scheduler {
293
347
  bodyJson: string;
294
348
  originHost?: TaskRecord["originHost"];
295
349
  originCwd?: string;
350
+ /** The session a bound job wakes; its runs become that session's notices (KTD7). */
351
+ originSessionId?: string;
296
352
  }, details: Record<string, unknown>): Promise<boolean>;
297
353
  /**
298
354
  * Defer a task. Returns a promise that resolves with the task's eventual
@@ -325,9 +381,11 @@ export declare class Scheduler {
325
381
  * an empty prompt) with `command.origin: "cli"` and no job id, planned
326
382
  * like any provider call. Only the CLI tick's command adapter runs it.
327
383
  * 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.
384
+ * folder, valid caps, and the result path rules. Only the caps the caller
385
+ * set are stored; the time limits not set come from the settings when the
386
+ * run starts. `enqueueProviderCall` keeps refusing `command`, and
387
+ * `retryTask` refuses these rows: running a shell command again is the
388
+ * user's call.
331
389
  */
332
390
  enqueueCommandTask(task: {
333
391
  run: string;
@@ -411,9 +469,13 @@ export declare class Scheduler {
411
469
  /**
412
470
  * The progress callback of one run: the lines an adapter reports become
413
471
  * `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.
472
+ * ledger. Each write waits at most `PROGRESS_BUSY_MS` for a busy ledger.
473
+ * A failed write costs its line, never the run; the first failure of a
474
+ * task logs one warning that says later failed lines are dropped too.
415
475
  */
416
476
  private progressFor;
477
+ /** `{ tick }` for a `dispatched` event under the tick lock; else nothing. */
478
+ private tickDetails;
417
479
  /** `{ sleep }` for a `dispatched` event when the host reads a sleep counter; else nothing. Never throws. */
418
480
  private sleepDetails;
419
481
  /**
@@ -547,12 +609,27 @@ export declare class Scheduler {
547
609
  */
548
610
  rescheduleIfPending(taskId: string, newDeadline: Date): Promise<boolean>;
549
611
  /**
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.
612
+ * Retry a failed task by hand, starting a new attempt count. With a ready
613
+ * adapter for the task's provider in `adapters`, the call runs now and
614
+ * its result comes back. Otherwise, and always for a `command` or
615
+ * `claude-code` task, which only the tidegap tick runs, the task is due
616
+ * now ({@link retryLater}) and the next tick runs it. A manual retry
617
+ * ignores the deadline: the user asked for it. Throws for a task that is
618
+ * not failed, stopped during its Batch submit, closure-based or a run of
619
+ * a job.
554
620
  */
555
- retryTask(taskId: string, adapters: TickAdapters, opts?: ActorOptions): Promise<TickResultEntry>;
621
+ retryTask(taskId: string, adapters: TickAdapters, opts?: ActorOptions): Promise<RetryResult>;
622
+ /**
623
+ * Retry a failed task on the next tick: `failed → scheduled`, due now, its
624
+ * earliest start, error and completion time cleared, with a `rescheduled`
625
+ * event (`reason: retry`), which starts a new attempt count. A write
626
+ * only, for a process that does not dispatch (the CLI, the page's server)
627
+ * or holds no adapter for the task. A manual retry ignores the deadline.
628
+ * Throws {@link TaskActionError} for a task that is not failed, stopped
629
+ * during its Batch submit, closure-based or a run of a job, and when
630
+ * another process moved the row first.
631
+ */
632
+ retryLater(taskId: string, opts?: ActorOptions): TaskRecord<unknown>;
556
633
  /**
557
634
  * Pure read-only planning helper: compute the scheduled window and
558
635
  * carbon receipt that the same call to `enqueueProviderCall` would
@@ -589,11 +666,72 @@ export declare class Scheduler {
589
666
  listTasks(): ReadonlyArray<TaskRecord<unknown>>;
590
667
  /** Runs the dispatch of a row the tick moved to `running`, holding the row until it settles. */
591
668
  private holding;
669
+ /**
670
+ * Watch a held row while its run is in flight: read its status every
671
+ * {@link RUN_STATUS_CHECK_MS} and abort the returned signal once another
672
+ * writer moved it off `running` (a cancel, or a `failed` written
673
+ * elsewhere), so a retry can never overlap the run; `end` stops the watch
674
+ * when the run settles.
675
+ */
676
+ private cancelWatch;
677
+ /**
678
+ * A run the watch stopped because its row left `running`. A cancel keeps
679
+ * the row, and its event gains `stopped_run: true`; any other move (a row
680
+ * failed elsewhere) keeps what that writer wrote. Nothing else is written,
681
+ * as for a late result; the writer that moved the row settled its series.
682
+ */
683
+ private stoppedRun;
684
+ /**
685
+ * The retry funnel: every provider-call run that fails ends here. A
686
+ * one-off row whose failure class may retry, with retries left and a next
687
+ * start that fits before its deadline, goes back to `scheduled`
688
+ * (compare-and-set on `expected`, `running` by default) with an
689
+ * `attempt_failed` event: `notBefore` is the next start, the fallback time
690
+ * one minute later, the deadline unchanged, the estimate, the run-now mark
691
+ * and any batch id cleared. Anything else fails for good: `failed`, with
692
+ * `attempts` and `failure_class` on the event and `(after N attempts)` on
693
+ * the error when more than one ran. A job row always fails for good (the
694
+ * job sweep makes its retry row). The series rolls on a final failure
695
+ * only. Synchronous; an async caller then plans the next attempt's window
696
+ * ({@link planRetryWindow}).
697
+ */
698
+ private failRun;
699
+ /** {@link failRun} for a thrown error: its facts, and its run details (`steps`, `stopped_by`, `truncated`) for the event. */
700
+ private failRunWith;
701
+ /**
702
+ * After {@link failRun} queued another attempt: plan it at the cleanest
703
+ * hour between its earliest start and its deadline. Best effort: without
704
+ * a deadline, or when the forecast fails, the row keeps its fallback time
705
+ * and `replanSweep` plans it before a later tick.
706
+ */
707
+ private planRetryWindow;
708
+ /**
709
+ * The tick-lock rule for a `running` row, shared by the head of a locked
710
+ * tick and the job sweep: true when the run was dispatched under another
711
+ * locked tick whose process is gone, false when that tick is this one or
712
+ * its process still runs. Undefined when this scheduler holds no lock, the
713
+ * row's newest event (progress lines aside) is not a dispatch with tick
714
+ * details (no locked tick ran it, or the row moved on since), or the host
715
+ * cannot tell whether that tick's process runs: the run may be live.
716
+ */
717
+ deadTickRun(row: TaskRecord<unknown>): boolean | undefined;
718
+ /**
719
+ * The head of a locked tick, before any sweep claims a row: a one-off
720
+ * `running` row whose run a dead tick dispatched ({@link deadTickRun})
721
+ * fails as interrupted through the retry funnel (another attempt when the
722
+ * policy allows it), and a Batch row with its batch id goes back to
723
+ * `submitted` for the poll sweep. Compare-and-set from `running`. Job rows
724
+ * are the job sweep's; rows this scheduler holds are live. Returns the
725
+ * entries of the rows it failed or queued again.
726
+ */
727
+ private freeDeadTickRuns;
592
728
  /**
593
729
  * A forced stop of the tick (KTD12, batch 25 KTD4): settle every row this
594
730
  * scheduler moved to `running` in a tick whose dispatch has not settled,
595
731
  * by what the row was doing:
596
- * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`);
732
+ * - a provider call fails as interrupted (`JOB_INTERRUPTED_ERROR`)
733
+ * through the retry funnel: a one-off row with retries left is
734
+ * queued again, its window planned before a later tick;
597
735
  * - a Batch poll goes back to `submitted` with its `batchId`: the batch
598
736
  * is live at the provider, and the next tick polls it again;
599
737
  * - a Batch submit fails with `BATCH_SUBMIT_INTERRUPTED_ERROR`: the
@@ -602,8 +740,8 @@ export declare class Scheduler {
602
740
  * keeps its status; rows another process holds, or a crashed tick
603
741
  * stranded, are not touched (the job sweep frees job runs, and the next
604
742
  * 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.
743
+ * a process about to exit. Returns the ids it failed or queued again; a
744
+ * second call changes nothing.
607
745
  */
608
746
  failHeldRuns(): string[];
609
747
  /** Cancel and clean up timers. Mostly for tests. */
@@ -726,11 +864,17 @@ export declare function pickBestWindow(entries: GridForecastEntry[], deadline: D
726
864
  * errors raised *before* the request could reach the provider
727
865
  * (ECONNREFUSED / ENOTFOUND / EAI_AGAIN). Ambiguous mid-flight errors
728
866
  * (ETIMEDOUT, ECONNRESET) are NOT retried — the provider may already
729
- * have accepted and billed the call. Other 4xx bubble up immediately.
867
+ * have accepted and billed the call. Other 4xx bubble up immediately;
868
+ * a 408 or 425 then gets the task retry (`isPermanentStatus` in run-limits).
869
+ *
870
+ * This is the in-call resend for Tidegap: provider adapters construct
871
+ * their SDK clients with `maxRetries: 0` so vendor-side retries cannot
872
+ * multiply with this one. The task's retry policy (a later attempt) is a
873
+ * separate layer, in the scheduler's retry funnel.
730
874
  *
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.
875
+ * `signal` (the task's cancel watch) ends the waits: once it aborts, no
876
+ * further call is made, even when the adapter ignored the signal, and the
877
+ * last error is thrown.
734
878
  */
735
- export declare function retryWithBackoff<T>(fn: () => Promise<T>): Promise<T>;
879
+ export declare function retryWithBackoff<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T>;
736
880
  //# sourceMappingURL=scheduler.d.ts.map