@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.
- package/dist/channels/digest.js +3 -3
- package/dist/channels/format.d.ts +11 -0
- package/dist/channels/format.js +26 -8
- package/dist/energy.d.ts +7 -0
- package/dist/energy.js +7 -0
- package/dist/handoff.d.ts +22 -3
- package/dist/handoff.js +69 -17
- package/dist/history.d.ts +15 -0
- package/dist/history.js +11 -0
- package/dist/index.d.ts +17 -13
- package/dist/index.js +12 -10
- package/dist/jobs.d.ts +25 -15
- package/dist/jobs.js +186 -63
- package/dist/notify.d.ts +9 -0
- package/dist/notify.js +17 -3
- package/dist/providers/anthropic.js +8 -6
- package/dist/providers/base.d.ts +40 -9
- package/dist/providers/base.js +29 -4
- package/dist/providers/gemini.d.ts +3 -0
- package/dist/providers/gemini.js +9 -6
- package/dist/providers/http.d.ts +40 -0
- package/dist/providers/http.js +82 -0
- package/dist/providers/index.d.ts +1 -1
- package/dist/providers/index.js +1 -1
- package/dist/providers/ollama.d.ts +3 -0
- package/dist/providers/ollama.js +8 -5
- package/dist/providers/openai.js +7 -5
- package/dist/providers/timeout.d.ts +26 -8
- package/dist/providers/timeout.js +53 -15
- package/dist/readiness.d.ts +39 -3
- package/dist/readiness.js +73 -1
- package/dist/run-limits.d.ts +268 -0
- package/dist/run-limits.js +572 -0
- package/dist/schedule-job.d.ts +23 -0
- package/dist/schedule-job.js +48 -0
- package/dist/scheduler.d.ts +159 -17
- package/dist/scheduler.js +482 -128
- package/dist/storage/sqlite.d.ts +28 -2
- package/dist/storage/sqlite.js +65 -5
- package/dist/task-events.d.ts +19 -4
- package/dist/task-events.js +42 -5
- package/dist/tool-surface.js +38 -7
- package/dist/types.d.ts +31 -10
- package/dist/types.js +1 -3
- package/package.json +5 -2
|
@@ -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
|
package/dist/schedule-job.d.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* argument is refused with the CLI command the user runs instead.
|
|
10
10
|
*/
|
|
11
11
|
import { type JobInput } from "./jobs.js";
|
|
12
|
+
import { type DurationValue } from "./run-limits.js";
|
|
12
13
|
import type { Scheduler } from "./scheduler.js";
|
|
13
14
|
import type { JobRecord, JobTools, ProviderName } from "./types.js";
|
|
14
15
|
/** The `repeat` values that create a job. */
|
|
@@ -60,8 +61,30 @@ export interface ScheduleJobArgs {
|
|
|
60
61
|
tools: JobTools;
|
|
61
62
|
/** The project directory a run starts in; never a session to fork (KD8). */
|
|
62
63
|
cwd?: string;
|
|
64
|
+
/** The job's own LLM time limit (`llm_timeout`), in ms or `"none"`; unset follows the settings. */
|
|
65
|
+
llmTimeoutMs?: DurationValue;
|
|
66
|
+
/** The job's own retries per slot and retry delay in ms (`retries`, `retry_delay`); unset follows the settings. */
|
|
67
|
+
retries?: number;
|
|
68
|
+
retryDelayMs?: number;
|
|
63
69
|
host: "mcp" | "openclaw";
|
|
64
70
|
}
|
|
71
|
+
/**
|
|
72
|
+
* The `llm_timeout` tool argument in ms or `"none"`, or undefined when it
|
|
73
|
+
* is absent. Throws an Error whose message names the grammar and `none`.
|
|
74
|
+
*/
|
|
75
|
+
export declare function llmTimeoutArg(value: unknown): DurationValue | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* The `retries` and `retry_delay` tool arguments as caps (`retries`,
|
|
78
|
+
* `retryDelayMs`), each only when given. Throws an Error whose message names
|
|
79
|
+
* the parameter and its rule.
|
|
80
|
+
*/
|
|
81
|
+
export declare function retryCapsArgs(args: {
|
|
82
|
+
retries?: unknown;
|
|
83
|
+
retry_delay?: unknown;
|
|
84
|
+
}): {
|
|
85
|
+
retries?: number;
|
|
86
|
+
retryDelayMs?: number;
|
|
87
|
+
};
|
|
65
88
|
/**
|
|
66
89
|
* The {@link JobInput} for a `schedule_task` job call. Throws an Error with
|
|
67
90
|
* a plain message on a bad cadence, window or zone.
|
package/dist/schedule-job.js
CHANGED
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
import { includesFileTool, includesWebTool } from "./claude-tools.js";
|
|
12
12
|
import { guaranteeText, parseWindow, validateJobSchedule } from "./job-cadence.js";
|
|
13
13
|
import { getJob, removeJob } from "./jobs.js";
|
|
14
|
+
import { DURATION_FORM_ERROR, parseDuration, parseRetryDelay, RETRY_DELAY_ERROR, runLimitValueError, } from "./run-limits.js";
|
|
14
15
|
import { systemTimeZone } from "./zone-time.js";
|
|
15
16
|
/** The `repeat` values that create a job. */
|
|
16
17
|
export const JOB_REPEATS = ["daily", "weekdays", "weekly", "every_n_hours"];
|
|
@@ -109,6 +110,47 @@ export function jobToolsFor(tools) {
|
|
|
109
110
|
return "web";
|
|
110
111
|
return "none";
|
|
111
112
|
}
|
|
113
|
+
/**
|
|
114
|
+
* The `llm_timeout` tool argument in ms or `"none"`, or undefined when it
|
|
115
|
+
* is absent. Throws an Error whose message names the grammar and `none`.
|
|
116
|
+
*/
|
|
117
|
+
export function llmTimeoutArg(value) {
|
|
118
|
+
if (value === undefined)
|
|
119
|
+
return undefined;
|
|
120
|
+
if (typeof value !== "string")
|
|
121
|
+
throw new Error(`llm_timeout: ${DURATION_FORM_ERROR}`);
|
|
122
|
+
try {
|
|
123
|
+
return parseDuration(value);
|
|
124
|
+
}
|
|
125
|
+
catch (err) {
|
|
126
|
+
throw new Error(`llm_timeout: ${err.message}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* The `retries` and `retry_delay` tool arguments as caps (`retries`,
|
|
131
|
+
* `retryDelayMs`), each only when given. Throws an Error whose message names
|
|
132
|
+
* the parameter and its rule.
|
|
133
|
+
*/
|
|
134
|
+
export function retryCapsArgs(args) {
|
|
135
|
+
const out = {};
|
|
136
|
+
if (args.retries !== undefined) {
|
|
137
|
+
const error = runLimitValueError("retries", args.retries);
|
|
138
|
+
if (error)
|
|
139
|
+
throw new Error(`retries: ${error}`);
|
|
140
|
+
out.retries = args.retries;
|
|
141
|
+
}
|
|
142
|
+
if (args.retry_delay !== undefined) {
|
|
143
|
+
if (typeof args.retry_delay !== "string")
|
|
144
|
+
throw new Error(`retry_delay: ${RETRY_DELAY_ERROR}`);
|
|
145
|
+
try {
|
|
146
|
+
out.retryDelayMs = parseRetryDelay(args.retry_delay);
|
|
147
|
+
}
|
|
148
|
+
catch (err) {
|
|
149
|
+
throw new Error(`retry_delay: ${err.message}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
112
154
|
/** Today's weekday in `timeZone` (a `weekly` job with no days, KTD16). */
|
|
113
155
|
function weekdayIn(timeZone, now) {
|
|
114
156
|
return new Intl.DateTimeFormat("en-US", { weekday: "short", timeZone }).format(now).toLowerCase().slice(0, 3);
|
|
@@ -142,6 +184,11 @@ export function scheduleJobInput(args, now = new Date()) {
|
|
|
142
184
|
const cadence = cadenceOf(args, timeZone, now);
|
|
143
185
|
const window = args.window !== undefined ? parseWindow(args.window) : undefined;
|
|
144
186
|
const schedule = validateJobSchedule({ cadence, window, timeZone });
|
|
187
|
+
const caps = {
|
|
188
|
+
...(args.llmTimeoutMs !== undefined ? { llmTimeoutMs: args.llmTimeoutMs } : {}),
|
|
189
|
+
...(args.retries !== undefined ? { retries: args.retries } : {}),
|
|
190
|
+
...(args.retryDelayMs !== undefined ? { retryDelayMs: args.retryDelayMs } : {}),
|
|
191
|
+
};
|
|
145
192
|
return {
|
|
146
193
|
title: args.title?.trim() ? args.title : args.prompt,
|
|
147
194
|
cadence: schedule.cadence,
|
|
@@ -157,6 +204,7 @@ export function scheduleJobInput(args, now = new Date()) {
|
|
|
157
204
|
},
|
|
158
205
|
originHost: args.host,
|
|
159
206
|
originCwd: args.cwd,
|
|
207
|
+
...(caps && Object.keys(caps).length > 0 ? { caps } : {}),
|
|
160
208
|
...(args.deadline !== undefined ? { deadline: args.deadline } : {}),
|
|
161
209
|
};
|
|
162
210
|
}
|