neurastream 0.1.27 → 0.1.28

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
@@ -105,6 +105,9 @@ A relaunch keeps the flags of the first run (`--model`, `--session-dir`, …) an
105
105
 
106
106
  In both modes:
107
107
 
108
+ - If omp does not exit within `rollover.exit_grace_s` seconds (default 20, `docs/config.md`) after a relaunch was requested, the adapter stops waiting and rolls over in-process: the fresh session opens in the same process and carries the owner's typed messages in its handoff. A real shutdown (`session_shutdown`) cancels the fallback.
109
+ - The relaunch is requested only when Main's run has really ended: a tool result mid-run never restarts the session, and while a relaunch is pending every later terminal run end calls `shutdown()` again (omp re-checks its deferred exit only then).
110
+ - The launcher prints one stderr line while it collects the handoff state (`neurastream: starting a new session from the handoff (collecting state, about a minute)…`) and removes the request only after the handoff message is built; a fresh `neurastream main` with no message of its own continues an interrupted rollover whose request is at most one hour old.
108
111
  - A note counts only if it was written after the threshold was crossed and is at most one hour old.
109
112
  - 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).
110
113
  - 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neurastream",
3
- "version": "0.1.27",
3
+ "version": "0.1.28",
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",
@@ -26,7 +26,7 @@ import { checkInject, checkPlanEdit, checkStop, checkTool, MAIN_PLAN_FILE, recor
26
26
  import { applyQueueEnv } from "../../core/queue/env.ts";
27
27
  import { mainStartText, runDailyCheck } from "../../core/main-start.ts";
28
28
  import { readBlocks } from "../../core/metrics.ts";
29
- import { buildHandoff, holdsBlock, notePath, noteRequest, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
29
+ import { buildHandoff, holdsBlock, notePath, noteRequest, OWNER_AWAY, ownerText, relaunchPath, rolloverState, spawnRefusal, type RolloverState } from "../../core/rollover.ts";
30
30
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
31
31
  import { packageJsonPath, packageVersion } from "./package-root.ts";
32
32
  import * as q from "../../core/queue/lib.ts";
@@ -364,7 +364,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
364
364
  };
365
365
 
366
366
  pi.on("tool_result", (event, ctx) => {
367
- onSizeCheck(event, ctx);
367
+ onSizeCheck("tool_result", event, ctx);
368
368
  const e = asRecord(event);
369
369
  const c = asCtx(ctx);
370
370
  const id = asString(e.toolCallId);
@@ -488,6 +488,67 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
488
488
  };
489
489
 
490
490
  let relaunched = false;
491
+ // omp 18.11.1 defers an extension shutdown: it re-checks only when shutdown() is called again or
492
+ // an owner submission finishes, so a refused exit once left a dead UI that swallowed every owner
493
+ // message (I-20261024-4). One unref'd timer per request: if omp still has not exited
494
+ // rollover.exit_grace_s after the request, the adapter rolls over in-process. The timer keeps its
495
+ // own clearer: session_shutdown cancels the fallback when omp really exits.
496
+ let clearGrace: (() => void) | null = null;
497
+ const armGraceTimer = (c: RolloverCtx): void => {
498
+ clearGrace?.();
499
+ const t = setTimeout(() => {
500
+ clearGrace = null;
501
+ exitGraceElapsed(c);
502
+ }, cfg.rollover.exit_grace_s * 1000);
503
+ if (t && typeof t === "object" && "unref" in t && typeof t.unref === "function") t.unref();
504
+ clearGrace = () => {
505
+ clearTimeout(t);
506
+ clearGrace = null;
507
+ };
508
+ };
509
+
510
+ // One /main-rollover at a time: while one waits for idle, a second call adds its text to the owner message.
511
+ let flight: string[] | null = null;
512
+
513
+ // The one in-process rollover, shared by /main-rollover and the exit-grace fallback: gather the
514
+ // generated state, wait for idle, then start a fresh session whose first message is the handoff.
515
+ // A state change during the wait sends the owner's text to this session as an ordinary message.
516
+ const rolloverInProcess = async (c: RolloverCtx, owner: string[], notice: string): Promise<void> => {
517
+ const previous = c.sessionFile;
518
+ const path = notePath(c.sessionId);
519
+ flight = owner;
520
+ try {
521
+ c.notify(notice);
522
+ const generated = [
523
+ await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
524
+ holdsBlock(q.ownerHolds()),
525
+ ].join("\n");
526
+ const note = readFileSync(path, "utf8");
527
+ adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
528
+ await c.waitForIdle();
529
+ const again = rolloverSnapshot(c).state;
530
+ if (relaunched || again !== "ready") {
531
+ c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
532
+ // The owner's text is not lost: it goes to this session as an ordinary message.
533
+ const pending = owner.filter(s => s !== "").join("\n");
534
+ if (pending !== "") pi.sendUserMessage(pending);
535
+ return;
536
+ }
537
+ const r = asRecord(await c.newSession({ parentSession: previous }));
538
+ if (r.cancelled === true) return;
539
+ // Read after the await: owner messages that arrived during newSession are part of the handoff.
540
+ const handoff = buildHandoff({
541
+ generated,
542
+ note,
543
+ previousSessionFile: previous,
544
+ ownerMessage: owner.filter(s => s !== "").join("\n"),
545
+ });
546
+ pi.sendUserMessage(handoff);
547
+ } finally {
548
+ flight = null;
549
+ }
550
+ };
551
+
491
552
  // The launcher restarts omp: the request file carries the note and the editor draft, and omp
492
553
  // shuts down only after the file is written. A failed write keeps the session running.
493
554
  // Returns whether the request was written.
@@ -502,6 +563,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
502
563
  relaunched = true;
503
564
  adapterLog(cfg, `rollover: relaunch requested from ${c.sessionFile}`);
504
565
  c.shutdown();
566
+ armGraceTimer(c);
505
567
  return true;
506
568
  };
507
569
 
@@ -521,22 +583,49 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
521
583
  }
