@xzzpig/pi-subagents 0.1.0 → 0.3.0

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.
Files changed (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -40,6 +40,7 @@ export interface RunnerSubagentStep {
40
40
  outputMode?: "inline" | "file-only";
41
41
  sessionFile?: string;
42
42
  maxSubagentDepth?: number;
43
+ timeoutMs?: number;
43
44
  waitToolEnabled?: boolean;
44
45
  structuredOutput?: {
45
46
  schema: import("../../shared/types.ts").JsonSchemaObject;
@@ -60,6 +61,8 @@ export interface RunnerSubagentStep {
60
61
  toolBudget?: import("../../shared/types.ts").ResolvedToolBudget;
61
62
  capabilityCeiling?: import("./capability-ceiling.ts").ResolvedSubagentCapabilityCeiling;
62
63
  capabilityAudit?: import("./capability-ceiling.ts").SubagentCapabilityAudit;
64
+ /** Private stable logical-child path for inherited run fan-out accounting. */
65
+ runFanoutPath?: string;
63
66
  }
64
67
 
65
68
  export interface RunnerCheckpointStep {
@@ -23,8 +23,10 @@ import {
23
23
  type JsonSchemaObject,
24
24
  type LaunchResolvedChildExtensionsV1,
25
25
  type ResolvedToolBudget,
26
+ type RunFanoutBudgetDescriptor,
26
27
  } from "../../shared/types.ts";
27
28
  import { THINKING_LEVELS } from "../../shared/model-info.ts";
29
+ import { encodeRunFanoutBudgetDescriptor, RUN_FANOUT_BUDGET_ENV } from "./run-fanout-budget.ts";
28
30
  import {
29
31
  TOOL_BUDGET_ENV,
30
32
  TOOL_BUDGET_ZERO_AUTH_ENV,
@@ -63,6 +65,32 @@ import {
63
65
  } from "./capability-ceiling.ts";
64
66
 
65
67
  const TASK_ARG_LIMIT = 8000;
68
+
69
+ /**
70
+ * Env override for how the task text reaches the child process. Endpoint
71
+ * protection (EDR) pre-execution command-line scanning may deny exec of
72
+ * children whose argv embeds a long natural-language task, which surfaces
73
+ * as an immediate zero-activity SIGKILL. File delivery keeps the task out
74
+ * of argv entirely.
75
+ */
76
+ export const SUBAGENT_TASK_DELIVERY_ENV = "PI_SUBAGENT_TASK_DELIVERY";
77
+
78
+ export type SubagentTaskDelivery = "auto" | "file";
79
+
80
+ export function resolveSubagentTaskDelivery(
81
+ env: NodeJS.ProcessEnv = process.env,
82
+ ): SubagentTaskDelivery {
83
+ return env[SUBAGENT_TASK_DELIVERY_ENV]?.trim().toLowerCase() === "file"
84
+ ? "file"
85
+ : "auto";
86
+ }
87
+
88
+ function shouldDeliverTaskViaFile(
89
+ task: string,
90
+ delivery: SubagentTaskDelivery,
91
+ ): boolean {
92
+ return delivery === "file" || task.length > TASK_ARG_LIMIT;
93
+ }
66
94
  const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
67
95
  const PROMPT_RUNTIME_EXTENSION_PATH = path.join(
68
96
  path.dirname(fileURLToPath(import.meta.url)),
@@ -136,6 +164,7 @@ export interface BuildPiArgsInput {
136
164
  parentDepth?: number;
137
165
  parentPath?: NestedPathEntry[];
138
166
  parentCapabilityToken?: string;
167
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
139
168
  steerInboxDir?: string;
140
169
  steerCapabilityPath?: string;
141
170
  steerAckDir?: string;
@@ -149,6 +178,12 @@ export interface BuildPiArgsInput {
149
178
  permissionRules?: PermissionRules;
150
179
  permissionAuditPath?: string;
151
180
  childWatchdog?: ChildWatchdogConfig;
181
+ /**
182
+ * Per-launch override of the task delivery mode. Startup-retry paths set
183
+ * this to "file" after an unexplained zero-activity SIGKILL so the retry
184
+ * keeps the task text out of the child's argv.
185
+ */
186
+ taskDelivery?: SubagentTaskDelivery;
152
187
  waitToolEnabled?: boolean;
153
188
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
154
189
  }
@@ -595,7 +630,12 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
595
630
  );
596
631
  }
597
632
 
598
- if (input.task.length > TASK_ARG_LIMIT) {
633
+ if (
634
+ shouldDeliverTaskViaFile(
635
+ input.task,
636
+ input.taskDelivery ?? resolveSubagentTaskDelivery(),
637
+ )
638
+ ) {
599
639
  if (!tempDir) {
600
640
  tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
601
641
  }
@@ -704,6 +744,9 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
704
744
  process.env[SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV] ??
705
745
  "")
706
746
  : "";
747
+ env[RUN_FANOUT_BUDGET_ENV] = toolPlan.fanoutAuthorized
748
+ ? (input.runFanoutBudget ? encodeRunFanoutBudgetDescriptor(input.runFanoutBudget) : process.env[RUN_FANOUT_BUDGET_ENV])
749
+ : undefined;
707
750
  env.PI_SUBAGENT_INHERIT_PROJECT_CONTEXT = input.inheritProjectContext
708
751
  ? "1"
709
752
  : "0";
@@ -0,0 +1,280 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS, waitForFileSystemRetry } from "../../shared/file-system-retry.ts";
5
+ import {
6
+ TEMP_ROOT_DIR,
7
+ type RunFanoutBudgetDescriptor,
8
+ type RunFanoutBudgetSnapshot,
9
+ type RunFanoutRejection,
10
+ } from "../../shared/types.ts";
11
+
12
+ export const RUN_FANOUT_BUDGET_ENV = "PI_SUBAGENT_RUN_FANOUT_BUDGET";
13
+ const RUN_FANOUT_ROOT = path.join(TEMP_ROOT_DIR, "run-fanout-budgets");
14
+
15
+ interface ManifestV1 {
16
+ version: 1;
17
+ rootRunId: string;
18
+ limit: number;
19
+ createdAt: number;
20
+ }
21
+
22
+ interface ClaimV1 {
23
+ version: 1;
24
+ claimId: string;
25
+ path: string;
26
+ claimedAt: number;
27
+ }
28
+
29
+ export class RunFanoutLimitError extends Error {
30
+ readonly rejection: RunFanoutRejection;
31
+ readonly snapshot: RunFanoutBudgetSnapshot;
32
+
33
+ constructor(rejection: RunFanoutRejection) {
34
+ super(formatRunFanoutRejection(rejection));
35
+ this.name = "RunFanoutLimitError";
36
+ this.rejection = rejection;
37
+ this.snapshot = { used: rejection.used, limit: rejection.limit, remaining: rejection.remaining };
38
+ }
39
+ }
40
+
41
+ function safeRootRunId(rootRunId: string): string {
42
+ return rootRunId.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 120) || randomUUID();
43
+ }
44
+
45
+ function parseManifest(value: unknown): ManifestV1 | undefined {
46
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
47
+ const manifest = value as Partial<ManifestV1>;
48
+ if (manifest.version !== 1 || typeof manifest.rootRunId !== "string" || !manifest.rootRunId
49
+ || !Number.isInteger(manifest.limit) || (manifest.limit ?? 0) <= 0
50
+ || typeof manifest.createdAt !== "number" || !Number.isFinite(manifest.createdAt)) return undefined;
51
+ return manifest as ManifestV1;
52
+ }
53
+
54
+ function readManifest(directory: string): ManifestV1 {
55
+ let parsed: unknown;
56
+ try {
57
+ parsed = JSON.parse(fs.readFileSync(path.join(directory, "manifest.json"), "utf-8"));
58
+ } catch (error) {
59
+ throw new Error(`Run fan-out budget manifest is unreadable at '${directory}': ${error instanceof Error ? error.message : String(error)}`);
60
+ }
61
+ const manifest = parseManifest(parsed);
62
+ if (!manifest) throw new Error(`Run fan-out budget manifest is invalid at '${directory}'.`);
63
+ return manifest;
64
+ }
65
+
66
+ function validateDirectory(directory: string): string {
67
+ let realDirectory: string;
68
+ let realRoot: string;
69
+ try {
70
+ realDirectory = fs.realpathSync(path.resolve(directory));
71
+ realRoot = fs.realpathSync(path.resolve(RUN_FANOUT_ROOT));
72
+ } catch (error) {
73
+ throw new Error(`Run fan-out budget directory is unavailable: ${error instanceof Error ? error.message : String(error)}`);
74
+ }
75
+ if (realDirectory !== realRoot && !realDirectory.startsWith(`${realRoot}${path.sep}`)) {
76
+ throw new Error("Run fan-out budget directory resolves outside the managed budget root.");
77
+ }
78
+ return realDirectory;
79
+ }
80
+
81
+ export function createRunFanoutBudget(rootRunId: string, limit: number): RunFanoutBudgetDescriptor {
82
+ if (!Number.isInteger(limit) || limit <= 0) throw new Error("Run fan-out limit must be a positive integer.");
83
+ fs.mkdirSync(RUN_FANOUT_ROOT, { recursive: true, mode: 0o700 });
84
+ let directory: string;
85
+ do directory = path.join(RUN_FANOUT_ROOT, `${safeRootRunId(rootRunId)}-${randomUUID()}`);
86
+ while (fs.existsSync(directory));
87
+ fs.mkdirSync(path.join(directory, "claims"), { recursive: true, mode: 0o700 });
88
+ const manifest: ManifestV1 = { version: 1, rootRunId, limit, createdAt: Date.now() };
89
+ fs.writeFileSync(path.join(directory, "manifest.json"), `${JSON.stringify(manifest)}\n`, { mode: 0o600, flag: "wx" });
90
+ return { version: 1, rootRunId, directory, limit };
91
+ }
92
+
93
+ export function validateRunFanoutBudgetDescriptor(value: unknown): RunFanoutBudgetDescriptor {
94
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Run fan-out budget descriptor is missing or invalid.");
95
+ const descriptor = value as Partial<RunFanoutBudgetDescriptor>;
96
+ if (descriptor.version !== 1 || typeof descriptor.rootRunId !== "string" || !descriptor.rootRunId
97
+ || typeof descriptor.directory !== "string" || !descriptor.directory
98
+ || !Number.isInteger(descriptor.limit) || (descriptor.limit ?? 0) <= 0
99
+ || (descriptor.parentPath !== undefined && typeof descriptor.parentPath !== "string")) {
100
+ throw new Error("Run fan-out budget descriptor is invalid.");
101
+ }
102
+ const directory = validateDirectory(descriptor.directory);
103
+ const manifest = readManifest(directory);
104
+ if (manifest.rootRunId !== descriptor.rootRunId || manifest.limit !== descriptor.limit) {
105
+ throw new Error("Run fan-out budget descriptor does not match its manifest.");
106
+ }
107
+ return { version: 1, rootRunId: descriptor.rootRunId, directory, limit: descriptor.limit, ...(descriptor.parentPath ? { parentPath: descriptor.parentPath } : {}) };
108
+ }
109
+
110
+ export function writeRunFanoutBudgetDescriptor(asyncDir: string, descriptor: RunFanoutBudgetDescriptor): void {
111
+ const valid = validateRunFanoutBudgetDescriptor(descriptor);
112
+ fs.mkdirSync(asyncDir, { recursive: true });
113
+ fs.writeFileSync(path.join(asyncDir, "run-fanout-budget.json"), `${JSON.stringify(valid)}\n`, { mode: 0o600 });
114
+ }
115
+
116
+ export function readRunFanoutBudgetDescriptor(asyncDir: string | undefined): RunFanoutBudgetDescriptor | undefined {
117
+ if (!asyncDir) return undefined;
118
+ const descriptorPath = path.join(asyncDir, "run-fanout-budget.json");
119
+ if (!fs.existsSync(descriptorPath)) return undefined;
120
+ try {
121
+ return validateRunFanoutBudgetDescriptor(JSON.parse(fs.readFileSync(descriptorPath, "utf-8")));
122
+ } catch (error) {
123
+ throw new Error(`Invalid persisted run fan-out budget '${descriptorPath}': ${error instanceof Error ? error.message : String(error)}`);
124
+ }
125
+ }
126
+
127
+ export function encodeRunFanoutBudgetDescriptor(descriptor: RunFanoutBudgetDescriptor): string {
128
+ return Buffer.from(JSON.stringify(validateRunFanoutBudgetDescriptor(descriptor)), "utf-8").toString("base64url");
129
+ }
130
+
131
+ export function decodeRunFanoutBudgetDescriptor(encoded: string | undefined): RunFanoutBudgetDescriptor | undefined {
132
+ if (!encoded) return undefined;
133
+ try {
134
+ return validateRunFanoutBudgetDescriptor(JSON.parse(Buffer.from(encoded, "base64url").toString("utf-8")));
135
+ } catch (error) {
136
+ throw new Error(`Invalid inherited run fan-out budget: ${error instanceof Error ? error.message : String(error)}`);
137
+ }
138
+ }
139
+
140
+ interface AdmissionLockOwner {
141
+ pid: number;
142
+ token: string;
143
+ }
144
+
145
+ const ADMISSION_LOCK_STALE_MS = 60_000;
146
+
147
+ function readAdmissionLockOwner(lockPath: string): AdmissionLockOwner | undefined {
148
+ try {
149
+ const owner = JSON.parse(fs.readFileSync(path.join(lockPath, "owner.json"), "utf-8")) as Partial<AdmissionLockOwner>;
150
+ if (Number.isSafeInteger(owner.pid) && (owner.pid ?? 0) > 0 && typeof owner.token === "string" && owner.token) return owner as AdmissionLockOwner;
151
+ } catch {}
152
+ return undefined;
153
+ }
154
+
155
+ function admissionLockIsStale(lockPath: string): boolean {
156
+ const owner = readAdmissionLockOwner(lockPath);
157
+ if (owner) {
158
+ try {
159
+ process.kill(owner.pid, 0);
160
+ return false;
161
+ } catch (error) {
162
+ return (error as NodeJS.ErrnoException).code !== "EPERM";
163
+ }
164
+ }
165
+ try { return Date.now() - fs.statSync(lockPath).mtimeMs > ADMISSION_LOCK_STALE_MS; }
166
+ catch (error) {
167
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
168
+ throw error;
169
+ }
170
+ }
171
+
172
+ function withAdmissionLock<T>(directory: string, operation: () => T): T {
173
+ const lockPath = path.join(directory, "admission.lock");
174
+ const owner: AdmissionLockOwner = { pid: process.pid, token: randomUUID() };
175
+ for (let attempt = 0; ; attempt++) {
176
+ try {
177
+ fs.mkdirSync(lockPath, { mode: 0o700 });
178
+ try { fs.writeFileSync(path.join(lockPath, "owner.json"), JSON.stringify(owner), { mode: 0o600 }); }
179
+ catch (error) {
180
+ fs.rmSync(lockPath, { recursive: true, force: true });
181
+ throw error;
182
+ }
183
+ break;
184
+ } catch (error) {
185
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
186
+ if (admissionLockIsStale(lockPath)) {
187
+ const stalePath = path.join(directory, `admission.stale-${randomUUID()}`);
188
+ try {
189
+ fs.renameSync(lockPath, stalePath);
190
+ fs.rmSync(stalePath, { recursive: true, force: true });
191
+ continue;
192
+ } catch (reclaimError) {
193
+ if ((reclaimError as NodeJS.ErrnoException).code !== "ENOENT") throw reclaimError;
194
+ }
195
+ }
196
+ const delay = DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS[attempt];
197
+ if (delay === undefined) throw new Error(`Timed out acquiring run fan-out admission lock at '${directory}'.`);
198
+ waitForFileSystemRetry(delay);
199
+ }
200
+ }
201
+ try { return operation(); }
202
+ finally {
203
+ if (readAdmissionLockOwner(lockPath)?.token === owner.token) fs.rmSync(lockPath, { recursive: true, force: true });
204
+ }
205
+ }
206
+
207
+ function claimCount(directory: string): number {
208
+ const claimsDir = path.join(directory, "claims");
209
+ let entries: fs.Dirent[];
210
+ try { entries = fs.readdirSync(claimsDir, { withFileTypes: true }); }
211
+ catch (error) {
212
+ throw new Error(`Run fan-out claims directory is unreadable at '${claimsDir}': ${error instanceof Error ? error.message : String(error)}`);
213
+ }
214
+ return entries.filter((entry) => /^\d{6}\.json$/.test(entry.name)).length;
215
+ }
216
+
217
+ export function getRunFanoutBudgetSnapshot(descriptor: RunFanoutBudgetDescriptor): RunFanoutBudgetSnapshot {
218
+ const valid = validateRunFanoutBudgetDescriptor(descriptor);
219
+ const used = claimCount(valid.directory);
220
+ return { used, limit: valid.limit, remaining: Math.max(0, valid.limit - used) };
221
+ }
222
+
223
+ function qualifyRunFanoutPaths(descriptor: RunFanoutBudgetDescriptor, paths: string[]): string[] {
224
+ const prefix = descriptor.parentPath?.trim();
225
+ return paths.map((item) => prefix ? `${prefix}/${item}` : item);
226
+ }
227
+
228
+ function commitRunFanoutBatch<T>(descriptor: RunFanoutBudgetDescriptor, paths: string[], commit: (snapshot: RunFanoutBudgetSnapshot) => T): T {
229
+ const valid = validateRunFanoutBudgetDescriptor(descriptor);
230
+ if (paths.length === 0) return commit(getRunFanoutBudgetSnapshot(valid));
231
+ const qualified = qualifyRunFanoutPaths(valid, paths);
232
+ return withAdmissionLock(valid.directory, () => {
233
+ const before = getRunFanoutBudgetSnapshot(valid);
234
+ if (qualified.length > before.remaining) {
235
+ throw new RunFanoutLimitError({ code: "RUN_FANOUT_LIMIT", path: qualified[before.remaining] ?? qualified[0]!, requested: qualified.length, ...before });
236
+ }
237
+ const created: string[] = [];
238
+ try {
239
+ for (const claimPath of qualified) {
240
+ for (let slot = 0; slot < valid.limit; slot++) {
241
+ const slotPath = path.join(valid.directory, "claims", `${String(slot).padStart(6, "0")}.json`);
242
+ try {
243
+ const fd = fs.openSync(slotPath, "wx", 0o600);
244
+ created.push(slotPath);
245
+ try {
246
+ const claim: ClaimV1 = { version: 1, claimId: randomUUID(), path: claimPath, claimedAt: Date.now() };
247
+ fs.writeFileSync(fd, `${JSON.stringify(claim)}\n`, "utf-8");
248
+ } finally { fs.closeSync(fd); }
249
+ break;
250
+ } catch (error) {
251
+ if ((error as NodeJS.ErrnoException).code === "EEXIST") continue;
252
+ throw error;
253
+ }
254
+ }
255
+ }
256
+ return commit(getRunFanoutBudgetSnapshot(valid));
257
+ } catch (error) {
258
+ for (const slotPath of created) {
259
+ try { fs.unlinkSync(slotPath); } catch {}
260
+ }
261
+ throw error;
262
+ }
263
+ });
264
+ }
265
+
266
+ export function claimRunFanoutBatch(descriptor: RunFanoutBudgetDescriptor, paths: string[]): RunFanoutBudgetSnapshot {
267
+ return commitRunFanoutBatch(descriptor, paths, (snapshot) => snapshot);
268
+ }
269
+
270
+ export function claimRunFanoutBatchWithCommit<T>(descriptor: RunFanoutBudgetDescriptor, paths: string[], commit: () => T): T {
271
+ return commitRunFanoutBatch(descriptor, paths, commit);
272
+ }
273
+
274
+ export function formatRunFanoutBudget(snapshot: RunFanoutBudgetSnapshot): string {
275
+ return `Run fan-out: ${snapshot.used}/${snapshot.limit} used, ${snapshot.remaining} remaining`;
276
+ }
277
+
278
+ function formatRunFanoutRejection(rejection: RunFanoutRejection): string {
279
+ return `Run fan-out limit reached at ${rejection.path} (${rejection.used}/${rejection.limit} used; ${rejection.requested} requested, ${rejection.remaining} remaining). No children from this admission group were started. Start a new top-level run or raise config.maxSubagentSpawnsPerRun.`;
280
+ }
@@ -214,17 +214,19 @@ export function finalizeSingleOutput(params: {
214
214
  outputPath?: string;
215
215
  outputMode?: OutputMode;
216
216
  exitCode: number;
217
+ /** Keep the saved-output reference when a post-run acceptance gate rejects an otherwise completed child. */
218
+ preserveSavedOutput?: boolean;
217
219
  savedPath?: string;
218
220
  outputReference?: SavedOutputReference;
219
221
  saveError?: string;
220
222
  }): { displayOutput: string; savedPath?: string; outputReference?: SavedOutputReference; saveError?: string } {
221
223
  let displayOutput = params.truncatedOutput || params.fullOutput;
222
- if (params.exitCode === 0 && params.savedPath) {
224
+ if ((params.exitCode === 0 || params.preserveSavedOutput) && params.savedPath) {
223
225
  const outputReference = params.outputReference ?? formatSavedOutputReference(params.savedPath, params.fullOutput);
224
226
  if (params.outputMode === "file-only") {
225
227
  return { displayOutput: outputReference.message, savedPath: params.savedPath, outputReference };
226
228
  }
227
- displayOutput += `\n\n${outputReference.message}`;
229
+ if (!displayOutput.includes(outputReference.message)) displayOutput += `\n\n${outputReference.message}`;
228
230
  return { displayOutput, savedPath: params.savedPath, outputReference };
229
231
  }
230
232
  if (params.exitCode === 0 && params.saveError && params.outputPath) {
@@ -30,6 +30,8 @@ import { drainOutstandingWork } from "../background/auto-drain.ts";
30
30
  const SUBAGENT_INHERIT_PROJECT_CONTEXT_ENV = "PI_SUBAGENT_INHERIT_PROJECT_CONTEXT";
31
31
  const SUBAGENT_INHERIT_SKILLS_ENV = "PI_SUBAGENT_INHERIT_SKILLS";
32
32
  export const SUBAGENT_INTERCOM_SESSION_NAME_ENV = "PI_SUBAGENT_INTERCOM_SESSION_NAME";
33
+ const STEERING_LEGACY_SETTLE_FALLBACK_MS = 1000;
34
+ const STEERING_SAFETY_POLL_INTERVAL_MS = 5000;
33
35
 
34
36
  const STRUCTURED_OUTPUT_INSTRUCTIONS = [
35
37
  "This subagent step has a strict structured output contract.",
@@ -330,7 +332,13 @@ function registerToolBudget(pi: ExtensionAPI, budget: ResolvedToolBudget | undef
330
332
 
331
333
  export function registerSteeringInbox(
332
334
  pi: ExtensionAPI,
333
- deps: { watch?: typeof fs.watch; nativeRealpath?: (filePath: string) => string } = {},
335
+ deps: {
336
+ watch?: typeof fs.watch;
337
+ nativeRealpath?: (filePath: string) => string;
338
+ legacySettleFallbackMs?: number;
339
+ safetyPollIntervalMs?: number;
340
+ timers?: Pick<typeof globalThis, "setInterval" | "clearInterval">;
341
+ } = {},
334
342
  ): void {
335
343
  const steerInbox = process.env[SUBAGENT_STEER_INBOX_ENV]?.trim();
336
344
  if (!steerInbox) return;
@@ -343,11 +351,15 @@ export function registerSteeringInbox(
343
351
  let disposed = false;
344
352
  let agentRunning = false;
345
353
  let inTurn = false;
354
+ let awaitingSettlement = false;
346
355
  let flushing = false;
347
356
  let started = false;
348
357
  let canSteer = typeof sendUserMessage === "function";
349
358
  let watcher: fs.FSWatcher | undefined;
350
359
  let interval: NodeJS.Timeout | undefined;
360
+ let safetyInterval: NodeJS.Timeout | undefined;
361
+ let settleFallback: NodeJS.Timeout | undefined;
362
+ const legacySettleFallbackMs = deps.legacySettleFallbackMs ?? STEERING_LEGACY_SETTLE_FALLBACK_MS;
351
363
  const acknowledge = (request: SteerRequest, state: "delivered" | "queued" | "failed", message: string, deliveryStatus?: SteerDeliveryStatus): void => {
352
364
  if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;
353
365
  writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {
@@ -375,7 +387,8 @@ export function registerSteeringInbox(
375
387
  continue;
376
388
  }
377
389
  const requestedMode = request.mode ?? "steer";
378
- const delivery = requestedMode === "follow_up" || (requestedMode === "auto" && inTurn) ? "followUp" as const : "steer" as const;
390
+ const autoCanUseIdle = requestedMode === "auto" && !agentRunning && !awaitingSettlement;
391
+ const delivery = requestedMode === "follow_up" || (requestedMode === "auto" && (inTurn || awaitingSettlement)) ? "followUp" as const : "steer" as const;
379
392
  const pendingFollowUps = [...pending.values()].reduce((count, entries) => count + entries.filter((entry) => entry.deliveryStatus === "queued").length, 0);
380
393
  if (delivery === "followUp" && queued.length + pendingFollowUps >= MAX_STEER_QUEUE_SIZE) {
381
394
  acknowledge(request, "failed", `Follow-up queue is full (${MAX_STEER_QUEUE_SIZE} messages).`);
@@ -386,7 +399,7 @@ export function registerSteeringInbox(
386
399
  entries.push({ request, deliveryStatus: delivery === "followUp" ? "queued" : "delivered" });
387
400
  pending.set(formatted, entries);
388
401
  try {
389
- sendUserMessage(formatted, requestedMode === "auto" && !agentRunning ? undefined : { deliverAs: delivery });
402
+ sendUserMessage(formatted, autoCanUseIdle ? undefined : { deliverAs: delivery });
390
403
  } catch (error) {
391
404
  entries.pop();
392
405
  if (entries.length === 0) pending.delete(formatted);
@@ -426,28 +439,95 @@ export function registerSteeringInbox(
426
439
  return;
427
440
  }
428
441
  started = true;
442
+ const startPolling = (): void => {
443
+ if (interval || disposed) return;
444
+ interval = (deps.timers?.setInterval ?? setInterval)(flush, 250) as NodeJS.Timeout;
445
+ interval.unref?.();
446
+ };
447
+ const startSafetyPolling = (): void => {
448
+ if (safetyInterval || disposed) return;
449
+ safetyInterval = (deps.timers?.setInterval ?? setInterval)(flush, deps.safetyPollIntervalMs ?? STEERING_SAFETY_POLL_INTERVAL_MS) as NodeJS.Timeout;
450
+ safetyInterval.unref?.();
451
+ };
429
452
  try {
430
453
  watcher = (deps.watch ?? fs.watch)(resolveWatchPath(steerInbox, deps.nativeRealpath), () => flush());
431
- watcher.on("error", () => {});
454
+ watcher.on("error", startPolling);
455
+ startSafetyPolling();
432
456
  } catch {
433
457
  watcher = undefined;
458
+ startPolling();
434
459
  }
435
- interval = setInterval(flush, 250);
436
- interval.unref?.();
437
460
  };
438
461
  const activate = (): undefined => {
439
462
  start();
440
463
  flush();
441
464
  return undefined;
442
465
  };
466
+ const clearSettleFallback = (): void => {
467
+ if (!settleFallback) return;
468
+ clearTimeout(settleFallback);
469
+ settleFallback = undefined;
470
+ };
471
+ const markSettled = (): undefined => {
472
+ clearSettleFallback();
473
+ agentRunning = false;
474
+ inTurn = false;
475
+ awaitingSettlement = false;
476
+ return activate();
477
+ };
478
+ const armLegacySettleFallback = (): void => {
479
+ clearSettleFallback();
480
+ settleFallback = setTimeout(() => {
481
+ settleFallback = undefined;
482
+ if (disposed || !awaitingSettlement) return;
483
+ agentRunning = false;
484
+ inTurn = false;
485
+ awaitingSettlement = false;
486
+ activate();
487
+ }, legacySettleFallbackMs);
488
+ settleFallback.unref?.();
489
+ };
443
490
 
444
491
  const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx?: unknown) => unknown) => void;
445
492
  // Register input before the watcher so an accepted extension input cannot race request dispatch.
446
493
  onRuntimeEvent("input", onInput);
447
494
  onRuntimeEvent("session_start", () => start());
448
- onRuntimeEvent("agent_start", () => { agentRunning = true; return activate(); });
449
- onRuntimeEvent("agent_end", () => { agentRunning = false; inTurn = false; return activate(); });
495
+ onRuntimeEvent("agent_start", () => {
496
+ clearSettleFallback();
497
+ agentRunning = true;
498
+ awaitingSettlement = false;
499
+ return activate();
500
+ });
501
+ onRuntimeEvent("agent_end", (event) => {
502
+ inTurn = false;
503
+ if ((event as { willRetry?: unknown } | undefined)?.willRetry === true) {
504
+ clearSettleFallback();
505
+ agentRunning = true;
506
+ awaitingSettlement = true;
507
+ return activate();
508
+ }
509
+ agentRunning = true;
510
+ awaitingSettlement = true;
511
+ armLegacySettleFallback();
512
+ return activate();
513
+ });
514
+ onRuntimeEvent("agent_settled", markSettled);
515
+ onRuntimeEvent("session_compact", () => {
516
+ const unresolved = [...pending.values()].flat();
517
+ pending.clear();
518
+ for (const entry of unresolved) {
519
+ try {
520
+ writeSteerRequestToDir(steerInbox, { ...entry.request, mode: "follow_up" });
521
+ } catch (error) {
522
+ acknowledge(entry.request, "failed", `Could not retry steering after compaction: ${error instanceof Error ? error.message : String(error)}`);
523
+ }
524
+ }
525
+ return activate();
526
+ });
450
527
  onRuntimeEvent("turn_start", () => {
528
+ clearSettleFallback();
529
+ agentRunning = true;
530
+ awaitingSettlement = false;
451
531
  inTurn = true;
452
532
  const next = queued.findIndex((entry) => entry.ready);
453
533
  if (next >= 0) {
@@ -466,9 +546,14 @@ export function registerSteeringInbox(
466
546
  }
467
547
  onRuntimeEvent("session_shutdown", () => {
468
548
  for (const entry of queued) acknowledge(entry.request, "failed", "Run ended before queued follow-up delivery.", "queued");
549
+ for (const entries of pending.values()) {
550
+ for (const entry of entries) acknowledge(entry.request, "failed", "Run ended before Pi confirmed steering input delivery.");
551
+ }
469
552
  disposed = true;
553
+ clearSettleFallback();
470
554
  try { watcher?.close(); } catch {}
471
- if (interval) clearInterval(interval);
555
+ if (interval) (deps.timers?.clearInterval ?? clearInterval)(interval);
556
+ if (safetyInterval) (deps.timers?.clearInterval ?? clearInterval)(safetyInterval);
472
557
  });
473
558
  }
474
559
 
@@ -70,6 +70,18 @@ const RESEARCH_AGENT_PATTERNS = [
70
70
  /\bresearch(?:er)?\b/i,
71
71
  ];
72
72
 
73
+ // Review/severity vocabulary like "must-fix items" or "should-fix tests" is not
74
+ // the verb. Rather than dash-guarding every pattern (which would also suppress
75
+ // CLI flags like "--fix" and genuine clause-level dashes like "branch—fix it"),
76
+ // strip the known severity compounds (must|should|needs + dash + verb) from the
77
+ // task text before matching. Dash coverage: ASCII hyphen + U+2010..U+2015.
78
+ const SEVERITY_COMPOUND_PATTERN = /\b(?:must|should|needs)[\-\u2010-\u2015](?:fix|edit|update|add|remove|replace|create|apply|make|do|implement|modify|delete|patch)\b/gi;
79
+
80
+ function stripSeverityCompounds(task: string): string {
81
+ return task.replace(SEVERITY_COMPOUND_PATTERN, " ");
82
+ }
83
+ export { stripSeverityCompounds };
84
+
73
85
  const FIX_OR_PATCH_IMPLEMENTATION_PATTERN = /\b(?:fix|patch)\s+(?:(?:it|this|that|them|each|any|all|these|those)\b|(?:(?:a|an|the|any|all)\s+)?(?:(?:failing|failed|broken|flaky|red|cold|start|current|existing|reported|approved|known|regression|unit|integration|e2e|source|typescript|type-?script|ts|type-?check|compiler)\s+)*(?:bug|defect|issues?|problems?|failures?|regressions?|tests?|errors?|items?|typos?|code|source|implementation|component|function|module|class|method|logic|file|files|readme|docs?|changelog|package\.json|config|manifest|extension|prompt|command|lint(?:ing)?|build|ci|type-?check|type\s+checking)\b)/i;
74
86
 
75
87
  const WORKER_IMPLEMENTATION_PATTERNS = [
@@ -146,7 +158,7 @@ function hasImplementationIntent(agent: string, taskText: string): boolean {
146
158
  }
147
159
 
148
160
  export function classifyTaskMutationIntent(agent: string, task: string): TaskMutationIntent {
149
- const taskText = stripFrameworkInstructions(task);
161
+ const taskText = stripSeverityCompounds(stripFrameworkInstructions(task));
150
162
  const taskTextWithoutScopedConstraints = stripPatterns(taskText, SCOPED_NO_EDIT_CONSTRAINT_PATTERNS);
151
163
  const prohibitions = analyzeNoEditProhibitions(taskTextWithoutScopedConstraints);
152
164
  if (prohibitions.present) {
@@ -164,7 +176,11 @@ export function expectsImplementationMutation(agent: string, task: string): bool
164
176
  return classifyTaskMutationIntent(agent, task).kind === "implementation";
165
177
  }
166
178
 
167
- /** Bare write verbs that make a task write-capable for acceptance inference. */
179
+ /** Bare write verbs that make a task write-capable for acceptance inference.
180
+ * Severity compounds ("must-fix items") are stripped before matching, so they
181
+ * are not write imperatives, while CLI flags ("--fix", "-w"), clause-level
182
+ * dashes ("branch—fix it"), and hyphenated imperatives ("hot-fix the bug")
183
+ * all stay write-capable. */
168
184
  const MAY_MUTATE_VERB_PATTERN = /\b(?:fix|implement|update|write|edit|modify|migrate|delete|remove|refactor|commit)\b/i;
169
185
 
170
186
  /**
@@ -174,7 +190,7 @@ const MAY_MUTATE_VERB_PATTERN = /\b(?:fix|implement|update|write|edit|modify|mig
174
190
  * does.
175
191
  */
176
192
  export function taskMayMutate(task: string): boolean {
177
- const taskText = stripPatterns(stripFrameworkInstructions(task), SCOPED_NO_EDIT_CONSTRAINT_PATTERNS);
193
+ const taskText = stripPatterns(stripSeverityCompounds(stripFrameworkInstructions(task)), SCOPED_NO_EDIT_CONSTRAINT_PATTERNS);
178
194
  const prohibitions = analyzeNoEditProhibitions(taskText);
179
195
  if (prohibitions.blanket) return false;
180
196
  return MAY_MUTATE_VERB_PATTERN.test(stripPatterns(prohibitions.strippedText, READ_ONLY_DELIVERABLE_PATTERNS));