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.
@@ -6,6 +6,7 @@ import { homedir } from "node:os";
6
6
  import { dirname, join } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import type { WriteCheckConfig } from "./write-check.ts";
9
+ import { SPAWN_ROLES, type SpawnDirection, type SpawnProfileConfig, type SpawnRole } from "./runner.ts";
9
10
  import { teamConfigError } from "./team-labels.ts";
10
11
 
11
12
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -21,6 +22,15 @@ export class ConfigError extends Error {
21
22
  export interface Config {
22
23
  /** Which adapter (src/adapters/index.ts) serves runs, traces, launch, install and doctor. The template ships the only one; a second harness adds its name here (docs/adapter.md). */
23
24
  harness: string;
25
+ /** Cross-harness helper spawn runner settings and per-agent overrides. */
26
+ spawn: {
27
+ default_runner: string;
28
+ fallback_harness: string;
29
+ direction: SpawnDirection;
30
+ start_timeout_ms: number;
31
+ timeout_ms: number;
32
+ profiles: Record<string, SpawnProfileConfig>;
33
+ };
24
34
  /** Live project rules (src/core/repo-rules.ts): a repo's own AGENTS.md, handed to the agent that works in it. */
25
35
  rules: {
26
36
  /** Largest rules text a hook injects; past it the text is cut and one line names the file. */
@@ -551,8 +561,77 @@ function applyEnv(cfg: Record<string, unknown>, env: NodeJS.ProcessEnv): void {
551
561
  }
552
562
  }
553
563
 
564
+ const SPAWN_PROFILE_KEYS = new Set(["harness", "fallback_harness", "runner", "model", "provider", "role", "direction", "start_timeout_ms", "timeout_ms", "args", "env"]);
565
+ const SPAWN_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
566
+
567
+ /** Validates the `spawn` configuration block and all configured helper profiles. */
568
+ function checkSpawnConfig(spawn: Config["spawn"]): void {
569
+ if (typeof spawn.default_runner !== "string" || !SPAWN_SLUG_RE.test(spawn.default_runner)) {
570
+ throw new ConfigError("spawn.default_runner must be a non-empty runner slug");
571
+ }
572
+ if (typeof spawn.fallback_harness !== "string" || (spawn.fallback_harness !== "" && !SPAWN_SLUG_RE.test(spawn.fallback_harness))) {
573
+ throw new ConfigError("spawn.fallback_harness must be empty or a valid harness slug");
574
+ }
575
+ if (spawn.direction !== "right" && spawn.direction !== "down") {
576
+ throw new ConfigError('spawn.direction must be "right" or "down"');
577
+ }
578
+ if (typeof spawn.start_timeout_ms !== "number" || !Number.isFinite(spawn.start_timeout_ms) || !(spawn.start_timeout_ms > 0)) {
579
+ throw new ConfigError("spawn.start_timeout_ms must be a number > 0");
580
+ }
581
+ if (typeof spawn.timeout_ms !== "number" || !Number.isFinite(spawn.timeout_ms) || !(spawn.timeout_ms > 0)) {
582
+ throw new ConfigError("spawn.timeout_ms must be a number > 0");
583
+ }
584
+ if (!isObj(spawn.profiles)) {
585
+ throw new ConfigError("spawn.profiles must be an object");
586
+ }
587
+ for (const [name, raw] of Object.entries(spawn.profiles)) {
588
+ const at = `spawn.profiles.${name}`;
589
+ if (!isObj(raw)) throw new ConfigError(`${at} must be an object`);
590
+ for (const key of Object.keys(raw)) {
591
+ if (!SPAWN_PROFILE_KEYS.has(key)) throw new ConfigError(`unknown key ${at}.${key}`);
592
+ }
593
+ if (raw.harness !== undefined && (typeof raw.harness !== "string" || !SPAWN_SLUG_RE.test(raw.harness))) {
594
+ throw new ConfigError(`${at}.harness must be a non-empty harness slug`);
595
+ }
596
+ if (
597
+ raw.fallback_harness !== undefined &&
598
+ (typeof raw.fallback_harness !== "string" || (raw.fallback_harness !== "" && !SPAWN_SLUG_RE.test(raw.fallback_harness)))
599
+ ) {
600
+ throw new ConfigError(`${at}.fallback_harness must be empty or a valid harness slug`);
601
+ }
602
+ if (raw.runner !== undefined && (typeof raw.runner !== "string" || !SPAWN_SLUG_RE.test(raw.runner))) {
603
+ throw new ConfigError(`${at}.runner must be a non-empty runner slug`);
604
+ }
605
+ if (raw.model !== undefined && typeof raw.model !== "string") {
606
+ throw new ConfigError(`${at}.model must be a string`);
607
+ }
608
+ if (raw.provider !== undefined && (typeof raw.provider !== "string" || !SPAWN_SLUG_RE.test(raw.provider))) {
609
+ throw new ConfigError(`${at}.provider must be a non-empty provider slug`);
610
+ }
611
+ if (raw.role !== undefined && (typeof raw.role !== "string" || !SPAWN_ROLES.includes(raw.role as SpawnRole))) {
612
+ throw new ConfigError(`${at}.role must be "implementer", "planner", or "reviewer"`);
613
+ }
614
+ if (raw.direction !== undefined && raw.direction !== "right" && raw.direction !== "down") {
615
+ throw new ConfigError(`${at}.direction must be "right" or "down"`);
616
+ }
617
+ if (raw.start_timeout_ms !== undefined && (typeof raw.start_timeout_ms !== "number" || !Number.isFinite(raw.start_timeout_ms) || !(raw.start_timeout_ms > 0))) {
618
+ throw new ConfigError(`${at}.start_timeout_ms must be a number > 0`);
619
+ }
620
+ if (raw.timeout_ms !== undefined && (typeof raw.timeout_ms !== "number" || !Number.isFinite(raw.timeout_ms) || !(raw.timeout_ms > 0))) {
621
+ throw new ConfigError(`${at}.timeout_ms must be a number > 0`);
622
+ }
623
+ if (raw.args !== undefined && (!Array.isArray(raw.args) || raw.args.some(a => typeof a !== "string"))) {
624
+ throw new ConfigError(`${at}.args must be a list of strings`);
625
+ }
626
+ if (raw.env !== undefined && (!isObj(raw.env) || Object.values(raw.env).some(v => typeof v !== "string"))) {
627
+ throw new ConfigError(`${at}.env must be an object mapping strings to strings`);
628
+ }
629
+ }
630
+ }
631
+
554
632
  function check(cfg: Config): void {
555
633
  if (typeof cfg.harness !== "string" || cfg.harness === "") throw new ConfigError("harness must be a non-empty string");
634
+ checkSpawnConfig(cfg.spawn);
556
635
  try {
557
636
  const pattern = cfg.quota.reset_pattern;
558
637
  new RegExp(pattern);
@@ -6,12 +6,12 @@ import type { Decision, RunSource, SpawnEvent } from "../adapter.ts";
6
6
  import { currentPlanner, currentTier } from "../autonomy.ts";
7
7
  import { lint } from "../brief-lint.ts";
8
8
  import { heldByOther, type ClaimStore } from "../claims.ts";
9
- import { nowSec } from "../clock.ts";
9
+ import { nowSec, strftime } from "../clock.ts";
10
10
  import type { Config } from "../config.ts";
11
11
  import { ownerSaid, readOwnerMessages, type OwnerMessage } from "../incidents.ts";
12
12
  import { defaultRunner, type CommandRunner } from "../mr-sweep.ts";
13
13
  import { approvalProblem } from "../plan-approval.ts";
14
- import { outUntil, pinModel, providerOfModel, readOut } from "../provider-state.ts";
14
+ import { agentProvider, agentRole, outUntil, reachableAgentsForRole, readOut } from "../provider-state.ts";
15
15
  import * as q from "../queue/lib.ts";
16
16
  import type { Plan } from "../queue/lib.ts";
17
17
  import { realGraphify, type ReuseGraph } from "../reuse-map.ts";
@@ -204,7 +204,7 @@ export function preferProblem(agent: string, brief: string, runningJobs: readonl
204
204
  if (/\bPick note:/i.test(brief)) return null;
205
205
  for (let j = 0; j < mine; j++) {
206
206
  const higher = prefer[j]!;
207
- const provider = providerOfModel(pinModel(cfg, higher));
207
+ const provider = agentProvider(cfg, higher);
208
208
  if (provider === null || outUntil(cfg, provider) !== null) continue; // unknown or out
209
209
  const running = (runningJobs ?? []).filter(l => l.toLowerCase().includes(higher.toLowerCase())).length;
210
210
  if (running >= cfg.ledger.max_running_per_provider) continue; // the higher pick is at its provider cap
@@ -213,11 +213,41 @@ export function preferProblem(agent: string, brief: string, runningJobs: readonl
213
213
  return null;
214
214
  }
215
215
 
216
+ /**
217
+ * Refuses spawning an agent whose resolved provider is recorded out in `provider-out.jsonl`,
218
+ * naming the provider, local reset time, and reachable same-role alternatives, unless the brief
219
+ * carries `Pick note: <why>`.
220
+ *
221
+ * Args:
222
+ * agent (string): Agent/profile name being spawned
223
+ * brief (string): Task brief text
224
+ * cfg (Config): Loaded configuration
225
+ * now (number): Current unix epoch seconds
226
+ *
227
+ * Returns:
228
+ * string | null: Refusal reason, or null when allowed or overridden
229
+ */
230
+ export function providerOutProblem(agent: string, brief: string, cfg: Config, now: number = nowSec()): string | null {
231
+ if (/\bPick note:/i.test(brief)) return null;
232
+ const provider = agentProvider(cfg, agent);
233
+ if (provider === null) return null;
234
+ const until = outUntil(cfg, provider, now);
235
+ if (until === null) return null;
236
+ const role = agentRole(cfg, agent);
237
+ const alts = reachableAgentsForRole(cfg, role, now).filter(a => a !== agent);
238
+ const when = strftime(until, "%Y-%m-%d %H:%M");
239
+ const altText =
240
+ alts.length > 0
241
+ ? ` — spawn ${alts.join(" or ")} (${role}) instead, or add "Pick note: <why>" to override.`
242
+ : ` — add "Pick note: <why>" to override.`;
243
+ return `provider ${provider} is out until ${when} (local)${altText}`;
244
+ }
245
+
216
246
  /** P4 (plan 20261031_1207): `agent-ledger --cap`'s FULL line at spawn time — the agent's provider already runs its full share of live subagents. Counted from the caller's running job labels, the live data preferProblem counts (a caller without job info counts 0). */
217
247
  function ledgerCapProblem(agent: string, runningJobs: readonly string[] | undefined, cfg: Config): string | null {
218
- const provider = providerOfModel(pinModel(cfg, agent));
248
+ const provider = agentProvider(cfg, agent);
219
249
  if (provider === null || outUntil(cfg, provider) !== null) return null;
220
- const sharers = [agent, ...cfg.ledger.prefer.filter(a => providerOfModel(pinModel(cfg, a)) === provider)];
250
+ const sharers = [agent, ...cfg.ledger.prefer.filter(a => agentProvider(cfg, a) === provider)];
221
251
  const running = (runningJobs ?? []).filter(l => sharers.some(n => l.toLowerCase().includes(n.toLowerCase()))).length;
222
252
  if (running < cfg.ledger.max_running_per_provider) return null;
223
253
  return `provider ${provider} is at its cap (${running} live of ${cfg.ledger.max_running_per_provider} running); stop or wait for one before spawning more.`;
@@ -255,8 +285,8 @@ export function providerClaimProblem(text: string, cfg: Config): string | null {
255
285
  const free = (provider: string | null): boolean => provider !== null && recorded.has(provider) && outUntil(cfg, provider) === null;
256
286
  const names = new Map<string, string>();
257
287
  for (const p of cfg.ledger.providers) if (free(p)) names.set(p, p);
258
- for (const agent of cfg.ledger.prefer) {
259
- const provider = providerOfModel(pinModel(cfg, agent));
288
+ for (const agent of new Set([...cfg.ledger.prefer, ...Object.keys(cfg.spawn.profiles)])) {
289
+ const provider = agentProvider(cfg, agent);
260
290
  if (free(provider) && !names.has(agent) && provider !== null) names.set(agent, provider);
261
291
  }
262
292
  if (!names.size || !/\bis\b/i.test(text)) return null;
@@ -529,8 +559,13 @@ export function spawnProblem(
529
559
  const claim = providerClaimProblem(joined, cfg);
530
560
  if (claim) problems.push(claim);
531
561
  for (const t of tasks) {
532
- const pick = preferProblem(String(t?.agent ?? "task"), `${context}\n${String(t?.task ?? "")}`, runningJobs, cfg);
533
- if (pick) problems.push(`${String(t?.name ?? t?.agent ?? "task")}: ${pick}`);
562
+ const agent = String(t?.agent ?? "task");
563
+ const taskLabel = String(t?.name ?? agent);
564
+ const taskBrief = `${context}\n${String(t?.task ?? "")}`;
565
+ const out = providerOutProblem(agent, taskBrief, cfg);
566
+ if (out) problems.push(`${taskLabel}: ${out}`);
567
+ const pick = preferProblem(agent, taskBrief, runningJobs, cfg);
568
+ if (pick) problems.push(`${taskLabel}: ${pick}`);
534
569
  }
535
570
  // Priority gate (20261025_0215 P3): once per `task` call, over the plans this call names; the
536
571
  // skip lines may sit in the shared context or any task text.
@@ -683,6 +718,8 @@ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = def
683
718
  if (inc) problems.push(inc);
684
719
  const claim = providerClaimProblem(e.brief, cfg);
685
720
  if (claim) problems.push(`${e.agent}: ${claim}`);
721
+ const out = providerOutProblem(e.agent, e.brief, cfg);
722
+ if (out) problems.push(`${e.agent}: ${out}`);
686
723
  const pick = preferProblem(e.agent, e.brief, e.runningJobs, cfg);
687
724
  if (pick) problems.push(`${e.agent}: ${pick}`);
688
725
  const verdict = spawnVerdict(e.agent, problems, named.length ? named : briefPlans(e.brief, cfg).map(p => p.file), e.runningJobs, cfg);
@@ -4,6 +4,7 @@
4
4
  import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
5
5
  import path from "node:path";
6
6
  import type { Decision } from "../adapter.ts";
7
+ import { currentTier } from "../autonomy.ts";
7
8
  import type { Claim, Unreachable } from "../claims.ts";
8
9
  import { nowSec, strftime } from "../clock.ts";
9
10
  import type { Config } from "../config.ts";
@@ -178,6 +179,28 @@ export function mainCallsResetMs(w: EditWindow): number | null {
178
179
  return w.mainCalls > 0 ? ((w.mainCallsStart ?? 0) + MAIN_CALLS_RESET_SEC) * 1000 : null;
179
180
  }
180
181
 
182
+ /**
183
+ * Returns the latest future reset timestamp (ms since epoch) of any Main call or edit-window cap
184
+ * currently holding Main at `now`, or `null` when no limit is holding Main.
185
+ *
186
+ * Args:
187
+ * cfg (Config): Loaded configuration
188
+ * now (number): Reference epoch timestamp in milliseconds
189
+ *
190
+ * Returns:
191
+ * number | null: Latest pending reset timestamp in ms, or null when uncapped
192
+ */
193
+ export function nextLimitResetMs(cfg: Config, now = Date.now()): number | null {
194
+ const w = readWindow(cfg.paths);
195
+ const tier = currentTier(cfg);
196
+ const resets: number[] = [];
197
+ const calls = mainCallsResetMs(w);
198
+ if (mainCallsCapOn(cfg, tier) && w.mainCalls >= cfg.guards.main_max_calls && calls !== null && calls > now) resets.push(calls);
199
+ const edits = editWindowEndMs(w, cfg);
200
+ if (w.used.length >= mainEditLimit(cfg, tier) && edits > now) resets.push(edits);
201
+ return resets.length > 0 ? Math.max(...resets) : null;
202
+ }
203
+
181
204
  /** Main's terminal hand-back (the adapter's agent_end without willContinue): the turn is over, so
182
205
  * the next one starts at 0 calls. The edit window keeps its own reset rules. */
183
206
  export function resetMainCalls(paths: Pick<q.QueuePaths, "queue_state">): void {
@@ -197,9 +197,10 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
197
197
  // running subagent's brief names it (staffing ∩ live ledger); unrelated live subagents release
198
198
  // nothing. Valve (20261031_2320): like the incident block above, empty stops count toward
199
199
  // cfg.guards.idle_stops; a stop with calls in between resets the count and re-locks.
200
+ const liveAll = [...new Set([...liveSubagents(e.ledgerText), ...(e.liveAgents ?? [])])];
200
201
  const locked = q.activePlans(cfg.paths).filter(p => p.status === "open" && q.autoCloseCandidate(p) && q.lastCloseFailed(p.file, cfg.paths));
201
202
  if (locked.length) {
202
- const staffed = staffedPlans(readStaffing(cfg.paths), liveSubagents(e.ledgerText));
203
+ const staffed = staffedPlans(readStaffing(cfg.paths), liveAll);
203
204
  const unworked = locked.filter(s => !staffed.includes(s.file));
204
205
  if (unworked.length) {
205
206
  if (state.callsSinceStop === 0) state.idleStops++;
@@ -222,9 +223,8 @@ export function checkStop(e: StopEvent, cfg: Config): Decision {
222
223
  }
223
224
  }
224
225
  if (open.length === 0) return { ...ALLOW, state };
225
- const live = liveSubagents(e.ledgerText);
226
- if (live.length > 0) {
227
- log(cfg.paths.guard_log, `ALLOW stop: live subagents: ${live.join(", ")}`);
226
+ if (liveAll.length > 0) {
227
+ log(cfg.paths.guard_log, `ALLOW stop: live subagents: ${liveAll.join(", ")}`);
228
228
  return { ...ALLOW, state };
229
229
  }
230
230
  if (state.callsSinceStop === 0) state.idleStops++;