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.
@@ -13,7 +13,9 @@ import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
13
13
  import { join } from "node:path";
14
14
  import type { Config } from "./config.ts";
15
15
  import { nowSec, strftime } from "./clock.ts";
16
- import { parseWhen, wallToEpoch } from "./reset-time.ts";
16
+ import { allowedAgents } from "./queue/lib.ts";
17
+ import { parseWhen, wallToEpoch, type WallTime } from "./reset-time.ts";
18
+ import { SPAWN_ROLES, type SpawnRole } from "./runner.ts";
17
19
 
18
20
  /** One recorded out-until: `until`/`at` are epoch seconds. */
19
21
  export interface OutRecord {
@@ -126,37 +128,422 @@ export function pinModel(cfg: Config, agent: string): string | null {
126
128
  }
127
129
 
128
130
  /**
129
- * The first reset time a text names, as epoch seconds, or null when it names none we can trust.
130
- * Reuses parseWhen/wallToEpoch: the wall time comes from capture group 1, the zone from group 2
131
- * when the text names one (Z/UTC/GMT, ±HH:MM) and `rule.zone` otherwise. reset-time.ts cannot
132
- * grow an export for this (the plan freezes that file), so the ±HH:MM arithmetic sits here.
131
+ * Resolves an agent's provider from `spawn.profiles[agent].provider`, falling back to the
132
+ * provider prefix of its pin file's `model:` line when unconfigured.
133
+ *
134
+ * Args:
135
+ * cfg (Config): Loaded configuration
136
+ * agent (string): Agent or profile name
137
+ *
138
+ * Returns:
139
+ * string | null: Provider slug, or null when neither profile nor pin names one
133
140
  */
134
- export function resetEpochFromText(text: string, rule: { pattern: string; zone: string }): number | null {
135
- let pattern: RegExp;
141
+ export function agentProvider(cfg: Config, agent: string): string | null {
142
+ const explicit = cfg.spawn.profiles[agent]?.provider?.trim();
143
+ if (explicit) return explicit;
144
+ return providerOfModel(pinModel(cfg, agent));
145
+ }
146
+
147
+ /**
148
+ * Resolves an agent's functional role from `spawn.profiles[agent].role`, defaulting to
149
+ * `"reviewer"` when listed in `review.agents` and `"implementer"` otherwise.
150
+ *
151
+ * Args:
152
+ * cfg (Config): Loaded configuration
153
+ * agent (string): Agent or profile name
154
+ *
155
+ * Returns:
156
+ * SpawnRole: Resolved role (`"implementer" | "planner" | "reviewer"`)
157
+ */
158
+ export function agentRole(cfg: Config, agent: string): SpawnRole {
159
+ const explicit = cfg.spawn.profiles[agent]?.role;
160
+ if (explicit) return explicit;
161
+ return cfg.review.agents.includes(agent) ? "reviewer" : "implementer";
162
+ }
163
+
164
+ function reachableAgentsByRole(cfg: Config, now: number): { byRole: Record<SpawnRole, string[]>; hasSignal: boolean } {
165
+ const byRole: Record<SpawnRole, string[]> = {
166
+ implementer: [],
167
+ planner: [],
168
+ reviewer: [],
169
+ };
170
+ const candidates = [...new Set([...cfg.ledger.prefer, ...Object.keys(cfg.spawn.profiles)])];
171
+ if (candidates.length === 0) return { byRole, hasSignal: false };
172
+ const allowed = allowedAgents(cfg.paths.subagents);
173
+ let hasSignal = false;
174
+ for (const agent of candidates) {
175
+ if (allowed.size > 0 && !allowed.has(agent)) continue;
176
+ const profile = cfg.spawn.profiles[agent];
177
+ const provider = agentProvider(cfg, agent);
178
+ const explicitRole = profile?.role;
179
+ if (provider === null && explicitRole === undefined) continue;
180
+ hasSignal = true;
181
+ if (provider !== null && outUntil(cfg, provider, now) !== null) continue;
182
+ byRole[agentRole(cfg, agent)].push(agent);
183
+ }
184
+ return { byRole, hasSignal };
185
+ }
186
+
187
+ /**
188
+ * Returns currently reachable agents for a given role in `ledger.prefer` order followed by
189
+ * remaining configured profiles, excluding agents whose provider is currently recorded out.
190
+ *
191
+ * Args:
192
+ * cfg (Config): Loaded configuration
193
+ * role (SpawnRole): Target role (`"implementer" | "planner" | "reviewer"`)
194
+ * now (number): Current unix epoch seconds
195
+ *
196
+ * Returns:
197
+ * string[]: Reachable agent names for the role
198
+ */
199
+ export function reachableAgentsForRole(cfg: Config, role: SpawnRole, now: number = nowSec()): string[] {
200
+ return reachableAgentsByRole(cfg, now).byRole[role];
201
+ }
202
+
203
+ /**
204
+ * Formats a single summary line of currently reachable agents grouped by role
205
+ * (`implementer`, `planner`, `reviewer`) in `ledger.prefer` order followed by configured profiles.
206
+ * Returns null when no profile or `ledger.prefer` entry defines a provider or role, or none are reachable.
207
+ *
208
+ * Args:
209
+ * cfg (Config): Loaded configuration
210
+ * now (number): Current unix epoch seconds
211
+ *
212
+ * Returns:
213
+ * string | null: Formatted `reachable: ...` line, or null when unavailable
214
+ */
215
+ export function reachableAgentsLine(cfg: Config, now: number = nowSec()): string | null {
216
+ const { byRole, hasSignal } = reachableAgentsByRole(cfg, now);
217
+ if (!hasSignal) return null;
218
+ const parts: string[] = [];
219
+ for (const role of SPAWN_ROLES) {
220
+ if (byRole[role].length > 0) parts.push(`${role}: ${byRole[role].join(", ")}`);
221
+ }
222
+ if (parts.length === 0) return null;
223
+ return `reachable: ${parts.join(" · ")}`;
224
+ }
225
+
226
+ const HUMAN_MONTHS: Record<string, number> = {
227
+ jan: 1,
228
+ january: 1,
229
+ feb: 2,
230
+ february: 2,
231
+ mar: 3,
232
+ march: 3,
233
+ apr: 4,
234
+ april: 4,
235
+ may: 5,
236
+ jun: 6,
237
+ june: 6,
238
+ jul: 7,
239
+ july: 7,
240
+ aug: 8,
241
+ august: 8,
242
+ sep: 9,
243
+ sept: 9,
244
+ september: 9,
245
+ oct: 10,
246
+ october: 10,
247
+ nov: 11,
248
+ november: 11,
249
+ dec: 12,
250
+ december: 12,
251
+ };
252
+
253
+ const DURATION_UNITS_SEC: Record<string, number> = {
254
+ d: 86400,
255
+ day: 86400,
256
+ days: 86400,
257
+ h: 3600,
258
+ hr: 3600,
259
+ hrs: 3600,
260
+ hour: 3600,
261
+ hours: 3600,
262
+ m: 60,
263
+ min: 60,
264
+ mins: 60,
265
+ minute: 60,
266
+ minutes: 60,
267
+ s: 1,
268
+ sec: 1,
269
+ secs: 1,
270
+ second: 1,
271
+ seconds: 1,
272
+ };
273
+
274
+ const ISO_RESET_RE = /\b(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?)(?:\.\d+)?\s*(Z|[+-]\d{2}:?\d{2})(?![A-Za-z0-9])/i;
275
+ const RELATIVE_RESET_RE =
276
+ /(?:^|[\s(,.:;])(?:in|after)\s*~?\s*((?:\d+(?:\.\d+)?\s*(?:days?|d|hours?|hrs?|hr|h|minutes?|mins?|min|m|seconds?|secs?|sec|s)(?=\d|\s|$|[,.;:!?)\]])(?:\s*,?\s*(?:and\s+)?|\s*)?)+)/i;
277
+ const RELATIVE_TOKEN_RE = /(\d+(?:\.\d+)?)\s*(days?|d|hours?|hrs?|hr|h|minutes?|mins?|min|m|seconds?|secs?|sec|s)(?=\d|\s|$|[,.;:!?)\]])/gi;
278
+ const HUMAN_RESET_RE =
279
+ /\b(?:resets?(?:\s+(?:at|on))?|try\s+again(?:\s+(?:at|on))?|available(?:\s+(?:again\s+)?(?:at|on))?)\s+(?:(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|june?|july?|aug(?:ust)?|sep(?:t(?:ember)?)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\s+(\d{1,2})(?:st|nd|rd|th)?(?:,?\s*(\d{4}))?(?:\s*(?:,|at)\s*|\s+))?(?:(\d{1,2})(?::(\d{2})(?::(\d{2}))?)?\s*(am|pm)\b|(\d{1,2}):(\d{2})(?::(\d{2}))?\b)(?:\s*\(\s*(Z|UTC|GMT|[+-]\d{2}:?\d{2}|[A-Z]{2,5}|[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+)\s*\)|\s+(Z|UTC|GMT|[+-]\d{2}:?\d{2}|[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+))?/i;
280
+
281
+ /**
282
+ * Validates that a wall-clock tuple represents an existing calendar date and time.
283
+ *
284
+ * Args:
285
+ * wall (WallTime): Wall-clock components to validate
286
+ *
287
+ * Returns:
288
+ * boolean: True when calendar date and clock fields are in valid range
289
+ */
290
+ function isValidWall(wall: WallTime): boolean {
291
+ if (wall.mo < 1 || wall.mo > 12 || wall.d < 1 || wall.d > 31) return false;
292
+ if (wall.h < 0 || wall.h > 23 || wall.mi < 0 || wall.mi > 59 || wall.s < 0 || wall.s > 59) return false;
293
+ const check = new Date(Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s));
294
+ return (
295
+ check.getUTCFullYear() === wall.y &&
296
+ check.getUTCMonth() === wall.mo - 1 &&
297
+ check.getUTCDate() === wall.d &&
298
+ check.getUTCHours() === wall.h &&
299
+ check.getUTCMinutes() === wall.mi &&
300
+ check.getUTCSeconds() === wall.s
301
+ );
302
+ }
303
+
304
+ /**
305
+ * Converts a wall-clock time in an explicit zone (UTC, GMT, Z, ±HH:MM offset, or IANA zone)
306
+ * to unix epoch seconds.
307
+ *
308
+ * Args:
309
+ * wall (WallTime): Wall-clock components
310
+ * zone (string): Zone identifier or numeric UTC offset
311
+ *
312
+ * Returns:
313
+ * number | null: Unix epoch seconds, or null if the wall time or zone is invalid
314
+ */
315
+ function zoneToEpoch(wall: WallTime, zone: string): number | null {
316
+ if (!isValidWall(wall)) return null;
317
+ const z = zone.trim();
318
+ const upper = z.toUpperCase();
136
319
  try {
137
- pattern = new RegExp(rule.pattern);
320
+ if (upper === "Z" || upper === "UTC" || upper === "GMT") return wallToEpoch(wall, "UTC");
321
+ const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(z);
322
+ if (offset) {
323
+ const hh = Number(offset[2]);
324
+ const mm = Number(offset[3]);
325
+ if (hh > 23 || mm > 59) return null;
326
+ const minutes = (hh * 60 + mm) * (offset[1] === "+" ? 1 : -1);
327
+ return Math.floor((Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s) - minutes * 60_000) / 1000);
328
+ }
329
+ return wallToEpoch(wall, z);
138
330
  } catch {
139
331
  return null;
140
332
  }
141
- const m = pattern.exec(text);
142
- if (!m) return null;
143
- const wall = m[1] ? parseWhen(m[1]) : null;
144
- if (!wall) return null;
145
- const zone = (m[2] ?? "").trim();
333
+ }
334
+
335
+ /**
336
+ * Resolves the wall-clock components at `epochSec` in the given zone or offset.
337
+ *
338
+ * Args:
339
+ * epochSec (number): Unix epoch seconds
340
+ * zone (string): Zone identifier or numeric UTC offset
341
+ *
342
+ * Returns:
343
+ * WallTime | null: Wall-clock components in `zone`, or null if `zone` is invalid
344
+ */
345
+ function wallInZone(epochSec: number, zone: string): WallTime | null {
346
+ const z = zone.trim();
347
+ const upper = z.toUpperCase();
146
348
  try {
147
- if (!zone || zone === rule.zone) return wallToEpoch(wall, rule.zone);
148
- if (zone === "Z" || zone === "UTC" || zone === "GMT") return wallToEpoch(wall, "UTC");
149
- const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(zone);
349
+ const offset = /^([+-])(\d{2}):?(\d{2})$/.exec(z);
150
350
  if (offset) {
151
- const minutes = (Number(offset[2]) * 60 + Number(offset[3])) * (offset[1] === "+" ? 1 : -1);
152
- return Math.floor((Date.UTC(wall.y, wall.mo - 1, wall.d, wall.h, wall.mi, wall.s) - minutes * 60_000) / 1000);
351
+ const hh = Number(offset[2]);
352
+ const mm = Number(offset[3]);
353
+ if (hh > 23 || mm > 59) return null;
354
+ const minutes = (hh * 60 + mm) * (offset[1] === "+" ? 1 : -1);
355
+ const d = new Date(Math.floor(epochSec) * 1000 + minutes * 60_000);
356
+ return {
357
+ y: d.getUTCFullYear(),
358
+ mo: d.getUTCMonth() + 1,
359
+ d: d.getUTCDate(),
360
+ h: d.getUTCHours(),
361
+ mi: d.getUTCMinutes(),
362
+ s: d.getUTCSeconds(),
363
+ };
153
364
  }
154
- return wallToEpoch(wall, zone);
365
+ const targetZone = upper === "Z" || upper === "UTC" || upper === "GMT" ? "UTC" : z;
366
+ const parts = new Intl.DateTimeFormat("en-US", {
367
+ timeZone: targetZone,
368
+ hourCycle: "h23",
369
+ year: "numeric",
370
+ month: "numeric",
371
+ day: "numeric",
372
+ hour: "numeric",
373
+ minute: "numeric",
374
+ second: "numeric",
375
+ }).formatToParts(new Date(Math.floor(epochSec) * 1000));
376
+ const get = (type: string): number => Number(parts.find(p => p.type === type)?.value);
377
+ return {
378
+ y: get("year"),
379
+ mo: get("month"),
380
+ d: get("day"),
381
+ h: get("hour"),
382
+ mi: get("minute"),
383
+ s: get("second"),
384
+ };
155
385
  } catch {
156
386
  return null;
157
387
  }
158
388
  }
159
389
 
390
+ /**
391
+ * Parses an ISO-8601 timestamp with explicit `Z` or `±HH:MM` offset into unix epoch seconds.
392
+ *
393
+ * Args:
394
+ * text (string): Error or status text
395
+ *
396
+ * Returns:
397
+ * number | null: Unix epoch seconds, or null when no valid ISO-8601 timestamp is present
398
+ */
399
+ function parseIsoResetEpoch(text: string): number | null {
400
+ const m = ISO_RESET_RE.exec(text);
401
+ if (!m?.[1] || !m[2]) return null;
402
+ const wall = parseWhen(m[1]);
403
+ if (!wall) return null;
404
+ return zoneToEpoch(wall, m[2]);
405
+ }
406
+
407
+ /**
408
+ * Parses a relative reset duration (`in ~42091 min`, `in 2 hours 15 minutes`, `after 4h23m12s`,
409
+ * `after 90 seconds`) relative to `now`.
410
+ *
411
+ * Args:
412
+ * text (string): Error or status text
413
+ * now (number): Reference unix epoch seconds
414
+ *
415
+ * Returns:
416
+ * number | null: Unix epoch seconds (`floor(now) + durationSeconds`), or null when none matched
417
+ */
418
+ function parseRelativeResetEpoch(text: string, now: number): number | null {
419
+ const m = RELATIVE_RESET_RE.exec(text);
420
+ if (!m?.[1]) return null;
421
+ let totalSec = 0;
422
+ let matched = false;
423
+ for (const tok of m[1].matchAll(RELATIVE_TOKEN_RE)) {
424
+ const num = Number(tok[1]);
425
+ const unit = (tok[2] ?? "").toLowerCase();
426
+ const mult = DURATION_UNITS_SEC[unit];
427
+ if (!Number.isFinite(num) || !mult) continue;
428
+ totalSec += num * mult;
429
+ matched = true;
430
+ }
431
+ if (!matched || totalSec <= 0) return null;
432
+ return Math.floor(now) + Math.round(totalSec);
433
+ }
434
+
435
+ /**
436
+ * Parses human-readable 12h/24h reset strings with optional month/day/year and optional zone,
437
+ * defaulting to the local timezone and rolling time-only timestamps forward by one day when past `now`.
438
+ *
439
+ * Args:
440
+ * text (string): Error or status text
441
+ * now (number): Reference unix epoch seconds
442
+ *
443
+ * Returns:
444
+ * number | null: Unix epoch seconds, or null when no valid human reset timestamp is present
445
+ */
446
+ function parseHumanResetEpoch(text: string, now: number): number | null {
447
+ const m = HUMAN_RESET_RE.exec(text);
448
+ if (!m) return null;
449
+ const monthName = m[1];
450
+ const dayStr = m[2];
451
+ const yearStr = m[3];
452
+ const h12Str = m[4];
453
+ const mi12Str = m[5];
454
+ const s12Str = m[6];
455
+ const ampm = m[7];
456
+ const h24Str = m[8];
457
+ const mi24Str = m[9];
458
+ const s24Str = m[10];
459
+ const explicitZone = (m[11] ?? m[12])?.trim();
460
+
461
+ let h: number;
462
+ let mi: number;
463
+ let s: number;
464
+ if (ampm && h12Str) {
465
+ const rawH = Number(h12Str);
466
+ mi = mi12Str ? Number(mi12Str) : 0;
467
+ s = s12Str ? Number(s12Str) : 0;
468
+ if (rawH < 1 || rawH > 12 || mi > 59 || s > 59) return null;
469
+ const lower = ampm.toLowerCase();
470
+ h = lower === "am" ? (rawH === 12 ? 0 : rawH) : (rawH === 12 ? 12 : rawH + 12);
471
+ } else if (h24Str && mi24Str) {
472
+ h = Number(h24Str);
473
+ mi = Number(mi24Str);
474
+ s = s24Str ? Number(s24Str) : 0;
475
+ if (h > 23 || mi > 59 || s > 59) return null;
476
+ } else {
477
+ return null;
478
+ }
479
+
480
+ const zone = explicitZone || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
481
+ const nowWall = wallInZone(now, zone);
482
+ if (!nowWall) return null;
483
+
484
+ if (monthName && dayStr) {
485
+ const mo = HUMAN_MONTHS[monthName.toLowerCase()];
486
+ const d = Number(dayStr);
487
+ if (!mo) return null;
488
+ if (yearStr) {
489
+ return zoneToEpoch({ y: Number(yearStr), mo, d, h, mi, s }, zone);
490
+ }
491
+ const thisYear = zoneToEpoch({ y: nowWall.y, mo, d, h, mi, s }, zone);
492
+ if (thisYear !== null && now - thisYear <= 180 * 86400) return thisYear;
493
+ return zoneToEpoch({ y: nowWall.y + 1, mo, d, h, mi, s }, zone);
494
+ }
495
+
496
+ const todayEpoch = zoneToEpoch({ y: nowWall.y, mo: nowWall.mo, d: nowWall.d, h, mi, s }, zone);
497
+ if (todayEpoch === null) return null;
498
+ if (todayEpoch > now) return todayEpoch;
499
+ const nextDay = new Date(Date.UTC(nowWall.y, nowWall.mo - 1, nowWall.d + 1));
500
+ return zoneToEpoch(
501
+ { y: nextDay.getUTCFullYear(), mo: nextDay.getUTCMonth() + 1, d: nextDay.getUTCDate(), h, mi, s },
502
+ zone,
503
+ );
504
+ }
505
+
506
+ /**
507
+ * Extracts the first rate-limit reset time from provider output/error text as unix epoch seconds.
508
+ * Checks in order: configured `rule.pattern` (defaulting bare timestamps to `rule.zone`),
509
+ * ISO-8601 timestamps with explicit `Z` or `±HH:MM` offsets, relative durations (`in`/`after`),
510
+ * and human 12h/24h clock/date reset phrases (defaulting bare times to local zone with +24h rollover).
511
+ *
512
+ * Args:
513
+ * text (string): Provider output or error text
514
+ * rule ({ pattern: string; zone: string }): Configured reset pattern and default zone
515
+ * now (number): Reference unix epoch seconds for relative and time-only rollover calculations
516
+ *
517
+ * Returns:
518
+ * number | null: Parsed reset unix epoch seconds, or null when no valid reset time is found
519
+ */
520
+ export function resetEpochFromText(text: string, rule: { pattern: string; zone: string }, now: number = nowSec()): number | null {
521
+ let pattern: RegExp | null = null;
522
+ try {
523
+ pattern = new RegExp(rule.pattern);
524
+ } catch {
525
+ pattern = null;
526
+ }
527
+ if (pattern) {
528
+ const m = pattern.exec(text);
529
+ if (m) {
530
+ const wall = m[1] ? parseWhen(m[1]) : null;
531
+ if (wall) {
532
+ const zone = (m[2] ?? "").trim();
533
+ if (zone && zone !== rule.zone) return zoneToEpoch(wall, zone);
534
+ const trailing = text.slice((m.index ?? 0) + m[0].length);
535
+ const parenZone = /^\(\s*(Z|UTC|GMT|[+-]\d{2}:?\d{2}|[A-Z]{2,5}|[A-Za-z_]+(?:\/[A-Za-z0-9_+-]+)+)\s*\)/.exec(trailing)?.[1];
536
+ if (parenZone) {
537
+ const explicitEpoch = zoneToEpoch(wall, parenZone);
538
+ if (explicitEpoch !== null) return explicitEpoch;
539
+ }
540
+ return zoneToEpoch(wall, rule.zone);
541
+ }
542
+ }
543
+ }
544
+ return parseIsoResetEpoch(text) ?? parseRelativeResetEpoch(text, now) ?? parseHumanResetEpoch(text, now);
545
+ }
546
+
160
547
  /** What a harness reports for one provider. `partial` is display-only and never an out-until. */
161
548
  export interface ProviderStatus {
162
549
  provider: string;
@@ -0,0 +1,223 @@
1
+ // Harness- and multiplexer-agnostic agent runner contract and spawn helpers.
2
+ // No harness or multiplexer names anywhere in src/core.
3
+
4
+ import type { Config } from "./config.ts";
5
+
6
+ /** Normalized lifecycle state reported by an agent runner. */
7
+ export type AgentLifecycleState = "idle" | "working" | "blocked" | "done" | "unknown";
8
+
9
+ /** Supported pane split directions when launching a helper in a managed pane. */
10
+ export type SpawnDirection = "right" | "down";
11
+
12
+ /** Supported functional roles for spawn profiles used in cross-harness routing. */
13
+ export type SpawnRole = "implementer" | "planner" | "reviewer";
14
+
15
+ /** Valid spawn role values for profile validation and role-grouped routing. */
16
+ export const SPAWN_ROLES: readonly SpawnRole[] = ["implementer", "planner", "reviewer"];
17
+
18
+ /** Per-agent override entry configured under `spawn.profiles.<agent>` in config.yml. */
19
+ export interface SpawnProfileConfig {
20
+ harness?: string;
21
+ fallback_harness?: string;
22
+ runner?: string;
23
+ model?: string;
24
+ provider?: string;
25
+ role?: SpawnRole;
26
+ direction?: SpawnDirection;
27
+ start_timeout_ms?: number;
28
+ timeout_ms?: number;
29
+ args?: string[];
30
+ env?: Record<string, string>;
31
+ }
32
+
33
+ /** Fully resolved spawn profile for one helper agent. */
34
+ export interface SpawnProfile {
35
+ agent: string;
36
+ harness: string;
37
+ fallbackHarness?: string;
38
+ runner: string;
39
+ model?: string;
40
+ provider?: string;
41
+ role?: SpawnRole;
42
+ direction: SpawnDirection;
43
+ startTimeoutMs: number;
44
+ timeoutMs: number;
45
+ args: string[];
46
+ env: Record<string, string>;
47
+ }
48
+
49
+ /** Launch specification passed from the CLI to an `AgentRunner`. */
50
+ export interface SpawnLaunchSpec {
51
+ name: string;
52
+ kind: string;
53
+ cwd: string;
54
+ env: Record<string, string>;
55
+ args: string[];
56
+ direction?: SpawnDirection;
57
+ startTimeoutMs?: number;
58
+ pane?: string;
59
+ }
60
+
61
+ /** Handle identifying a live helper started by an `AgentRunner`. */
62
+ export interface SpawnHandle {
63
+ runner: string;
64
+ target: string;
65
+ name: string;
66
+ paneId: string;
67
+ kind: string;
68
+ cwd: string;
69
+ }
70
+
71
+ /** Options for delivering a prompt/brief to a running helper. */
72
+ export interface SpawnSendOptions {
73
+ wait?: boolean;
74
+ until?: AgentLifecycleState[];
75
+ timeoutMs?: number;
76
+ }
77
+
78
+ /** Result of sending a prompt/brief to a running helper. */
79
+ export interface SpawnSendResult {
80
+ state?: AgentLifecycleState;
81
+ }
82
+
83
+ /** Options for waiting on a helper's lifecycle state transition. */
84
+ export interface SpawnWaitOptions {
85
+ until?: AgentLifecycleState[];
86
+ timeoutMs?: number;
87
+ }
88
+
89
+ /** Result of waiting on a helper's lifecycle state transition. */
90
+ export interface SpawnWaitResult {
91
+ state: AgentLifecycleState;
92
+ }
93
+
94
+ /** Options for reading recent terminal output from a helper. */
95
+ export interface SpawnReadOptions {
96
+ source?: "visible" | "recent" | "recent-unwrapped" | "detection";
97
+ lines?: number;
98
+ }
99
+
100
+ /** Normalized live agent status entry returned by `AgentRunner.list()`. */
101
+ export interface RunnerAgentInfo {
102
+ name: string;
103
+ kind: string;
104
+ paneId: string;
105
+ state: AgentLifecycleState;
106
+ cwd?: string;
107
+ workspaceId?: string;
108
+ tabId?: string;
109
+ }
110
+
111
+ /** Execution-plane interface for starting, prompting, waiting on, reading, listing, and stopping helpers. */
112
+ export interface AgentRunner {
113
+ readonly name: string;
114
+ start(spec: SpawnLaunchSpec): Promise<SpawnHandle>;
115
+ send(handle: SpawnHandle | string, brief: string, opts?: SpawnSendOptions): Promise<SpawnSendResult>;
116
+ wait(handle: SpawnHandle | string, opts?: SpawnWaitOptions): Promise<SpawnWaitResult>;
117
+ read(handle: SpawnHandle | string, opts?: SpawnReadOptions): Promise<string>;
118
+ list(): Promise<RunnerAgentInfo[]>;
119
+ stop(handle: SpawnHandle | string): Promise<void>;
120
+ }
121
+
122
+ const SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
123
+
124
+ /** Options for validating resolved runner and harness names against live registries. */
125
+ export interface ResolveProfileOptions {
126
+ knownRunners?: readonly string[];
127
+ knownHarnesses?: readonly string[];
128
+ /** Active Main harness (e.g. from `NEURASTREAM_HARNESS`) used as default when the profile has no explicit `harness`. */
129
+ defaultHarness?: string;
130
+ }
131
+
132
+ /**
133
+ * Resolves a helper's spawn profile from `cfg.spawn.profiles[agentName]`, falling back to
134
+ * `opts.defaultHarness` (Main's active native harness), then `cfg.harness` and `cfg.spawn` defaults
135
+ * when unconfigured, and validates runner and harness names.
136
+ *
137
+ * Args:
138
+ * agentName (string): Profile or agent name requested by the caller
139
+ * cfg (Config): Loaded configuration
140
+ * opts (ResolveProfileOptions): Optional known runner/harness lists and active default harness
141
+ *
142
+ * Returns:
143
+ * SpawnProfile: Resolved and validated spawn profile
144
+ */
145
+ export function resolveSpawnProfile(agentName: string, cfg: Config, opts: ResolveProfileOptions = {}): SpawnProfile {
146
+ const trimmed = agentName.trim();
147
+ if (!trimmed) throw new Error("spawn profile: agent name must be non-empty");
148
+ const entry = cfg.spawn.profiles[trimmed];
149
+ const activeDefault = opts.defaultHarness?.trim();
150
+ const harness = (entry?.harness ?? (activeDefault || cfg.harness)).trim();
151
+ const rawFallback = (entry?.fallback_harness ?? cfg.spawn.fallback_harness ?? "").trim();
152
+ const runner = (entry?.runner ?? cfg.spawn.default_runner).trim();
153
+ const rawProvider = entry?.provider !== undefined ? entry.provider.trim() : undefined;
154
+ const role = entry?.role;
155
+ const direction = entry?.direction ?? cfg.spawn.direction;
156
+ const startTimeoutMs = entry?.start_timeout_ms ?? cfg.spawn.start_timeout_ms;
157
+ const timeoutMs = entry?.timeout_ms ?? cfg.spawn.timeout_ms;
158
+ if (!SLUG_RE.test(harness)) throw new Error(`spawn profile "${trimmed}": invalid harness name "${harness}"`);
159
+ if (rawFallback !== "" && !SLUG_RE.test(rawFallback)) {
160
+ throw new Error(`spawn profile "${trimmed}": invalid fallback_harness name "${rawFallback}"`);
161
+ }
162
+ if (!SLUG_RE.test(runner)) throw new Error(`spawn profile "${trimmed}": invalid runner name "${runner}"`);
163
+ if (rawProvider !== undefined && !SLUG_RE.test(rawProvider)) {
164
+ throw new Error(`spawn profile "${trimmed}": invalid provider name "${entry?.provider}"`);
165
+ }
166
+ if (role !== undefined && !SPAWN_ROLES.includes(role)) {
167
+ throw new Error(`spawn profile "${trimmed}": role must be "implementer", "planner", or "reviewer"`);
168
+ }
169
+ if (opts.knownHarnesses && !opts.knownHarnesses.includes(harness)) {
170
+ throw new Error(`spawn profile "${trimmed}": unknown harness "${harness}"; known: ${opts.knownHarnesses.join(", ")}`);
171
+ }
172
+ if (rawFallback !== "" && opts.knownHarnesses && !opts.knownHarnesses.includes(rawFallback)) {
173
+ throw new Error(`spawn profile "${trimmed}": unknown fallback_harness "${rawFallback}"; known: ${opts.knownHarnesses.join(", ")}`);
174
+ }
175
+ if (opts.knownRunners && !opts.knownRunners.includes(runner)) {
176
+ throw new Error(`spawn profile "${trimmed}": unknown runner "${runner}"; known: ${opts.knownRunners.join(", ")}`);
177
+ }
178
+ if (direction !== "right" && direction !== "down") {
179
+ throw new Error(`spawn profile "${trimmed}": direction must be "right" or "down"`);
180
+ }
181
+ if (!Number.isFinite(startTimeoutMs) || startTimeoutMs <= 0) {
182
+ throw new Error(`spawn profile "${trimmed}": start_timeout_ms must be > 0`);
183
+ }
184
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
185
+ throw new Error(`spawn profile "${trimmed}": timeout_ms must be > 0`);
186
+ }
187
+ return {
188
+ agent: trimmed,
189
+ harness,
190
+ ...(rawFallback !== "" && rawFallback !== harness ? { fallbackHarness: rawFallback } : {}),
191
+ runner,
192
+ ...(entry?.model !== undefined && entry.model !== "" ? { model: entry.model } : {}),
193
+ ...(rawProvider ? { provider: rawProvider } : {}),
194
+ ...(role !== undefined ? { role } : {}),
195
+ direction,
196
+ startTimeoutMs,
197
+ timeoutMs,
198
+ args: entry?.args ? [...entry.args] : [],
199
+ env: entry?.env ? { ...entry.env } : {},
200
+ };
201
+ }
202
+
203
+ /**
204
+ * Builds deterministic subagent guard environment variables (`NEURASTREAM_ROLE=sub`,
205
+ * `NEURASTREAM_AGENT_ID`, and optional `NEURASTREAM_PLAN`) merged over any extra env pairs.
206
+ *
207
+ * Args:
208
+ * opts ({ agentId: string; plan?: string; extra?: Record<string, string> }): Subagent identity and optional plan/extra env
209
+ *
210
+ * Returns:
211
+ * Record<string, string>: Environment map ready for runner injection
212
+ */
213
+ export function buildSubagentEnv(opts: { agentId: string; plan?: string; extra?: Record<string, string> }): Record<string, string> {
214
+ const agentId = opts.agentId.trim();
215
+ if (!agentId) throw new Error("buildSubagentEnv: agentId must be non-empty");
216
+ const env: Record<string, string> = { ...opts.extra };
217
+ env.NEURASTREAM_ROLE = "sub";
218
+ env.NEURASTREAM_AGENT_ID = agentId;
219
+ if (opts.plan && opts.plan.trim() !== "") {
220
+ env.NEURASTREAM_PLAN = opts.plan.trim();
221
+ }
222
+ return env;
223
+ }