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 CHANGED
@@ -58,8 +58,16 @@ omp -p "say hi" # plain omp: no neurastream hook, no guard-log line
58
58
 
59
59
  ## Install
60
60
 
61
+ `neurastream setup` is the one-command path: it detects this machine (harness, Tailscale, machine, secrets), asks the settings in groups with the detected values as defaults, installs the adapter, runs `doctor`, and prints `Next: neurastream main` when it passes. `--yes` takes the detected settings without asking.
62
+
61
63
  ```sh
62
64
  bun add -g neurastream
65
+ neurastream setup
66
+ ```
67
+
68
+ The manual path, if you want each step yourself:
69
+
70
+ ```sh
63
71
  neurastream init
64
72
  neurastream adapter install omp
65
73
  neurastream doctor
@@ -250,6 +258,29 @@ watch:
250
258
  interval_min: 15 # minutes between watcher runs
251
259
  ```
252
260
 
261
+ ## Several Mains
262
+
263
+ You can run more than one Main at a time on the same queue. Each one claims the plans it works on, and no other Main can touch a claimed plan while the claim is live. Start each with its own name:
264
+
265
+ ```sh
266
+ neurastream main --name a # terminal 1
267
+ neurastream main --name b # terminal 2
268
+ ```
269
+
270
+ Names match `[a-z0-9-]{1,24}`; plain `neurastream main` is named `main`. A second launcher with the same name refuses (`Main a is already running`) — the running lock under `<queue_state>/mains/<id>/` is freed by the kernel when the launcher dies, so a crash leaves nothing to clean up.
271
+
272
+ What each Main keeps for itself, under `<queue_state>/mains/<id>/`:
273
+
274
+ - its claims: a spawn on a plan claims it for this Main first, and another Main's live claim refuses the launch with `plan <file> is held by Main <id> since HH:MM` (a Main's own plan edit, tick, close or push is gated the same way) — two Mains racing for one plan get exactly one winner;
275
+ - its owner-inbox cursor (`inbox-cursor`): a message you send starting `@<id> ` goes only to that Main, anything else reaches all running Mains, and `@<id>` naming a Main that is not running is refused (`Main b is not running; running: a`) before anything is stored;
276
+ - its rollover notes (`rollover/`) and edit-window state (`edit-window.json`).
277
+
278
+ Who holds what: the queue summary, `neurastream main-start` and the phone page flag every plan `held by <id> since HH:MM` or `free`, and queue cards carry the holder chip. `neurastream claim list` prints the live claims, `neurastream claim next` claims the highest free plan by the queue's own order, and `neurastream claim release <plan>` frees your Main's own claim.
279
+
280
+ The 30-minute rule: a claim lives by its heartbeat — the adapter beats every claim its Main holds once a minute while that session lives. When a Main dies (crash, kill, closed terminal), the beats stop and a claim whose last beat is `queue.claim_ttl_min` (default 30) minutes old is free; the next Main to spawn on that plan takes it. A session that shuts down releases nothing — the TTL is what frees a dead Main's claims (closing a plan the normal way, with `queue-close`, frees the closer's own claim). To free another Main's live claim sooner there is `neurastream claim release <plan> --force` — refused for every agent by the guard; that is the owner's move, in a terminal.
281
+
282
+ Claim heartbeats are not the job heartbeats of the watch section above. A job heartbeat says a cron job ran (`<queue_state>/heartbeats/<name>.json`, stale per `watch.expect`); a claim heartbeat is per-Main liveness recorded in the claim itself, under `<queue_state>/claims/` — one JSON file per plan, its `beat` refreshed every minute. Claims are never wired into `watch`.
283
+
253
284
  ## Secrets never reach the chat
254
285
 
255
286
  A value the machine holds is hidden before the model, the chat and the session log see it (`src/core/secret-redact.ts`, plan 20261025_2204, incident I-20261025-197). Detection is by **content**, not by file name — the old name list never knew about `~/.npmrc`.
@@ -284,17 +315,11 @@ Then set `secrets.proxy: secretgate` and restart Main: `neurastream main` starts
284
315
 
285
316
  ## Provider rate limits
286
317
 