522
584
  };
523
585
 
524
- const onSizeCheck = (_e: unknown, ctx: unknown): void => {
586
+ // The grace elapsed without a session_shutdown: omp refused the exit. Read the request's draft,
587
+ // drop the request and roll over here, so the owner's messages reach a live session instead of a
588
+ // dead UI. The owner-away text stands in when nothing was typed.
589
+ const exitGraceElapsed = (c: RolloverCtx): void => {
590
+ adapterLog(cfg, `rollover: omp did not exit within ${cfg.rollover.exit_grace_s}s; rolling over in-process`);
591
+ let draft = "";
592
+ try {
593
+ draft = asString(asRecord(JSON.parse(readFileSync(relaunchPath(), "utf8"))).draft);
594
+ } catch {}
595
+ rmSync(relaunchPath(), { force: true });
596
+ relaunched = false;
597
+ rolloverInProcess(c, [draft.trim() === "" ? OWNER_AWAY : draft], "rollover: omp did not restart; continuing in a new session here").catch((err: unknown) => {
598
+ adapterLog(cfg, `rollover: in-process rollover failed: ${err instanceof Error ? err.message : String(err)}`);
599
+ });
600
+ };
601
+
602
+ const onSizeCheck = (kind: "tool_result" | "agent_end", e: unknown, ctx: unknown): void => {
525
603
  const c = asRolloverCtx(ctx);
526
604
  if (!cfg.rollover.enabled || !c || !isMain(ctx)) return;
527
605
  const snap = rolloverSnapshot(c);
528
606
  const key = `${c.sessionFile}:${snap.noteMtimeMs ?? "none"}`;
607
+ // A terminal run end: omp 18.11.1 sets willContinue on a non-terminal agent_end.
608
+ const terminal = kind === "agent_end" && asRecord(e).willContinue !== true;
529
609
  if (snap.state === "need-note" && asked !== key) {
530
610
  asked = key;
531
611
  pi.sendMessage(
532
612
  { customType: "main-guard.rollover", content: noteRequestFor(c, snap), display: false },
533
613
  { triggerTurn: true, deliverAs: "nextTurn" },
534
614
  );
535
- } else if (snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && !relaunched) {
615
+ } else if (terminal && snap.state === "ready" && process.env.NEURASTREAM_MAIN_LAUNCHER === "1" && !relaunched && flight === null) {
616
+ // flight !== null: an in-process rollover (fallback or /main-rollover) owns this session's end.
536
617
  requestRelaunch(c, notePath(c.sessionId));
618
+ } else if (terminal && relaunched) {
619
+ // A tool result mid-run never restarts the session (I-20261024-4), and omp's interactive
620
+ // mode re-runs its deferred exit check only when shutdown() is called again: re-arm at
621
+ // every later terminal run end instead of waiting for an owner message.
622
+ c.shutdown();
537
623
  }
538
624
  };
539
- pi.on("agent_end", onSizeCheck);
625
+ pi.on("agent_end", (e, ctx) => onSizeCheck("agent_end", e, ctx));
626
+
627
+ // omp is really shutting down: the exit-grace fallback must not fire.
628
+ pi.on("session_shutdown", () => clearGrace?.());
540
629
 
541
630
  // Compaction keeps the owner's holds true: a summary may state a hold only as a plans' WAITING on owner line says it.
542
631
  pi.on("session.compacting", (_e, ctx) => {
@@ -581,6 +670,8 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
581
670
  }
582
671
  if (appendToRelaunch(text)) c.notify("rollover in progress: your message goes to the new session");
583
672
  else c.notify("rollover in progress: your message could not be saved and was not sent; send it again after the rollover");
673
+ // omp re-checks its deferred exit only when shutdown() is called again: re-arm per message.
674
+ c.shutdown();
584
675
  return { handled: true };
585
676
  }
586
677
  if (rolloverSnapshot(c).state !== "ready") return undefined;
@@ -588,7 +679,6 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
588
679
  });
