neurastream 0.1.17 → 0.1.19

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
@@ -103,9 +103,9 @@ In both modes:
103
103
 
104
104
  - A note counts only if it was written after the threshold was crossed and is at most one hour old.
105
105
  - The running plugin going stale counts as over the threshold too: at every check the adapter re-reads the `package.json` it was loaded from, and a different (or unreadable) version asks for the handoff note even below `rollover.max_session_mb`, naming both versions (`NEURASTREAM_PACKAGE_JSON` overrides the path it watches).
106
- - While a rollover is pending (no fresh note, or own jobs still running), Main cannot start new subagents: a `task` call is refused until the running jobs finish and the session rolls over.
106
+ - While a rollover is pending (no fresh note, own jobs still running, or the handoff is ready and waiting for idle), Main cannot start new subagents: a `task` call is refused until the running jobs finish and the session rolls over.
107
107
  - While own jobs (subagents included) are still running, the switch waits: a rollover would cancel them.
108
- - `/main-rollover <message>` does the same by hand. It refuses below the threshold, without a fresh note, or while jobs run.
108
+ - `/main-rollover <message>` does the same by hand. It refuses below the threshold, without a fresh note, or while jobs run. Under neurastream main it is refused and the owner's next message starts the rollover; in plain omp a second call while one waits adds its text to the same handoff.
109
109
  - `/main-rollover` shows a notice at once and gathers `main-start` in the background, so omp keeps repainting and reading keys until the new session opens.
110
110
  - The previous session file stays where it is.
111
111
  - `rollover.enabled: false` turns the feature off.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
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": ["ai-agents", "coding-agents", "orchestration", "guardrails", "omp", "bun", "cli"],
6
6
  "homepage": "https://github.com/umiddey/neurastream#readme",
@@ -16,7 +16,7 @@
16
16
  // Harness payloads are untyped at the boundary: every field read goes through a runtime check.
17
17
 
18
18
  import { execFileSync, spawn } from "node:child_process";
