neurastream 0.2.65 → 0.2.67

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.
@@ -0,0 +1,327 @@
1
+ // `neurastream setup [--yes]` (plan 20261028_2356 P4): the guided first run. It shows what this
2
+ // machine has (src/core/setup-detect.ts), lays out the home (initHome), asks in groups, writes each
3
+ // group's answers through the one config editor (src/core/config-edit.ts), then runs the adapter
4
+ // install and doctor. Every answer is proven to load before it is kept; --yes takes the proposals
5
+ // without asking. SetupDeps carries the terminal, the seams, and the install/doctor runs, so tests
6
+ // drive the whole flow without a real terminal, systemctl or Tailscale.
7
+
8
+ import { readFileSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { getAdapter, harnessBins } from "../adapters/index.ts";
11
+ import { TEMPLATE_PATH, configFile } from "../core/config.ts";
12
+ import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../core/config-edit.ts";
13
+ import { pagesDoctor } from "../core/pages-doctor.ts";
14
+ import { detect, realSeams, type SetupFacts, type SetupSeams } from "../core/setup-detect.ts";
15
+ import { invalidSlugs } from "../core/subagents.ts";
16
+ import { TAILSCALE_MISSING, TAILSCALE_STOPPED } from "../core/ui-setup.ts";
17
+ import { askLine, initHome } from "./init.ts";
18
+
19
+ export interface SetupDeps {
20
+ home: string;
21
+ env: NodeJS.ProcessEnv;
22
+ invoked: string;
23
+ terminal: boolean;
24
+ ask: (question: string) => string;
25
+ seams: SetupSeams;
26
+ install: () => number;
27
+ doctor: () => number;
28
+ say: (line: string) => void;
29
+ // `neurastream notify test`, injected by dispatch (setup.ts does not import dispatch.ts).
30
+ notifyTest: () => Promise<number>;
31
+ }
32
+
33
+ /** The production deps: the real home, terminal, PATH, Tailscale, adapter install and doctor. */
34
+ export function realSetupDeps(notifyTest: () => Promise<number>): SetupDeps {
35
+ const home = homedir();
36
+ return {
37
+ home,
38
+ env: process.env,
39
+ invoked: process.argv[1] ?? "",
40
+ terminal: process.stdin.isTTY === true,
41
+ ask: askLine,
42
+ seams: realSeams(harnessBins(), home, process.env),
43
+ install: () => getAdapter().install(["install", getAdapter().name]),
44
+ doctor: () => {
45
+ for (const warning of pagesDoctor(home)) console.warn(`warning: ${warning}`);
46
+ return getAdapter().doctor();
47
+ },
48
+ say: (line) => console.log(line),
49
+ notifyTest,
50
+ };
51
+ }
52
+
53
+ // Trailing `# comment` of each leaf key, by dotted path. The indentation stack gives a key's path
54
+ // from its parents' keys, so a nested key never takes a neighbour's comment.
55
+ export function templateComments(text: string): Record<string, string> {
56
+ const out: Record<string, string> = {};
57
+ const stack: { indent: number; key: string }[] = [];
58
+ for (const line of text.split("\n")) {
59
+ const m = /^( *)([A-Za-z_][\w-]*):(.*)$/.exec(line);
60
+ if (!m) continue;
61
+ const indent = m[1]!.length;
62
+ while (stack.length > 0 && stack[stack.length - 1]!.indent >= indent) stack.pop();
63
+ stack.push({ indent, key: m[2]! });
64
+ const comment = /#\s*(.*)$/.exec(m[3]!)?.[1]?.trim() ?? "";
65
+ if (comment !== "") out[stack.map((s) => s.key).join(".")] = comment;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ const TEMPLATE_TEXT = readFileSync(TEMPLATE_PATH, "utf8");
71
+ const TEMPLATE = Bun.YAML.parse(TEMPLATE_TEXT);
72
+ const COMMENTS = templateComments(TEMPLATE_TEXT);
73
+ const VALID_KEYS = leafKeys(TEMPLATE);
74
+ const TIERS = ["strict", "opinionated", "full"];
75
+
76
+ // The asked groups, in order. Keys outside them form the advanced walk.
77
+ const GROUPS: { name: string; keys: string[] }[] = [
78
+ { name: "Paths", keys: ["paths.work_roots"] },
79
+ { name: "Harness", keys: ["harness"] },
80
+ { name: "Autonomy", keys: ["autonomy.tier", "autonomy.strict_edit_limit", "autonomy.go_minutes", "autonomy.go_phrase"] },
81
+ { name: "Phone page", keys: ["ui.enabled", "ui.owner_login"] },
82
+ { name: "Static pages", keys: ["pages.enabled", "pages.port", "pages.dir"] },
83
+ { name: "Notify", keys: ["notify.discord_webhook_file", "notify.slack_webhook_file"] },
84
+ { name: "Secrets", keys: ["secrets.redact", "secrets.known_value_files", "secrets.proxy"] },
85
+ { name: "Machine", keys: ["machine.load_over_cores", "machine.avail_min_mb", "machine.disk_min_gb"] },
86
+ { name: "Session rollover", keys: ["rollover.enabled", "rollover.max_session_mb", "rollover.exit_grace_s"] },
87
+ ];
88
+
89
+ type Kind = "bool" | "num" | "list" | "str";
90
+ interface Change {
91
+ key: string;
92
+ old: unknown;
93
+ next: unknown;
94
+ }
95
+ interface Ctx {
96
+ deps: SetupDeps;
97
+ facts: SetupFacts;
98
+ fresh: boolean;
99
+ file: string;
100
+ text: string;
101
+ changed: Change[];
102
+ // none: ask every key. group: accept proposals until this group ends (s). all: accept every proposal (q, --yes).
103
+ auto: "none" | "group" | "all";
104
+ // set when the Notify group was asked and a webhook file is set; runSetup then offers the test.
105
+ testOffer: boolean;
106
+ }
107
+
108
+ export async function runSetup(args: string[], deps: SetupDeps): Promise<number> {
109
+ const yes = args.includes("--yes");
110
+ if (!yes && !deps.terminal) {
111
+ deps.say("neurastream setup needs a terminal or --yes");
112
+ return 2;
113
+ }
114
+ const facts = detect(deps.seams);
115
+ printFacts(deps, facts);
116
+ const ctx: Ctx = {
117
+ deps,
118
+ facts,
119
+ fresh: facts.current === null,
120
+ file: configFile(deps.home),
121
+ text: "",
122
+ changed: [],
123
+ auto: yes ? "all" : "none",
124
+ testOffer: false,
125
+ };
126
+ const allow = yes ? [] : askSubagents(deps);
127
+ const made = initHome(deps.home, { invoked: deps.invoked, env: deps.env, allow: allow.length > 0 ? allow : undefined });
128
+ deps.say(`layout: created ${made.created.length}, kept ${made.unchanged.length}`);
129
+ ctx.text = readFileSync(ctx.file, "utf8");
130
+ for (const group of GROUPS) {
131
+ if (runGroup(ctx, group.name, group.keys) !== 0) return 1;
132
+ }
133
+ if (ctx.auto === "none") {
134
+ const advanced = VALID_KEYS.filter((k) => !GROUPS.some((g) => g.keys.includes(k)));
135
+ const open = deps.ask(`Show the ${advanced.length} advanced settings? [y/N]: `).trim();
136
+ if (/^y(es)?$/i.test(open) && runGroup(ctx, "Advanced", advanced) !== 0) return 1;
137
+ }
138
+ if (ctx.testOffer) await offerTest(ctx);
139
+ const installed = deps.install();
140
+ if (installed !== 0) {
141
+ deps.say("adapter install failed");
142
+ return installed;
143
+ }
144
+ const doctor = deps.doctor();
145
+ printChanges(deps, ctx.changed);
146
+ if (doctor === 0) deps.say("Next: neurastream main");
147
+ return doctor;
148
+ }
149
+
150
+ function printFacts(deps: SetupDeps, facts: SetupFacts): void {
151
+ deps.say("Detected on this machine:");
152
+ deps.say(` work roots: ${facts.workRoots.join(", ") || "none"}`);
153
+ deps.say(` harnesses on PATH: ${facts.harnesses.join(", ") || "none"}`);
154
+ deps.say(` tailscale: ${facts.tailscale.state}`);
155
+ deps.say(` secretgate: ${facts.secretgate ? "on PATH" : "not on PATH"}`);
156
+ deps.say(` machine: ${facts.machine.cores} cores, ${facts.machine.ramMb} MB RAM, ${facts.machine.diskFreeGb} GB free disk`);
157
+ }
158
+
159
+ function askSubagents(deps: SetupDeps): string[] {
160
+ for (;;) {
161
+ const names = deps.ask("Subagents allowed to spawn (comma-separated names, empty = none): ")
162
+ .split(",")
163
+ .map((s) => s.trim())
164
+ .filter((s) => s !== "");
165
+ const bad = invalidSlugs(names);
166
+ if (bad.length === 0) return names;
167
+ deps.say(` not a valid name: ${bad.join(", ")}`);
168
+ }
169
+ }
170
+
171
+ function printChanges(deps: SetupDeps, changed: Change[]): void {
172
+ if (changed.length === 0) {
173
+ deps.say("No settings changed.");
174
+ return;
175
+ }
176
+ deps.say("Changed:");
177
+ for (const c of changed) deps.say(` ${c.key}: ${JSON.stringify(c.old)} → ${JSON.stringify(c.next)}`);
178
+ }
179
+
180
+ // Asks one group, then writes the changed keys once through the editor. Returns non-zero only
181
+ // when the edited file would not load (nothing is written then). A Notify group the owner was
182
+ // asked, with a webhook file set, sets ctx.testOffer so runSetup offers the test.
183
+ function runGroup(ctx: Ctx, name: string, keys: string[]): number {
184
+ ctx.deps.say(`\n${name}`);
185
+ const now = Bun.YAML.parse(ctx.text);
186
+ const picks: Record<string, unknown> = {};
187
+ const asking = ctx.auto === "none";
188
+ for (const key of keys) {
189
+ if (key === "ui.owner_login" && picks["ui.enabled"] !== true) continue;
190
+ const proposed = proposal(ctx, key, valueAt(now, key));
191
+ let value = askKey(ctx, key, kindOf(key), proposed);
192
+ if (key === "ui.enabled" && value === true && !phoneReady(ctx)) value = false;
193
+ picks[key] = value;
194
+ }
195
+ if (asking && Object.keys(picks).some((key) => key.startsWith("notify.") && picks[key] !== "")) {
196
+ ctx.testOffer = true;
197
+ }
198
+ if (ctx.auto === "group") ctx.auto = "none";
199
+ const changes: Record<string, string> = {};
200
+ for (const key of Object.keys(picks)) {
201
+ const old = valueAt(now, key);
202
+ if (JSON.stringify(old) === JSON.stringify(picks[key])) continue;
203
+ changes[key] = yamlValue(picks[key]);
204
+ ctx.changed.push({ key, old, next: picks[key] });
205
+ }
206
+ if (Object.keys(changes).length === 0) return 0;
207
+ const edited = setConfigKeys(ctx.text, changes);
208
+ if (!checkEdited(edited, ctx.deps.home, (line) => ctx.deps.say(line))) return 1;
209
+ writeFileSync(ctx.file, edited);
210
+ ctx.text = edited;
211
+ return 0;
212
+ }
213
+
214
+ // The notify test offer. A yes runs `neurastream notify test` through the injected seam. A failed
215
+ // test is printed by that command and setup goes on: the webhook is the owner's to fix.
216
+ async function offerTest(ctx: Ctx): Promise<void> {
217
+ const answer = ctx.deps.ask("send a test message now? [y/N]: ").trim();
218
+ if (/^y(es)?$/i.test(answer)) await ctx.deps.notifyTest();
219
+ }
220
+
221
+ // The value offered for Enter. A fresh home offers what this machine has; a re-run offers the
222
+ // current config, so a setting the owner already chose never moves on its own.
223
+ function proposal(ctx: Ctx, key: string, current: unknown): unknown {
224
+ if (!ctx.fresh) return current;
225
+ const fromFacts: Record<string, unknown> = {
226
+ "paths.work_roots": ctx.facts.workRoots,
227
+ harness: ctx.facts.harnesses[0],
228
+ "machine.load_over_cores": ctx.facts.proposed.load_over_cores,
229
+ "machine.avail_min_mb": ctx.facts.proposed.avail_min_mb,
230
+ "machine.disk_min_gb": ctx.facts.proposed.disk_min_gb,
231
+ };
232
+ return fromFacts[key] ?? current;
233
+ }
234
+
235
+ function kindOf(key: string): Kind {
236
+ const t = valueAt(TEMPLATE, key);
237
+ if (typeof t === "boolean") return "bool";
238
+ if (typeof t === "number") return "num";
239
+ if (Array.isArray(t)) return "list";
240
+ return "str";
241
+ }
242
+
243
+ function askKey(ctx: Ctx, key: string, kind: Kind, proposed: unknown): unknown {
244
+ if (ctx.auto !== "none") return proposed;
245
+ const comment = COMMENTS[key] ?? "";
246
+ for (;;) {
247
+ const raw = ctx.deps
248
+ .ask(`${key}: ${comment} [${yamlValue(proposed)}] (Enter keeps; s keeps the rest of this group; q keeps the rest): `)
249
+ .trim();
250
+ if (raw === "") return proposed;
251
+ if (raw === "s" || raw === "q") {
252
+ ctx.auto = raw === "s" ? "group" : "all";
253
+ return proposed;
254
+ }
255
+ const parsed = parseAnswer(kind, raw);
256
+ if ("error" in parsed) {
257
+ ctx.deps.say(` ${parsed.error}`);
258
+ continue;
259
+ }
260
+ const problem = validate(ctx, key, parsed.value);
261
+ if (problem !== null) {
262
+ ctx.deps.say(` ${problem}`);
263
+ continue;
264
+ }
265
+ return parsed.value;
266
+ }
267
+ }
268
+
269
+ function parseAnswer(kind: Kind, raw: string): { value: unknown } | { error: string } {
270
+ if (kind === "bool") {
271
+ if (/^(true|yes|y|on)$/i.test(raw)) return { value: true };
272
+ if (/^(false|no|n|off)$/i.test(raw)) return { value: false };
273
+ return { error: "answer yes or no" };
274
+ }
275
+ if (kind === "num") {
276
+ const n = Number(raw);
277
+ return Number.isFinite(n) ? { value: n } : { error: "answer a number" };
278
+ }
279
+ if (kind === "list") {
280
+ if (!raw.startsWith("[")) return { value: raw.split(",").map((s) => s.trim()).filter((s) => s !== "") };
281
+ try {
282
+ const list: unknown = Bun.YAML.parse(raw);
283
+ if (Array.isArray(list) && list.every((x) => typeof x === "string")) return { value: list };
284
+ } catch {
285
+ // not YAML: reported below
286
+ }
287
+ return { error: "answer a list of strings, e.g. [\"a\", \"b\"] or a, b" };
288
+ }
289
+ return { value: raw };
290
+ }
291
+
292
+ // Why an answer is refused, or null. The file must load with the answer in place (checkEdited),
293
+ // and the named keys must hold values the setup understands.
294
+ function validate(ctx: Ctx, key: string, value: unknown): string | null {
295
+ const problem = rule(ctx, key, value);
296
+ if (problem !== null) return problem;
297
+ const messages: string[] = [];
298
+ const candidate = setConfigKeys(ctx.text, { [key]: yamlValue(value) });
299
+ return checkEdited(candidate, ctx.deps.home, (line) => messages.push(line)) ? null : messages.join("\n");
300
+ }
301
+
302
+ function rule(ctx: Ctx, key: string, value: unknown): string | null {
303
+ if (key === "autonomy.tier" && !TIERS.includes(String(value))) return `autonomy.tier must be ${TIERS.join(", ")}`;
304
+ if (key === "harness" && !ctx.deps.seams.harnesses.some((h) => h.name === value)) {
305
+ return `harness must be one of: ${ctx.deps.seams.harnesses.map((h) => h.name).join(", ")}`;
306
+ }
307
+ if (key === "secrets.proxy" && value === "secretgate" && !ctx.facts.secretgate) return "secretgate is not on PATH";
308
+ if (key === "secrets.proxy" && value !== "none" && value !== "secretgate") return "secrets.proxy must be none or secretgate";
309
+ return null;
310
+ }
311
+
312
+ // The phone page needs a running tailnet. Without one the page stays off and the setup says why.
313
+ function phoneReady(ctx: Ctx): boolean {
314
+ const tailscale = ctx.deps.seams.tailscale;
315
+ const state = tailscale.state();
316
+ if (state === "missing") {
317
+ ctx.deps.say(TAILSCALE_MISSING);
318
+ return false;
319
+ }
320
+ if (state === "stopped") {
321
+ ctx.deps.say(TAILSCALE_STOPPED);
322
+ return false;
323
+ }
324
+ const logins = tailscale.logins() ?? [];
325
+ if (logins.length > 0) ctx.deps.say(` logins on this tailnet: ${logins.join(", ")}`);
326
+ return true;
327
+ }
package/src/cli/ui.ts CHANGED
@@ -10,7 +10,7 @@ import { beat, errorLine } from "../core/heartbeat.ts";
10
10
  import { startOwnerUi, type OwnerUiOptions, type OwnerUiServer } from "../core/owner-ui.ts";
11
11
  import { applyQueueEnv } from "../core/queue/env.ts";
12
12
  import { realTailscale, type Tailscale } from "../core/tailscale.ts";
13
- import { uiOff, uiOn, type Runner } from "../core/ui-setup.ts";
13
+ import { systemTerminal, uiOff, uiOn, type Runner } from "../core/ui-setup.ts";
14
14
 
15
15
  export interface UiDeps {
16
16
  /** The merged config. Default: loadConfig(). */
@@ -56,7 +56,9 @@ function runUiSetup(args: string[], deps: UiDeps): number {
56
56
  console.error("neurastream ui on: --login <tailscale login> is required — e.g. neurastream ui on --login me@example.com");
57
57
  return 1;
58
58
  }
59
- return uiOn({ login, port, ...setup });
59
+ // A question only on a terminal: scripted runs get the message and exit 1, no prompt.
60
+ const terminal = process.stdin.isTTY && process.stdout.isTTY ? systemTerminal : undefined;
61
+ return uiOn({ login, port, terminal, ...setup });
60
62
  }
61
63
  return uiOff(setup);
62
64
  }
@@ -0,0 +1,111 @@
1
+ // The one config.yml editor. setConfigKeys edits dotted keys line by line and keeps every other
2
+ // line byte-for-byte (comments, order, other sections): it never re-serialises YAML.
3
+ // checkEdited proves an edited file still loads before anything is written.
4
+
5
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { ConfigError, loadConfig } from "./config.ts";
9
+
10
+ const leading = (line: string): number => line.length - line.trimStart().length;
11
+ const isBlank = (line: string): boolean => line.trim() === "";
12
+
13
+ // Leaf dotted paths: a mapping recurses; a scalar, a list or null is a leaf.
14
+ export function leafKeys(node: unknown, prefix: string[] = []): string[] {
15
+ if (node === null || typeof node !== "object" || Array.isArray(node)) return [prefix.join(".")];
16
+ return Object.entries(node).flatMap(([k, v]) => leafKeys(v, [...prefix, k]));
17
+ }
18
+
19
+ export function valueAt(cfg: unknown, key: string): unknown {
20
+ let node = cfg;
21
+ for (const seg of key.split(".")) node = (node as Record<string, unknown>)[seg];
22
+ return node;
23
+ }
24
+
25
+ // A value as YAML text for setConfigKeys: lists in flow style on one line ([a, b]); scalars as JSON, which is valid YAML.
26
+ export function yamlValue(value: unknown): string {
27
+ return Array.isArray(value) ? `[${value.map((x) => JSON.stringify(x)).join(", ")}]` : JSON.stringify(value);
28
+ }
29
+
30
+ // First line at or after `from` that is not part of a block whose keys sit at column `col`.
31
+ // A block is the following lines that are blank or indented deeper than the key.
32
+ function blockEnd(lines: string[], from: number, col: number): number {
33
+ let j = from;
34
+ while (j < lines.length && (isBlank(lines[j]!) || leading(lines[j]!) > col)) j++;
35
+ return j;
36
+ }
37
+
38
+ // Just past the last non-blank line in [from, end): where a new line joins that block.
39
+ function afterLast(lines: string[], from: number, end: number): number {
40
+ let at = from;
41
+ for (let i = from; i < end; i++) if (!isBlank(lines[i]!)) at = i + 1;
42
+ return at;
43
+ }
44
+
45
+ // Sets one path segment list inside the block of `parent` (-1 = the whole file). `indent` is the
46
+ // column its keys sit at. Recurses one level per segment, so a.b.c only matches inside a's and b's blocks.
47
+ function setPath(lines: string[], segs: string[], value: string, parent: number, indent: string): void {
48
+ const [seg, ...deeper] = segs as [string, ...string[]];
49
+ const lo = parent < 0 ? 0 : parent + 1;
50
+ const hi = parent < 0 ? lines.length : blockEnd(lines, lo, leading(lines[parent]!));
51
+ const re = new RegExp("^" + indent + seg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "(\\s*):(.*)$");
52
+ let k = -1;
53
+ for (let i = lo; i < hi; i++) {
54
+ if (re.test(lines[i]!)) {
55
+ k = i;
56
+ break;
57
+ }
58
+ }
59
+ if (deeper.length === 0) {
60
+ if (k < 0) {
61
+ lines.splice(afterLast(lines, lo, hi), 0, `${indent}${seg}: ${value}`);
62
+ return;
63
+ }
64
+ // Replace the leaf and any child lines under it; keep its trailing comment.
65
+ const rest = re.exec(lines[k]!)![2]!;
66
+ const comment = rest.match(/\s+#.*$/)?.[0] ?? "";
67
+ const cut = afterLast(lines, k + 1, blockEnd(lines, k + 1, indent.length));
68
+ lines.splice(k, cut - k, `${indent}${seg}: ${value}${comment}`);
69
+ return;
70
+ }
71
+ if (k < 0) {
72
+ k = afterLast(lines, lo, hi);
73
+ lines.splice(k, 0, `${indent}${seg}:`);
74
+ }
75
+ const end = blockEnd(lines, k + 1, indent.length);
76
+ const child = lines.slice(k + 1, end).find((l) => !isBlank(l));
77
+ const childIndent = child === undefined ? `${indent} ` : /^[ \t]*/.exec(child)![0];
78
+ setPath(lines, deeper, value, k, childIndent);
79
+ }
80
+
81
+ // `values` maps each dotted key to its already-formatted YAML value text (`true`, `7788`,
82
+ // `["a", "b"]`, `"quoted"`). A value with a line break is refused: it would write extra keys.
83
+ export function setConfigKeys(text: string | null, values: Record<string, string>): string {
84
+ for (const [key, value] of Object.entries(values)) {
85
+ if (/[\n\r]/.test(value)) throw new ConfigError(`config ${key}: a value cannot contain a line break`);
86
+ }
87
+ // "".split("\n") is [""], so an empty file still ends with a newline after the first insert.
88
+ let base = text ?? "";
89
+ if (base !== "" && !base.endsWith("\n")) base += "\n";
90
+ const lines = base.split("\n");
91
+ for (const [key, value] of Object.entries(values)) setPath(lines, key.split("."), value, -1, "");
92
+ return lines.join("\n");
93
+ }
94
+
95
+ // Proves an edited config still loads through loadConfig before anything is written. The copy goes
96
+ // to a fresh mkdtemp dir (mode 0700, unpredictable name, so no planted symlink can redirect it);
97
+ // the dir is removed in finally. Returns false after reporting the error when the file does not load.
98
+ export function checkEdited(edited: string, home: string, error: (line: string) => void): boolean {
99
+ const dir = mkdtempSync(join(tmpdir(), "neurastream-check-"));
100
+ try {
101
+ const file = join(dir, "config.yml");
102
+ writeFileSync(file, edited, { mode: 0o600 });
103
+ loadConfig({ file, home });
104
+ return true;
105
+ } catch (err) {
106
+ error(err instanceof ConfigError ? err.message : String(err));
107
+ return false;
108
+ } finally {
109
+ rmSync(dir, { recursive: true, force: true });
110
+ }
111
+ }
@@ -134,16 +134,20 @@ export interface Config {
134
134
  idle_stops: number;
135
135
  /** A Main stop reply matching this regex (case-insensitive) offers to plan instead of planning; the stop is refused (20261028_0900 P2). */
136
136
  plan_offer: string;
137
- /** Provider rate limits (src/core/rate-limit.ts): a turn that ends on one waits it out instead of
138
- * asking again straight into the limit. The words and the waits come from here. */
137
+ /** Provider rate limits (src/core/rate-limit.ts, src/core/limit-probe.ts): a turn that ends on one waits for the
138
+ * named reset, or probes the provider until it answers. The words and the timings come from here. */
139
139
  rate_limit: {
140
140
  /** Case-insensitive substrings in the error text that mark a rate limit. */
141
141
  patterns: string[];
142
- /** Wait when the error text names no retry-after. */
143
- default_wait_s: number;
144
- /** Cap for the parsed (or doubled) wait, before slack. */
145
- max_wait_s: number;
146
- /** Added on top of every wait. */
142
+ /** Probe the provider this often (s) while it names no reset. */
143
+ probe_interval_s: number;
144
+ /** Probes before the episode gives up. */
145
+ max_probes: number;
146
+ /** Kill a probe that runs longer than this (s). */
147
+ probe_timeout_s: number;
148
+ /** Shell command that probes the provider; {model} is replaced by the shell-quoted model. Exit 0 means it answered. */
149
+ probe_cmd: string;
150
+ /** Added on top of every wait (s). */
147
151
  slack_s: number;
148
152
  };
149
153
  blocker_timeout_ms: number;
@@ -581,8 +585,12 @@ function check(cfg: Config): void {
581
585
  if (!Array.isArray(cfg.guards.rate_limit.patterns) || cfg.guards.rate_limit.patterns.some(p => typeof p !== "string" || p === "")) {
582
586
  throw new ConfigError("guards.rate_limit.patterns must be a list of non-empty strings");
583
587
  }
584
- if (!(cfg.guards.rate_limit.default_wait_s >= 1)) throw new ConfigError("guards.rate_limit.default_wait_s must be >= 1");
585
- if (!(cfg.guards.rate_limit.max_wait_s >= 1)) throw new ConfigError("guards.rate_limit.max_wait_s must be >= 1");
588
+ if (!(cfg.guards.rate_limit.probe_interval_s >= 1)) throw new ConfigError("guards.rate_limit.probe_interval_s must be >= 1");
589
+ if (!(cfg.guards.rate_limit.max_probes >= 1)) throw new ConfigError("guards.rate_limit.max_probes must be >= 1");
590
+ if (!(cfg.guards.rate_limit.probe_timeout_s >= 1)) throw new ConfigError("guards.rate_limit.probe_timeout_s must be >= 1");
591
+ if (typeof cfg.guards.rate_limit.probe_cmd !== "string" || !cfg.guards.rate_limit.probe_cmd.includes("{model}")) {
592
+ throw new ConfigError("guards.rate_limit.probe_cmd must be a string containing {model}");
593
+ }
586
594
  if (!(cfg.guards.rate_limit.slack_s >= 0)) throw new ConfigError("guards.rate_limit.slack_s must be >= 0");
587
595
  if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
588
596
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");