589
680
 
590
681
  // One /main-rollover at a time: while one waits for idle, a second call adds its text to the owner message.
591
- let flight: string[] | null = null;
592
682
  pi.registerCommand("main-rollover", {
593
683
  description: "Start a fresh session from Main's handoff note; the rest of the message is the owner's first message",
594
684
  handler: async (args: unknown, ctx: unknown) => {
@@ -618,39 +708,7 @@ export function createOmpAdapter(pi: ExtensionHost, cfg: Config): void {
618
708
  c.notify(`main-rollover: own jobs are still running (${c.runningJobs().join(", ")}); a rollover would cancel them.`);
619
709
  return;
620
710
  }
621
- const previous = c.sessionFile;
622
- const owner = [text];
623
- flight = owner;
624
- try {
625
- c.notify("main-rollover: collecting main-start state for the handoff (this can take a minute)…");
626
- const generated = [
627
- await mainStartText([], cfg, { inheritStdin: false }, { source: defaultRunSource(cfg), results: defaultCompletedResults(cfg) }),
628
- holdsBlock(q.ownerHolds()),
629
- ].join("\n");
630
- const note = readFileSync(path, "utf8");
631
- adapterLog(cfg, `rollover: new session from ${previous}; note ${path}`);
632
- await c.waitForIdle();
633
- const again = rolloverSnapshot(c).state;
634
- if (relaunched || again !== "ready") {
635
- c.notify(`main-rollover: the state changed while waiting for idle (${relaunched ? "relaunch requested" : again}); no new session.`);
636
- // The owner's text is not lost: it goes to this session as an ordinary message.
637
- const pending = owner.filter(s => s !== "").join("\n");
638
- if (pending !== "") pi.sendUserMessage(pending);
639
- return;
640
- }
641
- const r = asRecord(await c.newSession({ parentSession: previous }));
642
- if (r.cancelled === true) return;
643
- // Read after the await: owner messages that arrived during newSession are part of the handoff.
644
- const handoff = buildHandoff({
645
- generated,
646
- note,
647
- previousSessionFile: previous,
648
- ownerMessage: owner.filter(s => s !== "").join("\n"),
649
- });
650
- pi.sendUserMessage(handoff);
651
- } finally {
652
- flight = null;
653
- }
711
+ await rolloverInProcess(c, [text], "main-rollover: collecting main-start state for the handoff (this can take a minute)…");
654
712
  },
655
713
  });
656
714
  }
@@ -10,7 +10,7 @@ import type { Config } from "../../core/config.ts";
10
10
  import { mainStartText } from "../../core/main-start.ts";
11
11
  import { applyQueueEnv } from "../../core/queue/env.ts";
12
12
  import * as q from "../../core/queue/lib.ts";
13
- import { buildHandoff, holdsBlock, relaunchPath } from "../../core/rollover.ts";
13
+ import { buildHandoff, holdsBlock, MAX_NOTE_AGE_MS, OWNER_AWAY, relaunchPath } from "../../core/rollover.ts";
14
14
  import { adapterLog } from "./index.ts";
15
15
  import { PACKAGE_ROOT, packageJsonPath, packageVersion } from "./package-root.ts";
16
16
  import { defaultCompletedResults, defaultRunSource } from "./sessions.ts";
