@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
@@ -0,0 +1,572 @@
1
+ /**
2
+ * The run-limits registry: the one place that names each run limit and
3
+ * retry setting, its `~/.tidegap/config` keys, its per-runner defaults, the
4
+ * value grammar, the settings read and the precedence resolver; plus the
5
+ * failure classifier and the retry planner. Every surface parses and prints
6
+ * a run limit through this module and keeps no default of its own.
7
+ *
8
+ * Precedence for each setting, first match wins: the task's or job's own
9
+ * value (`task`), the per-runner setting `<KEY>_<RUNNER>`
10
+ * (`setting:<runner>`), the all-runners setting `<KEY>` (`setting`), the
11
+ * built-in default for the runner (`default`).
12
+ *
13
+ * `none` switches a time limit off; `0` is refused, so one character never
14
+ * means both "nothing" and "no limit". For retries `0` means no automatic
15
+ * retry, and a retry delay takes neither.
16
+ *
17
+ * Core stays environment-pure: the settings come from the config file only,
18
+ * read fresh by the host at each tick, request or tool call. The Python twin
19
+ * is packages/core-py/src/tidegap/run_limits.py; both pass
20
+ * test/fixtures/run-limits-vectors.json.
21
+ */
22
+ import { readFileSync } from "node:fs";
23
+ import { carbonBudgetConfigPath, parseKeyValues } from "./budget.js";
24
+ /** The caps marker of writers that store only the values a caller set. */
25
+ export const CAPS_VERSION = 2;
26
+ const SECOND_MS = 1000;
27
+ const MINUTE_MS = 60 * SECOND_MS;
28
+ const HOUR_MS = 60 * MINUTE_MS;
29
+ const DAY_MS = 24 * HOUR_MS;
30
+ const MIN_DURATION_MS = SECOND_MS;
31
+ const MAX_DURATION_MS = 7 * DAY_MS;
32
+ /** The most automatic retries a setting or a task can ask for. */
33
+ export const MAX_RETRIES = 10;
34
+ /** Every runner: retries and the retry delay apply to all of them. */
35
+ function everyRunner(value) {
36
+ return Object.freeze({ command: value, "claude-code": value, anthropic: value, openai: value, gemini: value, ollama: value });
37
+ }
38
+ export const RUN_LIMITS = Object.freeze([
39
+ Object.freeze({
40
+ name: "command_timeout",
41
+ kind: "time_limit",
42
+ key: "TIDEGAP_COMMAND_TIMEOUT",
43
+ cliName: "command-timeout",
44
+ capsKey: "commandTimeoutMs",
45
+ defaults: Object.freeze({ command: 30 * MINUTE_MS }),
46
+ perRunner: false,
47
+ legacyDefaultMs: 5 * MINUTE_MS,
48
+ }),
49
+ Object.freeze({
50
+ name: "llm_timeout",
51
+ kind: "time_limit",
52
+ key: "TIDEGAP_LLM_TIMEOUT",
53
+ cliName: "llm-timeout",
54
+ capsKey: "llmTimeoutMs",
55
+ defaults: Object.freeze({
56
+ "claude-code": 30 * MINUTE_MS,
57
+ anthropic: 10 * MINUTE_MS,
58
+ openai: 10 * MINUTE_MS,
59
+ gemini: 10 * MINUTE_MS,
60
+ ollama: 10 * MINUTE_MS,
61
+ }),
62
+ perRunner: true,
63
+ legacyDefaultMs: 10 * MINUTE_MS,
64
+ }),
65
+ Object.freeze({
66
+ name: "retries",
67
+ kind: "count",
68
+ key: "TIDEGAP_RETRIES",
69
+ cliName: "retries",
70
+ capsKey: "retries",
71
+ defaults: everyRunner(1),
72
+ perRunner: true,
73
+ }),
74
+ Object.freeze({
75
+ name: "retry_delay",
76
+ kind: "delay",
77
+ key: "TIDEGAP_RETRY_DELAY",
78
+ cliName: "retry-delay",
79
+ capsKey: "retryDelayMs",
80
+ defaults: everyRunner(30 * MINUTE_MS),
81
+ perRunner: true,
82
+ }),
83
+ ]);
84
+ /** The registry entry of `name`. */
85
+ export function runLimitDefinition(name) {
86
+ return RUN_LIMITS.find((d) => d.name === name);
87
+ }
88
+ /** A value the duration grammar refuses; the message is a fixed sentence. */
89
+ export class DurationError extends Error {
90
+ name = "DurationError";
91
+ }
92
+ export const DURATION_FORM_ERROR = "Use a duration from 1s to 7d, such as 90s, 30m, 1.5h or 2d, or none for no time limit.";
93
+ export const DURATION_ZERO_ERROR = "0 is not a time limit; use none for no time limit.";
94
+ export const DURATION_RANGE_ERROR = "A time limit must be from 1s to 7d; use none for no time limit.";
95
+ const UNIT_MS = { s: SECOND_MS, m: MINUTE_MS, min: MINUTE_MS, h: HOUR_MS, d: DAY_MS };
96
+ /**
97
+ * Parse a time limit: a number with an optional unit `s`, `m` (or `min`),
98
+ * `h` or `d`, case-insensitive, a bare number being seconds; from 1 second
99
+ * to 7 days; or `none`. Returns milliseconds or `"none"`; throws a
100
+ * {@link DurationError} with a fixed sentence that names `none`.
101
+ */
102
+ export function parseDuration(input) {
103
+ const text = input.trim().toLowerCase();
104
+ if (text === "none")
105
+ return "none";
106
+ const m = /^(\d+(?:\.\d+)?)\s*(s|m|min|h|d)?$/.exec(text);
107
+ if (!m)
108
+ throw new DurationError(DURATION_FORM_ERROR);
109
+ const n = Number(m[1]);
110
+ if (n === 0)
111
+ throw new DurationError(DURATION_ZERO_ERROR);
112
+ const ms = Math.round(n * UNIT_MS[m[2] ?? "s"]);
113
+ if (ms < MIN_DURATION_MS || ms > MAX_DURATION_MS)
114
+ throw new DurationError(DURATION_RANGE_ERROR);
115
+ return ms;
116
+ }
117
+ /** The canonical form of a time limit: the largest whole unit, else seconds; `none` as is. */
118
+ export function formatDuration(value) {
119
+ if (value === "none")
120
+ return "none";
121
+ if (value % DAY_MS === 0)
122
+ return `${value / DAY_MS}d`;
123
+ if (value % HOUR_MS === 0)
124
+ return `${value / HOUR_MS}h`;
125
+ if (value % MINUTE_MS === 0)
126
+ return `${value / MINUTE_MS}m`;
127
+ return `${value / SECOND_MS}s`;
128
+ }
129
+ export const RETRIES_ERROR = "Retries must be a whole number from 0 to 10; 0 turns automatic retries off.";
130
+ export const RETRY_DELAY_ERROR = "A retry delay must be a duration from 1s to 7d, such as 90s, 30m or 2h; 0 and none are refused.";
131
+ /** Parse a retry count: a whole number from 0 to 10. Throws a {@link DurationError} with {@link RETRIES_ERROR}. */
132
+ export function parseRetries(input) {
133
+ const text = input.trim();
134
+ if (!/^[0-9]+$/.test(text))
135
+ throw new DurationError(RETRIES_ERROR);
136
+ const n = Number(text);
137
+ if (n > MAX_RETRIES)
138
+ throw new DurationError(RETRIES_ERROR);
139
+ return n;
140
+ }
141
+ /** Parse a retry delay: the duration grammar without `none`. Throws a {@link DurationError} with {@link RETRY_DELAY_ERROR}. */
142
+ export function parseRetryDelay(input) {
143
+ let value;
144
+ try {
145
+ value = parseDuration(input);
146
+ }
147
+ catch {
148
+ throw new DurationError(RETRY_DELAY_ERROR);
149
+ }
150
+ if (value === "none")
151
+ throw new DurationError(RETRY_DELAY_ERROR);
152
+ return value;
153
+ }
154
+ /** Parse a value of setting `def` by its kind; throws a {@link DurationError} with the setting's sentence. */
155
+ export function parseRunLimitValue(def, input) {
156
+ if (def.kind === "count")
157
+ return parseRetries(input);
158
+ if (def.kind === "delay")
159
+ return parseRetryDelay(input);
160
+ return parseDuration(input);
161
+ }
162
+ /** A value of setting `def` as a person reads and writes it: `30m`, `none`, `2`. */
163
+ export function formatRunLimitValue(def, value) {
164
+ return def.kind === "count" ? String(value) : formatDuration(value);
165
+ }
166
+ /** The config-key suffix of a runner: `claude-code` → `CLAUDE_CODE`. */
167
+ function runnerSuffix(runner) {
168
+ return runner.toUpperCase().replace(/-/g, "_");
169
+ }
170
+ /** The reason a `<KEY>_<SUFFIX>` line is not read, or undefined when the suffix is a runner the limit takes. */
171
+ function suffixError(def, suffix) {
172
+ if (!def.perRunner)
173
+ return `${def.key} takes no runner suffix.`;
174
+ const runners = Object.keys(def.defaults);
175
+ if (runners.some((r) => runnerSuffix(r) === suffix))
176
+ return undefined;
177
+ const names = runners.map(runnerSuffix);
178
+ return `${def.key} takes a runner suffix of ${names.slice(0, -1).join(", ")} or ${names.at(-1)}.`;
179
+ }
180
+ /**
181
+ * The run-limit settings out of already-read KEY=VALUE pairs. Keys outside
182
+ * the registry are left alone; an empty value counts as unset; any other
183
+ * line under a run-limit key that cannot be used is listed in `ignored`.
184
+ */
185
+ export function runLimitSettingsFromValues(pairs) {
186
+ const values = {};
187
+ const ignored = [];
188
+ for (const [key, raw] of Object.entries(pairs)) {
189
+ const def = RUN_LIMITS.find((d) => key === d.key || key.startsWith(`${d.key}_`));
190
+ if (!def)
191
+ continue;
192
+ const value = raw.trim();
193
+ if (value === "")
194
+ continue;
195
+ const keyError = key === def.key ? undefined : suffixError(def, key.slice(def.key.length + 1));
196
+ if (keyError) {
197
+ ignored.push({ key, value, reason: keyError });
198
+ continue;
199
+ }
200
+ try {
201
+ values[key] = parseRunLimitValue(def, value);
202
+ }
203
+ catch (err) {
204
+ ignored.push({ key, value, reason: err.message });
205
+ }
206
+ }
207
+ return { values, ignored };
208
+ }
209
+ const reportedLines = new Set();
210
+ /**
211
+ * Read the run-limit settings from `~/.tidegap/config` (or `opts.path`). A
212
+ * missing or unreadable file gives no settings and never throws. Each
213
+ * ignored line is reported on stderr once per process.
214
+ */
215
+ export function loadRunLimitSettings(opts = {}) {
216
+ let contents;
217
+ try {
218
+ contents = readFileSync(opts.path ?? carbonBudgetConfigPath(), "utf8");
219
+ }
220
+ catch {
221
+ return { values: {}, ignored: [] };
222
+ }
223
+ const settings = runLimitSettingsFromValues(parseKeyValues(contents));
224
+ for (const line of settings.ignored) {
225
+ const id = `${line.key}=${line.value}`;
226
+ if (reportedLines.has(id))
227
+ continue;
228
+ reportedLines.add(id);
229
+ console.warn(`tidegap: ~/.tidegap/config: ${line.key} ignored: ${line.reason}`);
230
+ }
231
+ return settings;
232
+ }
233
+ /** A stored per-task value, or undefined when it is unset or not a valid value of the setting. */
234
+ function taskValue(def, caps) {
235
+ const stored = caps[def.capsKey];
236
+ if (def.kind === "count")
237
+ return isRetryCount(stored) ? stored : undefined;
238
+ if (stored === "none")
239
+ return def.kind === "time_limit" ? "none" : undefined;
240
+ if (typeof stored !== "number" || !Number.isFinite(stored) || stored <= 0)
241
+ return undefined;
242
+ const versioned = typeof caps.capsVersion === "number" && caps.capsVersion >= CAPS_VERSION;
243
+ if (!versioned && stored === def.legacyDefaultMs)
244
+ return undefined;
245
+ return stored;
246
+ }
247
+ /** A whole number from 0 to {@link MAX_RETRIES}. */
248
+ function isRetryCount(value) {
249
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_RETRIES;
250
+ }
251
+ /** One limit for `runner`: the first of the task's value, the per-runner setting, the all-runners setting and `fallback`. */
252
+ function resolveRunLimit(def, caps, settings, runner, fallback) {
253
+ const own = caps ? taskValue(def, caps) : undefined;
254
+ if (own !== undefined)
255
+ return { value: own, source: "task" };
256
+ const perRunner = def.perRunner ? settings.values[`${def.key}_${runnerSuffix(runner)}`] : undefined;
257
+ if (perRunner !== undefined)
258
+ return { value: perRunner, source: `setting:${runner}` };
259
+ const all = settings.values[def.key];
260
+ if (all !== undefined)
261
+ return { value: all, source: "setting" };
262
+ return { value: fallback, source: "default" };
263
+ }
264
+ /**
265
+ * Each limit that applies to `runner`, with its value and source. `caps` is
266
+ * the row's spec caps or the job's caps as stored; only the keys the caller
267
+ * set count, and on caps without `capsVersion: 2` a value equal to the old
268
+ * stored default counts as unset.
269
+ */
270
+ export function resolveRunLimits(caps, settings, runner) {
271
+ const out = {};
272
+ for (const def of RUN_LIMITS) {
273
+ const fallback = def.defaults[runner];
274
+ if (fallback !== undefined)
275
+ out[def.name] = resolveRunLimit(def, caps, settings, runner, fallback);
276
+ }
277
+ return out;
278
+ }
279
+ /**
280
+ * The limits of one run: a model call's for its runner; a command's for
281
+ * the `command` runner, plus, when it has a summarize step, that step's LLM
282
+ * limit for the summarize provider. `spec` is the row's body or a job
283
+ * occurrence's.
284
+ */
285
+ export function resolveTaskRunLimits(spec, settings) {
286
+ const out = resolveRunLimits(spec.caps, settings, spec.provider);
287
+ if (spec.provider === "command" && spec.summarize) {
288
+ const step = resolveRunLimits(spec.caps, settings, spec.summarize.provider).llm_timeout;
289
+ if (step)
290
+ out.llm_timeout = step;
291
+ }
292
+ return out;
293
+ }
294
+ /** An effective time limit as a person reads it: `30m (default)`, `none (setting:claude-code)`. */
295
+ export function describeRunLimit(limit) {
296
+ return `${formatDuration(limit.value)} (${limit.source})`;
297
+ }
298
+ /**
299
+ * The fixed sentence a writer refuses a stored time limit with, or
300
+ * undefined for a valid one: milliseconds from 1 second to 7 days, or
301
+ * `"none"`.
302
+ */
303
+ export function timeLimitError(value) {
304
+ if (value === "none")
305
+ return undefined;
306
+ if (typeof value !== "number" || !Number.isFinite(value))
307
+ return DURATION_FORM_ERROR;
308
+ if (value === 0)
309
+ return DURATION_ZERO_ERROR;
310
+ if (value < MIN_DURATION_MS || value > MAX_DURATION_MS)
311
+ return DURATION_RANGE_ERROR;
312
+ return undefined;
313
+ }
314
+ /** The fixed sentence a writer refuses a stored retry delay with, or undefined: milliseconds from 1 second to 7 days. */
315
+ function retryDelayError(value) {
316
+ if (typeof value !== "number" || !Number.isFinite(value) || value < MIN_DURATION_MS || value > MAX_DURATION_MS)
317
+ return RETRY_DELAY_ERROR;
318
+ return undefined;
319
+ }
320
+ /**
321
+ * True for a caps key that holds a run-limit setting (`commandTimeoutMs`,
322
+ * `llmTimeoutMs`, `retries`, `retryDelayMs`): a writer drops it on `null`,
323
+ * so the setting or the default applies at each run.
324
+ */
325
+ export function isRunLimitCap(key) {
326
+ return RUN_LIMITS.some((d) => d.capsKey === key);
327
+ }
328
+ /**
329
+ * The fixed sentence a writer refuses a stored run-limit setting with
330
+ * (caps key `commandTimeoutMs`, `llmTimeoutMs`, `retries` or
331
+ * `retryDelayMs`), or undefined for a valid value or another key: a time
332
+ * limit per {@link timeLimitError}, retries a whole number from 0 to 10, a
333
+ * retry delay from 1 second to 7 days.
334
+ */
335
+ export function runLimitValueError(key, value) {
336
+ const def = RUN_LIMITS.find((d) => d.capsKey === key);
337
+ if (!def)
338
+ return undefined;
339
+ if (def.kind === "count")
340
+ return isRetryCount(value) ? undefined : RETRIES_ERROR;
341
+ return def.kind === "delay" ? retryDelayError(value) : timeLimitError(value);
342
+ }
343
+ /** Why a writer refuses a cap value, or undefined: a run-limit setting per {@link runLimitValueError}, any other cap a positive number. */
344
+ export function capValueError(key, value) {
345
+ if (isRunLimitCap(key)) {
346
+ const error = runLimitValueError(key, value);
347
+ return error ? `cap ${key}: ${error}` : undefined;
348
+ }
349
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? undefined : `cap ${key} must be a positive number`;
350
+ }
351
+ /**
352
+ * Caps as a writer stores them from now on: on caps without `capsVersion`,
353
+ * a time limit equal to the old stored default is dropped (it counted as
354
+ * unset), then `capsVersion: 2` is added, so each time limit left is one a
355
+ * caller set.
356
+ */
357
+ export function versionedCaps(caps) {
358
+ const out = { ...caps };
359
+ const versioned = typeof out.capsVersion === "number" && out.capsVersion >= CAPS_VERSION;
360
+ if (!versioned) {
361
+ for (const def of RUN_LIMITS)
362
+ if (def.legacyDefaultMs !== undefined && out[def.capsKey] === def.legacyDefaultMs)
363
+ delete out[def.capsKey];
364
+ }
365
+ out.capsVersion = CAPS_VERSION;
366
+ return out;
367
+ }
368
+ /** A time limit as event details and HTTP JSON carry it: seconds, or `"none"`. */
369
+ export function durationSeconds(value) {
370
+ return value === "none" ? "none" : value / SECOND_MS;
371
+ }
372
+ export function runLimitsDetails(limits) {
373
+ const out = {};
374
+ for (const def of RUN_LIMITS) {
375
+ const limit = limits[def.name];
376
+ if (!limit)
377
+ continue;
378
+ out[def.name] =
379
+ def.kind === "count" ? { value: limit.value, source: limit.source } : { value_s: durationSeconds(limit.value), source: limit.source };
380
+ }
381
+ return out;
382
+ }
383
+ /** A detail's value back in the registry's unit (ms, a count or `"none"`), or undefined when it is not valid. */
384
+ function detailValue(def, entry) {
385
+ if (def.kind === "count")
386
+ return isRetryCount(entry.value) ? entry.value : undefined;
387
+ const s = entry.value_s;
388
+ if (s === "none")
389
+ return def.kind === "time_limit" ? "none" : undefined;
390
+ return typeof s === "number" && Number.isFinite(s) && s > 0 ? s * SECOND_MS : undefined;
391
+ }
392
+ /** The limits a `dispatched` event's details record, or undefined when it records none (a run from before they were recorded). */
393
+ export function runLimitsFromDetails(details) {
394
+ const limits = details?.limits;
395
+ if (!limits || typeof limits !== "object")
396
+ return undefined;
397
+ const out = {};
398
+ for (const def of RUN_LIMITS) {
399
+ const entry = limits[def.name];
400
+ if (!entry || typeof entry.source !== "string")
401
+ continue;
402
+ const value = detailValue(def, entry);
403
+ if (value !== undefined)
404
+ out[def.name] = { value, source: entry.source };
405
+ }
406
+ return Object.keys(out).length > 0 ? out : undefined;
407
+ }
408
+ /**
409
+ * The limits of a task: the ones its newest `dispatched` event recorded,
410
+ * or, before a run recorded them, the ones a run that starts now gets.
411
+ * `events` are the task's events, oldest first.
412
+ */
413
+ export function taskRunLimitsView(bodyJson, events, settings) {
414
+ for (let i = events.length - 1; i >= 0; i--) {
415
+ if (events[i].kind !== "dispatched")
416
+ continue;
417
+ const recorded = runLimitsFromDetails(events[i].details);
418
+ if (recorded)
419
+ return { limits: runLimitsDetails(recorded), from: "dispatch" };
420
+ break;
421
+ }
422
+ let spec;
423
+ try {
424
+ spec = JSON.parse(bodyJson ?? "null");
425
+ }
426
+ catch {
427
+ spec = undefined;
428
+ }
429
+ const provider = spec?.provider;
430
+ if (typeof provider !== "string")
431
+ return { limits: {}, from: "now" };
432
+ return { limits: runLimitsDetails(resolveTaskRunLimits(spec, settings)), from: "now" };
433
+ }
434
+ /** `command 30m (default), LLM 10m (setting)`: each time limit of a view, or undefined when it has none. */
435
+ export function runLimitsText(limits) {
436
+ const label = { command_timeout: "command", llm_timeout: "LLM" };
437
+ const parts = RUN_LIMITS.flatMap((def) => {
438
+ const l = limits[def.name];
439
+ const value = l && def.kind === "time_limit" ? detailValue(def, l) : undefined;
440
+ return value !== undefined ? [`${label[def.name]} ${formatDuration(value)} (${l.source})`] : [];
441
+ });
442
+ return parts.length > 0 ? parts.join(", ") : undefined;
443
+ }
444
+ /** `1 after 30m (default)`: the retry policy of a view, or undefined when it has none. The delay's source is named when it differs. */
445
+ export function retryPolicyText(limits) {
446
+ const retries = limits.retries;
447
+ const delay = limits.retry_delay;
448
+ const count = retries ? detailValue(runLimitDefinition("retries"), retries) : undefined;
449
+ const wait = delay ? detailValue(runLimitDefinition("retry_delay"), delay) : undefined;
450
+ if (typeof count !== "number" || wait === undefined)
451
+ return undefined;
452
+ const sources = retries.source === delay.source ? `(${retries.source})` : `(${retries.source}; delay ${delay.source})`;
453
+ if (count === 0)
454
+ return `0, no automatic retry ${sources}`;
455
+ return `${count} after ${formatDuration(wait)}${count > 1 ? ", doubling" : ""} ${sources}`;
456
+ }
457
+ export const FAILURE_CLASSES = [
458
+ "timeout",
459
+ "exit",
460
+ "transient",
461
+ "interrupted",
462
+ "permanent",
463
+ "after_command",
464
+ "batch_submit_interrupted",
465
+ ];
466
+ const RETRYABLE = new Set(["timeout", "exit", "transient", "interrupted"]);
467
+ /** True for a class whose failure may retry. */
468
+ export function isRetryableFailure(cls) {
469
+ return RETRYABLE.has(cls);
470
+ }
471
+ /**
472
+ * The facts of a thrown error: its HTTP status (`status` or `statusCode`),
473
+ * the adapter's `permanent`, `exit` and `interrupted` marks, and the `steps`
474
+ * and `stopped_by` of its run details.
475
+ */
476
+ export function failureFactsOf(err) {
477
+ if (!err || typeof err !== "object")
478
+ return {};
479
+ const e = err;
480
+ const status = typeof e.status === "number" ? e.status : typeof e.statusCode === "number" ? e.statusCode : undefined;
481
+ const steps = Array.isArray(e.details?.steps) ? e.details.steps.filter((s) => typeof s === "string") : undefined;
482
+ const stoppedBy = typeof e.details?.stopped_by === "string" ? e.details.stopped_by : undefined;
483
+ return {
484
+ ...(status !== undefined ? { status } : {}),
485
+ ...(e.permanent === true ? { permanent: true } : {}),
486
+ ...(e.exit === true ? { exit: true } : {}),
487
+ ...(steps ? { steps } : {}),
488
+ ...(stoppedBy ? { stopped_by: stoppedBy } : {}),
489
+ ...(e.interrupted === "run" || e.interrupted === "batch_submit" ? { interrupted: e.interrupted } : {}),
490
+ };
491
+ }
492
+ /**
493
+ * True for an HTTP status a retry of the task cannot fix: a 4xx other than
494
+ * 408 (the server stopped waiting), 425 (the server asks for the request
495
+ * again) and 429 (rate limit). Every other status may retry.
496
+ */
497
+ export function isPermanentStatus(status) {
498
+ return status >= 400 && status < 500 && status !== 408 && status !== 425 && status !== 429;
499
+ }
500
+ /** The class of a failure; an unmarked unknown error is `transient`: one more attempt costs less than a lost task. */
501
+ export function classifyFailure(facts) {
502
+ if (facts.interrupted === "batch_submit")
503
+ return "batch_submit_interrupted";
504
+ if (facts.steps?.includes("prompt"))
505
+ return "after_command";
506
+ if (facts.interrupted === "run")
507
+ return "interrupted";
508
+ if (facts.permanent === true || facts.stopped_by === "budget")
509
+ return "permanent";
510
+ if (facts.stopped_by === "command_timeout" || facts.stopped_by === "llm_timeout")
511
+ return "timeout";
512
+ const status = facts.status;
513
+ if (typeof status === "number" && isPermanentStatus(status))
514
+ return "permanent";
515
+ if (facts.exit === true || facts.steps?.includes("command"))
516
+ return "exit";
517
+ return "transient";
518
+ }
519
+ /** The retry policy of resolved limits: retries and the first delay in ms (the registry gives every runner both). */
520
+ export function retryPolicyOf(limits) {
521
+ return { retries: limits.retries.value, delayMs: limits.retry_delay.value };
522
+ }
523
+ /** The sentence a final failure's error ends with, for a reason that has one. */
524
+ export const NO_TIME_LEFT_TEXT = "no time left before the deadline for a retry";
525
+ /**
526
+ * The next attempt after attempt `attempt` (1-based) failed at `failedAt`:
527
+ * retry k waits `delayMs × 2^(k−1)`, a later `notBefore` wins, and the start
528
+ * must not pass `deadline`. All times in ms since the epoch; no deadline
529
+ * means no bound.
530
+ */
531
+ export function planRetry(input) {
532
+ if (input.attempt > input.retries)
533
+ return { final: "no_retries_left" };
534
+ const retryAt = Math.max(input.failedAt + input.delayMs * 2 ** (input.attempt - 1), input.notBefore ?? 0);
535
+ if (input.deadline !== undefined && retryAt > input.deadline)
536
+ return { final: "no_time_left" };
537
+ return { retryAt };
538
+ }
539
+ /**
540
+ * The number of the attempt a run of a task is: one plus the
541
+ * `attempt_failed` events since the newest `created` event or manual retry
542
+ * (a `rescheduled` event with reason `retry`). `events` are oldest first.
543
+ */
544
+ export function attemptNumber(events) {
545
+ let failed = 0;
546
+ for (let i = events.length - 1; i >= 0; i--) {
547
+ const e = events[i];
548
+ if (e.kind === "created")
549
+ break;
550
+ if (e.kind === "rescheduled" && e.details?.reason === "retry")
551
+ break;
552
+ if (e.kind === "attempt_failed")
553
+ failed++;
554
+ }
555
+ return failed + 1;
556
+ }
557
+ /** The error a final failure stores: the run's error, then the attempt count when more than one ran, then the no-time reason. */
558
+ export function finalFailureError(error, attempts, reason) {
559
+ const counted = attempts > 1 ? ` (after ${attempts} attempts)` : "";
560
+ return `${error}${counted}${reason === "no_time_left" ? ` (${NO_TIME_LEFT_TEXT})` : ""}`;
561
+ }
562
+ /**
563
+ * The notice for a task's own LLM time limit that a Batch API run does not
564
+ * apply: the provider owns a Batch run's hour and its 24-hour window, so the
565
+ * limit is kept for a regular call and ignored for a Batch one.
566
+ */
567
+ export const BATCH_LLM_TIMEOUT_NOTE = "not applied if the task runs through the provider Batch API (a deadline over 24 h away); a Batch run has no time limit";
568
+ /** True when a task of `provider` with this deadline may go to a provider Batch API, where no LLM time limit applies. */
569
+ export function mayRunAsBatch(provider, deadlineMs, nowMs) {
570
+ return (provider === "anthropic" || provider === "openai") && deadlineMs - nowMs > 24 * HOUR_MS;
571
+ }
572
+ //# sourceMappingURL=run-limits.js.map
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Where a `claude-code` task ran: in a copy (fork) of the Claude Code
3
+ * session that queued it, or in a fresh session, and why. The adapter in
4
+ * the `tidegap` CLI decides; the scheduler copies the result onto the
5
+ * receipt, and every surface words it with the helpers below.
6
+ */
7
+ import type { ProviderCallOrigin, TaskRecord } from "./types.js";
8
+ /** `fork`: a copy of the origin session. `fresh`: a new session with no history. */
9
+ export type RunSessionMode = "fork" | "fresh";
10
+ /** Why a task with (or without) an origin ran fresh. */
11
+ export type FreshReason = "disabled" | "no-origin" | "api-provider" | "web-tools" | "cwd-missing" | "cwd-unsafe" | "session-missing" | "too-large" | "other-cwd";
12
+ /** The session facts of one run, on `DispatchResult.session` and `CarbonReceipt.session`. */
13
+ export interface RunSession {
14
+ mode: RunSessionMode;
15
+ /** The session that ran: the fork's id, or the fresh session's id. */
16
+ sessionId?: string;
17
+ /** The session the task came from, when it had one. */
18
+ originSessionId?: string;
19
+ /** Why the run was fresh. Absent for a fork. */
20
+ reason?: FreshReason;
21
+ /** The context estimate of the origin session, when one was made. */
22
+ contextTokens?: number;
23
+ }
24
+ /** The first 8 characters of a session id, for display. */
25
+ export declare function shortSessionId(id: string): string;
26
+ /** `about 620k tokens`. */
27
+ export declare function tokensLabel(tokens: number): string;
28
+ /** A fresh-run reason in words: `session too large`, `web tools`, ... */
29
+ export declare function freshReasonText(reason: FreshReason): string;
30
+ /** The origin facts of a task's spec (`ProviderCallSpec.origin`), or undefined. */
31
+ export declare function taskOrigin(record: Pick<TaskRecord<unknown>, "bodyJson">): ProviderCallOrigin | undefined;
32
+ /** The command that opens the fork a task ran in (`cd <dir> && claude --resume <fork id>`), or undefined. */
33
+ export declare function forkCommand(record: Pick<TaskRecord<unknown>, "originCwd" | "receipt">): string | undefined;
34
+ /** `fork f1a2b3c4 of 11111111` or `fresh (too-large, about 620k tokens)`. */
35
+ export declare function runSessionSummary(session: RunSession): string;
36
+ //# sourceMappingURL=run-session.d.ts.map
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Where a `claude-code` task ran: in a copy (fork) of the Claude Code
3
+ * session that queued it, or in a fresh session, and why. The adapter in
4
+ * the `tidegap` CLI decides; the scheduler copies the result onto the
5
+ * receipt, and every surface words it with the helpers below.
6
+ */
7
+ import { resumeCommand } from "./history.js";
8
+ /** The first 8 characters of a session id, for display. */
9
+ export function shortSessionId(id) {
10
+ return id.slice(0, 8);
11
+ }
12
+ /** `about 620k tokens`. */
13
+ export function tokensLabel(tokens) {
14
+ if (tokens >= 1000)
15
+ return `about ${Math.round(tokens / 1000)}k tokens`;
16
+ return `about ${tokens} tokens`;
17
+ }
18
+ /** A fresh-run reason in words: `session too large`, `web tools`, ... */
19
+ export function freshReasonText(reason) {
20
+ switch (reason) {
21
+ case "disabled":
22
+ return "session resume is off (TIDEGAP_RESUME=off)";
23
+ case "no-origin":
24
+ return "no session found";
25
+ case "api-provider":
26
+ return "the API provider has no session";
27
+ case "web-tools":
28
+ return "web tools";
29
+ case "cwd-missing":
30
+ return "the session directory is gone";
31
+ case "cwd-unsafe":
32
+ return "the session directory is the root or home directory, or not yours";
33
+ case "session-missing":
34
+ return "the session transcript is gone";
35
+ case "too-large":
36
+ return "session too large";
37
+ case "other-cwd":
38
+ return "the task names another folder";
39
+ }
40
+ }
41
+ /** The origin facts of a task's spec (`ProviderCallSpec.origin`), or undefined. */
42
+ export function taskOrigin(record) {
43
+ if (!record.bodyJson)
44
+ return undefined;
45
+ try {
46
+ const origin = JSON.parse(record.bodyJson).origin;
47
+ if (!origin || typeof origin !== "object")
48
+ return undefined;
49
+ const agent = origin.agent;
50
+ return agent === "claude-code" || agent === "codex" ? origin : undefined;
51
+ }
52
+ catch {
53
+ return undefined;
54
+ }
55
+ }
56
+ /** The command that opens the fork a task ran in (`cd <dir> && claude --resume <fork id>`), or undefined. */
57
+ export function forkCommand(record) {
58
+ const session = record.receipt?.session;
59
+ if (session?.mode !== "fork" || !session.sessionId)
60
+ return undefined;
61
+ return resumeCommand({ originCwd: record.originCwd, originSessionId: session.sessionId });
62
+ }
63
+ /** `fork f1a2b3c4 of 11111111` or `fresh (too-large, about 620k tokens)`. */
64
+ export function runSessionSummary(session) {
65
+ if (session.mode === "fork") {
66
+ const fork = session.sessionId ? shortSessionId(session.sessionId) : "?";
67
+ return session.originSessionId ? `fork ${fork} of ${shortSessionId(session.originSessionId)}` : `fork ${fork}`;
68
+ }
69
+ const parts = [session.reason, session.contextTokens !== undefined ? tokensLabel(session.contextTokens) : undefined].filter(Boolean);
70
+ return parts.length > 0 ? `fresh (${parts.join(", ")})` : "fresh";
71
+ }
72
+ //# sourceMappingURL=run-session.js.map