287
- When a Main turn ends on a provider rate limit, neurastream waits it out instead of asking again straight into the limit. The stop guard sees the turn's error text, matches it against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive) and, on a hit, allows the stop without consulting the normal stop rules or touching the idle-stop counters. The chat channels get one post per episode — `⏳ Main is rate limited by its provider until HH:MM (local); it resumes on its own.` — and exactly one resume timer is armed (replacing any earlier one). When the wait is over, the plugin gives Main a new turn: `main-guard: the provider rate limit is over (waited until HH:MM). Continue the queue where you stopped.`, and the guard log carries the whole story:
288
-
289
- ```
290
- RATE-LIMIT stop: resume at 08:12 (35s, attempt 1)
291
- notify: posted (rate-limit)
292
- RATE-LIMIT resume: new turn sent (waited until 08:12)
293
- ```
318
+ When a Main turn ends on a provider rate limit, the stop guard matches the turn's error text against `guards.rate_limit.patterns` (default `["429", "rate_limit", "rate limit", "overloaded", "529"]`, case-insensitive), allows the stop without consulting the normal stop rules, and one episode opens. The chat channels get the first of exactly two posts: `⏳ Main hit its limit at HH:MM; resets at HH:MM` when the error text names a reset — a `retry-after-ms=<ms>` or `retry-after: <seconds>` the provider appended, or a timestamp it printed — or `⏳ Main hit its limit at HH:MM; checking every 5 min` when it names none.
294
319
 
