neurastream 0.3.27 → 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 +15 -3
- package/src/adapters/codex/adapter.ts +1 -0
- package/src/adapters/index.ts +25 -10
- package/src/adapters/omp/index.ts +5 -2
- package/src/adapters/shared.ts +301 -22
- package/src/cli/spawn.ts +18 -5
- package/src/core/guards/spawn.ts +1 -1
- package/src/core/guards/stop.ts +6 -4
- package/src/core/guards/tool.ts +65 -9
- package/templates/config.yml +1 -1
package/package.json
CHANGED
|
@@ -48,7 +48,9 @@ import {
|
|
|
48
48
|
statMtimeSec,
|
|
49
49
|
str,
|
|
50
50
|
subagentLaunchSpecFrom,
|
|
51
|
+
subSpawnBlockReason,
|
|
51
52
|
writeJsonConfigObject,
|
|
53
|
+
applyHookChatCommand,
|
|
52
54
|
} from "../shared.ts";
|
|
53
55
|
|
|
54
56
|
/** Hook command wired into Antigravity's SessionStart lifecycle. */
|
|
@@ -65,9 +67,12 @@ export const AGY_STOP_CMD = "neurastream adapter hook agy stop";
|
|
|
65
67
|
|
|
66
68
|
const AGY_TOOL_MAP: Record<string, string> = {
|
|
67
69
|
run_command: "bash",
|
|
70
|
+
write_file: "write",
|
|
68
71
|
write_to_file: "write",
|
|
72
|
+
edit_file: "edit",
|
|
69
73
|
replace_file_content: "edit",
|
|
70
74
|
multi_replace_file_content: "edit",
|
|
75
|
+
read_file: "read",
|
|
71
76
|
view_file: "read",
|
|
72
77
|
view_file_outline: "read",
|
|
73
78
|
view_code_item: "read",
|
|
@@ -399,7 +404,9 @@ export function handleAgyHook(
|
|
|
399
404
|
const payload = parseHookPayload(stdinText);
|
|
400
405
|
if (isDuplicateAgyPrompt(payload, cfg)) return { code: 0, stdout: "{}" };
|
|
401
406
|
const prompt = extractHookPrompt(payload);
|
|
402
|
-
const
|
|
407
|
+
const cmdNote = applyHookChatCommand(prompt, cfg);
|
|
408
|
+
const injected = checkInject({ inject: prompt, agent: "main" }, cfg).inject;
|
|
409
|
+
const text = [cmdNote, injected].filter(Boolean).join("\n");
|
|
403
410
|
return {
|
|
404
411
|
code: 0,
|
|
405
412
|
stdout: text ? JSON.stringify({ injectSteps: [{ systemMessage: { systemMessage: text } }] }) : "{}",
|
|
@@ -412,8 +419,13 @@ export function handleAgyHook(
|
|
|
412
419
|
const toolCall = asObj(payload.toolCall) ?? {};
|
|
413
420
|
const rawTool = typeof toolCall.name === "string" ? toolCall.name : typeof payload.tool === "string" ? payload.tool : "";
|
|
414
421
|
const agent = hookAgent(env);
|
|
415
|
-
if (
|
|
416
|
-
|
|
422
|
+
if (rawTool === "invoke_subagent") {
|
|
423
|
+
if (agent === "sub") {
|
|
424
|
+
return { code: 0, stdout: JSON.stringify({ decision: "deny", reason: subSpawnBlockReason(rawTool) }) };
|
|
425
|
+
}
|
|
426
|
+
if (agent === "main" && env.HERDR_ENV === "1") {
|
|
427
|
+
return { code: 0, stdout: JSON.stringify({ decision: "deny", reason: nativeSpawnBlockReason(rawTool) }) };
|
|
428
|
+
}
|
|
417
429
|
}
|
|
418
430
|
const rawArgs = asObj(toolCall.args) ?? asObj(payload.args) ?? {};
|
|
419
431
|
const ws = Array.isArray(payload.workspacePaths) ? payload.workspacePaths : [];
|
|
@@ -460,6 +460,7 @@ export function handleCodexHook(
|
|
|
460
460
|
env,
|
|
461
461
|
defaultId: "codex",
|
|
462
462
|
toolMap: CODEX_TOOL_MAP,
|
|
463
|
+
nativeSpawnTools: ["spawn_agent"],
|
|
463
464
|
extraPaths: extractPatchPaths,
|
|
464
465
|
fallbackSessionId: (payload) => str(payload.session_id) ?? str(payload.thread_id),
|
|
465
466
|
formatPreToolDeny: (reason) => JSON.stringify({ decision: "deny", reason }),
|
package/src/adapters/index.ts
CHANGED
|
@@ -63,25 +63,40 @@ export interface HarnessAdapter {
|
|
|
63
63
|
handleHook?(event: string, stdinText: string, cfg: Config | undefined, env?: NodeJS.ProcessEnv): { code: number; stdout: string };
|
|
64
64
|
}
|
|
65
65
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
66
|
+
let adaptersCache: Record<string, HarnessAdapter> | null = null;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Lazily builds and caches the harness adapter map so circular module imports
|
|
70
|
+
* between `hook-bridge.ts`, `shared.ts`, and adapter modules cannot hit top-level TDZ.
|
|
71
|
+
*
|
|
72
|
+
* Returns:
|
|
73
|
+
* Record<string, HarnessAdapter>: Map of harness names to adapter instances
|
|
74
|
+
*/
|
|
75
|
+
function adaptersMap(): Record<string, HarnessAdapter> {
|
|
76
|
+
if (!adaptersCache) {
|
|
77
|
+
adaptersCache = {
|
|
78
|
+
[ompAdapter.name]: ompAdapter,
|
|
79
|
+
[agyAdapter.name]: agyAdapter,
|
|
80
|
+
[claudeAdapter.name]: claudeAdapter,
|
|
81
|
+
[codexAdapter.name]: codexAdapter,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
return adaptersCache;
|
|
85
|
+
}
|
|
72
86
|
|
|
73
87
|
/** The adapter the config names (`harness:`; without a config, the shipped default). An unknown
|
|
74
88
|
* name throws, so a typo fails loudly instead of silently reading another harness's files. */
|
|
75
89
|
export function getAdapter(cfg?: Pick<Config, "harness">): HarnessAdapter {
|
|
76
90
|
const name = cfg?.harness ?? "omp";
|
|
77
|
-
const
|
|
78
|
-
|
|
91
|
+
const adapters = adaptersMap();
|
|
92
|
+
const adapter = adapters[name];
|
|
93
|
+
if (!adapter) throw new Error(`unknown harness "${name}"; known: ${Object.keys(adapters).join(", ")}`);
|
|
79
94
|
return adapter;
|
|
80
95
|
}
|
|
81
96
|
|
|
82
97
|
/** Every registered harness with the command it runs (setup checks those are on PATH). */
|
|
83
98
|
export function harnessBins(): Pick<HarnessAdapter, "name" | "bin">[] {
|
|
84
|
-
return Object.values(
|
|
99
|
+
return Object.values(adaptersMap());
|
|
85
100
|
}
|
|
86
101
|
|
|
87
102
|
/**
|
|
@@ -91,5 +106,5 @@ export function harnessBins(): Pick<HarnessAdapter, "name" | "bin">[] {
|
|
|
91
106
|
* HarnessAdapter[]: All registered harness adapters
|
|
92
107
|
*/
|
|
93
108
|
export function allAdapters(): HarnessAdapter[] {
|
|
94
|
-
return Object.values(
|
|
109
|
+
return Object.values(adaptersMap());
|
|
95
110
|
}
|
|
@@ -564,9 +564,12 @@ export function createOmpAdapter(pi: ExtensionHost, initial: Config, freshConfig
|
|
|
564
564
|
});
|
|
565
565
|
|
|
566
566
|
// The spawn event carries no brief, so the plan gate runs at the task tool call (original
|
|
567
|
-
// behaviour); here only the allow-list
|
|
568
|
-
pi.on("before_subagent_spawn", (event,
|
|
567
|
+
// behaviour); here only the allow-list, task-only rule, and Main-only guard apply.
|
|
568
|
+
pi.on("before_subagent_spawn", (event, ctx) => {
|
|
569
569
|
cfg = freshPlannerConfig(freshConfig);
|
|
570
|
+
if (process.env.NEURASTREAM_ROLE === "sub" || asCtx(ctx).kind === "sub") {
|
|
571
|
+
return { block: true, reason: "plan-guard: only Main may spawn subagents." };
|
|
572
|
+
}
|
|
570
573
|
const agent = asString(asRecord(event).agent);
|
|
571
574
|
const kind = asString(asRecord(event).invocationKind);
|
|
572
575
|
if (!q.allowedAgents(cfg.paths.subagents).has(agent))
|
package/src/adapters/shared.ts
CHANGED
|
@@ -4,9 +4,10 @@
|
|
|
4
4
|
import { spawn, spawnSync } from "node:child_process";
|
|
5
5
|
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
|
-
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
8
|
import type { OwnerTurn, Run, RunSource, TraceRun, TraceSource, TraceUsage } from "../core/adapter.ts";
|
|
9
|
-
import { currentTier } from "../core/autonomy.ts";
|
|
9
|
+
import { chatGo, chatPlanner, chatTier, currentTier } from "../core/autonomy.ts";
|
|
10
|
+
import { strftime } from "../core/clock.ts";
|
|
10
11
|
import type { Config } from "../core/config.ts";
|
|
11
12
|
import {
|
|
12
13
|
checkInject,
|
|
@@ -19,6 +20,10 @@ import {
|
|
|
19
20
|
openQueue,
|
|
20
21
|
readWindow,
|
|
21
22
|
} from "../core/guards.ts";
|
|
23
|
+
import { chatApprove } from "../core/plan-approval.ts";
|
|
24
|
+
import { recordOut, resetEpochFromText } from "../core/provider-state.ts";
|
|
25
|
+
import * as q from "../core/queue/lib.ts";
|
|
26
|
+
import { rateLimited } from "../core/rate-limit.ts";
|
|
22
27
|
import type { SpawnProfile } from "../core/runner.ts";
|
|
23
28
|
import {
|
|
24
29
|
buildSessionStartContext,
|
|
@@ -573,6 +578,17 @@ export function runAdapterDoctorCli(
|
|
|
573
578
|
/** Wake prompt delivered when Main's per-turn call or edit-window cap resets with plans open. */
|
|
574
579
|
export const LIMIT_WAKE_TEXT = "main-guard: the call/edit limit has reset — continue the queue where you stopped.";
|
|
575
580
|
|
|
581
|
+
/** Wake prompt delivered when Main's provider quota or rate limit resets with plans open. */
|
|
582
|
+
export const PROVIDER_LIMIT_WAKE_TEXT =
|
|
583
|
+
"main-guard: the provider cooldown has reset — continue the queue where you stopped.";
|
|
584
|
+
|
|
585
|
+
/** Rate-limit snippet extracted from Main's `herdr` pane scrollback tail. */
|
|
586
|
+
export interface PaneRateLimitMatch {
|
|
587
|
+
snippet: string;
|
|
588
|
+
sig: string;
|
|
589
|
+
retryAfterMs: number | null;
|
|
590
|
+
}
|
|
591
|
+
|
|
576
592
|
/** Injectable dependencies and options for `startPaneLimitWake`. */
|
|
577
593
|
export interface PaneLimitWakeOptions {
|
|
578
594
|
cfg: Config | (() => Config);
|
|
@@ -580,6 +596,8 @@ export interface PaneLimitWakeOptions {
|
|
|
580
596
|
pollMs?: number;
|
|
581
597
|
nowMs?: () => number;
|
|
582
598
|
exec?: (args: string[], env: NodeJS.ProcessEnv) => { code: number; stdout: string };
|
|
599
|
+
harness?: string;
|
|
600
|
+
provider?: string;
|
|
583
601
|
}
|
|
584
602
|
|
|
585
603
|
/** Handle returned by `startPaneLimitWake` to stop polling or drive a synchronous tick in tests. */
|
|
@@ -588,6 +606,9 @@ export interface PaneLimitWake {
|
|
|
588
606
|
tick(): void;
|
|
589
607
|
}
|
|
590
608
|
|
|
609
|
+
const ANSI_CSI_RE = new RegExp(`${String.fromCharCode(27)}\\[[0-9;?]*[ -/]*[@-~]`, "g");
|
|
610
|
+
const BARE_PROMPT_RE = /^[>$%❯#]+$/;
|
|
611
|
+
|
|
591
612
|
function defaultHerdrSyncExec(args: string[], env: NodeJS.ProcessEnv): { code: number; stdout: string } {
|
|
592
613
|
try {
|
|
593
614
|
const res = spawnSync("herdr", args, { timeout: 3000, encoding: "utf8", env });
|
|
@@ -624,6 +645,120 @@ function parseHerdrPaneId(stdout: string): string | undefined {
|
|
|
624
645
|
}
|
|
625
646
|
}
|
|
626
647
|
|
|
648
|
+
/**
|
|
649
|
+
* Extracts terminal output text from `herdr pane read` stdout (JSON envelope or plain text).
|
|
650
|
+
*
|
|
651
|
+
* Args:
|
|
652
|
+
* stdout (string): Raw stdout returned by `herdr pane read`
|
|
653
|
+
*
|
|
654
|
+
* Returns:
|
|
655
|
+
* string: Extracted terminal tail text
|
|
656
|
+
*/
|
|
657
|
+
function parseHerdrPaneReadText(stdout: string): string {
|
|
658
|
+
const trimmed = stdout.trim();
|
|
659
|
+
if (!trimmed.startsWith("{")) return stdout;
|
|
660
|
+
try {
|
|
661
|
+
const parsed = asObj(JSON.parse(trimmed));
|
|
662
|
+
const result = asObj(parsed?.result);
|
|
663
|
+
const readObj = asObj(result?.read);
|
|
664
|
+
if (typeof readObj?.text === "string") return readObj.text;
|
|
665
|
+
if (typeof result?.text === "string") return result.text;
|
|
666
|
+
if (typeof parsed?.text === "string") return parsed.text;
|
|
667
|
+
} catch {
|
|
668
|
+
return stdout;
|
|
669
|
+
}
|
|
670
|
+
return stdout;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
/**
|
|
674
|
+
* Extracts the current `agent_status` for `paneId` from `herdr agent list` JSON stdout,
|
|
675
|
+
* returning `"unknown"` when absent or unparseable.
|
|
676
|
+
*
|
|
677
|
+
* Args:
|
|
678
|
+
* stdout (string): Raw stdout returned by `herdr agent list`
|
|
679
|
+
* paneId (string): Target pane identifier
|
|
680
|
+
*
|
|
681
|
+
* Returns:
|
|
682
|
+
* string: Agent lifecycle status (`"working"`, `"idle"`, etc.) or `"unknown"`
|
|
683
|
+
*/
|
|
684
|
+
function parseHerdrPaneStatus(stdout: string, paneId: string): string {
|
|
685
|
+
const trimmed = stdout.trim();
|
|
686
|
+
if (!trimmed.startsWith("{")) return "unknown";
|
|
687
|
+
try {
|
|
688
|
+
const parsed = asObj(JSON.parse(trimmed));
|
|
689
|
+
const result = asObj(parsed?.result);
|
|
690
|
+
const agents = result?.agents;
|
|
691
|
+
if (!Array.isArray(agents)) return "unknown";
|
|
692
|
+
for (const item of agents) {
|
|
693
|
+
const row = asObj(item);
|
|
694
|
+
if (!row || str(row.pane_id) !== paneId) continue;
|
|
695
|
+
return str(row.agent_status) ?? str(row.status) ?? "unknown";
|
|
696
|
+
}
|
|
697
|
+
return "unknown";
|
|
698
|
+
} catch {
|
|
699
|
+
return "unknown";
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* Resolves a single unambiguous provider slug for `startPaneLimitWake` from `opts.provider` or
|
|
705
|
+
* `cfg.spawn.profiles` entries matching `opts.harness`.
|
|
706
|
+
*
|
|
707
|
+
* Args:
|
|
708
|
+
* cfg (Config): Loaded neurastream configuration
|
|
709
|
+
* opts (PaneLimitWakeOptions): Pane wake options carrying optional `provider` and `harness`
|
|
710
|
+
*
|
|
711
|
+
* Returns:
|
|
712
|
+
* string | undefined: Unambiguous provider slug, or undefined when none/ambiguous
|
|
713
|
+
*/
|
|
714
|
+
function resolveProviderForWake(cfg: Config, opts: PaneLimitWakeOptions): string | undefined {
|
|
715
|
+
const explicit = str(opts.provider)?.trim();
|
|
716
|
+
if (explicit) return explicit;
|
|
717
|
+
const harness = str(opts.harness)?.trim();
|
|
718
|
+
if (!harness) return undefined;
|
|
719
|
+
const providers = new Set<string>();
|
|
720
|
+
for (const profile of Object.values(cfg.spawn.profiles)) {
|
|
721
|
+
if (profile.harness?.trim() !== harness) continue;
|
|
722
|
+
const p = profile.provider?.trim();
|
|
723
|
+
if (p) providers.add(p);
|
|
724
|
+
}
|
|
725
|
+
return providers.size === 1 ? [...providers][0] : undefined;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Scans Main's recent pane tail from bottom to top for the newest line matching
|
|
730
|
+
* `cfg.guards.rate_limit`, collecting that line and up to two following context lines.
|
|
731
|
+
*
|
|
732
|
+
* Args:
|
|
733
|
+
* tail (string): Terminal output tail from `herdr pane read`
|
|
734
|
+
* cfg (Config): Loaded neurastream configuration
|
|
735
|
+
*
|
|
736
|
+
* Returns:
|
|
737
|
+
* PaneRateLimitMatch | null: Matched snippet, dedup signature, and optional `retryAfterMs`, or null
|
|
738
|
+
*/
|
|
739
|
+
export function extractPaneRateLimit(tail: string, cfg: Config): PaneRateLimitMatch | null {
|
|
740
|
+
const lines = tail.split(/\r?\n/).map((line) => line.replace(ANSI_CSI_RE, "").trim());
|
|
741
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
742
|
+
const line = lines[i];
|
|
743
|
+
if (!line || line.includes("main-guard:")) continue;
|
|
744
|
+
if (!rateLimited("error", line, cfg.guards.rate_limit)) continue;
|
|
745
|
+
const collected = [line];
|
|
746
|
+
for (let offset = 1; offset <= 2 && i + offset < lines.length; offset++) {
|
|
747
|
+
const next = lines[i + offset];
|
|
748
|
+
if (!next || BARE_PROMPT_RE.test(next) || next.includes("main-guard:")) continue;
|
|
749
|
+
collected.push(next);
|
|
750
|
+
}
|
|
751
|
+
const snippet = collected.join("\n");
|
|
752
|
+
const hit = rateLimited("error", snippet, cfg.guards.rate_limit);
|
|
753
|
+
return {
|
|
754
|
+
snippet,
|
|
755
|
+
sig: snippet,
|
|
756
|
+
retryAfterMs: hit?.retryAfterMs ?? null,
|
|
757
|
+
};
|
|
758
|
+
}
|
|
759
|
+
return null;
|
|
760
|
+
}
|
|
761
|
+
|
|
627
762
|
function hasOpenQueuePlans(cfg: Config): boolean {
|
|
628
763
|
try {
|
|
629
764
|
return openQueue(cfg.paths, cfg.review.agents).length > 0;
|
|
@@ -640,12 +775,12 @@ function stillLimitCapped(cfg: Config): boolean {
|
|
|
640
775
|
|
|
641
776
|
/**
|
|
642
777
|
* Starts a lightweight unref'd limit-wake poller for `HERDR_ENV=1` Main sessions so that when
|
|
643
|
-
* Main hits its per-turn call cap or
|
|
644
|
-
*
|
|
645
|
-
* automatically
|
|
778
|
+
* Main hits its per-turn call/edit-window cap or a provider quota/rate limit with open plans,
|
|
779
|
+
* one continuation prompt is delivered into Main's `herdr` pane upon reset (and cancelled
|
|
780
|
+
* automatically on early reset or manual resume).
|
|
646
781
|
*
|
|
647
782
|
* Args:
|
|
648
|
-
* opts (PaneLimitWakeOptions): Config provider, environment, poll interval, clock, and
|
|
783
|
+
* opts (PaneLimitWakeOptions): Config provider, environment, poll interval, clock, exec seam, and harness/provider metadata
|
|
649
784
|
*
|
|
650
785
|
* Returns:
|
|
651
786
|
* PaneLimitWake: Handle with `stop()` and `tick()`
|
|
@@ -660,6 +795,7 @@ export function startPaneLimitWake(opts: PaneLimitWakeOptions): PaneLimitWake {
|
|
|
660
795
|
const nowMs = opts.nowMs ?? Date.now;
|
|
661
796
|
const exec = opts.exec ?? defaultHerdrSyncExec;
|
|
662
797
|
const pollMs = opts.pollMs ?? 15_000;
|
|
798
|
+
const providerWakeEnabled = Boolean(str(opts.harness) || str(opts.provider));
|
|
663
799
|
|
|
664
800
|
let cachedPaneId = str(env.HERDR_PANE_ID);
|
|
665
801
|
const resolvePaneId = (): string | undefined => {
|
|
@@ -669,7 +805,27 @@ export function startPaneLimitWake(opts: PaneLimitWakeOptions): PaneLimitWake {
|
|
|
669
805
|
return cachedPaneId;
|
|
670
806
|
};
|
|
671
807
|
|
|
808
|
+
const deliverWakeText = (paneId: string, text: string): void => {
|
|
809
|
+
const promptRes = exec(["agent", "prompt", paneId, text], env);
|
|
810
|
+
if (promptRes.code !== 0) {
|
|
811
|
+
exec(["pane", "send-text", paneId, text], env);
|
|
812
|
+
exec(["pane", "send-keys", paneId, "Enter"], env);
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
|
|
816
|
+
const queryPaneStatus = (paneId: string): string => {
|
|
817
|
+
const res = exec(["agent", "list"], env);
|
|
818
|
+
return res.code === 0 ? parseHerdrPaneStatus(res.stdout, paneId) : "unknown";
|
|
819
|
+
};
|
|
820
|
+
|
|
821
|
+
const readPaneTail = (paneId: string): string | null => {
|
|
822
|
+
const res = exec(["pane", "read", paneId, "--source", "recent", "--lines", "15"], env);
|
|
823
|
+
return res.code === 0 ? parseHerdrPaneReadText(res.stdout) : null;
|
|
824
|
+
};
|
|
825
|
+
|
|
672
826
|
let wakeAt: number | null = null;
|
|
827
|
+
let providerWakeAt: number | null = null;
|
|
828
|
+
let handledRateLimitSig: string | null = null;
|
|
673
829
|
let stopped = false;
|
|
674
830
|
|
|
675
831
|
const tick = (): void => {
|
|
@@ -686,19 +842,66 @@ export function startPaneLimitWake(opts: PaneLimitWakeOptions): PaneLimitWake {
|
|
|
686
842
|
}
|
|
687
843
|
return;
|
|
688
844
|
}
|
|
689
|
-
if (wakeAt
|
|
690
|
-
|
|
845
|
+
if (wakeAt !== null) {
|
|
846
|
+
if (!stillLimitCapped(cfg) || now < wakeAt) {
|
|
847
|
+
wakeAt = null;
|
|
848
|
+
return;
|
|
849
|
+
}
|
|
691
850
|
wakeAt = null;
|
|
851
|
+
if (!hasOpenQueuePlans(cfg)) return;
|
|
852
|
+
const paneId = resolvePaneId();
|
|
853
|
+
if (!paneId) return;
|
|
854
|
+
deliverWakeText(paneId, LIMIT_WAKE_TEXT);
|
|
855
|
+
return;
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
if (!providerWakeEnabled) return;
|
|
859
|
+
if (!hasOpenQueuePlans(cfg)) {
|
|
860
|
+
providerWakeAt = null;
|
|
692
861
|
return;
|
|
693
862
|
}
|
|
694
|
-
wakeAt = null;
|
|
695
|
-
if (!hasOpenQueuePlans(cfg)) return;
|
|
696
863
|
const paneId = resolvePaneId();
|
|
697
864
|
if (!paneId) return;
|
|
698
|
-
|
|
699
|
-
if (
|
|
700
|
-
|
|
701
|
-
|
|
865
|
+
|
|
866
|
+
if (providerWakeAt !== null) {
|
|
867
|
+
if (queryPaneStatus(paneId) === "working") {
|
|
868
|
+
providerWakeAt = null;
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
if (now < providerWakeAt) return;
|
|
872
|
+
providerWakeAt = null;
|
|
873
|
+
if (!hasOpenQueuePlans(cfg)) return;
|
|
874
|
+
deliverWakeText(paneId, PROVIDER_LIMIT_WAKE_TEXT);
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
const tail = readPaneTail(paneId);
|
|
879
|
+
if (tail === null) return;
|
|
880
|
+
const match = extractPaneRateLimit(tail, cfg);
|
|
881
|
+
if (!match) {
|
|
882
|
+
handledRateLimitSig = null;
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
if (match.sig === handledRateLimitSig) return;
|
|
886
|
+
if (queryPaneStatus(paneId) === "working") return;
|
|
887
|
+
|
|
888
|
+
const parsedEpoch = resetEpochFromText(
|
|
889
|
+
match.snippet,
|
|
890
|
+
{ pattern: cfg.quota.reset_pattern, zone: cfg.quota.reset_tz },
|
|
891
|
+
Math.floor(now / 1000),
|
|
892
|
+
);
|
|
893
|
+
const slackMs = cfg.guards.rate_limit.slack_s * 1000;
|
|
894
|
+
const candidateWakeAt =
|
|
895
|
+
parsedEpoch !== null && parsedEpoch * 1000 > now
|
|
896
|
+
? parsedEpoch * 1000 + slackMs
|
|
897
|
+
: now + (match.retryAfterMs ?? cfg.guards.rate_limit.probe_interval_s * 1000) + slackMs;
|
|
898
|
+
|
|
899
|
+
providerWakeAt = candidateWakeAt;
|
|
900
|
+
handledRateLimitSig = match.sig;
|
|
901
|
+
|
|
902
|
+
const provider = resolveProviderForWake(cfg, opts);
|
|
903
|
+
if (provider) {
|
|
904
|
+
recordOut(cfg, provider, Math.floor(providerWakeAt / 1000), "main-pane-rate-limit", Math.floor(now / 1000));
|
|
702
905
|
}
|
|
703
906
|
};
|
|
704
907
|
|
|
@@ -711,6 +914,8 @@ export function startPaneLimitWake(opts: PaneLimitWakeOptions): PaneLimitWake {
|
|
|
711
914
|
if (stopped) return;
|
|
712
915
|
stopped = true;
|
|
713
916
|
wakeAt = null;
|
|
917
|
+
providerWakeAt = null;
|
|
918
|
+
handledRateLimitSig = null;
|
|
714
919
|
clearInterval(timer);
|
|
715
920
|
},
|
|
716
921
|
};
|
|
@@ -730,7 +935,7 @@ export function startPaneLimitWake(opts: PaneLimitWakeOptions): PaneLimitWake {
|
|
|
730
935
|
*/
|
|
731
936
|
export async function spawnHarnessMain(bin: string, args: string[], cfg?: Config): Promise<number> {
|
|
732
937
|
const env: NodeJS.ProcessEnv = { ...process.env, NEURASTREAM_MAIN_LAUNCHER: "1", NEURASTREAM_HARNESS: bin };
|
|
733
|
-
const wake = cfg ? startPaneLimitWake({ cfg, env }) : null;
|
|
938
|
+
const wake = cfg ? startPaneLimitWake({ cfg, env, harness: bin }) : null;
|
|
734
939
|
const { promise, resolve } = Promise.withResolvers<number>();
|
|
735
940
|
let settled = false;
|
|
736
941
|
const finish = (code: number): void => {
|
|
@@ -897,6 +1102,19 @@ export function nativeSpawnBlockReason(rawTool: string): string {
|
|
|
897
1102
|
return `neurastream: native subagent tool "${rawTool}" is blocked inside a managed terminal session (HERDR_ENV=1). Spawn helpers via: neurastream spawn --agent <profile> --plan <plan.md> --cwd <worktree> --brief "<brief>"`;
|
|
898
1103
|
}
|
|
899
1104
|
|
|
1105
|
+
/**
|
|
1106
|
+
* Builds the refusal reason when a subagent invokes a harness-native subagent tool.
|
|
1107
|
+
*
|
|
1108
|
+
* Args:
|
|
1109
|
+
* rawTool (string): Native subagent tool name blocked by the hook
|
|
1110
|
+
*
|
|
1111
|
+
* Returns:
|
|
1112
|
+
* string: Actionable refusal message enforcing Main-only subagent spawning
|
|
1113
|
+
*/
|
|
1114
|
+
export function subSpawnBlockReason(rawTool: string): string {
|
|
1115
|
+
return `plan-guard: subagents may not spawn subagents ("${rawTool}" is Main-only). Report what is needed in your plan's "## Progress" instead.`;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
900
1118
|
/**
|
|
901
1119
|
* Extracts owner prompt text from a `UserPromptSubmit` hook payload (`prompt`, `userPrompt`,
|
|
902
1120
|
* `user_prompt`, or `message`).
|
|
@@ -919,6 +1137,41 @@ export function extractHookPrompt(payload: Record<string, unknown>): string {
|
|
|
919
1137
|
return msg ? (str(msg.content) ?? str(msg.text) ?? "") : "";
|
|
920
1138
|
}
|
|
921
1139
|
|
|
1140
|
+
/**
|
|
1141
|
+
* Applies interactive owner chat commands (`unlock`, `unlock N`, `lock`, `tier`, `planner`,
|
|
1142
|
+
* `go_phrase`, `approve`) for native harness `user-prompt` / `PreInvocation` hooks when
|
|
1143
|
+
* `cfg.guards.chat_unlock` is enabled.
|
|
1144
|
+
*
|
|
1145
|
+
* Args:
|
|
1146
|
+
* prompt (string): Raw owner prompt text from the hook payload
|
|
1147
|
+
* cfg (Config): Active NeuraStream config
|
|
1148
|
+
*
|
|
1149
|
+
* Returns:
|
|
1150
|
+
* string | null: Confirmation note to inject into context if a command matched, else `null`
|
|
1151
|
+
*/
|
|
1152
|
+
export function applyHookChatCommand(prompt: string, cfg: Config): string | null {
|
|
1153
|
+
if (!cfg.guards.chat_unlock) return null;
|
|
1154
|
+
const t = chatTier(prompt, cfg, "interactive");
|
|
1155
|
+
if (t.applied && t.tier !== undefined) return `Owner set autonomy tier to ${t.tier} in chat.`;
|
|
1156
|
+
const p = chatPlanner(prompt, cfg, "interactive");
|
|
1157
|
+
if (p.applied && p.planner !== undefined) return `Owner set planner mode to ${p.planner} in chat.`;
|
|
1158
|
+
const g = chatGo(prompt, cfg, "interactive");
|
|
1159
|
+
if (g.applied && g.minutes !== undefined) {
|
|
1160
|
+
return `Owner approved ${cfg.autonomy.go_phrase} in chat for ${g.minutes} min.`;
|
|
1161
|
+
}
|
|
1162
|
+
const a = chatApprove(prompt, cfg, "interactive");
|
|
1163
|
+
if (a.applied) return `Owner approved ${basename(a.plan)} in chat.`;
|
|
1164
|
+
if (a.problem !== undefined) return a.problem;
|
|
1165
|
+
const u = q.chatUnlock(prompt, cfg, "interactive");
|
|
1166
|
+
if (u.applied) {
|
|
1167
|
+
if (u.command === "unlock" && u.minutes !== undefined && u.until !== undefined) {
|
|
1168
|
+
return `Owner unlocked the guards in chat for ${u.minutes} min (until ${strftime(u.until, "%H:%M")}).`;
|
|
1169
|
+
}
|
|
1170
|
+
if (u.command === "lock") return "Owner locked the guards again in chat.";
|
|
1171
|
+
}
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
922
1175
|
/**
|
|
923
1176
|
* Evaluates `session-start`, `user-prompt`, `pre-tool`, or `stop` hooks for Claude/Codex-style
|
|
924
1177
|
* payloads, delegating only the `pre-tool` deny JSON formatting to the caller.
|
|
@@ -955,7 +1208,9 @@ export function handleStandardHook(opts: {
|
|
|
955
1208
|
if (event === "user-prompt") {
|
|
956
1209
|
if (!isHookActive(env) || !cfg || hookAgent(env) !== "main") return { code: 0, stdout: "" };
|
|
957
1210
|
const prompt = extractHookPrompt(parseHookPayload(stdinText));
|
|
958
|
-
const
|
|
1211
|
+
const cmdNote = applyHookChatCommand(prompt, cfg);
|
|
1212
|
+
const injected = checkInject({ inject: prompt, agent: "main" }, cfg).inject;
|
|
1213
|
+
const text = [cmdNote, injected].filter(Boolean).join("\n");
|
|
959
1214
|
if (!text) return { code: 0, stdout: "" };
|
|
960
1215
|
return {
|
|
961
1216
|
code: 0,
|
|
@@ -968,8 +1223,13 @@ export function handleStandardHook(opts: {
|
|
|
968
1223
|
const payload = parseHookPayload(stdinText);
|
|
969
1224
|
const rawTool = str(payload.tool_name) ?? str(payload.tool) ?? "";
|
|
970
1225
|
const agent = hookAgent(env);
|
|
971
|
-
if (
|
|
972
|
-
|
|
1226
|
+
if (opts.nativeSpawnTools?.includes(rawTool)) {
|
|
1227
|
+
if (agent === "sub") {
|
|
1228
|
+
return { code: 0, stdout: opts.formatPreToolDeny(subSpawnBlockReason(rawTool)) };
|
|
1229
|
+
}
|
|
1230
|
+
if (agent === "main" && env.HERDR_ENV === "1") {
|
|
1231
|
+
return { code: 0, stdout: opts.formatPreToolDeny(nativeSpawnBlockReason(rawTool)) };
|
|
1232
|
+
}
|
|
973
1233
|
}
|
|
974
1234
|
const toolInput = asObj(payload.tool_input) ?? asObj(payload.input) ?? {};
|
|
975
1235
|
const cwd = str(payload.cwd) ?? process.cwd();
|
|
@@ -999,10 +1259,26 @@ export function handleStandardHook(opts: {
|
|
|
999
1259
|
return { code: 2, stdout: "" };
|
|
1000
1260
|
}
|
|
1001
1261
|
|
|
1262
|
+
function activeHeavyOwner(cfg: Config): string | null {
|
|
1263
|
+
try {
|
|
1264
|
+
const raw = readFileSync(cfg.paths.heavy_owner, "utf8").trim();
|
|
1265
|
+
const m = raw.match(/^([^|\n]+)\|.*\|\s*pid\s+(\d+)\b/);
|
|
1266
|
+
if (!m) return null;
|
|
1267
|
+
const owner = m[1]!.trim().toLowerCase();
|
|
1268
|
+
const pid = Number(m[2]);
|
|
1269
|
+
if (!owner || !Number.isInteger(pid) || pid <= 0) return null;
|
|
1270
|
+
process.kill(pid, 0);
|
|
1271
|
+
return owner;
|
|
1272
|
+
} catch {
|
|
1273
|
+
return null;
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
|
|
1002
1277
|
/**
|
|
1003
|
-
* Returns the names of live
|
|
1004
|
-
*
|
|
1005
|
-
* (`agy`, `claude`, `codex`) pass structured
|
|
1278
|
+
* Returns the names of live `herdr` panes that were spawned by `neurastream spawn` (intersected
|
|
1279
|
+
* against `staffing.json`, excluding Main's own pane) and are either actively `working` or holding
|
|
1280
|
+
* a live `heavy-run` lock, so native-harness Stop hooks (`agy`, `claude`, `codex`) pass structured
|
|
1281
|
+
* live helper names to `checkStop`.
|
|
1006
1282
|
*
|
|
1007
1283
|
* Args:
|
|
1008
1284
|
* env (Record<string, string | undefined>): Process environment map
|
|
@@ -1015,6 +1291,7 @@ export function liveHerdrSubagents(env: Record<string, string | undefined>, cfg:
|
|
|
1015
1291
|
if (env.HERDR_ENV !== "1") return [];
|
|
1016
1292
|
const staffed = new Set(Object.values(readStaffing(cfg.paths)).flat());
|
|
1017
1293
|
if (staffed.size === 0) return [];
|
|
1294
|
+
const heavyOwner = activeHeavyOwner(cfg);
|
|
1018
1295
|
const bin = env.HERDR_BIN_PATH || "herdr";
|
|
1019
1296
|
const r = spawnSync(bin, ["agent", "list"], { encoding: "utf8", timeout: 2000 });
|
|
1020
1297
|
if (r.status !== 0 || !r.stdout) return [];
|
|
@@ -1025,11 +1302,13 @@ export function liveHerdrSubagents(env: Record<string, string | undefined>, cfg:
|
|
|
1025
1302
|
const selfPane = env.HERDR_PANE_ID;
|
|
1026
1303
|
const live: string[] = [];
|
|
1027
1304
|
for (const item of agents) {
|
|
1028
|
-
if (item.agent_status !== "working") continue;
|
|
1029
1305
|
const paneId = typeof item.pane_id === "string" ? item.pane_id : "";
|
|
1030
1306
|
if (selfPane && paneId === selfPane) continue;
|
|
1031
1307
|
const name = typeof item.name === "string" ? item.name : "";
|
|
1032
1308
|
if (!name || !staffed.has(name)) continue;
|
|
1309
|
+
const working = item.agent_status === "working";
|
|
1310
|
+
const holdingHeavy = heavyOwner !== null && name.toLowerCase() === heavyOwner;
|
|
1311
|
+
if (!working && !holdingHeavy) continue;
|
|
1033
1312
|
if (!live.includes(name)) live.push(name);
|
|
1034
1313
|
}
|
|
1035
1314
|
return live;
|
package/src/cli/spawn.ts
CHANGED
|
@@ -7,7 +7,7 @@ import { allAdapters, getAdapter, type HarnessAdapter } from "../adapters/index.
|
|
|
7
7
|
import { MultiRunSource } from "../core/adapter.ts";
|
|
8
8
|
import { nowSec } from "../core/clock.ts";
|
|
9
9
|
import { ConfigError, loadConfig, type Config } from "../core/config.ts";
|
|
10
|
-
import { checkSpawn } from "../core/guards.ts";
|
|
10
|
+
import { checkSpawn, reviewSpawnEnd } from "../core/guards.ts";
|
|
11
11
|
import { defaultRunner } from "../core/mr-sweep.ts";
|
|
12
12
|
import { agentProvider, agentRole, reachableAgentsForRole, recordOut, resetEpochFromText } from "../core/provider-state.ts";
|
|
13
13
|
import { readIndex } from "../core/queue/lib.ts";
|
|
@@ -30,6 +30,7 @@ export interface SpawnDeps {
|
|
|
30
30
|
getRunner?: (name: string) => AgentRunner;
|
|
31
31
|
knownRunners?: () => string[];
|
|
32
32
|
cwd?: () => string;
|
|
33
|
+
env?: NodeJS.ProcessEnv;
|
|
33
34
|
out?: (line: string) => void;
|
|
34
35
|
err?: (line: string) => void;
|
|
35
36
|
}
|
|
@@ -369,9 +370,10 @@ function nextSameRoleAgent(cfg: Config, failedAgent: string, now: number): strin
|
|
|
369
370
|
|
|
370
371
|
/**
|
|
371
372
|
* Executes `neurastream spawn` and its management subcommands (`list`, `read`, `stop`).
|
|
372
|
-
*
|
|
373
|
-
*
|
|
374
|
-
*
|
|
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.
|
|
375
377
|
*
|
|
376
378
|
* Args:
|
|
377
379
|
* args (string[]): CLI arguments after `spawn`
|
|
@@ -388,6 +390,7 @@ export async function runSpawn(args: string[], injectedDeps: SpawnDeps = {}): Pr
|
|
|
388
390
|
getRunner: injectedDeps.getRunner ?? getRunner,
|
|
389
391
|
knownRunners: injectedDeps.knownRunners ?? knownRunners,
|
|
390
392
|
cwd: injectedDeps.cwd ?? (() => process.cwd()),
|
|
393
|
+
env: injectedDeps.env ?? process.env,
|
|
391
394
|
out: injectedDeps.out ?? ((line) => console.log(line)),
|
|
392
395
|
err: injectedDeps.err ?? ((line) => console.error(line)),
|
|
393
396
|
};
|
|
@@ -397,6 +400,14 @@ export async function runSpawn(args: string[], injectedDeps: SpawnDeps = {}): Pr
|
|
|
397
400
|
return args.length === 0 ? 2 : 0;
|
|
398
401
|
}
|
|
399
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
|
+
|
|
400
411
|
let cfg: Config;
|
|
401
412
|
try {
|
|
402
413
|
cfg = deps.loadConfig();
|
|
@@ -405,7 +416,6 @@ export async function runSpawn(args: string[], injectedDeps: SpawnDeps = {}): Pr
|
|
|
405
416
|
return 1;
|
|
406
417
|
}
|
|
407
418
|
|
|
408
|
-
const sub = args[0];
|
|
409
419
|
if (sub === "list") return runList(args.slice(1), cfg, deps);
|
|
410
420
|
if (sub === "read") return runRead(args.slice(1), cfg, deps);
|
|
411
421
|
if (sub === "stop") return runStop(args.slice(1), cfg, deps);
|
|
@@ -550,12 +560,14 @@ export async function runSpawn(args: string[], injectedDeps: SpawnDeps = {}): Pr
|
|
|
550
560
|
if (blocked && !rateLimitHit) {
|
|
551
561
|
keepPane = true;
|
|
552
562
|
}
|
|
563
|
+
const reviewNote = !failed ? reviewSpawnEnd(agentId, cfg) : null;
|
|
553
564
|
if (parsed.json) {
|
|
554
565
|
deps.out(
|
|
555
566
|
JSON.stringify({
|
|
556
567
|
ok: !failed,
|
|
557
568
|
...(blocked ? { blocked: true } : {}),
|
|
558
569
|
...(rateLimitHit ? { rateLimited: true } : {}),
|
|
570
|
+
...(reviewNote ? { reviewNote } : {}),
|
|
559
571
|
agent: resolvedProfile.agent,
|
|
560
572
|
name: handle.name,
|
|
561
573
|
harness: activeHarness,
|
|
@@ -571,6 +583,7 @@ export async function runSpawn(args: string[], injectedDeps: SpawnDeps = {}): Pr
|
|
|
571
583
|
} else {
|
|
572
584
|
if (output.trim() !== "") deps.out(output.replace(/\n$/, ""));
|
|
573
585
|
else deps.out(`${handle.name} finished (${sent.state ?? "done"})`);
|
|
586
|
+
if (reviewNote) deps.err(reviewNote);
|
|
574
587
|
if (rateLimitHit) deps.err(`spawn: ${handle.name} hit rate limit`);
|
|
575
588
|
else if (blocked) deps.err(`spawn: ${handle.name} is blocked and requires input`);
|
|
576
589
|
}
|
package/src/core/guards/spawn.ts
CHANGED
|
@@ -737,7 +737,7 @@ function checkSpawnRules(e: SpawnEvent, cfg: Config, runner: CommandRunner = def
|
|
|
737
737
|
}
|
|
738
738
|
// The owner's pick order and live provider state (plan 20261025_1700 P3), before the spawn records.
|
|
739
739
|
const staffing: Record<string, string[]> = {};
|
|
740
|
-
for (const f of named) staffing[f] = [e.agent];
|
|
740
|
+
for (const f of named) staffing[f] = [e.name || e.agent];
|
|
741
741
|
recordSpawns(named, cfg.paths, staffing);
|
|
742
742
|
if (e.name) recordReviewSpawn(e.name, role.plan, cfg.paths);
|
|
743
743
|
// planner mode P2 (b): the approved planner spawn binds its name to the plan its brief named.
|
package/src/core/guards/stop.ts
CHANGED
|
@@ -109,11 +109,13 @@ export function checkInject(e: InjectEvent, cfg: Config): Decision {
|
|
|
109
109
|
};
|
|
110
110
|
}
|
|
111
111
|
|
|
112
|
-
// Plans still responsible for: open plans (parked "WAITING on owner"
|
|
112
|
+
// Plans still responsible for: open plans (parked "WAITING on owner", awaiting merge, or waiting on
|
|
113
|
+
// another open plan excluded) plus queue problems.
|
|
113
114
|
export function openQueue(paths: q.QueuePaths, reviewAgents: string[] = []): string[] {
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
115
|
+
const plans = q.activePlans(paths);
|
|
116
|
+
const rank = new Map(plans.map((p, i) => [p.file, i + 1]));
|
|
117
|
+
const open = plans
|
|
118
|
+
.filter(p => !p.waiting && !q.awaitingMerge(p, paths) && q.openWaits(p, plans, rank).length === 0)
|
|
117
119
|
.map(p => p.file);
|
|
118
120
|
for (const prob of q.queueProblems(paths, reviewAgents)) open.push(`${prob.where}: ${prob.problem}`);
|
|
119
121
|
const unique: string[] = [];
|
package/src/core/guards/tool.ts
CHANGED
|
@@ -101,6 +101,31 @@ function runsCloser(input: Record<string, unknown>): boolean {
|
|
|
101
101
|
});
|
|
102
102
|
}
|
|
103
103
|
|
|
104
|
+
/**
|
|
105
|
+
* Detects whether a tool input invokes `neurastream spawn` (launch or `stop`) in any shell
|
|
106
|
+
* segment, while allowing read-only `neurastream spawn list` and `neurastream spawn read`.
|
|
107
|
+
*
|
|
108
|
+
* Args:
|
|
109
|
+
* input (Record<string, unknown>): Tool input object to inspect
|
|
110
|
+
*
|
|
111
|
+
* Returns:
|
|
112
|
+
* boolean: True when any command segment invokes a mutating `neurastream spawn` command
|
|
113
|
+
*/
|
|
114
|
+
function runsSpawner(input: Record<string, unknown>): boolean {
|
|
115
|
+
const text = Object.values(input).filter((v): v is string => typeof v === "string").join("\n");
|
|
116
|
+
return text.split(/&&|\|\||;|\||\n|\$\(|`/).some(seg => {
|
|
117
|
+
const words = seg.trim().split(/\s+/).filter(Boolean).map(w => w.replace(/^["'(]+|["')]+$/g, ""));
|
|
118
|
+
let i = 0;
|
|
119
|
+
while (i < words.length && (LAUNCHERS[words[i] ?? ""] === true || /^\w+=/.test(words[i] ?? "") || /(^|\/)main\.ts$/.test(words[i] ?? ""))) {
|
|
120
|
+
if (bin(words[i]) === "neurastream") break;
|
|
121
|
+
i++;
|
|
122
|
+
}
|
|
123
|
+
const seq = words.slice(i).map(bin);
|
|
124
|
+
if (seq[0] === "neurastream") seq.shift();
|
|
125
|
+
return seq[0] === "spawn" && seq[1] !== "list" && seq[1] !== "read";
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
104
129
|
const bin = (w: string | undefined) => (w ?? "").replace(/^["']+|["']+$/g, "").split("/").pop() ?? "";
|
|
105
130
|
|
|
106
131
|
// P5g (plan 20261027_0915): the shell text a call would really run — bash's command line, eval's
|
|
@@ -218,8 +243,21 @@ function pathArgs(input: Record<string, unknown>): Record<string, unknown> {
|
|
|
218
243
|
return out;
|
|
219
244
|
}
|
|
220
245
|
|
|
221
|
-
|
|
222
|
-
|
|
246
|
+
/**
|
|
247
|
+
* Evaluates subagent-specific tool rules (commit diff-check, closer/spawner CLI blocks, redaction
|
|
248
|
+
* placeholder protection, delegated planner scope, call budget, and phase-0 blockers).
|
|
249
|
+
*
|
|
250
|
+
* Args:
|
|
251
|
+
* e (ToolEvent): Incoming pre-tool event for a subagent
|
|
252
|
+
* input (Record<string, unknown>): Normalized tool input arguments
|
|
253
|
+
* paths (string[]): Resolved paths referenced by the call
|
|
254
|
+
* writes (string[]): Resolved paths mutated by the call
|
|
255
|
+
* cfg (Config): Loaded configuration
|
|
256
|
+
* cap (number): Effective hard call cap for this subagent
|
|
257
|
+
*
|
|
258
|
+
* Returns:
|
|
259
|
+
* string | null: Refusal reason when blocked, or null when allowed
|
|
260
|
+
*/
|
|
223
261
|
function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
|
|
224
262
|
// P6 (plan 20261024_1915): a sub's `git commit` is scanned first — its staged diff must not add
|
|
225
263
|
// the removal comments diff-check flags. Detected through GIT_ADD_OR_COMMIT (the predicate
|
|
@@ -243,6 +281,9 @@ function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[],
|
|
|
243
281
|
// Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
|
|
244
282
|
if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
|
|
245
283
|
return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
|
|
284
|
+
// Spawning or stopping subagents is Main's responsibility only: subs cannot run `neurastream spawn` (except read-only list/read).
|
|
285
|
+
if (cfg.guards.shell_tools.includes(e.tool) && runsSpawner(input))
|
|
286
|
+
return 'only Main may spawn or stop subagents; report what is needed in your plan\'s "## Progress" instead.';
|
|
246
287
|
// The read tool prints a placeholder for a value it hid, never the value (I-20261027-158,
|
|
247
288
|
// I-20261027-160: one copy silently broke the shipped config template). Writing that text back
|
|
248
289
|
// is refused; the file that produces one and the tests that exercise it are the exceptions.
|
|
@@ -425,6 +466,17 @@ export function checkTool(e: ToolEvent, cfg: Config, runs?: RunSource): Decision
|
|
|
425
466
|
return tuned(checkToolRules(e, cfg, runs), cfg);
|
|
426
467
|
}
|
|
427
468
|
|
|
469
|
+
/**
|
|
470
|
+
* Evaluates pre-tool guard rules for both Main and subagent callers.
|
|
471
|
+
*
|
|
472
|
+
* Args:
|
|
473
|
+
* e (ToolEvent): Incoming pre-tool event
|
|
474
|
+
* cfg (Config): Loaded configuration
|
|
475
|
+
* runs (RunSource | undefined): Optional run source for team-cap accounting
|
|
476
|
+
*
|
|
477
|
+
* Returns:
|
|
478
|
+
* Decision: Guard allow/deny decision with optional context injection
|
|
479
|
+
*/
|
|
428
480
|
function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
|
|
429
481
|
const lock = e.agent === "sub" ? reviewLockProblem(e, cfg) : null;
|
|
430
482
|
if (lock) {
|
|
@@ -522,13 +574,17 @@ function checkToolRules(e: ToolEvent, cfg: Config, runs?: RunSource): Decision {
|
|
|
522
574
|
log(cfg.paths.plan_guard_log, `BLOCK sub:${e.agentId} tool=${e.tool} ${why} rule=sub.rule`);
|
|
523
575
|
return deny(`plan-guard: ${why}`, "sub.rule");
|
|
524
576
|
}
|
|
525
|
-
//
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
577
|
+
// Subagents may never spawn nested subagents via `task` or `bypass_spawn` shell commands.
|
|
578
|
+
if (e.tool === "task") {
|
|
579
|
+
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} sub-spawn refused rule=sub.launch`);
|
|
580
|
+
return deny('plan-guard: only Main may spawn subagents; report what is needed in your plan\'s "## Progress" instead.', "sub.launch");
|
|
581
|
+
}
|
|
582
|
+
if (cfg.guards.shell_tools.includes(e.tool)) {
|
|
583
|
+
const cmd = String(input?.command ?? input?.code ?? "");
|
|
584
|
+
if (cfg.guards.bypass_spawn.some(entry => bypassRegExp(entry).test(cmd))) {
|
|
585
|
+
log(cfg.paths.plan_guard_log, `BLOCK ${e.agent}:${e.agentId} tool=${e.tool} bypass-spawn refused rule=sub.launch`);
|
|
586
|
+
return deny('plan-guard: only Main may spawn subagents; report what is needed in your plan\'s "## Progress" instead.', "sub.launch");
|
|
587
|
+
}
|
|
532
588
|
}
|
|
533
589
|
const n = e.calls + 1;
|
|
534
590
|
// The warn band has the global width (sub_max_calls - sub_warn_calls) ending at the cap;
|
package/templates/config.yml
CHANGED
|
@@ -145,7 +145,7 @@ guards:
|
|
|
145
145
|
idle_stops: 3 # idle stops before the guard intervenes
|
|
146
146
|
plan_offer: 'want me to (write|make) a plan|should i plan|shall i plan|if you want, i(''ll)? plan|plan it or|\bi will\b|\bi(''|’)ll\b' # refused: don't promise or offer it — do it now, or write the plan and index it
|
|
147
147
|
rate_limit:
|
|
148
|
-
patterns: ["429", "rate_limit", "rate limit", "overloaded", "529", "usage limit", "limit reached", "hit your limit", "quota_exhausted", "quota exceeded"] # error-text substrings (case-insensitive) that mark a provider rate limit
|
|
148
|
+
patterns: ["429", "rate_limit", "rate limit", "overloaded", "529", "usage limit", "limit reached", "hit your limit", "quota_exhausted", "quota exceeded", "quota reached"] # error-text substrings (case-insensitive) that mark a provider rate limit
|
|
149
149
|
slack_s: 15 # added on top of every wait
|
|
150
150
|
probe_interval_s: 300 # probe the provider this often (s) while it names no reset
|
|
151
151
|
max_probes: 288 # probes before the episode gives up (288 x 300 s = 24 h)
|