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