295
- The wait is the `retry-after-ms=<ms>` or `retry-after: <seconds>` the error text names (omp appends the provider's header to the error message), else `default_wait_s` (300). A turn the resume started that ends on a limit again is the same episode at attempt 2: named retry-after values remain unchanged; only the default wait doubles, no second post. Any turn that ends without a limit ends the episode and disarms the timer. Every wait is clamped to `max_wait_s` (3600) before `slack_s` (15) is added on top. Your own message takes over and cancels the resume (`RATE-LIMIT resume cancelled: owner message`) when it starts a turn; a slash command or a handled input such as a chat unlock leaves the resume armed. A rate-limited deferred hand-back (an `agent_end` while an async job is pending) arms the same timer instead of logging "no reply text". The words and the waits live in `config.yml` (`guards.rate_limit`, `docs/config.md`); turns that did not end on a rate limit are unaffected.
320
+ A named reset is waited out (`slack_s`, default 15, added on top). An unnamed one is probed: a detached child runs `guards.rate_limit.probe_cmd` (default `omp -p --no-extensions --no-session --model {model} 'reply ok'`; `{model}` is replaced by the shell-quoted model, exit 0 = the provider answered) every `probe_interval_s` (default 300), killing any probe that runs longer than `probe_timeout_s` (default 90) — a killed or failing probe counts as still limited — up to `max_probes` (default 288 = 24 h at one probe per 5 min). When the named reset passes or a probe gets through, the plugin gives Main a new turn — `main-guard: the provider limit is over (back at HH:MM). Continue the queue where you stopped.` — and posts `✅ Main is back at HH:MM (limited N min, M checks)`; when `max_probes` is spent without an answer it posts `⚠ Main still limited after 24 h` once and closes the episode. Each finished episode appends one `{type: "limit", since, back_at, minutes, probes, reset_named}` metric, and the weekly report shows it as "Main limited: N h over K episodes". Posts, metric and report carry times and counts only, never the provider's error text.
296
321
 
297
- omp retries a 429 itself while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what neurastream waits out.
322
+ Your own message takes over and cancels the wait (`RATE-LIMIT tick cancelled: owner message (probe count kept)`) when it starts a turn; a slash command or a handled input such as a chat unlock leaves it armed. A rate-limited deferred hand-back does not open a second episode. omp itself retries a 429 while the provider's wait fits its `retry.maxDelayMs` (300000 ms by default); only a longer wait ends the turn (`Retry failed after 1 attempts: Provider requested 731000ms wait, exceeds retry.maxDelayMs`), and that turn end is what opens the episode.
298
323
 
299
324
  ## Provider reset times
300
325
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.2.65",
3
+ "version": "0.2.67",
4
4
  "description": "Guardrails for running many AI coding agents at once: plan queue, blockers, call budgets, provider caps, scoring, merge-verified close.",
5
5
  "keywords": [
6
6
  "ai-agents",
@@ -11,6 +11,8 @@ import { ompAdapter } from "./omp/adapter.ts";
11
11
 
12
12
  export interface HarnessAdapter {
13
13
  name: string;
14
+ /** The command the harness runs; setup checks it is on PATH. */
15
+ bin: string;
14
16
  /** Session reader: the runs and the main session (docs/adapter.md). */
15
17
  runSource(cfg: Config): RunSource;
16
18
  /** Completed subagent task-results announced in the newest main session file. */
@@ -53,3 +55,8 @@ export function getAdapter(cfg?: Pick<Config, "harness">): HarnessAdapter {
53
55
  if (!adapter) throw new Error(`unknown harness "${name}"; known: ${Object.keys(ADAPTERS).join(", ")}`);
54
56
  return adapter;
55
57
  }
58
+
59
+ /** Every registered harness with the command it runs (setup checks those are on PATH). */
60
+ export function harnessBins(): Pick<HarnessAdapter, "name" | "bin">[] {
61
+ return Object.values(ADAPTERS);
62
+ }
@@ -10,6 +10,7 @@ import { dumpModel, dumpParts, dumpPromptTokens, ompDumps, ompScoreTraces, ompTr
10
10
 
11
11
  export const ompAdapter: HarnessAdapter = {
12
12
  name: "omp",
13
+ bin: "omp",
13
14
  runSource: defaultRunSource,
14
15
  completedResults: defaultCompletedResults,
15
16
  scoreTraces: ompScoreTraces,
@@ -220,9 +220,11 @@ export function doctorReport(home: string, env: NodeJS.ProcessEnv = process.env,
220
220
  // The owner page (plan 20261024_2230): when it is switched on, the login must be set and
221
221
  // tailscale must answer, or the unit will start and refuse, or serve nobody.
222
222
  if (cfg.ui.enabled) {
223
+ const state = tailscale.state();
224
+ if (state === "running") ok.push("tailscale: ok");
225
+ else problems.push(`tailscale: ${state === "missing" ? "missing" : "logged out"}`);
223
226
  if (!cfg.ui.owner_login) problems.push("ui.enabled but ui.owner_login is empty");
224
- else if (tailscale.ip4() === null) problems.push("ui.enabled but tailscale does not answer (tailscale ip -4)");
225
- else ok.push(`ui owner page: login ${cfg.ui.owner_login}`);
227
+ else if (state === "running") ok.push(`ui owner page: login ${cfg.ui.owner_login}`);
226
228
  }
227
229
  // One index (20261024_1400_one_index): repo-directory lines in the main index are the old
228
230
  // two-level queue; the plans they hold are invisible to queue-check until migrate folds them.
@@ -30,7 +30,9 @@ import { runDetectors, type DetectorInput } from "../../core/incident-detectors.
30
30
  import { fileClaimStore } from "../../core/claims.ts";
31
31
  import { appendOwnerAnswer, readOwnerAnswers, readOwnerMessages } from "../../core/incidents.ts";
32
32
  import { checkInject, checkPlanEdit, checkStop, checkTool, findingsValue, MAIN_PLAN_FILE, mainId, mainStateDir, newProgressEntries, planReadNote, recordMainResult, resetMainCalls, revertMainEdit, rekeySpawnFile, reviewSpawnEnd, STOP_PLAN_OFFER_REFUSAL } from "../../core/guards.ts";
33
- import { rateLimitWait } from "../../core/rate-limit.ts";
33
+ import { rateLimited } from "../../core/rate-limit.ts";
34
+ import { backPost, clearLimitState, limitMetric, limitedPost, onLimited, readLimitState, timingOf, writeLimitState } from "../../core/limit-probe.ts";
35
+ import { appendMetric } from "../../core/metrics.ts";
34
36
  import { notifyProviders, ownerAnswerHandback, ownerAnswerSteer, postReply } from "../../core/notify.ts";
35
37
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../../core/secret-redact.ts";
36
38
  import { inboxPath } from "../../core/owner-ui.ts";
@@ -40,7 +42,7 @@ import { actionsRules, ownedRepoOf, suspiciousActions, unreportedFindings } from
40
42
  import { applyQueueEnv } from "../../core/queue/env.ts";
41
43
  import { mainDetectors, mainStartText } from "../../core/main-start.ts";
42
44
 
43
- import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, withUnanswered, type RolloverState } from "../../core/rollover.ts";
45
+ import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, unansweredOwnerMessages, type RolloverState } from "../../core/rollover.ts";
44
46
  import { defaultCompletedResults, defaultRunSource, runIdOf } from "./sessions.ts";
45
47
  import { adapterLog, MAIN_ENV } from "./launch.ts";
46
48
  import { parseTraceFile } from "./traces.ts";
@@ -76,6 +78,7 @@ interface HostCtx {
76
78
  id?: string;
77
79
  cwd?: string;
78
80
  setInterval?: (cb: () => void, ms: number) => unknown;
81
+ spawnLimitProbe?: () => void;
79
82
  }
80
83
 
81
84
  function asRecord(v: unknown): Record<string, unknown> {
@@ -139,6 +142,9 @@ function asCtx(v: unknown): HostCtx {
139
142
  // Harness-injected timer with the original main-guard signature (ctx.setInterval).
140
143
  const interval = r.setInterval as ((cb: () => void, ms: number) => unknown) | undefined;
141
144
  if (typeof interval === "function") out.setInterval = interval;
145
+ // Harness-injected probe spawner (tests); the default starts the niced probe child.
146
+ const probe = r.spawnLimitProbe as (() => void) | undefined;
147
+ if (typeof probe === "function") out.spawnLimitProbe = probe;
142
148
  return out;
143
149
  }
144
150
 
@@ -353,14 +359,18 @@ function recordProviderOutFromTask(e: Record<string, unknown>, content: unknown[
353
359
  adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (task result)`);
354
360
  }
355
361
 
356
- /** Rate-limited turn end: record the reset time the error text names, else the armed wait. */
357
- function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): void {
358
- const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
359
- if (!provider) return;
362
+ /** Rate-limited turn end: record the reset time the error text names, else the armed wait. Returns the
363
+ * named reset in epoch ms (null when the text names none): the one parse of that text, which the call
364
+ * site passes on to the rate-limit episode (plan 20261027_1500 P2/P3). */
365
+ export function recordProviderOutFromRateLimit(reply: EventReply | null, untilMs: number, cfg: Config): number | null {
360
366
  const named = reply ? resetEpochFromText(reply.errorMessage ?? "", resetRule(cfg)) : null;
361
- const epoch = named ?? Math.floor(untilMs / 1000);
362
- recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
363
- adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
367
+ const provider = reply?.provider ?? providerOfModel(reply?.model ?? null);
368
+ if (provider) {
369
+ const epoch = named ?? Math.floor(untilMs / 1000);
370
+ recordOut(cfg, provider, epoch, named !== null ? "rate-limit-reset" : "rate-limit");
371
+ adapterLog(cfg, `PROVIDER-OUT recorded: ${provider} out until ${new Date(epoch * 1000).toISOString()} (${named !== null ? "reset time in error text" : "rate limit, no reset time"})`);
372
+ }
373
+ return named === null ? null : named * 1000;
364
374
  }
365
375
 
366
376
  // Session rollover helpers: the harness context read through runtime checks, and the file size and
@@ -595,6 +605,15 @@ export function deliverOwnerInbox(pi: ExtensionHost, cfg: Config): void {
595
605
 
596
606
  /** The most recently registered createOmpAdapter cleanup, for the exported reset(). */
597
607
  let activeAdapterReset: (() => void) | null = null;
608
+ /** The limit tick: one check of the open episode every 30 s (plan 20261027_1500 P3). */
609
+ const LIMIT_TICK_MS = 30_000;
610
+ /** One limit probe as a niced child (cli/limit-probe.ts). It writes the episode state itself;
611
+ * a failed start is logged and the next tick tries again. */
612
+ function spawnLimitProbeChild(cfg: Config): void {
613
+ const child = spawn("nice", ["-n", "19", process.execPath, join(import.meta.dir, "../../cli/limit-probe.ts")], { detached: true, stdio: "ignore", env: process.env });
614
+ child.on("error", err => adapterLog(cfg, `RATE-LIMIT probe: could not start: ${err.message}`));
615
+ child.unref();
616
+ }
598
617
  /** Register the guard handlers on one extension host. `initial` is injectable for tests; `freshConfig` re-reads the config per guarded call. */
599
618
  export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig: () => Config = () => initial): void {
600
619
  // Guarded handlers take `cfg = freshConfig()` first, so an edited config.yml reaches the next call (P4e).
@@ -643,24 +662,25 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
643
662
  // emits (sessionStopWillContinue) consumes it and posts nothing — a blocked stop's reply is a
644
663
  // mid-work report, never a hand-back.
645
664
  let stopBlocked = false;
646
- // Rate-limit wait-it-out (plan 20261025_0640): consecutive turn ends on a provider rate limit
647
- // form one episode. Named provider retry-after values remain authoritative; otherwise the
648
- // attempt doubles the default wait. The owner chat is told once per episode, and ONE timer
649
- // gives Main a new turn when the wait is over; a new Main turn before expiry takes over and
650
- // cancels it. Inputs that do not start a turn leave it armed. Any turn that ends without a
651
- // limit resets the episode and disarms it.
652
- let rateAttempt = 0;
653
- let rateTimer: NodeJS.Timeout | null = null;
665
+ // Rate-limit probe loop (plan 20261027_1500 P3). A limited turn end opens one episode in
666
+ // main-limit.json: a named reset is waited for; otherwise a niced probe child runs every
667
+ // probe_interval_s until one gets through or max_probes is spent. ONE tick (LIMIT_TICK_MS)
668
+ // reads the episode: it spawns a due probe, or, once the provider is back, sends Main ONE new
669
+ // turn. A new Main turn cancels the tick and keeps the episode (probe count kept); a turn that
670
+ // ends without a limit clears it.
671
+ let limitTickArmed = false;
672
+ let limitTick: NodeJS.Timeout | null = null;
654
673
  const rateClock = (ms: number): string => strftime(ms / 1000, "%H:%M");
655
- const clearRateTimer = (): void => {
656
- if (rateTimer !== null) {
657
- clearTimeout(rateTimer);
658
- rateTimer = null;
674
+ const stopLimitTick = (): void => {
675
+ limitTickArmed = false;
676
+ if (limitTick !== null) {
677
+ clearInterval(limitTick);
678
+ limitTick = null;
659
679
  }
660
680
  };
661
681
  const disarmRateEpisode = (): void => {
662
- clearRateTimer();
663
- rateAttempt = 0;
682
+ stopLimitTick();
683
+ clearLimitState(cfg);
664
684
  };
665
685
  // P5b: a real turn end answers every owner message it followed — the answer (the turn's own
666
686
  // reply, the page's lastAnswerFor shape) rides the same owner-message store. Rate-limited,
@@ -673,32 +693,69 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
673
693
  adapterLog(cfg, `OWNER-ANSWER record failed: ${err instanceof Error ? err.message : String(err)}`);
674
694
  }
675
695
  };
676
- // The one resume: replacing any armed timer, exactly one new user message when the wait is over.
677
- const armRateResume = (untilMs: number): void => {
678
- clearRateTimer();
679
- rateTimer = setTimeout(() => {
680
- rateTimer = null;
681
- // P5b: whichever resume text exists, it quotes owner messages no turn has answered.
682
- pi.sendUserMessage(withUnanswered(`main-guard: the provider rate limit is over (waited until ${rateClock(untilMs)}). Continue the queue where you stopped.`, readOwnerMessages(), readOwnerAnswers()));
683
- adapterLog(cfg, `RATE-LIMIT resume: new turn sent (waited until ${rateClock(untilMs)})`);
684
- }, untilMs - Date.now());
696
+ const limitTickFire = (c: HostCtx): void => {
697
+ if (!limitTickArmed) return;
698
+ const state = readLimitState(cfg);
699
+ if (state === null) {
700
+ stopLimitTick();
701
+ adapterLog(cfg, "RATE-LIMIT give up: episode state gone (max_probes spent or unreadable)");
702
+ return;
703
+ }
704
+ const now = Date.now();
705
+ if (state.back_at !== null) {
706
+ if (now < state.back_at) return;
707
+ stopLimitTick();
708
+ clearLimitState(cfg);
709
+ // P4: the finished episode is recorded once and the owner hears one back post; both are
710
+ // times and counts only — the episode's last_error never reaches chat or ledger.
711
+ appendMetric(cfg, limitMetric(state, now));
712
+ adapterLog(cfg, `RATE-LIMIT back: provider limit over (back at ${rateClock(state.back_at)}); new turn sent`);
713
+ void postReply(backPost(state), cfg).then(results => {
714
+ for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
715
+ });
716
+ pi.sendUserMessage(`main-guard: the provider limit is over (back at ${rateClock(state.back_at)}). Continue the queue where you stopped.`);
717
+ return;
718
+ }
719
+ if (now < state.next_probe_at) return;
720
+ (c.spawnLimitProbe ?? (() => spawnLimitProbeChild(cfg)))();
721
+ };
722
+ const armLimitTick = (c: HostCtx): void => {
723
+ stopLimitTick();
724
+ limitTickArmed = true;
725
+ const t: unknown = c.setInterval ? c.setInterval(() => limitTickFire(c), LIMIT_TICK_MS) : setInterval(() => limitTickFire(c), LIMIT_TICK_MS);
726
+ if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
727
+ limitTick = t as NodeJS.Timeout;
685
728
  };
686
- // A turn that ended on a rate limit: log, tell the owner once per episode, arm the resume.
687
- const onRateLimitedStop = (untilMs: number, waitMs: number): void => {
688
- rateAttempt++;
689
- const at = rateClock(untilMs);
690
- adapterLog(cfg, `RATE-LIMIT stop: resume at ${at} (${Math.round(waitMs / 1000)}s, attempt ${rateAttempt})`);
691
- if (rateAttempt === 1) {
729
+ // A turn that ended on a provider rate limit: the episode opens (or continues with its probe
730
+ // count), the owner chat hears once per episode, and the tick takes over.
731
+ const onRateLimitedStop = (c: HostCtx, namedResetMs: number | null, errorText: string, model: string): void => {
732
+ const prev = readLimitState(cfg);
733
+ const timing = timingOf(cfg);
734
+ const state = onLimited(prev, namedResetMs, errorText, Date.now(), model, timing);
735
+ try {
736
+ writeLimitState(cfg, state);
737
+ } catch (err) {
738
+ adapterLog(cfg, `RATE-LIMIT state write failed: ${err instanceof Error ? err.message : String(err)}`);
739
+ return;
740
+ }
741
+ adapterLog(cfg, `RATE-LIMIT stop: ${state.reset_named ? "named reset" : "probe"} at ${rateClock(state.next_probe_at)} (probes ${state.probes} of ${timing.max_probes})`);
742
+ if (prev === null) {
692
743
  adapterLog(cfg, "notify: posted (rate-limit)");
693
- void postReply(`⏳ Main is rate limited by its provider until ${at} (local); it resumes on its own.`, cfg).then(results => {
744
+ void postReply(limitedPost(state, timing.probe_interval_s), cfg).then(results => {
694
745
  for (const r of results) if (!r.posted) adapterLog(cfg, `notify: ${r.provider}: ${r.error}`);
695
746
  });
696
747
  }
697
- armRateResume(untilMs);
748
+ armLimitTick(c);
749
+ };
750
+ // The rate-limit decision for one turn end, from the event's own last assistant message. The
751
+ // untilMs is the fallback wait recorded with PROVIDER-OUT when the error text names no reset.
752
+ const rateLimitOf = (reply: EventReply | null): { untilMs: number } | null => {
753
+ const rl = cfg.guards.rate_limit;
754
+ const hit = rateLimited(reply?.stopReason ?? null, reply?.errorMessage ?? null, rl);
755
+ if (!hit) return null;
756
+ const waitMs = (hit.retryAfterMs ?? rl.probe_interval_s * 1000) + rl.slack_s * 1000;
757
+ return { untilMs: Date.now() + waitMs };
698
758
  };
699
- // The rate-limit decision for one turn end, from the event's own last assistant message.
700
- const rateLimitOf = (reply: EventReply | null): { untilMs: number; waitMs: number } | null =>
701
- rateLimitWait(reply?.stopReason ?? null, reply?.errorMessage ?? null, Date.now(), cfg.guards.rate_limit, rateAttempt + 1);
702
759
  // One guard-log line per notify decision: `notify: posted|skipped (<why>)`. Fire-and-forget:
703
760
  // the decision never awaits the post; a failed or slow post logs one line and never blocks
704
761
  // or retries.
@@ -871,9 +928,9 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
871
928
  const content = unhanded(asString(c.id) || "sub", plans.find(file => prompt.includes(file)) ?? null);
872
929
  return content ? { message: { customType: "main-guard.rules", content, display: false } } : undefined;
873
930
  }
874
- if (rateTimer !== null) {
875
- clearRateTimer();
876
- adapterLog(cfg, "RATE-LIMIT resume cancelled: owner message");
931
+ if (limitTickArmed) {
932
+ stopLimitTick();
933
+ adapterLog(cfg, "RATE-LIMIT tick cancelled: owner message (probe count kept)");
877
934
  }
878
935
  const d = checkInject({ inject: prompt, agent: "main" }, cfg);
879
936
  callsSinceStop = d.state?.callsSinceStop ?? callsSinceStop;
@@ -1133,13 +1190,14 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1133
1190
  const rl = rateLimitOf(reply);
1134
1191
  if (rl) {
1135
1192
  // Who is rate-limited is live data (plan 20261025_1700 P1): the error text's own reset
1136
- // time, else the armed wait. Best effort — a failed write never changes the stop.
1193
+ // time, else the fallback wait. Best effort — a failed write never changes the stop.
1194
+ let named: number | null = null;
1137
1195
  try {
1138
- recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1196
+ named = recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1139
1197
  } catch (err) {
1140
1198
  adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1141
1199
  }
1142
- onRateLimitedStop(rl.untilMs, rl.waitMs);
1200
+ onRateLimitedStop(c, named, reply?.errorMessage ?? "", reply?.model ?? "");
1143
1201
  return undefined;
1144
1202
  }
1145
1203
  // Any turn that ends without a rate limit ends the episode and disarms its resume timer.
@@ -1302,7 +1360,10 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1302
1360
  };
1303
1361
  // Clear the previous adapter's armed grace timer before this one overwrites the pointer (P3c).
1304
1362
  activeAdapterReset?.();
1305
- activeAdapterReset = clearRolloverState;
1363
+ activeAdapterReset = (): void => {
1364
+ clearRolloverState();
1365
+ stopLimitTick();
1366
+ };
1306
1367
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
1307
1368
  // shuts down only after the file is written. A failed write keeps the session running.
1308
1369
  // Returns whether the request was written.
@@ -1395,12 +1456,20 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
1395
1456
  }
1396
1457
  const reply = lastAssistantIn(asRecord(e).messages);
1397
1458
  // The same rate-limit check as session_stop (plan 20261025_0640): a rate-limited deferred
1398
- // hand-back arms the resume timer instead of logging "no reply text" — its reply carries an
1459
+ // hand-back opens the episode instead of logging "no reply text" — its reply carries an
1399
1460
  // error, no text. A mid-run continuation (tool calls, auto-retry) is not a turn end: the
1400
1461
  // episode state stays as it is.
1401
1462
  const rl = rateLimitOf(reply);
1402
1463
  if (rl) {
1403
- onRateLimitedStop(rl.untilMs, rl.waitMs);
1464
+ // The same one parse as session_stop (plan 20261027_1500 P1/P3): the error text's own
1465
+ // reset time, else the fallback wait. Best effort — a failed write never changes the stop.
1466
+ let named: number | null = null;
1467
+ try {
1468
+ named = recordProviderOutFromRateLimit(reply, rl.untilMs, cfg);
1469
+ } catch (err) {
1470
+ adapterLog(cfg, `PROVIDER-OUT record failed: ${err instanceof Error ? err.message : String(err)}`);
1471
+ }
1472
+ onRateLimitedStop(asCtx(ctx), named, reply?.errorMessage ?? "", reply?.model ?? "");
1404
1473
  return;
1405
1474
  }
1406
1475
  const jobCount = asRolloverCtx(ctx)?.runningJobs().length ?? 0;
@@ -0,0 +1,56 @@
1
+ // `neurastream config set|get|list <key> [value]` (plan 20261028_2356 P1b): the non-interactive door
2
+ // to the generic config editor (src/core/config-edit.ts). Keys are the leaf paths of
3
+ // templates/config.yml, so a typo is refused and never written. A set writes through the same
4
+ // line-based editor and is refused, with the file untouched, when the result would not load.
5
+
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
+ import { homedir } from "node:os";
8
+ import { dirname } from "node:path";
9
+ import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../core/config-edit.ts";
10
+ import { TEMPLATE_PATH, configFile, loadConfig } from "../core/config.ts";
11
+
12
+ const VALID_KEYS = leafKeys(Bun.YAML.parse(readFileSync(TEMPLATE_PATH, "utf8")));
13
+
14
+ export function runConfigKeys(args: string[], home: string = homedir()): number {
15
+ const [verb, key, raw] = args;
16
+ try {
17
+ if (verb === "list") {
18
+ const cfg = loadConfig({ home });
19
+ for (const k of VALID_KEYS) {
20
+ const v = valueAt(cfg, k);
21
+ console.log(`${k} = ${Array.isArray(v) ? JSON.stringify(v) : String(v)}`);
22
+ }
23
+ return 0;
24
+ }
25
+ if (key === undefined || !VALID_KEYS.includes(key)) {
26
+ console.error(`neurastream config ${verb ?? ""}: unknown key ${key ?? "(none)"}; valid keys: ${VALID_KEYS.join(", ")}`);
27
+ return 1;
28
+ }
29
+ if (verb === "get") {
30
+ const v = valueAt(loadConfig({ home }), key);
31
+ console.log(Array.isArray(v) ? JSON.stringify(v) : String(v));
32
+ return 0;
33
+ }
34
+ if (verb !== "set") {
35
+ console.error("usage: neurastream config set|get|list [key] [value]");
36
+ return 1;
37
+ }
38
+ const parsed: unknown = raw === undefined ? null : Bun.YAML.parse(raw);
39
+ if (parsed === null || parsed === undefined || (typeof parsed === "object" && !Array.isArray(parsed))) {
40
+ console.error(`neurastream config set ${key}: give a scalar or a list (e.g. 7788, true, '["a", "b"]')`);
41
+ return 1;
42
+ }
43
+ // Lists in flow style on one line ([a, b]); scalars as JSON, which is valid YAML.
44
+ const text = yamlValue(parsed);
45
+ const file = configFile(home);
46
+ const original = existsSync(file) ? readFileSync(file, "utf8") : null;
47
+ const edited = setConfigKeys(original, { [key]: text });
48
+ if (!checkEdited(edited, home, (line) => console.error(line))) return 1;
49
+ mkdirSync(dirname(file), { recursive: true });
50
+ writeFileSync(file, edited);
51
+ return 0;
52
+ } catch (err) {
53
+ console.error(err instanceof Error ? err.message : String(err));
54
+ return 1;
55
+ }
56
+ }
@@ -15,11 +15,13 @@ import { applyQueueEnv } from "../core/queue/env.ts";
15
15
  import { getAdapter } from "../adapters/index.ts";
16
16
  import { GUARD_USAGE, runGuard } from "./guard.ts";
17
17
  import { runInit } from "./init.ts";
18
+ import { realSetupDeps, runSetup } from "./setup.ts";
18
19
  import { PORTED, runMain, runPorted } from "./commands.ts";
19
20
  import { runMetrics } from "./metrics.ts";
20
21
  import { runIncident } from "./incident.ts";
21
22
  import { runTraces } from "./traces.ts";
22
23
  import { runUi } from "./ui.ts";
24
+ import { runConfigKeys } from "./config-set.ts";
23
25
  import { runDiagram } from "./diagram.ts";
24
26
  import { runNotes } from "./notes.ts";
25
27
  import { runPages } from "./pages.ts";
@@ -63,6 +65,9 @@ export function helpText(): string {
63
65
  " create config, index, notes, blockers, queue template, state dirs",
64
66
  " (--agent-dir: keep an existing index/notes/blockers dir)",
65
67
  " (--allow a,b: subagents allowed to spawn; on a terminal init asks instead)",
68
+ " neurastream setup [--yes]",
69
+ " guided first run: detect this machine, ask in groups, install, doctor",
70
+ " (--yes: take the detected settings without asking)",
66
71
  " neurastream adapter install omp",
67
72
  " link the omp extension under this HOME",
68
73
  " neurastream uninstall [--purge] [--yes]",
@@ -84,6 +89,7 @@ export function helpText(): string {
84
89
  " move a listed plan to rank N; the index file itself is 0444,",
85
90
  " these two commands are the only agent writes to it",
86
91
  " neurastream config [--json] print the merged config (defaults + file + env)",
92
+ " neurastream config set|get|list <key> [value] read or write one key (ui.port, paths.work_roots, ...)",
87
93
  " neurastream guard <event> --json",
88
94
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
89
95
  " neurastream main [args] run omp under the launcher (automatic session rollover)",
@@ -137,6 +143,8 @@ export async function run(cmd: string, args: string[]): Promise<number> {
137
143
  if (cmd === "notes") return runNotes(args);
138
144
  if (cmd === "diagram") return runDiagram(args);
139
145
  if (cmd === "adapter") return getAdapter().install(args);
146
+ if (cmd === "setup") return runSetup(args, realSetupDeps(async () => runNotify(["test"])));
147
+ if (cmd === "config" && ["set", "get", "list"].includes(args[0] ?? "")) return runConfigKeys(args);
140
148
  if (cmd === "config") {
141
149
  try {
142
150
  const cfg = loadConfig();
package/src/cli/init.ts CHANGED
@@ -71,9 +71,11 @@ function configText(home: string, invoked: string, agentDir?: string): string {
71
71
  text = text.replace(AGENT_DIR_KEYS, (_m, key: string) => `${key}${yamlQuote(agent).slice(0, -1)}`);
72
72
  }
73
73
  const protectedPaths = [...installedBins(home, invoked), `${agent}/notes/`, `${agent}/blockers/`, `${agent}/queue/`];
74
- const list = [" protected:", ...protectedPaths.map(p => ` - ${yamlQuote(p)}`)].join("\n");
75
- if (!text.includes(" protected: []")) throw new Error("templates/config.yml has no protected placeholder");
76
- return text.replace(" protected: []", list);
74
+ const items = protectedPaths.map(p => ` - ${yamlQuote(p)}`);
75
+ const placeholder = /^ protected: \[\].*$/m;
76
+ if (!placeholder.test(text)) throw new Error("templates/config.yml has no protected placeholder");
77
+ // The header stays a bare ` protected:`: install, uninstall and the guards read it in that form.
78
+ return text.replace(placeholder, [" protected:", ...items].join("\n"));
77
79
  }
78
80
 
79
81
  function putFile(dest: string, body: string, mode: number, created: string[], unchanged: string[]): void {
@@ -162,7 +164,7 @@ export function printInit(result: InitResult): void {
162
164
  }
163
165
 
164
166
  /** One line from stdin, read synchronously; a terminal hands over a line at a time. */
165
- function askLine(prompt: string): string {
167
+ export function askLine(prompt: string): string {
166
168
  process.stdout.write(prompt);
167
169
  const buf = Buffer.alloc(4096);
168
170
  const n = readSync(0, buf, 0, buf.length, null);
@@ -0,0 +1,11 @@
1
+ // One tick of the main-agent limit probe (plan 20261027_1500, P3). The adapter spawns this detached
2
+ // every probe_interval_s while an episode is open; it runs at most one probe and exits. A give-up
3
+ // posts the ⚠ to the owner chat (P4), so the serial notify queue is drained before exit.
4
+
5
+ import { loadConfig } from "../core/config.ts";
6
+ import { probeStep } from "../core/limit-probe.ts";
7
+ import { notifyIdle } from "../core/notify.ts";
8
+
9
+ const cfg = loadConfig();
10
+ probeStep(cfg, Date.now());
11
+ await notifyIdle();