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.
- package/README.md +34 -9
- package/package.json +1 -1
- package/src/adapters/index.ts +7 -0
- package/src/adapters/omp/adapter.ts +1 -0
- package/src/adapters/omp/doctor.ts +4 -2
- package/src/adapters/omp/index.ts +121 -52
- package/src/cli/config-set.ts +56 -0
- package/src/cli/dispatch.ts +8 -0
- package/src/cli/init.ts +6 -4
- package/src/cli/limit-probe.ts +11 -0
- package/src/cli/setup.ts +327 -0
- package/src/cli/ui.ts +4 -2
- package/src/core/config-edit.ts +111 -0
- package/src/core/config.ts +17 -9
- package/src/core/limit-probe.ts +225 -0
- package/src/core/notify.ts +7 -0
- package/src/core/pages-setup.ts +6 -21
- package/src/core/rate-limit.ts +16 -44
- package/src/core/report.ts +8 -0
- package/src/core/setup-detect.ts +120 -0
- package/src/core/tailscale.ts +20 -0
- package/src/core/ui-setup.ts +52 -64
- package/templates/config.yml +131 -130
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
// The probe loop (plan 20261027_1500, P2): when the provider rate-limits the main agent, wait for
|
|
2
|
+
// the named reset if the provider gave one; otherwise probe it every probe_interval_s until it
|
|
3
|
+
// answers, up to max_probes. The state transitions are pure (onLimited, onProbe); runProbe runs the
|
|
4
|
+
// configured probe command under the main-limit lock. The episode file (main-limit.json) and
|
|
5
|
+
// probeStep (one tick of the loop) live here too. Harness-neutral: nothing here names a harness or a provider.
|
|
6
|
+
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { dirname, join } from "node:path";
|
|
10
|
+
import type { Config } from "./config.ts";
|
|
11
|
+
import { strftime } from "./clock.ts";
|
|
12
|
+
import { tryLock } from "./file-lock.ts";
|
|
13
|
+
import { appendMetric } from "./metrics.ts";
|
|
14
|
+
import { postReply } from "./notify.ts";
|
|
15
|
+
import { loadKnownSecrets, redactSecrets } from "./secret-redact.ts";
|
|
16
|
+
|
|
17
|
+
/** One rate-limit episode of the main agent. Times are epoch ms. */
|
|
18
|
+
export interface LimitState {
|
|
19
|
+
since: number;
|
|
20
|
+
model: string;
|
|
21
|
+
reset_named: boolean;
|
|
22
|
+
next_probe_at: number;
|
|
23
|
+
probes: number;
|
|
24
|
+
last_error: string;
|
|
25
|
+
back_at: number | null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ProbeTiming {
|
|
29
|
+
probe_interval_s: number;
|
|
30
|
+
max_probes: number;
|
|
31
|
+
slack_s: number;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export type ProbeOutcome = { kind: "resume" } | { kind: "again"; at: number } | { kind: "give_up" };
|
|
35
|
+
|
|
36
|
+
export interface ProbeStep {
|
|
37
|
+
state: LimitState;
|
|
38
|
+
outcome: ProbeOutcome;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface ProbeResult {
|
|
42
|
+
ok: boolean;
|
|
43
|
+
exitCode: number | null;
|
|
44
|
+
stderr: string;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type ProbeRunner = (
|
|
48
|
+
file: string,
|
|
49
|
+
args: string[],
|
|
50
|
+
opts: { timeout: number },
|
|
51
|
+
) => { status: number | null; stderr: string; error?: Error };
|
|
52
|
+
|
|
53
|
+
const defaultRun: ProbeRunner = (file, args, opts) => spawnSync(file, args, { ...opts, encoding: "utf8" as const });
|
|
54
|
+
|
|
55
|
+
const shellQuote = (value: string): string => `'${value.replaceAll("'", "'\\''")}'`;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The main agent was rate-limited at `now`. A named reset (epoch ms) is waited for, plus slack;
|
|
59
|
+
* without one the first probe comes after probe_interval_s.
|
|
60
|
+
*/
|
|
61
|
+
export function onLimited(
|
|
62
|
+
state: LimitState | null,
|
|
63
|
+
namedResetMs: number | null,
|
|
64
|
+
errorText: string,
|
|
65
|
+
now: number,
|
|
66
|
+
model: string,
|
|
67
|
+
timing: ProbeTiming,
|
|
68
|
+
): LimitState {
|
|
69
|
+
const named = namedResetMs !== null;
|
|
70
|
+
const next = named ? namedResetMs + timing.slack_s * 1000 : now + timing.probe_interval_s * 1000;
|
|
71
|
+
return {
|
|
72
|
+
since: state?.since ?? now,
|
|
73
|
+
model,
|
|
74
|
+
reset_named: named,
|
|
75
|
+
next_probe_at: next,
|
|
76
|
+
probes: state?.probes ?? 0,
|
|
77
|
+
last_error: errorText,
|
|
78
|
+
back_at: named ? next : null,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* A probe finished at `now`. Every probe counts. A successful probe resumes; a failed one probes
|
|
84
|
+
* again after probe_interval_s until max_probes is reached, then gives up.
|
|
85
|
+
*/
|
|
86
|
+
export function onProbe(state: LimitState, ok: boolean, errorText: string, now: number, timing: ProbeTiming): ProbeStep {
|
|
87
|
+
const probes = state.probes + 1;
|
|
88
|
+
if (ok) return { state: { ...state, probes }, outcome: { kind: "resume" } };
|
|
89
|
+
if (probes >= timing.max_probes) {
|
|
90
|
+
return { state: { ...state, probes, last_error: errorText }, outcome: { kind: "give_up" } };
|
|
91
|
+
}
|
|
92
|
+
const at = now + timing.probe_interval_s * 1000;
|
|
93
|
+
return { state: { ...state, probes, last_error: errorText, next_probe_at: at }, outcome: { kind: "again", at } };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Run guards.rate_limit.probe_cmd once, with {model} replaced by the shell-quoted model, under the
|
|
98
|
+
* main-limit lock. Returns "busy" when another probe holds the lock. The output is never logged in
|
|
99
|
+
* full: stderr is redacted, then cut to 200 characters.
|
|
100
|
+
*/
|
|
101
|
+
export function runProbe(cfg: Config, model: string, run: ProbeRunner = defaultRun): ProbeResult | "busy" {
|
|
102
|
+
const lock = tryLock(join(cfg.paths.queue_state, "main-limit.lock"));
|
|
103
|
+
if (!lock) return "busy";
|
|
104
|
+
try {
|
|
105
|
+
const rl = cfg.guards.rate_limit;
|
|
106
|
+
const cmd = rl.probe_cmd.replaceAll("{model}", shellQuote(model));
|
|
107
|
+
const r = run("sh", ["-c", cmd], { timeout: rl.probe_timeout_s * 1000 });
|
|
108
|
+
const stderr = redactSecrets(r.stderr, loadKnownSecrets(cfg), cfg.secrets.extra_patterns).text.slice(0, 200);
|
|
109
|
+
return { ok: r.status === 0 && !r.error, exitCode: r.status, stderr };
|
|
110
|
+
} finally {
|
|
111
|
+
lock.release();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Where the open episode lives: one JSON file in queue_state, replaced atomically. */
|
|
116
|
+
export function limitStatePath(cfg: Config): string {
|
|
117
|
+
return join(cfg.paths.queue_state, "main-limit.json");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** The open episode, or null when there is none (or the file cannot be parsed). */
|
|
121
|
+
export function readLimitState(cfg: Config): LimitState | null {
|
|
122
|
+
try {
|
|
123
|
+
return JSON.parse(readFileSync(limitStatePath(cfg), "utf8")) as LimitState;
|
|
124
|
+
} catch {
|
|
125
|
+
return null;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function writeLimitState(cfg: Config, state: LimitState): void {
|
|
130
|
+
const path = limitStatePath(cfg);
|
|
131
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
132
|
+
writeFileSync(`${path}.tmp`, `${JSON.stringify(state)}\n`);
|
|
133
|
+
renameSync(`${path}.tmp`, path);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function clearLimitState(cfg: Config): void {
|
|
137
|
+
rmSync(limitStatePath(cfg), { force: true });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function timingOf(cfg: Config): ProbeTiming {
|
|
141
|
+
const rl = cfg.guards.rate_limit;
|
|
142
|
+
return { probe_interval_s: rl.probe_interval_s, max_probes: rl.max_probes, slack_s: rl.slack_s };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* One tick of the probe loop at `now`. Returns "idle" when no episode is open, the episode is
|
|
147
|
+
* already back, or the next probe is not due; "busy" when another probe holds the lock. Otherwise
|
|
148
|
+
* runs one probe and records its outcome. A give-up closes the episode: one ⚠ post to the owner
|
|
149
|
+
* chat (via `notify`, default the redacting postReply) and one `limit` metric. If the episode was
|
|
150
|
+
* closed (turn-end disarm) or replaced while the probe ran, the result is dropped instead of
|
|
151
|
+
* written back. A resume only marks the episode back — the adapter's tick posts the ✅ and the
|
|
152
|
+
* metric when it sends Main's new turn.
|
|
153
|
+
*/
|
|
154
|
+
export function probeStep(
|
|
155
|
+
cfg: Config,
|
|
156
|
+
now: number,
|
|
157
|
+
run: ProbeRunner = defaultRun,
|
|
158
|
+
notify: (text: string) => void = (text) => {
|
|
159
|
+
void postReply(text, cfg);
|
|
160
|
+
},
|
|
161
|
+
): "idle" | "busy" | ProbeOutcome["kind"] {
|
|
162
|
+
const st = readLimitState(cfg);
|
|
163
|
+
if (!st || st.back_at !== null || now < st.next_probe_at) return "idle";
|
|
164
|
+
const r = runProbe(cfg, st.model, run);
|
|
165
|
+
if (r === "busy") return "busy";
|
|
166
|
+
const current = readLimitState(cfg);
|
|
167
|
+
if (!current || current.since !== st.since) return "idle";
|
|
168
|
+
const timing = timingOf(cfg);
|
|
169
|
+
const step = onProbe(current, r.ok, r.stderr, now, timing);
|
|
170
|
+
if (step.outcome.kind === "give_up") {
|
|
171
|
+
clearLimitState(cfg);
|
|
172
|
+
appendMetric(cfg, limitMetric(step.state, now));
|
|
173
|
+
notify(giveUpPost(timing));
|
|
174
|
+
} else if (step.outcome.kind === "resume") writeLimitState(cfg, { ...step.state, back_at: now });
|
|
175
|
+
else writeLimitState(cfg, step.state);
|
|
176
|
+
return step.outcome.kind;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---- P4 tell + record: the owner-facing texts and the metric record of a finished episode ----
|
|
180
|
+
// Every text here is built from times and counts only; the error text in LimitState.last_error is
|
|
181
|
+
// unredacted, so no builder takes it — a post, the metric and the report line cannot carry it.
|
|
182
|
+
|
|
183
|
+
/** Minutes the main agent has been limited, from `since` to the episode's end. */
|
|
184
|
+
function limitedMinutes(state: LimitState, now: number): number {
|
|
185
|
+
return Math.max(0, Math.round(((state.back_at ?? now) - state.since) / 60000));
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** A duration in whole units the owner reads at a glance: "24 h", "15 min", "5 s". */
|
|
189
|
+
function durationText(seconds: number): string {
|
|
190
|
+
if (seconds >= 3600) return `${Math.round(seconds / 360) / 10} h`;
|
|
191
|
+
if (seconds >= 60) return `${Math.round(seconds / 60)} min`;
|
|
192
|
+
return `${seconds} s`;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
const clockHM = (ms: number): string => strftime(ms / 1000, "%H:%M");
|
|
196
|
+
|
|
197
|
+
/** The post when an episode opens: a named reset announces when it lifts, an unnamed one the probe cadence. */
|
|
198
|
+
export function limitedPost(state: LimitState, interval_s: number): string {
|
|
199
|
+
const at = clockHM(state.since);
|
|
200
|
+
return state.reset_named
|
|
201
|
+
? `⏳ Main hit its limit at ${at}; resets at ${clockHM(state.next_probe_at)}`
|
|
202
|
+
: `⏳ Main hit its limit at ${at}; checking every ${durationText(interval_s)}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** The post when the provider answered or the named reset passed: times and counts only. */
|
|
206
|
+
export function backPost(state: LimitState): string {
|
|
207
|
+
return `✅ Main is back at ${clockHM(state.back_at!)} (limited ${limitedMinutes(state, state.back_at!)} min, ${state.probes} checks)`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** The post when max_probes is spent without an answer. */
|
|
211
|
+
export function giveUpPost(timing: ProbeTiming): string {
|
|
212
|
+
return `⚠ Main still limited after ${durationText(timing.max_probes * timing.probe_interval_s)}`;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** The metric record of one finished episode: numbers and a boolean, never the error text. */
|
|
216
|
+
export function limitMetric(state: LimitState, now: number): Record<string, unknown> {
|
|
217
|
+
return {
|
|
218
|
+
type: "limit",
|
|
219
|
+
since: state.since,
|
|
220
|
+
back_at: state.back_at,
|
|
221
|
+
minutes: limitedMinutes(state, now),
|
|
222
|
+
probes: state.probes,
|
|
223
|
+
reset_named: state.reset_named,
|
|
224
|
+
};
|
|
225
|
+
}
|
package/src/core/notify.ts
CHANGED
|
@@ -209,6 +209,13 @@ const enqueuePost = <T>(operation: () => Promise<T>): Promise<T> => {
|
|
|
209
209
|
return result;
|
|
210
210
|
}
|
|
211
211
|
|
|
212
|
+
/** Resolves once every post enqueued so far has finished. Posts are fire-and-forget for callers;
|
|
213
|
+
* tests drain the queue before clearing their hit lists, so one test's late post never lands in
|
|
214
|
+
* the next test's window. */
|
|
215
|
+
export function notifyIdle(): Promise<void> {
|
|
216
|
+
return postQueue;
|
|
217
|
+
}
|
|
218
|
+
|
|
212
219
|
/** Post Main's final reply to every configured provider, serially across calls. 429s retry once
|
|
213
220
|
* after Discord's requested delay (capped at 10 seconds); other failures return to the caller. */
|
|
214
221
|
export function postReply(text: string, cfg: Config): Promise<NotifyPostResult[]> {
|
package/src/core/pages-setup.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { checkDiagram } from "./diagram-check.ts";
|
|
|
11
11
|
import { gitRaw } from "./proc.ts";
|
|
12
12
|
import { recordPublish } from "./pages-expiry.ts";
|
|
13
13
|
import { realTailscale, type Tailscale } from "./tailscale.ts";
|
|
14
|
+
import { checkEdited, setConfigKeys } from "./config-edit.ts";
|
|
14
15
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
15
16
|
export const PAGES_UNIT_TEMPLATE = join(HERE, "../../templates/systemd/neurastream-pages.service");
|
|
16
17
|
const DATA_MARK = "/* === DATA === */";
|
|
@@ -19,30 +20,13 @@ export interface RunnerResult { status: number | null; stderr: string; stdout?:
|
|
|
19
20
|
export type Runner = (args: string[]) => RunnerResult;
|
|
20
21
|
export const systemRunner: Runner = args => { const r = spawnSync("systemctl", args, { encoding:"utf8" }); return { status:r.status, stderr:r.stderr ?? "", stdout:r.stdout ?? "" }; };
|
|
21
22
|
export interface Setup { home?: string; runner?: Runner; tailscale?: Tailscale }
|
|
22
|
-
function editBlock(text: string | null, values: { enabled: boolean; port: number; dir: string }): string {
|
|
23
|
-
const fresh = ["pages:", ` enabled: ${values.enabled}`, ` port: ${values.port}`, ` dir: "${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`];
|
|
24
|
-
if (text === null) return `${fresh.join("\n")}\n`;
|
|
25
|
-
const lines = text.split("\n");
|
|
26
|
-
let start = -1;
|
|
27
|
-
for (let i = 0; i < lines.length; i++) if (/^pages\s*:(\s*(?:#.*)?)?$/.test(lines[i] ?? "")) { start = i; break; }
|
|
28
|
-
if (start < 0) return `${text === "" || text.endsWith("\n") ? text : `${text}\n`}${fresh.join("\n")}\n`;
|
|
29
|
-
let end = start + 1;
|
|
30
|
-
while (end < lines.length && (lines[end] === "" || /^[ \t]/.test(lines[end]!))) end++;
|
|
31
|
-
const setKey = (key: string, value: string): void => {
|
|
32
|
-
const re = new RegExp(`^([ \\t]+)${key}\\s*:.*$`);
|
|
33
|
-
for (let i = start + 1; i < end; i++) if (re.test(lines[i]!)) { lines[i] = lines[i]!.replace(re, `$1${key}: ${value}`); return; }
|
|
34
|
-
let at = start + 1;
|
|
35
|
-
for (let i = start + 1; i < end; i++) if (lines[i]!.trim() !== "") at = i + 1;
|
|
36
|
-
lines.splice(at, 0, ` ${key}: ${value}`); end++;
|
|
37
|
-
};
|
|
38
|
-
setKey("enabled", String(values.enabled)); setKey("port", String(values.port)); setKey("dir", `"${values.dir.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`);
|
|
39
|
-
return lines.join("\n");
|
|
40
|
-
}
|
|
41
23
|
export function pagesOn(opts: Setup & { port?: number; dir?: string }): number {
|
|
42
24
|
const home = opts.home ?? homedir(), runner = opts.runner ?? systemRunner, ts = opts.tailscale ?? realTailscale;
|
|
43
25
|
const file = configFile(home), old = existsSync(file) ? readFileSync(file,"utf8") : null; const cfg = loadConfig({ home });
|
|
44
26
|
const port = opts.port ?? cfg.pages.port, dir = opts.dir ?? cfg.pages.dir;
|
|
45
|
-
|
|
27
|
+
const edited = setConfigKeys(old, { "pages.enabled": "true", "pages.port": String(port), "pages.dir": JSON.stringify(dir) });
|
|
28
|
+
if (!checkEdited(edited, home, msg => console.error(msg))) return 1;
|
|
29
|
+
mkdirSync(dirname(file), { recursive:true }); writeFileSync(file, edited);
|
|
46
30
|
mkdirSync(dir, { recursive:true });
|
|
47
31
|
mkdirSync(join(home,".config/systemd/user"),{recursive:true}); copyFileSync(PAGES_UNIT_TEMPLATE, join(home,".config/systemd/user/neurastream-pages.service"));
|
|
48
32
|
for (const args of [["--user","daemon-reload"],["--user","enable","--now","neurastream-pages"]]) { const r=runner(args); if(r.status!==0){console.error(r.stderr);return 1;} }
|
|
@@ -50,7 +34,8 @@ export function pagesOn(opts: Setup & { port?: number; dir?: string }): number {
|
|
|
50
34
|
}
|
|
51
35
|
export function pagesOff(opts: Setup = {}): number {
|
|
52
36
|
const home=opts.home ?? homedir(), runner=opts.runner ?? systemRunner, file=configFile(home), old=existsSync(file)?readFileSync(file,"utf8"):null;
|
|
53
|
-
|
|
37
|
+
const cfg=loadConfig({home}); const edited=setConfigKeys(old,{"pages.enabled":"false","pages.port":String(cfg.pages.port),"pages.dir":JSON.stringify(cfg.pages.dir)});
|
|
38
|
+
if(!checkEdited(edited,home,msg=>console.error(msg))) return 1; writeFileSync(file,edited);
|
|
54
39
|
const r=runner(["--user","stop","neurastream-pages"]); if(r.status!==0){console.error(r.stderr);return 1;} return 0;
|
|
55
40
|
}
|
|
56
41
|
/**
|
package/src/core/rate-limit.ts
CHANGED
|
@@ -1,65 +1,37 @@
|
|
|
1
|
-
// Provider rate limits (plan 20261025_0640): a turn that ended on
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// the
|
|
1
|
+
// Provider rate limits (plan 20261025_0640, reshaped by 20261027_1500 P2): a turn that ended on a
|
|
2
|
+
// rate limit is recognised here; what happens next (a named wait or probing the provider) is decided
|
|
3
|
+
// by the adapter and src/core/limit-probe.ts. Pure: what counts as a rate limit, and the retry-after
|
|
4
|
+
// the provider names. The words come from config (guards.rate_limit); the adapter supplies the turn's
|
|
5
|
+
// stop reason and error text.
|
|
5
6
|
|
|
6
7
|
export interface RateLimitConfig {
|
|
7
8
|
/** Case-insensitive substrings in the error text that mark a rate limit. */
|
|
8
9
|
patterns: string[];
|
|
9
|
-
/** Wait when the error text names no retry-after. */
|
|
10
|
-
default_wait_s: number;
|
|
11
|
-
/** Cap for the parsed (or doubled) wait, before slack. */
|
|
12
|
-
max_wait_s: number;
|
|
13
|
-
/** Added on top of every wait. */
|
|
14
|
-
slack_s: number;
|
|
15
10
|
}
|
|
16
11
|
|
|
17
|
-
export interface
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
/** Total wait in ms, slack included. */
|
|
21
|
-
waitMs: number;
|
|
12
|
+
export interface RateLimited {
|
|
13
|
+
/** The provider's named retry-after in ms, or null when the error text names none. */
|
|
14
|
+
retryAfterMs: number | null;
|
|
22
15
|
}
|
|
23
16
|
|
|
24
17
|
const RETRY_AFTER_MS = /retry-after-ms[=:]\s*(\d+)/i;
|
|
25
18
|
const RETRY_AFTER_S = /retry-after[=:]\s*(\d+)/i;
|
|
26
19
|
|
|
27
|
-
function
|
|
20
|
+
function namedRetryAfterMs(errorText: string): number | null {
|
|
28
21
|
const ms = RETRY_AFTER_MS.exec(errorText);
|
|
29
|
-
if (ms) return
|
|
22
|
+
if (ms) return Number(ms[1]);
|
|
30
23
|
const s = RETRY_AFTER_S.exec(errorText);
|
|
31
|
-
if (s) return
|
|
32
|
-
return
|
|
24
|
+
if (s) return Number(s[1]) * 1000;
|
|
25
|
+
return null;
|
|
33
26
|
}
|
|
34
27
|
|
|
35
28
|
/**
|
|
36
|
-
* The
|
|
37
|
-
*
|
|
38
|
-
* (case-insensitive). A named retry-after is used as-is; otherwise default_wait_s is doubled
|
|
39
|
-
* for each later attempt. The resulting wait is clamped to max_wait_s, then slack_s is added.
|
|
29
|
+
* The rate limit a turn ended on, or null when it did not: the stop reason must be "error" and the
|
|
30
|
+
* error text must contain one of the configured patterns (case-insensitive).
|
|
40
31
|
*/
|
|
41
|
-
export function
|
|
42
|
-
stopReason: string | null,
|
|
43
|
-
errorText: string | null,
|
|
44
|
-
now: number,
|
|
45
|
-
cfg: RateLimitConfig,
|
|
46
|
-
attempt: number,
|
|
47
|
-
): RateLimitWait | null {
|
|
32
|
+
export function rateLimited(stopReason: string | null, errorText: string | null, cfg: RateLimitConfig): RateLimited | null {
|
|
48
33
|
if (stopReason !== "error" || !errorText) return null;
|
|
49
34
|
const text = errorText.toLowerCase();
|
|
50
35
|
if (!cfg.patterns.some(p => text.includes(p.toLowerCase()))) return null;
|
|
51
|
-
|
|
52
|
-
const retryAfter = retryAfterMs(errorText, cfg);
|
|
53
|
-
let baseMs = retryAfter.ms;
|
|
54
|
-
if (!retryAfter.named) {
|
|
55
|
-
for (let i = 1; i < Math.max(1, attempt); i++) {
|
|
56
|
-
baseMs *= 2;
|
|
57
|
-
if (baseMs >= capMs) {
|
|
58
|
-
baseMs = capMs;
|
|
59
|
-
break;
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
const waitMs = Math.min(baseMs, capMs) + cfg.slack_s * 1000;
|
|
64
|
-
return { untilMs: now + waitMs, waitMs };
|
|
36
|
+
return { retryAfterMs: namedRetryAfterMs(errorText) };
|
|
65
37
|
}
|
package/src/core/report.ts
CHANGED
|
@@ -292,10 +292,18 @@ export function buildReport(cfg: Config, source: RunSource, days: number, now: n
|
|
|
292
292
|
}),
|
|
293
293
|
];
|
|
294
294
|
const falseAlarms = events.filter((e) => e.type === "false-alarm" && inWindow(Number(e.ts), cur)).length;
|
|
295
|
+
// Plan 20261027_1500 P4: finished main-agent limit episodes, one line over the window. The
|
|
296
|
+
// metric record is numbers + a boolean, but read only the pinned fields here, so a stray
|
|
297
|
+
// last_error can never reach the report.
|
|
298
|
+
const limitEvents = events.filter((e) => e.type === "limit" && inWindow(Number(e.since) / 1000, cur));
|
|
299
|
+
const limitMinutes = limitEvents.reduce((n, e) => n + Number(e.minutes ?? 0), 0);
|
|
295
300
|
const noisy = noisyDetectors(incidents, cur, cfg.watch);
|
|
296
301
|
const quality = [
|
|
297
302
|
`Silent failures: ${silentFailures(incidents, cur)} watch incidents; suspected false blocks: ${m7(incidents, falseAlarms, cur)}`,
|
|
298
303
|
`Flaky jobs: ${events.filter((e) => e.type === "ci-flaky" && inWindow(Number(e.ts), cur)).length} same-commit red→green re-runs`,
|
|
304
|
+
...(limitEvents.length > 0
|
|
305
|
+
? [`Main limited: ${limitMinutes >= 60 ? `${Math.round(limitMinutes / 6) / 10} h` : `${limitMinutes} min`} over ${limitEvents.length} episodes`]
|
|
306
|
+
: []),
|
|
299
307
|
"Dismiss rate by kind (opened, planned, dismissed):",
|
|
300
308
|
...kindStats(incidents, cur).map((k) => `- ${k.kind}: ${k.opened}, ${k.planned}, ${k.dismissed} (${Math.round(k.dismissRate * 100)}% dismissed)`),
|
|
301
309
|
];
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// `neurastream setup` detection (plan 20261028_2356 P3): reads the machine and returns one typed
|
|
2
|
+
// object. Pure over injected seams (HOME as the fs root, a PATH lookup, the Tailscale seam, os
|
|
3
|
+
// facts): no prompts, no writes. realSeams wires the node fs/os, the given PATH and realTailscale.
|
|
4
|
+
// Core names no harness: the caller passes the harness binaries (the adapter registry lives in
|
|
5
|
+
// src/adapters, which core may not import).
|
|
6
|
+
|
|
7
|
+
import { existsSync, readdirSync, statfsSync, statSync } from "node:fs";
|
|
8
|
+
import { availableParallelism, homedir, totalmem } from "node:os";
|
|
9
|
+
import { join } from "node:path";
|
|
10
|
+
import { configFile, loadConfig, type Config } from "./config.ts";
|
|
11
|
+
import { PROXY_BIN } from "./secret-redact.ts";
|
|
12
|
+
import { realTailscale, type Tailscale, type TailscaleState } from "./tailscale.ts";
|
|
13
|
+
|
|
14
|
+
export interface HarnessBin {
|
|
15
|
+
name: string;
|
|
16
|
+
/** The binary name looked up on PATH. */
|
|
17
|
+
bin: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface OsFacts {
|
|
21
|
+
cores: number;
|
|
22
|
+
ramMb: number;
|
|
23
|
+
/** Free space on the filesystem holding HOME, in GB (1e9 bytes, as the machine guard counts). */
|
|
24
|
+
diskFreeGb: number;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface SetupSeams {
|
|
28
|
+
/** HOME: the fs root the config and the work roots resolve against. */
|
|
29
|
+
home: string;
|
|
30
|
+
onPath(bin: string): boolean;
|
|
31
|
+
harnesses: HarnessBin[];
|
|
32
|
+
tailscale: Tailscale;
|
|
33
|
+
os: OsFacts;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface MachineProposal {
|
|
37
|
+
load_over_cores: number;
|
|
38
|
+
avail_min_mb: number;
|
|
39
|
+
disk_min_gb: number;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface SetupFacts {
|
|
43
|
+
/** Absolute paths of HOME's direct non-dot children that hold a git repo one level down, sorted. */
|
|
44
|
+
workRoots: string[];
|
|
45
|
+
/** Names of the harnesses whose binary is on PATH. */
|
|
46
|
+
harnesses: string[];
|
|
47
|
+
tailscale: { state: TailscaleState; logins: string[] | null };
|
|
48
|
+
secretgate: boolean;
|
|
49
|
+
machine: OsFacts;
|
|
50
|
+
/** The values setup would write: the config.yml values on a re-run, else computed from the machine. */
|
|
51
|
+
proposed: MachineProposal;
|
|
52
|
+
/** The loaded config when config.yml exists; null on a first run. */
|
|
53
|
+
current: Config | null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function hasRepoBelow(dir: string): boolean {
|
|
57
|
+
try {
|
|
58
|
+
return readdirSync(dir, { withFileTypes: true }).some(c => c.isDirectory() && existsSync(join(dir, c.name, ".git")));
|
|
59
|
+
} catch {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function workRoots(home: string): string[] {
|
|
65
|
+
return readdirSync(home, { withFileTypes: true })
|
|
66
|
+
.filter(d => d.isDirectory() && !d.name.startsWith("."))
|
|
67
|
+
.map(d => join(home, d.name))
|
|
68
|
+
.filter(hasRepoBelow)
|
|
69
|
+
.toSorted();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function detect(seams: SetupSeams): SetupFacts {
|
|
73
|
+
// env {} so a live QUEUE_* override never leaks into what setup proposes.
|
|
74
|
+
const cfg = loadConfig({ home: seams.home, env: {} });
|
|
75
|
+
const current = existsSync(configFile(seams.home)) ? cfg : null;
|
|
76
|
+
const os = seams.os;
|
|
77
|
+
// Without a config.yml, loadConfig returns the shipped template, so its machine values are the defaults.
|
|
78
|
+
const proposed: MachineProposal = current
|
|
79
|
+
? { load_over_cores: cfg.machine.load_over_cores, avail_min_mb: cfg.machine.avail_min_mb, disk_min_gb: cfg.machine.disk_min_gb }
|
|
80
|
+
: {
|
|
81
|
+
load_over_cores: cfg.machine.load_over_cores,
|
|
82
|
+
avail_min_mb: Math.max(1024, Math.round(os.ramMb * 0.1)),
|
|
83
|
+
disk_min_gb: Math.max(1, Math.min(cfg.machine.disk_min_gb, Math.floor(os.diskFreeGb * 0.1))),
|
|
84
|
+
};
|
|
85
|
+
return {
|
|
86
|
+
workRoots: workRoots(seams.home),
|
|
87
|
+
harnesses: seams.harnesses.filter(h => seams.onPath(h.bin)).map(h => h.name),
|
|
88
|
+
tailscale: { state: seams.tailscale.state(), logins: seams.tailscale.logins() },
|
|
89
|
+
secretgate: seams.onPath(PROXY_BIN),
|
|
90
|
+
machine: os,
|
|
91
|
+
proposed,
|
|
92
|
+
current,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function binOnPath(bin: string, env: NodeJS.ProcessEnv): boolean {
|
|
97
|
+
for (const dir of (env.PATH ?? "").split(":")) {
|
|
98
|
+
if (dir === "") continue;
|
|
99
|
+
try {
|
|
100
|
+
if (statSync(join(dir, bin)).isFile()) return true;
|
|
101
|
+
} catch {}
|
|
102
|
+
}
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** The production seams: node fs/os, the given PATH, realTailscale. */
|
|
107
|
+
export function realSeams(harnesses: HarnessBin[], home: string = homedir(), env: NodeJS.ProcessEnv = process.env): SetupSeams {
|
|
108
|
+
const st = statfsSync(home);
|
|
109
|
+
return {
|
|
110
|
+
home,
|
|
111
|
+
onPath: bin => binOnPath(bin, env),
|
|
112
|
+
harnesses,
|
|
113
|
+
tailscale: realTailscale,
|
|
114
|
+
os: {
|
|
115
|
+
cores: availableParallelism(),
|
|
116
|
+
ramMb: totalmem() / 1024 / 1024,
|
|
117
|
+
diskFreeGb: (Number(st.bavail) * Number(st.bsize)) / 1e9,
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
}
|
package/src/core/tailscale.ts
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
import { spawnSync } from "node:child_process";
|
|
6
6
|
|
|
7
|
+
export type TailscaleState = "missing" | "stopped" | "running";
|
|
8
|
+
|
|
7
9
|
export interface Tailscale {
|
|
8
10
|
/** This machine's tailnet IPv4 address (first line of `tailscale ip -4`), or null when tailscale fails or answers nothing. */
|
|
9
11
|
ip4(): string | null;
|
|
@@ -13,6 +15,8 @@ export interface Tailscale {
|
|
|
13
15
|
whois(peer: string): string | null;
|
|
14
16
|
/** Every `User[*].LoginName` of `tailscale status --json`, or null when tailscale fails or the answer is unreadable — callers then skip their login check with a printed warning, never refuse on a tailscale failure. */
|
|
15
17
|
logins(): string[] | null;
|
|
18
|
+
/** `missing` when the binary does not exist; `stopped` when it is installed but `tailscale status --json` fails, answers unreadably, or its BackendState is not "Running"; else `running`. */
|
|
19
|
+
state(): TailscaleState;
|
|
16
20
|
}
|
|
17
21
|
|
|
18
22
|
function firstStdoutLine(args: string[]): string | null {
|
|
@@ -33,6 +37,16 @@ export function parseWhoisLogin(stdout: string): string | null {
|
|
|
33
37
|
}
|
|
34
38
|
}
|
|
35
39
|
|
|
40
|
+
/** `running` only when `BackendState` of `tailscale status --json` is "Running"; unreadable JSON or any other state is `stopped`. */
|
|
41
|
+
export function parseBackendState(stdout: string): "running" | "stopped" {
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(stdout) as { BackendState?: unknown };
|
|
44
|
+
return parsed.BackendState === "Running" ? "running" : "stopped";
|
|
45
|
+
} catch {
|
|
46
|
+
return "stopped";
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
36
50
|
export const realTailscale: Tailscale = {
|
|
37
51
|
ip4() {
|
|
38
52
|
return firstStdoutLine(["ip", "-4"]);
|
|
@@ -70,4 +84,10 @@ export const realTailscale: Tailscale = {
|
|
|
70
84
|
return null;
|
|
71
85
|
}
|
|
72
86
|
},
|
|
87
|
+
state() {
|
|
88
|
+
const r = spawnSync("tailscale", ["status", "--json"], { encoding: "utf8", timeout: 8000 });
|
|
89
|
+
if (r.error) return (r.error as NodeJS.ErrnoException).code === "ENOENT" ? "missing" : "stopped";
|
|
90
|
+
if (r.status !== 0) return "stopped";
|
|
91
|
+
return parseBackendState(r.stdout ?? "");
|
|
92
|
+
},
|
|
73
93
|
};
|