@@ -68,8 +68,21 @@ export function carriedArgs(args: string[]): string[] {
68
68
  /** Handoffs up to this many bytes go in the first message; larger ones go to a file. */
69
69
  const MAX_INLINE_HANDOFF = 100_000;
70
70
 
71
- const OWNER_AWAY =
72
- "Owner away (automatic rollover). Continue the work in the note and the queue; the owner reads results later.";
71
+ /** Printed before the launcher builds a handoff: main-start collects state, which takes about a minute. */
72
+ const HANDOFF_PENDING_LINE = "neurastream: starting a new session from the handoff (collecting state, about a minute)…";
73
+
74
+ /** Whether `args` carry a positional (the first message): flags with their values do not count. */
75
+ function hasPositional(args: string[]): boolean {
76
+ for (let i = 0; i < args.length; i++) {
77
+ const arg = args[i] ?? "";
78
+ if (arg === "--") return true;
79
+ if (!arg.startsWith("-")) return true;
80
+ const eq = arg.indexOf("=");
81
+ const flag = eq === -1 ? arg : arg.slice(0, eq);
82
+ if (eq === -1 && takesValue(flag, args[i + 1])) i++;
83
+ }
84
+ return false;
85
+ }
73
86
 
74
87
  export interface LaunchOptions {
75
88
  harness?: string;
@@ -103,14 +116,30 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
103
116
  if (Number.isFinite(since)) {
104
117
  const req = readRequest(since, cfg);
105
118
  if (req !== null) {
106
- rmSync(relaunchPath(), { force: true });
119
+ console.error(HANDOFF_PENDING_LINE);
107
120
  const message = await nextMessage(req, cfg, mainStart);
108
121
  if (message === null) return 1;
122
+ // The request is removed only once its message exists: a kill during main-start
123
+ // (I-20261024-4) must leave it for the next launcher to continue.
124
+ rmSync(relaunchPath(), { force: true });
109
125
  runArgs = [...carried, message];
110
126
  }
127
+ } else if (!hasPositional(args)) {
128
+ // A fresh start with no message of its own continues a rollover a killed launcher left
129
+ // behind: the request counts while it is at most MAX_NOTE_AGE_MS old, like a note. An
130
+ // older or unreadable one is left alone.
131
+ const req = readRequest(Date.now() - MAX_NOTE_AGE_MS, cfg);
132
+ if (req !== null) {
133
+ console.error(`neurastream: continuing the interrupted rollover from ${req.previousSessionFile}`);
134
+ console.error(HANDOFF_PENDING_LINE);
135
+ const message = await nextMessage(req, cfg, mainStart);
136
+ if (message !== null) {
137
+ rmSync(relaunchPath(), { force: true });
138
+ runArgs = [...carried, message];
139
+ }
140
+ }
111
141
  }
112
142
  for (;;) {
113
- rmSync(relaunchPath(), { force: true });
114
143
  const started = Date.now();
115
144
  const code = await runChild(harness, runArgs, { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1" });
116
145
  const req = readRequest(started, cfg);
@@ -124,9 +153,10 @@ export async function runMainLauncher(args: string[], cfg: Config, opts: LaunchO
124
153
  NEURASTREAM_RELAUNCH_SINCE: String(started),
125
154
  });
126
155
  }
127
- rmSync(relaunchPath(), { force: true });
156
+ console.error(HANDOFF_PENDING_LINE);
128
157
  const message = await nextMessage(req, cfg, mainStart);
129
158
  if (message === null) return code;
159
+ rmSync(relaunchPath(), { force: true });
130
160
  runArgs = [...carried, message];
131
161
  }
132
162
  }
@@ -116,7 +116,7 @@ export interface Config {
116
116
  protected: string[];
117
117
  ledger_command: string;
118
118
  };
119
- rollover: { enabled: boolean; max_session_mb: number };
119
+ rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
120
120
  metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
121
121
  /** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
122
122
  incidents: {
@@ -281,6 +281,7 @@ function check(cfg: Config): void {
281
281
  throw new ConfigError("guards.sub_warn_calls must be <= guards.sub_max_calls");
282
282
  }
283
283
  if (!(cfg.rollover.max_session_mb > 0)) throw new ConfigError("rollover.max_session_mb must be > 0");
284
+ if (!(cfg.rollover.exit_grace_s > 0)) throw new ConfigError("rollover.exit_grace_s must be > 0");
284
285
  if (!(cfg.metrics.report_days >= 1)) throw new ConfigError("metrics.report_days must be >= 1");
285
286
  for (const p of cfg.metrics.correction_patterns) {
286
287
  try {
@@ -104,6 +104,13 @@ export function holdsBlock(holds: readonly string[]): string {
104
104
  return ["=== owner holds (plans' WAITING on owner lines)", ...(holds.length > 0 ? holds : ["none"]), ""].join("\n");
105
105
  }
106
106
 
107
+ /**
108
+ * The launcher's owner-away text: the handoff's owner message when the owner typed nothing during the
109
+ * rollover. The adapter's in-process fallback carries the same text, so it lives here, harness-free.
110
+ */
111
+ export const OWNER_AWAY =
112
+ "Owner away (automatic rollover). Continue the work in the note and the queue; the owner reads results later.";
113
+
107
114
  /** The one-time note instruction for Main's next turn. `reason` (a stale install) names both versions and replaces the size line. */
108
115
  export function noteRequest(path: string, auto = false, reason = ""): string {
109
116
  return [
@@ -119,6 +119,7 @@ guards:
119
119
  rollover:
120
120
  enabled: true
121
121
  max_session_mb: 5
122
+ exit_grace_s: 20
122
123
 
123
124
  metrics:
124
125
  report_days: 7