19
- import { appendFileSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
19
+ import { appendFileSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
20
20
  import { dirname, join, resolve } from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
22
  import type { Decision } from "../../core/adapter.ts";
@@ -412,6 +412,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
412
412
  pi.on("session_stop", (_e, ctx) => {
413
413
  const c = asCtx(ctx);
414
414
  if (c.hasAgent && c.kind !== "main") return;
415
+ // A relaunch is requested: omp shuts down at the next idle, so the stop must not be continued.
416
+ if (relaunched) return undefined;
415
417
  const d = checkStop({ agent: "main", callsSinceStop, idleStops, ledgerText: ledgerText(cfg) }, cfg);
416
418
  callsSinceStop = d.state?.callsSinceStop ?? 0;
417
419
  idleStops = d.state?.idleStops ?? idleStops;
@@ -464,20 +466,35 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
464
466
  let relaunched = false;
465
467
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
466
468
  // shuts down only after the file is written. A failed write keeps the session running.
467
- const requestRelaunch = (c: RolloverCtx, note: string): void => {
469
+ // Returns whether the request was written.
470
+ const requestRelaunch = (c: RolloverCtx, note: string, draft = c.draft()): boolean => {
468
471
  try {
469
472
  mkdirSync(dirname(relaunchPath()), { recursive: true });
470
- writeFileSync(
471
- relaunchPath(),
472
- `${JSON.stringify({ previousSessionFile: c.sessionFile, notePath: note, draft: c.draft() })}\n`,
473
- );
473
+ writeFileSync(relaunchPath(), `${JSON.stringify({ previousSessionFile: c.sessionFile, notePath: note, draft })}\n`);
474
474
  } catch (err) {
475
475
  adapterLog(cfg, `rollover: relaunch request not written: ${String(err)}`);
476
- return;
476
+ return false;
477
477
  }
478
478
  relaunched = true;
479
479
  adapterLog(cfg, `rollover: relaunch requested from ${c.sessionFile}`);
480
480
  c.shutdown();
481
+ return true;
482
+ };
483
+
484
+ // An owner message typed while the relaunch is pending joins the request's draft, in order; the
485
+ // launcher's handoff carries it. The rewrite is atomic, so the launcher never reads a partial file.
486
+ const appendToRelaunch = (text: string): boolean => {
487
+ try {
488
+ const req = asRecord(JSON.parse(readFileSync(relaunchPath(), "utf8")));
489
+ const draft = [asString(req.draft), text].filter(s => s !== "").join("\n");
490
+ const tmp = `${relaunchPath()}.tmp`;
491
+ writeFileSync(tmp, `${JSON.stringify({ ...req, draft })}\n`);
492
+ renameSync(tmp, relaunchPath());
493
+ return true;
494
+ } catch (err) {
495
+ adapterLog(cfg, `rollover: owner message not added to the relaunch request: ${String(err)}`);
496
+ return false;
497
+ }
481
498
  };
482
499
 
483
500
  const onSizeCheck = (_e: unknown, ctx: unknown): void => {
@@ -527,22 +544,46 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
527
544
  return null;
528
545
  };
529
546
 
530
- // A plain interactive message in the ready state becomes the owner's first message of the new session.
547
+ // Under the launcher the relaunch is the only rollover path: a plain interactive message in the ready
548
+ // state requests it, and every such message joins the pending request's draft, in order. Plain omp keeps
549
+ // `/main-rollover <text>`: the message becomes the owner's first message of the new session.
531
550
  pi.on("input", (event, ctx) => {
532
551
  const e = asRecord(event);
533
552
  const c = asRolloverCtx(ctx);
534
553
  const text = asString(e.text);
535
554
  if (!cfg.rollover.enabled || !c || !isMain(ctx)) return undefined;
536
555
  if (asString(e.source) !== "interactive" || text === "" || text.startsWith("/")) return undefined;
556
+ if (process.env.NEURASTREAM_MAIN_LAUNCHER === "1") {
557
+ if (!relaunched) {
558
+ if (rolloverSnapshot(c).state !== "ready") return undefined;
559
+ // The message is the request's first owner text, so the editor draft is not carried.
560
+ if (!requestRelaunch(c, notePath(c.sessionId), "")) return undefined;
561
+ }
562
+ if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
563
+ else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
564
+ return { handled: true };
565
+ }
537
566
  if (rolloverSnapshot(c).state !== "ready") return undefined;
538
567
  return { text: `/main-rollover ${text}` };
539
568
  });
540
569
 
570
+ // One /main-rollover at a time: while one waits for idle, a second call adds its text to the owner message.
571
+ let flight: string[] | null = null;
541
572
  pi.registerCommand("main-rollover", {
542
573
  description: "Start a fresh session from Main's handoff note; the rest of the message is the owner's first message",
543
574
  handler: async (args: unknown, ctx: unknown) => {
544
575
  const c = asRolloverCtx(ctx);
545
576
  if (!c) return;
577
+ const text = asString(args);
578
+ if (process.env.NEURASTREAM_MAIN_LAUNCHER === "1") {
579
+ c.notify("main-rollover: under neurastream main the rollover starts from your next message, not from this command.");
580
+ return;
581
+ }
582
+ if (flight) {
583
+ flight.push(text);
584
+ c.notify("main-rollover: a rollover is already in progress; your message is added to its handoff.");
585
+ return;
586
+ }
546
587
  const path = notePath(c.sessionId);
547
588
  const state = rolloverSnapshot(c).state;
548
589
  if (state === "below") {
@@ -557,22 +598,39 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
557
598
  c.notify(`main-rollover: own jobs are still running (${c.runningJobs().join(", ")}); a rollover would cancel them.`);
558
599
  return;
559
600
  }
560
- c.notify("main-rollover: collecting main-start state for the handoff (this can take a minute)…");
561
- const generated = [
562
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
563
- holdsBlock(q.ownerHolds()),
564
- ].join("\n");
565
- const handoff = buildHandoff({
566
- generated,
567
- note: readFileSync(path, "utf8"),
568
- previousSessionFile: c.sessionFile,
569
- ownerMessage: asString(args),
570
- });
571
- adapterLog(cfg, `rollover: new session from ${c.sessionFile}; note ${path}`);
572
- await c.waitForIdle();
573
- const r = asRecord(await c.newSession({ parentSession: c.sessionFile }));
574
- if (r.cancelled === true) return;
575
- pi.sendUserMessage(handoff);
601
+ const previous = c.sessionFile;
602
+ const owner = [text];
603
+ flight = owner;
604
+ try {
605
+ c.notify("main-rollover: collecting main-start state for the handoff (this can take a minute)…");
606
+ const generated = [
607
+ await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
608
+ holdsBlock(q.ownerHolds()),
609
+ ].join("\n");
610
+ const note = readFileSync(path, "utf8");
611
+ adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
612
+ await c.waitForIdle();
613
+ const again = rolloverSnapshot(c).state;
614
+ if (relaunched || again !== "ready") {
615
+ c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
616
+ // The owner's text is not lost: it goes to this session as an ordinary message.
617
+ const pending = owner.filter(s => s !== "").join("\n");
618
+ if (pending !== "") pi.sendUserMessage(pending);
619
+ return;
620
+ }
621
+ const r = asRecord(await c.newSession({ parentSession: previous }));
622
+ if (r.cancelled === true) return;
623
+ // Read after the await: owner messages that arrived during newSession are part of the handoff.
624
+ const handoff = buildHandoff({
625
+ generated,
626
+ note,
627
+ previousSessionFile: previous,
628
+ ownerMessage: owner.filter(s => s !== "").join("\n"),
629
+ });
630
+ pi.sendUserMessage(handoff);
631
+ } finally {
632
+ flight = null;
633
+ }
576
634
  },
577
635
  });
578
636
  }
@@ -149,7 +149,7 @@ async function nextMessage(req: RelaunchRequest, cfg: Config): Promise<string |
149
149
  await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
150
150
  holdsBlock(q.ownerHolds()),
151
151
  ].join("\n");
152
- const draft = req.draft.trim() === "" ? "" : `\nOwner's unsent draft: ${req.draft}`;
152
+ const draft = req.draft.trim() === "" ? "" : `\nOwner's messages during the rollover (and any unsent draft): ${req.draft}`;
153
153
  const handoff = buildHandoff({
154
154
  generated,
155
155
  note,
@@ -45,12 +45,12 @@ export function rolloverState(p: RolloverInput): RolloverState {
45
45
  }
46
46
 
47
47
  /**
48
- * Drain: while a rollover is pending (need-note or wait-jobs) Main must not start new subagents —
49
- * a rollover would cancel them, or they would outlive the handoff. Returns the refusal text, or
50
- * null when the spawn may proceed (below, ready).
48
+ * Drain: while a rollover is pending (need-note, wait-jobs or ready) Main must not start new subagents —
49
+ * a rollover would cancel them, or they would outlive the handoff. Ready counts: the rollover follows the
50
+ * next idle, so a spawn now would be aborted. Returns the refusal text, or null when the spawn may proceed.
51
51
  */
52
52
  export function spawnRefusal(state: RolloverState, runningJobs: readonly string[]): string | null {
53
- if (state !== "need-note" && state !== "wait-jobs") return null;
53
+ if (state !== "need-note" && state !== "wait-jobs" && state !== "ready") return null;
54
54
  return `main-guard: rollover pending (${state}); no new subagents until the session rolls over. Running: ${runningJobs.join(", ")}.`;
55
55
  }
56
56
 
@@ -85,11 +85,12 @@ export function holdsBlock(holds: readonly string[]): string {
85
85
  return ["=== owner holds (plans' WAITING on owner lines)", ...(holds.length > 0 ? holds : ["none"]), ""].join("\n");
86
86
  }
87
87
 
88
- /** The one-time note instruction for Main's next turn. `reason` (a stale install) names both versions. */
88
+ /** The one-time note instruction for Main's next turn. `reason` (a stale install) names both versions and replaces the size line. */
89
89
  export function noteRequest(path: string, auto = false, reason = ""): string {
90
90
  return [
91
- "Session rollover: this session has grown past rollover.max_session_mb.",
92
- ...(reason ? [reason] : []),
91
+ reason
92
+ ? `Session rollover: a new neurastream version is installed (${reason}).`
93
+ : "Session rollover: this session has grown past rollover.max_session_mb.",
93
94
  `Write a handoff note to ${path} (overwrite it). Cover the work in progress and its state, the decisions made and why, the next step, and the files involved.`,
94
95
  "Do not list holds or owner blockers in the note; they come from the plans' WAITING on owner lines.",
95
96
  auto