neurastream 0.3.25 → 0.3.27

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.
@@ -0,0 +1,616 @@
1
+ // `neurastream spawn`: harness-agnostic subagent launcher gated by core spawn rules.
2
+ // Imports adapters only through ../adapters/index.ts and runners only through ../runners/index.ts.
3
+
4
+ import { readFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { allAdapters, getAdapter, type HarnessAdapter } from "../adapters/index.ts";
7
+ import { MultiRunSource } from "../core/adapter.ts";
8
+ import { nowSec } from "../core/clock.ts";
9
+ import { ConfigError, loadConfig, type Config } from "../core/config.ts";
10
+ import { checkSpawn } from "../core/guards.ts";
11
+ import { defaultRunner } from "../core/mr-sweep.ts";
12
+ import { agentProvider, agentRole, reachableAgentsForRole, recordOut, resetEpochFromText } from "../core/provider-state.ts";
13
+ import { readIndex } from "../core/queue/lib.ts";
14
+ import { rateLimited } from "../core/rate-limit.ts";
15
+ import { buildSubagentEnv, resolveSpawnProfile, type AgentRunner, type SpawnHandle, type SpawnProfile, type SpawnReadOptions } from "../core/runner.ts";
16
+ import { getRunner, knownRunners } from "../runners/index.ts";
17
+
18
+ export const SPAWN_USAGE = [
19
+ "usage: neurastream spawn --agent <profile> [--name <id>] [--plan <path>] [--cwd <dir>] (--brief <text> | --brief-file <path>) [--no-wait] [--keep-pane] [--json]",
20
+ " neurastream spawn list [--runner <name>] [--json]",
21
+ " neurastream spawn read <target> [--source <visible|recent|recent-unwrapped|detection>] [--lines <N>] [--runner <name>] [--json]",
22
+ " neurastream spawn stop <pane_id> [--runner <name>] [--json]",
23
+ ].join("\n");
24
+
25
+ /** Injectable seams for `runSpawn` unit tests. */
26
+ export interface SpawnDeps {
27
+ loadConfig?: () => Config;
28
+ getAdapter?: (cfg?: Pick<Config, "harness">) => HarnessAdapter;
29
+ allAdapters?: () => HarnessAdapter[];
30
+ getRunner?: (name: string) => AgentRunner;
31
+ knownRunners?: () => string[];
32
+ cwd?: () => string;
33
+ out?: (line: string) => void;
34
+ err?: (line: string) => void;
35
+ }
36
+
37
+ interface ParsedLaunchArgs {
38
+ agent: string;
39
+ name?: string;
40
+ plan?: string;
41
+ cwd?: string;
42
+ brief?: string;
43
+ briefFile?: string;
44
+ noWait: boolean;
45
+ keepPane: boolean;
46
+ json: boolean;
47
+ }
48
+
49
+ const READ_SOURCES = new Set<NonNullable<SpawnReadOptions["source"]>>([
50
+ "visible",
51
+ "recent",
52
+ "recent-unwrapped",
53
+ "detection",
54
+ ]);
55
+
56
+ /**
57
+ * Normalizes an agent instance name into a valid runner handle matching `[a-z][a-z0-9_-]{0,31}`.
58
+ *
59
+ * Args:
60
+ * raw (string): Explicit `--name` or fallback profile name
61
+ *
62
+ * Returns:
63
+ * string: Sanitized handle identifier
64
+ */
65
+ export function sanitizeAgentName(raw: string): string {
66
+ const cleaned = raw
67
+ .trim()
68
+ .toLowerCase()
69
+ .replace(/[^a-z0-9_-]+/g, "-")
70
+ .replace(/^-+|-+$/g, "");
71
+ const prefixed = cleaned === "" ? "sub" : /^[a-z]/.test(cleaned) ? cleaned : `a-${cleaned}`;
72
+ return prefixed.slice(0, 32);
73
+ }
74
+
75
+ /**
76
+ * Reads a `--flag <value>` or `--flag=<value>` argument at index `i`.
77
+ *
78
+ * Args:
79
+ * args (string[]): CLI argument list
80
+ * i (number): Current index
81
+ * flag (string): Flag name without `=`
82
+ *
83
+ * Returns:
84
+ * { value: string; nextIndex: number } | { error: string }: Parsed value and consumed index, or error
85
+ */
86
+ function takeFlagValue(args: string[], i: number, flag: string): { value: string; nextIndex: number } | { error: string } {
87
+ const arg = args[i] ?? "";
88
+ if (arg.startsWith(`${flag}=`)) {
89
+ const value = arg.slice(flag.length + 1);
90
+ return value !== "" ? { value, nextIndex: i } : { error: `${flag} requires a value` };
91
+ }
92
+ const next = args[i + 1];
93
+ if (next === undefined) return { error: `${flag} requires a value` };
94
+ return { value: next, nextIndex: i + 1 };
95
+ }
96
+
97
+ function parseLaunchArgs(args: string[]): ParsedLaunchArgs | { error: string } {
98
+ let agent = "";
99
+ let name: string | undefined;
100
+ let plan: string | undefined;
101
+ let cwd: string | undefined;
102
+ let brief: string | undefined;
103
+ let briefFile: string | undefined;
104
+ let noWait = false;
105
+ let keepPane = false;
106
+ let json = false;
107
+
108
+ for (let i = 0; i < args.length; i++) {
109
+ const arg = args[i] ?? "";
110
+ if (arg === "--no-wait") {
111
+ noWait = true;
112
+ continue;
113
+ }
114
+ if (arg === "--keep-pane") {
115
+ keepPane = true;
116
+ continue;
117
+ }
118
+ if (arg === "--json") {
119
+ json = true;
120
+ continue;
121
+ }
122
+ const matched = ["--agent", "--name", "--plan", "--cwd", "--brief", "--brief-file"].find(
123
+ (f) => arg === f || arg.startsWith(`${f}=`),
124
+ );
125
+ if (!matched) return { error: `unknown argument: ${arg}` };
126
+ const taken = takeFlagValue(args, i, matched);
127
+ if ("error" in taken) return taken;
128
+ i = taken.nextIndex;
129
+ switch (matched) {
130
+ case "--agent":
131
+ agent = taken.value;
132
+ break;
133
+ case "--name":
134
+ name = taken.value;
135
+ break;
136
+ case "--plan":
137
+ plan = taken.value;
138
+ break;
139
+ case "--cwd":
140
+ cwd = taken.value;
141
+ break;
142
+ case "--brief":
143
+ brief = taken.value;
144
+ break;
145
+ case "--brief-file":
146
+ briefFile = taken.value;
147
+ break;
148
+ }
149
+ }
150
+
151
+ if (!agent.trim()) return { error: "--agent <profile> is required" };
152
+ if (brief !== undefined && briefFile !== undefined) return { error: "pass either --brief or --brief-file, not both" };
153
+ if (brief === undefined && briefFile === undefined) return { error: "--brief <text> or --brief-file <path> is required" };
154
+ return { agent: agent.trim(), name, plan, cwd, brief, briefFile, noWait, keepPane, json };
155
+ }
156
+
157
+ function resolveRunnerName(args: string[], cfg: Config): { runnerName: string; rest: string[]; json: boolean } | { error: string } {
158
+ let runnerName = cfg.spawn.default_runner;
159
+ let json = false;
160
+ const rest: string[] = [];
161
+ for (let i = 0; i < args.length; i++) {
162
+ const arg = args[i] ?? "";
163
+ if (arg === "--json") {
164
+ json = true;
165
+ continue;
166
+ }
167
+ if (arg === "--runner" || arg.startsWith("--runner=")) {
168
+ const taken = takeFlagValue(args, i, "--runner");
169
+ if ("error" in taken) return taken;
170
+ runnerName = taken.value;
171
+ i = taken.nextIndex;
172
+ continue;
173
+ }
174
+ rest.push(arg);
175
+ }
176
+ return { runnerName, rest, json };
177
+ }
178
+
179
+ async function runList(args: string[], cfg: Config, deps: Required<SpawnDeps>): Promise<number> {
180
+ const parsed = resolveRunnerName(args, cfg);
181
+ if ("error" in parsed) {
182
+ deps.err(parsed.error);
183
+ return 2;
184
+ }
185
+ if (parsed.rest.length > 0) {
186
+ deps.err(`unknown argument for spawn list: ${parsed.rest[0]}`);
187
+ return 2;
188
+ }
189
+ try {
190
+ const runner = deps.getRunner(parsed.runnerName);
191
+ const agents = await runner.list();
192
+ if (parsed.json) {
193
+ deps.out(JSON.stringify(agents, null, 2));
194
+ } else if (agents.length === 0) {
195
+ deps.out("no live agents");
196
+ } else {
197
+ for (const a of agents) {
198
+ deps.out(`${a.name}\t${a.kind}\t${a.state}\t${a.paneId}${a.cwd ? `\t${a.cwd}` : ""}`);
199
+ }
200
+ }
201
+ return 0;
202
+ } catch (err) {
203
+ const msg = err instanceof Error ? err.message : String(err);
204
+ if (parsed.json) deps.out(JSON.stringify({ ok: false, error: msg }));
205
+ else deps.err(msg);
206
+ return 1;
207
+ }
208
+ }
209
+
210
+ async function runRead(args: string[], cfg: Config, deps: Required<SpawnDeps>): Promise<number> {
211
+ const base = resolveRunnerName(args, cfg);
212
+ if ("error" in base) {
213
+ deps.err(base.error);
214
+ return 2;
215
+ }
216
+ let source: SpawnReadOptions["source"];
217
+ let lines: number | undefined;
218
+ const positional: string[] = [];
219
+ for (let i = 0; i < base.rest.length; i++) {
220
+ const arg = base.rest[i] ?? "";
221
+ if (arg === "--source" || arg.startsWith("--source=")) {
222
+ const taken = takeFlagValue(base.rest, i, "--source");
223
+ if ("error" in taken) {
224
+ deps.err(taken.error);
225
+ return 2;
226
+ }
227
+ if (!READ_SOURCES.has(taken.value as NonNullable<SpawnReadOptions["source"]>)) {
228
+ deps.err(`invalid --source "${taken.value}"`);
229
+ return 2;
230
+ }
231
+ source = taken.value as SpawnReadOptions["source"];
232
+ i = taken.nextIndex;
233
+ continue;
234
+ }
235
+ if (arg === "--lines" || arg.startsWith("--lines=")) {
236
+ const taken = takeFlagValue(base.rest, i, "--lines");
237
+ if ("error" in taken) {
238
+ deps.err(taken.error);
239
+ return 2;
240
+ }
241
+ const n = Number(taken.value);
242
+ if (!Number.isInteger(n) || n < 1) {
243
+ deps.err("--lines must be an integer >= 1");
244
+ return 2;
245
+ }
246
+ lines = n;
247
+ i = taken.nextIndex;
248
+ continue;
249
+ }
250
+ if (arg.startsWith("-")) {
251
+ deps.err(`unknown argument for spawn read: ${arg}`);
252
+ return 2;
253
+ }
254
+ positional.push(arg);
255
+ }
256
+ if (positional.length !== 1) {
257
+ deps.err("usage: neurastream spawn read <target> [--source <source>] [--lines <N>] [--json]");
258
+ return 2;
259
+ }
260
+ const target = positional[0]!;
261
+ try {
262
+ const runner = deps.getRunner(base.runnerName);
263
+ const output = await runner.read(target, { ...(source ? { source } : {}), ...(lines ? { lines } : {}) });
264
+ if (base.json) deps.out(JSON.stringify({ ok: true, target, output }));
265
+ else deps.out(output.replace(/\n$/, ""));
266
+ return 0;
267
+ } catch (err) {
268
+ const msg = err instanceof Error ? err.message : String(err);
269
+ if (base.json) deps.out(JSON.stringify({ ok: false, error: msg }));
270
+ else deps.err(msg);
271
+ return 1;
272
+ }
273
+ }
274
+
275
+ async function runStop(args: string[], cfg: Config, deps: Required<SpawnDeps>): Promise<number> {
276
+ const base = resolveRunnerName(args, cfg);
277
+ if ("error" in base) {
278
+ deps.err(base.error);
279
+ return 2;
280
+ }
281
+ const badFlag = base.rest.find((a) => a.startsWith("-"));
282
+ if (badFlag) {
283
+ deps.err(`unknown argument for spawn stop: ${badFlag}`);
284
+ return 2;
285
+ }
286
+ if (base.rest.length !== 1) {
287
+ deps.err("usage: neurastream spawn stop <pane_id> [--json]");
288
+ return 2;
289
+ }
290
+ const paneId = base.rest[0]!;
291
+ try {
292
+ const runner = deps.getRunner(base.runnerName);
293
+ await runner.stop(paneId);
294
+ if (base.json) deps.out(JSON.stringify({ ok: true, stopped: paneId }));
295
+ else deps.out(`stopped ${paneId}`);
296
+ return 0;
297
+ } catch (err) {
298
+ const msg = err instanceof Error ? err.message : String(err);
299
+ if (base.json) deps.out(JSON.stringify({ ok: false, error: msg }));
300
+ else deps.err(msg);
301
+ return 1;
302
+ }
303
+ }
304
+
305
+ function loadBrief(parsed: ParsedLaunchArgs): string {
306
+ const raw = parsed.brief !== undefined ? parsed.brief : readFileSync(path.resolve(parsed.briefFile!), "utf8");
307
+ if (!raw.trim()) throw new Error("brief text must be non-empty");
308
+ if (!parsed.plan) return raw;
309
+ const planPath = path.resolve(parsed.plan);
310
+ return raw.includes(planPath) ? raw : `Plan: ${planPath}\n\n${raw}`;
311
+ }
312
+
313
+ function inferPlanPath(parsed: ParsedLaunchArgs, brief: string, cfg: Config): string | undefined {
314
+ if (parsed.plan) return path.resolve(parsed.plan);
315
+ try {
316
+ return readIndex(cfg.paths.queue_index).find((file) => brief.includes(file));
317
+ } catch {
318
+ return undefined;
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Records a provider lockout to `provider-out.jsonl` when a helper output or error
324
+ * matches `cfg.guards.rate_limit` and the agent's provider is known.
325
+ *
326
+ * Args:
327
+ * cfg (Config): Loaded configuration
328
+ * agent (string): Agent/profile name being spawned
329
+ * text (string): Helper output or error text to inspect
330
+ * now (number): Current unix epoch seconds
331
+ *
332
+ * Returns:
333
+ * boolean: True when a rate limit was detected in `text`
334
+ */
335
+ function maybeRecordSpawnRateLimit(cfg: Config, agent: string, text: string, now: number = nowSec()): boolean {
336
+ if (!rateLimited("error", text, cfg.guards.rate_limit)) return false;
337
+ const provider = agentProvider(cfg, agent);
338
+ if (provider) {
339
+ const parsedEpoch = resetEpochFromText(
340
+ text,
341
+ {
342
+ pattern: cfg.quota.reset_pattern,
343
+ zone: cfg.quota.reset_tz,
344
+ },
345
+ now,
346
+ );
347
+ const fallbackDuration = Math.min(1800, cfg.guards.rate_limit.probe_interval_s * cfg.guards.rate_limit.max_probes);
348
+ const fallbackEpoch = Math.floor(now) + fallbackDuration;
349
+ recordOut(cfg, provider, parsedEpoch ?? fallbackEpoch, "spawn-rate-limit", Math.floor(now));
350
+ }
351
+ return true;
352
+ }
353
+
354
+ /**
355
+ * Finds the next reachable agent with the same functional role as `failedAgent`.
356
+ *
357
+ * Args:
358
+ * cfg (Config): Loaded configuration
359
+ * failedAgent (string): Agent name that hit a rate limit
360
+ * now (number): Current unix epoch seconds
361
+ *
362
+ * Returns:
363
+ * string | null: Next reachable same-role agent name, or null when none are available
364
+ */
365
+ function nextSameRoleAgent(cfg: Config, failedAgent: string, now: number): string | null {
366
+ const role = agentRole(cfg, failedAgent);
367
+ return reachableAgentsForRole(cfg, role, now).find((agent) => agent !== failedAgent) ?? null;
368
+ }
369
+
370
+ /**
371
+ * Executes `neurastream spawn` and its management subcommands (`list`, `read`, `stop`).
372
+ * Enforces core `checkSpawn` gates before resolving the spawn profile, adapter launch spec,
373
+ * subagent environment, and configured `AgentRunner`. Automatically fails over once to the
374
+ * next reachable same-role agent when a helper hits a rate limit.
375
+ *
376
+ * Args:
377
+ * args (string[]): CLI arguments after `spawn`
378
+ * injectedDeps (SpawnDeps): Optional dependency overrides for tests
379
+ *
380
+ * Returns:
381
+ * Promise<number>: Process exit code (0 success, 1 runtime/blocked/rate-limited error, 2 gate refusal or usage error)
382
+ */
383
+ export async function runSpawn(args: string[], injectedDeps: SpawnDeps = {}): Promise<number> {
384
+ const deps: Required<SpawnDeps> = {
385
+ loadConfig: injectedDeps.loadConfig ?? (() => loadConfig()),
386
+ getAdapter: injectedDeps.getAdapter ?? getAdapter,
387
+ allAdapters: injectedDeps.allAdapters ?? allAdapters,
388
+ getRunner: injectedDeps.getRunner ?? getRunner,
389
+ knownRunners: injectedDeps.knownRunners ?? knownRunners,
390
+ cwd: injectedDeps.cwd ?? (() => process.cwd()),
391
+ out: injectedDeps.out ?? ((line) => console.log(line)),
392
+ err: injectedDeps.err ?? ((line) => console.error(line)),
393
+ };
394
+
395
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h" || args[0] === "help") {
396
+ deps.out(SPAWN_USAGE);
397
+ return args.length === 0 ? 2 : 0;
398
+ }
399
+
400
+ let cfg: Config;
401
+ try {
402
+ cfg = deps.loadConfig();
403
+ } catch (err) {
404
+ deps.err(err instanceof ConfigError ? err.message : String(err));
405
+ return 1;
406
+ }
407
+
408
+ const sub = args[0];
409
+ if (sub === "list") return runList(args.slice(1), cfg, deps);
410
+ if (sub === "read") return runRead(args.slice(1), cfg, deps);
411
+ if (sub === "stop") return runStop(args.slice(1), cfg, deps);
412
+
413
+ const parsed = parseLaunchArgs(args);
414
+ if ("error" in parsed) {
415
+ deps.err(`${parsed.error}\n${SPAWN_USAGE}`);
416
+ return 2;
417
+ }
418
+
419
+ let brief: string;
420
+ try {
421
+ brief = loadBrief(parsed);
422
+ } catch (err) {
423
+ deps.err(err instanceof Error ? err.message : String(err));
424
+ return 2;
425
+ }
426
+
427
+ const initialAgentId = sanitizeAgentName(parsed.name ?? parsed.agent);
428
+ const cwd = parsed.cwd ? path.resolve(parsed.cwd) : deps.cwd();
429
+ const primary = deps.getAdapter(cfg);
430
+ const others = deps.allAdapters().filter((a) => a.name !== primary.name);
431
+ const runSource = new MultiRunSource([primary, ...others].map((a) => a.runSource(cfg)));
432
+ const decision = checkSpawn(
433
+ { agent: parsed.agent, invocationKind: "task", brief, name: initialAgentId },
434
+ cfg,
435
+ defaultRunner,
436
+ runSource,
437
+ );
438
+ if (!decision.allow) {
439
+ if (parsed.json) deps.out(JSON.stringify({ ok: false, allow: false, reason: decision.reason }));
440
+ else deps.err(decision.reason);
441
+ return 2;
442
+ }
443
+
444
+ const planPath = inferPlanPath(parsed, brief, cfg);
445
+ let currentAgent = parsed.agent;
446
+ let failoverFrom: string | undefined;
447
+
448
+ for (let attempt = 0; attempt < 2; attempt++) {
449
+ const agentId = sanitizeAgentName(parsed.name ?? currentAgent);
450
+ let handle: SpawnHandle | null = null;
451
+ let profile: SpawnProfile | null = null;
452
+ let runner: AgentRunner | null = null;
453
+ let keepPane = parsed.keepPane;
454
+
455
+ try {
456
+ profile = resolveSpawnProfile(currentAgent, cfg, {
457
+ knownRunners: deps.knownRunners(),
458
+ knownHarnesses: deps.allAdapters().map((a) => a.name),
459
+ defaultHarness: process.env.NEURASTREAM_HARNESS,
460
+ });
461
+ const resolvedProfile = profile;
462
+ runner = deps.getRunner(resolvedProfile.runner);
463
+ const activeRunner = runner;
464
+
465
+ const startWithHarness = async (harnessName: string): Promise<SpawnHandle> => {
466
+ const targetAdapter = deps.getAdapter({ harness: harnessName });
467
+ const effectiveProfile =
468
+ harnessName === resolvedProfile.harness ? resolvedProfile : { ...resolvedProfile, harness: harnessName };
469
+ const spec = targetAdapter.subagentLaunchSpec?.(effectiveProfile) ?? {
470
+ kind: harnessName,
471
+ args: resolvedProfile.args,
472
+ env: resolvedProfile.env,
473
+ };
474
+ const env = buildSubagentEnv({
475
+ agentId,
476
+ plan: planPath,
477
+ extra: { ...resolvedProfile.env, ...spec.env },
478
+ });
479
+ targetAdapter.prepareSubagentCwd?.(cwd, cfg);
480
+ return activeRunner.start({
481
+ name: agentId,
482
+ kind: spec.kind,
483
+ cwd,
484
+ env,
485
+ args: spec.args,
486
+ direction: resolvedProfile.direction,
487
+ startTimeoutMs: resolvedProfile.startTimeoutMs,
488
+ });
489
+ };
490
+
491
+ let activeHarness = resolvedProfile.harness;
492
+ let fallbackFrom: string | undefined;
493
+ try {
494
+ handle = await startWithHarness(resolvedProfile.harness);
495
+ } catch (primaryErr) {
496
+ if (!resolvedProfile.fallbackHarness) throw primaryErr;
497
+ const primaryMsg = primaryErr instanceof Error ? primaryErr.message : String(primaryErr);
498
+ if (!parsed.json) {
499
+ deps.err(`spawn: ${resolvedProfile.harness} failed to start (${primaryMsg}); falling back to ${resolvedProfile.fallbackHarness}`);
500
+ }
501
+ activeHarness = resolvedProfile.fallbackHarness;
502
+ fallbackFrom = resolvedProfile.harness;
503
+ handle = await startWithHarness(resolvedProfile.fallbackHarness);
504
+ }
505
+
506
+ if (parsed.noWait) {
507
+ await activeRunner.send(handle, brief, { wait: false });
508
+ keepPane = true;
509
+ if (parsed.json) {
510
+ deps.out(
511
+ JSON.stringify({
512
+ ok: true,
513
+ agent: resolvedProfile.agent,
514
+ name: handle.name,
515
+ harness: activeHarness,
516
+ ...(fallbackFrom ? { fallbackFrom } : {}),
517
+ ...(failoverFrom ? { failoverFrom } : {}),
518
+ runner: resolvedProfile.runner,
519
+ paneId: handle.paneId,
520
+ keptPane: true,
521
+ }),
522
+ );
523
+ } else {
524
+ const via = fallbackFrom
525
+ ? `${activeHarness} fallback from ${fallbackFrom} via ${resolvedProfile.runner}`
526
+ : `${activeHarness} via ${resolvedProfile.runner}`;
527
+ const failoverNote = failoverFrom ? `, failover from ${failoverFrom}` : "";
528
+ deps.out(`spawned ${handle.name} in pane ${handle.paneId} (${via}${failoverNote})`);
529
+ }
530
+ return 0;
531
+ }
532
+
533
+ const sent = await activeRunner.send(handle, brief, { wait: true, timeoutMs: resolvedProfile.timeoutMs });
534
+ const output = await activeRunner.read(handle, { source: "recent-unwrapped" });
535
+ const eventNow = nowSec();
536
+ const rateLimitHit = maybeRecordSpawnRateLimit(cfg, resolvedProfile.agent, output, eventNow);
537
+ if (rateLimitHit && attempt === 0) {
538
+ const nextAgent = nextSameRoleAgent(cfg, resolvedProfile.agent, eventNow);
539
+ if (nextAgent) {
540
+ keepPane = false;
541
+ deps.err(`spawn: ${resolvedProfile.agent} hit rate limit; failing over to ${nextAgent}`);
542
+ failoverFrom = resolvedProfile.agent;
543
+ currentAgent = nextAgent;
544
+ continue;
545
+ }
546
+ }
547
+
548
+ const blocked = sent.state === "blocked";
549
+ const failed = blocked || rateLimitHit;
550
+ if (blocked && !rateLimitHit) {
551
+ keepPane = true;
552
+ }
553
+ if (parsed.json) {
554
+ deps.out(
555
+ JSON.stringify({
556
+ ok: !failed,
557
+ ...(blocked ? { blocked: true } : {}),
558
+ ...(rateLimitHit ? { rateLimited: true } : {}),
559
+ agent: resolvedProfile.agent,
560
+ name: handle.name,
561
+ harness: activeHarness,
562
+ ...(fallbackFrom ? { fallbackFrom } : {}),
563
+ ...(failoverFrom ? { failoverFrom } : {}),
564
+ runner: resolvedProfile.runner,
565
+ paneId: handle.paneId,
566
+ status: sent.state ?? "done",
567
+ keptPane: keepPane,
568
+ output,
569
+ }),
570
+ );
571
+ } else {
572
+ if (output.trim() !== "") deps.out(output.replace(/\n$/, ""));
573
+ else deps.out(`${handle.name} finished (${sent.state ?? "done"})`);
574
+ if (rateLimitHit) deps.err(`spawn: ${handle.name} hit rate limit`);
575
+ else if (blocked) deps.err(`spawn: ${handle.name} is blocked and requires input`);
576
+ }
577
+ return failed ? 1 : 0;
578
+ } catch (err) {
579
+ const msg = err instanceof Error ? err.message : String(err);
580
+ const eventNow = nowSec();
581
+ const rateLimitHit = profile ? maybeRecordSpawnRateLimit(cfg, profile.agent, msg, eventNow) : false;
582
+ if (rateLimitHit && profile && attempt === 0) {
583
+ const nextAgent = nextSameRoleAgent(cfg, profile.agent, eventNow);
584
+ if (nextAgent) {
585
+ keepPane = false;
586
+ deps.err(`spawn: ${profile.agent} hit rate limit; failing over to ${nextAgent}`);
587
+ failoverFrom = profile.agent;
588
+ currentAgent = nextAgent;
589
+ continue;
590
+ }
591
+ }
592
+ if (parsed.json) {
593
+ deps.out(
594
+ JSON.stringify({
595
+ ok: false,
596
+ error: msg,
597
+ ...(failoverFrom ? { failoverFrom } : {}),
598
+ ...(handle ? { paneId: handle.paneId } : {}),
599
+ }),
600
+ );
601
+ } else {
602
+ deps.err(msg);
603
+ }
604
+ return 1;
605
+ } finally {
606
+ if (!keepPane && handle && runner) {
607
+ try {
608
+ await runner.stop(handle);
609
+ } catch {
610
+ // best-effort pane cleanup on completion or failure
611
+ }
612
+ }
613
+ }
614
+ }
615
+ return 1;
616
+ }
@@ -49,6 +49,57 @@ export interface RunSource {
49
49
  mainSession(file?: string): MainSession | null;
50
50
  }
51
51
 
52
+ /**
53
+ * Combines multiple RunSource implementations into a single merged view, sorting runs by
54
+ * lastWriteAt descending, deduplicating by run id, and delegating mainSession to the primary source.
55
+ */
56
+ export class MultiRunSource implements RunSource {
57
+ private readonly sources: readonly RunSource[];
58
+
59
+ constructor(sources: readonly RunSource[]) {
60
+ this.sources = sources;
61
+ }
62
+
63
+ /**
64
+ * Lists runs across all registered sources at or after `since`, sorted by `lastWriteAt`
65
+ * descending and deduplicated by `id`.
66
+ *
67
+ * Args:
68
+ * since (number): Minimum unix timestamp (seconds)
69
+ *
70
+ * Returns:
71
+ * Run[]: Merged deduplicated runs sorted newest-first
72
+ */
73
+ listRuns(since: number): Run[] {
74
+ const combined: Run[] = [];
75
+ for (const source of this.sources) {
76
+ combined.push(...source.listRuns(since));
77
+ }
78
+ combined.sort((a, b) => b.lastWriteAt - a.lastWriteAt);
79
+ const seen = new Set<string>();
80
+ const out: Run[] = [];
81
+ for (const run of combined) {
82
+ if (seen.has(run.id)) continue;
83
+ seen.add(run.id);
84
+ out.push(run);
85
+ }
86
+ return out;
87
+ }
88
+
89
+ /**
90
+ * Delegates main-session lookup to the primary RunSource, or returns null when empty.
91
+ *
92
+ * Args:
93
+ * file (string | undefined): Optional explicit session file path
94
+ *
95
+ * Returns:
96
+ * MainSession | null: Primary main session or null
97
+ */
98
+ mainSession(file?: string): MainSession | null {
99
+ return this.sources[0]?.mainSession(file) ?? null;
100
+ }
101
+ }
102
+
52
103
  /** One line of the recall backfill (plan 20261109_2335 P3): an owner prompt or a Main reply found in a session file. `at` is epoch seconds. */
53
104
  export interface OwnerTurn {
54
105
  at: number;
@@ -148,6 +199,8 @@ export interface StopEvent {
148
199
  callsSinceStop: number;
149
200
  idleStops: number;
150
201
  ledgerText: string;
202
+ /** Structured names of live spawned subagents (intersected with staffing state). */
203
+ liveAgents?: string[];
151
204
  /** The reply text Main is stopping with, when the harness has it (20261028_0900 P2: a reply that offers to plan instead of planning refuses the stop). */
152
205
  reply?: string;
153
206
  }
@@ -18,7 +18,10 @@ export function leafKeys(node: unknown, prefix: string[] = []): string[] {
18
18
 
19
19
  export function valueAt(cfg: unknown, key: string): unknown {
20
20
  let node = cfg;
21
- for (const seg of key.split(".")) node = (node as Record<string, unknown>)[seg];
21
+ for (const seg of key.split(".")) {
22
+ if (node === null || node === undefined || typeof node !== "object") return undefined;
23
+ node = (node as Record<string, unknown>)[seg];
24
+ }
22
25
  return node;
23
26
  }
24
27
 
@@ -71,6 +74,11 @@ function setPath(lines: string[], segs: string[], value: string, parent: number,
71
74
  if (k < 0) {
72
75
  k = afterLast(lines, lo, hi);
73
76
  lines.splice(k, 0, `${indent}${seg}:`);
77
+ } else {
78
+ // Expand an inline empty mapping (e.g. `profiles: {}`) before inserting nested keys below it.
79
+ const rest = re.exec(lines[k]!)![2]!;
80
+ const emptyMap = rest.match(/^\s*\{\s*\}(\s+#.*)?$/);
81
+ if (emptyMap) lines[k] = `${indent}${seg}:${emptyMap[1] ?? ""}`;
74
82
  }
75
83
  const end = blockEnd(lines, k + 1, indent.length);
76
84
  const child = lines.slice(k + 1, end).find((l) => !isBlank(l));