neurastream 0.3.26 → 0.3.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.
@@ -25,7 +25,9 @@ import { wipSnapshot } from "../core/wip-snapshot.ts";
25
25
  import { withHeartbeat } from "../core/heartbeat.ts";
26
26
  import { runtime } from "./runtime.ts";
27
27
  import { claimCli } from "./claim.ts";
28
- import { getAdapter } from "../adapters/index.ts";
28
+ import { allAdapters, getAdapter, type HarnessAdapter } from "../adapters/index.ts";
29
+ import { MultiRunSource, type RunSource } from "../core/adapter.ts";
30
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
29
31
 
30
32
  export const PORTED = [
31
33
  "agent-score",
@@ -79,19 +81,120 @@ function runCliDoctor(): Promise<string> {
79
81
  return promise;
80
82
  }
81
83
 
82
- export async function runMain(args: string[]): Promise<number> {
83
- const cfg = runtime().cfg;
84
- return getAdapter(cfg).launchMain(args, cfg);
84
+ /**
85
+ * Builds a combined `RunSource` with the primary configured adapter first followed by all other
86
+ * registered adapters so ledger and score commands see runs across harnesses while preserving
87
+ * primary `mainSession()` delegation.
88
+ *
89
+ * Args:
90
+ * cfg (Config): Loaded neurastream configuration
91
+ *
92
+ * Returns:
93
+ * RunSource: Merged RunSource across registered adapters
94
+ */
95
+ function combinedRunSource(cfg: Config): RunSource {
96
+ const primary = getAdapter(cfg);
97
+ const others = allAdapters().filter((a) => a.name !== primary.name);
98
+ return new MultiRunSource([primary, ...others].map((a) => a.runSource(cfg)));
99
+ }
100
+
101
+ /** Injectable seams for `runMain` tests. */
102
+ export interface MainDeps {
103
+ loadConfig?: () => Config;
104
+ getAdapter?: (cfg?: Pick<Config, "harness">) => HarnessAdapter;
105
+ err?: (line: string) => void;
106
+ }
107
+
108
+ /**
109
+ * Splits `--harness <name>` / `--harness=<name>` from `neurastream main` arguments, stopping
110
+ * option scanning at `--` and forwarding all remaining arguments verbatim to `launchMain`.
111
+ *
112
+ * Args:
113
+ * args (string[]): Raw CLI arguments passed to `neurastream main`
114
+ *
115
+ * Returns:
116
+ * { harness?: string; rest: string[] } | { error: string }: Parsed harness override and forwarded args, or a syntax error
117
+ */
118
+ export function parseMainArgs(args: string[]): { harness?: string; rest: string[] } | { error: string } {
119
+ let harness: string | undefined;
120
+ const rest: string[] = [];
121
+ for (let i = 0; i < args.length; i++) {
122
+ const arg = args[i] ?? "";
123
+ if (arg === "--") {
124
+ rest.push(...args.slice(i));
125
+ break;
126
+ }
127
+ if (arg === "--harness") {
128
+ const next = args[i + 1];
129
+ if (next === undefined || !next.trim() || next.startsWith("-")) {
130
+ return { error: "--harness requires a value" };
131
+ }
132
+ harness = next;
133
+ i++;
134
+ continue;
135
+ }
136
+ if (arg.startsWith("--harness=")) {
137
+ const val = arg.slice("--harness=".length);
138
+ if (!val.trim()) return { error: "--harness requires a value" };
139
+ harness = val;
140
+ continue;
141
+ }
142
+ rest.push(arg);
143
+ }
144
+ return harness !== undefined ? { harness, rest } : { rest };
145
+ }
146
+
147
+ /**
148
+ * Launches Main in the harness selected by `--harness` (or `cfg.harness`), forwarding remaining flags verbatim.
149
+ *
150
+ * Args:
151
+ * args (string[]): CLI arguments passed after `neurastream main`
152
+ * deps (MainDeps): Optional injectable seams for testing
153
+ *
154
+ * Returns:
155
+ * Promise<number>: Process exit code (2 on missing `--harness` value or unknown harness)
156
+ */
157
+ export async function runMain(args: string[], deps: MainDeps = {}): Promise<number> {
158
+ const errLog = deps.err ?? ((line: string) => console.error(line));
159
+ const parsed = parseMainArgs(args);
160
+ if ("error" in parsed) {
161
+ errLog(`neurastream main: ${parsed.error}`);
162
+ return 2;
163
+ }
164
+ const resolveAdapter = deps.getAdapter ?? getAdapter;
165
+ if (parsed.harness !== undefined) {
166
+ try {
167
+ resolveAdapter({ harness: parsed.harness });
168
+ } catch (err) {
169
+ errLog(err instanceof Error ? err.message : String(err));
170
+ return 2;
171
+ }
172
+ }
173
+ let cfg: Config;
174
+ try {
175
+ cfg = (deps.loadConfig ?? (() => loadConfig()))();
176
+ } catch (err) {
177
+ errLog(err instanceof ConfigError ? err.message : String(err));
178
+ return 1;
179
+ }
180
+ let adapter: HarnessAdapter;
181
+ try {
182
+ adapter = resolveAdapter(parsed.harness ? { harness: parsed.harness } : cfg);
183
+ } catch (err) {
184
+ errLog(err instanceof Error ? err.message : String(err));
185
+ return 2;
186
+ }
187
+ return adapter.launchMain(parsed.rest, { ...cfg, harness: adapter.name });
85
188
  }
86
189
 
87
190
  export async function runPorted(cmd: string, args: string[]): Promise<number> {
88
191
  const rt = runtime();
89
192
  switch (cmd) {
90
193
  case "agent-score":
91
- return agentScore(args, rt.cfg, rt.source, getAdapter(rt.cfg).scoreTraces(rt.cfg));
194
+ return agentScore(args, rt.cfg, combinedRunSource(rt.cfg), getAdapter(rt.cfg).scoreTraces(rt.cfg));
92
195
  case "agent-ledger":
93
196
  if (args.includes("--cap")) syncHarnessOut(rt.cfg, getAdapter(rt.cfg).providers(rt.cfg));
94
- return agentLedger(args, rt.cfg, rt.source);
197
+ return agentLedger(args, rt.cfg, combinedRunSource(rt.cfg));
95
198
  case "brief-lint":
96
199
  return briefLint(args, rt.cfg);
97
200
  case "oc-run":
@@ -11,6 +11,22 @@ import { checkEdited, leafKeys, setConfigKeys, valueAt, yamlValue } from "../cor
11
11
  import { TEMPLATE_PATH, configFile, loadConfig } from "../core/config.ts";
12
12
 
13
13
  const VALID_KEYS = leafKeys(Bun.YAML.parse(readFileSync(TEMPLATE_PATH, "utf8")));
14
+ const SPAWN_PROFILE_KEY_RE =
15
+ /^spawn\.profiles\.([a-z0-9][a-z0-9_-]*)\.(harness|fallback_harness|runner|model|provider|role|direction|start_timeout_ms|timeout_ms|args)$/;
16
+
17
+ /**
18
+ * Checks whether `key` is either a static leaf key in `templates/config.yml` or a valid
19
+ * `spawn.profiles.<slug>.<field>` override path.
20
+ *
21
+ * Args:
22
+ * key (string): Dotted config key
23
+ *
24
+ * Returns:
25
+ * boolean: True if `key` may be read or written via `neurastream config get|set`
26
+ */
27
+ function isValidConfigKey(key: string): boolean {
28
+ return VALID_KEYS.includes(key) || SPAWN_PROFILE_KEY_RE.test(key);
29
+ }
14
30
 
15
31
  export function runConfigKeys(args: string[], home: string = homedir(), tty: boolean = process.stdin.isTTY === true): number {
16
32
  const [verb, key, raw] = args;
@@ -21,22 +37,28 @@ export function runConfigKeys(args: string[], home: string = homedir(), tty: boo
21
37
  const v = valueAt(cfg, k);
22
38
  console.log(`${k} = ${Array.isArray(v) ? JSON.stringify(v) : String(v)}`);
23
39
  }
40
+ for (const [agent, prof] of Object.entries(cfg.spawn.profiles)) {
41
+ for (const [field, val] of Object.entries(prof)) {
42
+ if (val === undefined || (typeof val === "object" && !Array.isArray(val))) continue;
43
+ console.log(`spawn.profiles.${agent}.${field} = ${Array.isArray(val) ? JSON.stringify(val) : String(val)}`);
44
+ }
45
+ }
24
46
  return 0;
25
47
  }
26
- if (key === undefined || !VALID_KEYS.includes(key)) {
27
- console.error(`neurastream config ${verb ?? ""}: unknown key ${key ?? "(none)"}; valid keys: ${VALID_KEYS.join(", ")}`);
48
+ if (key === undefined || !isValidConfigKey(key)) {
49
+ console.error(`neurastream config ${verb ?? ""}: unknown key ${key ?? "(none)"}; valid keys: ${VALID_KEYS.join(", ")} (plus spawn.profiles.<agent>.<field>)`);
28
50
  return 1;
29
51
  }
30
52
  if (verb === "get") {
31
53
  const v = valueAt(loadConfig({ home }), key);
32
- console.log(Array.isArray(v) ? JSON.stringify(v) : String(v));
54
+ console.log(v === undefined ? "" : Array.isArray(v) ? JSON.stringify(v) : String(v));
33
55
  return 0;
34
56
  }
35
57
  if (verb !== "set") {
36
58
  console.error("usage: neurastream config set|get|list [key] [value]");
37
59
  return 1;
38
60
  }
39
- const parsed: unknown = raw === undefined ? null : Bun.YAML.parse(raw);
61
+ const parsed: unknown = raw === undefined ? null : raw === "" ? "" : Bun.YAML.parse(raw);
40
62
  if (parsed === null || parsed === undefined || (typeof parsed === "object" && !Array.isArray(parsed))) {
41
63
  console.error(`neurastream config set ${key}: give a scalar or a list (e.g. 7788, true, '["a", "b"]')`);
42
64
  return 1;
@@ -12,7 +12,7 @@ import { nowSec } from "../core/clock.ts";
12
12
  import { postReply } from "../core/notify.ts";
13
13
  import { log } from "../core/guards.ts";
14
14
  import { loadKnownSecrets, redactSecrets, redactSummary } from "../core/secret-redact.ts";
15
- import { getAdapter } from "../adapters/index.ts";
15
+ import { getAdapter, type HarnessAdapter } from "../adapters/index.ts";
16
16
  import { GUARD_USAGE, runGuard } from "./guard.ts";
17
17
  import { runInit } from "./init.ts";
18
18
  import { realSetupDeps, runSetup } from "./setup.ts";
@@ -38,6 +38,7 @@ import { allowAgents, denyAgents, invalidSlugs } from "../core/subagents.ts";
38
38
  import { runLabels } from "./labels.ts";
39
39
  import { runRules } from "./rules.ts";
40
40
  import { runDiffCheck } from "./diff-check.ts";
41
+ import { runSpawn } from "./spawn.ts";
41
42
 
42
43
  const BINS = [
43
44
  "agent-score",
@@ -75,8 +76,10 @@ export function helpText(): string {
75
76
  " neurastream setup [--yes]",
76
77
  " guided first run: detect this machine, ask in groups, install, doctor",
77
78
  " (--yes: take the detected settings without asking)",
78
- " neurastream adapter install omp",
79
- " link the omp extension under this HOME",
79
+ " neurastream adapter install <omp|agy|claude|codex>",
80
+ " link the omp extension or install harness hooks under this HOME",
81
+ " neurastream adapter hook <name> <event>",
82
+ " translate native harness hook stdin/stdout to neurastream guards",
80
83
  " neurastream uninstall [--purge] [--yes]",
81
84
  " inverse of init/install: removes our bins, the plugin link,",
82
85
  " template-identical pins and the AGENTS.md block (--purge adds",
@@ -111,7 +114,12 @@ export function helpText(): string {
111
114
  " `off --purge` also deletes graphify-out/ and uninstalls graphifyy",
112
115
  " neurastream guard <event> --json",
113
116
  ` (${GUARD_USAGE.slice(GUARD_USAGE.indexOf("(") + 1, -1)})`,
114
- " neurastream main [args] run omp under the launcher (automatic session rollover)",
117
+ " neurastream main [--harness <omp|agy|claude|codex>] [args]",
118
+ " run Main under the chosen or configured harness (omp includes automatic session rollover)",
119
+ " neurastream spawn --agent <profile> [--plan <path>] [--cwd <dir>] (--brief <text> | --brief-file <path>) [--no-wait] [--keep-pane] [--json]",
120
+ " spawn a guarded subagent in a managed runner pane",
121
+ " neurastream spawn list | read <target> | stop <pane_id>",
122
+ " inspect or stop runner-managed helper panes",
115
123
  " neurastream metrics <cmd> self-metrics: report, features, releases, ci, false-alarm, rule (see README)",
116
124
  " neurastream pressure machine pressure now: level, the sample, the line Main would read",
117
125
  " neurastream incident <cmd> incidents Main must act on: list, add, plan, dismiss (see README)",
@@ -194,7 +202,21 @@ export async function run(cmd: string, args: string[]): Promise<number> {
194
202
  if (cmd === "pages") return runPages(args);
195
203
  if (cmd === "notes") return runNotes(args);
196
204
  if (cmd === "diagram") return runDiagram(args);
197
- if (cmd === "adapter") return getAdapter().install(args);
205
+ if (cmd === "adapter") {
206
+ if (args[0] === "hook") {
207
+ return runAdapterHook(args.slice(1));
208
+ }
209
+ if (args[0] === "install" && args.length === 2 && args[1]) {
210
+ try {
211
+ return getAdapter({ harness: args[1] }).install(args);
212
+ } catch (err) {
213
+ console.error(err instanceof Error ? err.message : String(err));
214
+ return 2;
215
+ }
216
+ }
217
+ return getAdapter().install(args);
218
+ }
219
+ if (cmd === "spawn") return runSpawn(args);
198
220
  if (cmd === "setup") return runSetup(args, realSetupDeps(async () => runNotify(["test"])));
199
221
  if (cmd === "config" && ["set", "get", "list"].includes(args[0] ?? "")) return runConfigKeys(args);
200
222
  if (cmd === "wip") return runWip(args);
@@ -211,13 +233,14 @@ export async function run(cmd: string, args: string[]): Promise<number> {
211
233
  }
212
234
  if (cmd === "doctor") {
213
235
  for (const warning of pagesDoctor()) console.warn(`warning: ${warning}`);
236
+ let cfg: Config | undefined;
214
237
  try {
215
- const cfg = loadConfig();
238
+ cfg = loadConfig();
216
239
  const was = enforceReadOnlyIndex(cfg.paths.queue_index);
217
240
  if (was) console.warn(`warning: ${cfg.paths.queue_index} — was ${was}, set 0444 (the plan index is read-only on disk)`);
218
241
  console.log(watchDoctorLine(watchHealth(cfg, Date.now())));
219
242
  } catch {} // a broken config is doctor's own report; the adapter doctor names it
220
- return getAdapter().doctor();
243
+ return getAdapter(cfg).doctor();
221
244
  }
222
245
  if (cmd === "notify") return runNotify(args);
223
246
  if (cmd === "redact") return runRedact(args);
@@ -498,3 +521,53 @@ function runAgents(args: string[]): number {
498
521
  console.log(`file: ${file}`);
499
522
  return 0;
500
523
  }
524
+
525
+ /**
526
+ * Translates a native harness hook invocation (`neurastream adapter hook <name> <event>`)
527
+ * using a fast-path no-op when neither `NEURASTREAM_ROLE=sub` nor `NEURASTREAM_MAIN_LAUNCHER=1` is active.
528
+ *
529
+ * Args:
530
+ * args (string[]): Command arguments (`[<name>, <event>]`)
531
+ *
532
+ * Returns:
533
+ * number: Process exit code returned by the adapter hook handler
534
+ */
535
+ function runAdapterHook(args: string[]): number {
536
+ const [name, event] = args;
537
+ if (args.length !== 2 || !name || !event) {
538
+ console.error("usage: neurastream adapter hook <name> <event>");
539
+ return 2;
540
+ }
541
+ let adapter: HarnessAdapter;
542
+ try {
543
+ adapter = getAdapter({ harness: name });
544
+ } catch (err) {
545
+ console.error(err instanceof Error ? err.message : String(err));
546
+ return 2;
547
+ }
548
+ if (!adapter.handleHook) {
549
+ console.error(`adapter "${name}" does not support hook handling`);
550
+ return 2;
551
+ }
552
+ const active = process.env.NEURASTREAM_ROLE === "sub" || process.env.NEURASTREAM_MAIN_LAUNCHER === "1";
553
+ const subUserPrompt = event === "user-prompt" && process.env.NEURASTREAM_ROLE === "sub";
554
+ let res: { code: number; stdout: string };
555
+ if (!active || subUserPrompt) {
556
+ res = adapter.handleHook(event, "", undefined, process.env);
557
+ } else {
558
+ let stdinText = "";
559
+ try {
560
+ stdinText = readFileSync(0, "utf8");
561
+ } catch {}
562
+ let cfg: Config;
563
+ try {
564
+ cfg = loadConfig();
565
+ } catch (err) {
566
+ console.error(err instanceof ConfigError ? err.message : String(err));
567
+ return 1;
568
+ }
569
+ res = adapter.handleHook(event, stdinText, cfg, process.env);
570
+ }
571
+ if (res.stdout) process.stdout.write(res.stdout.endsWith("\n") ? res.stdout : `${res.stdout}\n`);
572
+ return res.code;
573
+ }
package/src/cli/recall.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  // `neurastream recall`: searches the owner's messages and Main's answers (the recall log, see
2
2
  // core/owner-log.ts) and shows an entry with the entry it pairs with. Read-only.
3
3
 
4
- import { getAdapter } from "../adapters/index.ts";
4
+ import { allAdapters, getAdapter } from "../adapters/index.ts";
5
5
  import { nowSec } from "../core/clock.ts";
6
6
  import { ConfigError, loadConfig, type Config } from "../core/config.ts";
7
7
  import { helpDoc, printText } from "../core/help.ts";
@@ -103,7 +103,10 @@ function backfillCli(args: string[], cfg: Config): number {
103
103
  }
104
104
  since = at;
105
105
  }
106
- const written = backfillOwnerLog(cfg, getAdapter(cfg).ownerTurns(cfg, since));
106
+ const turns = allAdapters()
107
+ .flatMap((a) => a.ownerTurns(cfg, since))
108
+ .sort((a, b) => a.at - b.at);
109
+ const written = backfillOwnerLog(cfg, turns);
107
110
  console.log(`backfill: ${written} entries`);
108
111
  return 0;
109
112
  }