@xzzpig/pi-subagents 0.2.0 → 0.4.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 (103) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +2 -0
  3. package/agents/oracle.md +7 -5
  4. package/agents/researcher.md +1 -1
  5. package/agents/reviewer.md +2 -2
  6. package/agents/scout.md +1 -1
  7. package/agents/worker.md +1 -1
  8. package/docs/agents.md +3 -0
  9. package/docs/configuration.md +121 -10
  10. package/docs/extension-api.md +36 -0
  11. package/docs/missions.md +5 -3
  12. package/docs/observability.md +43 -3
  13. package/docs/tool-reference.md +20 -3
  14. package/docs/workflows.md +2 -2
  15. package/package.json +4 -4
  16. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  17. package/skills/pi-subagents/references/execution-controls.md +5 -4
  18. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  19. package/skills/pi-subagents/references/prompting-and-roles.md +31 -15
  20. package/src/agents/agent-serializer.ts +2 -0
  21. package/src/agents/agents.ts +46 -15
  22. package/src/api/external-runs.ts +174 -84
  23. package/src/api/preflight.ts +13 -7
  24. package/src/extension/config.ts +59 -0
  25. package/src/extension/doctor.ts +40 -0
  26. package/src/extension/index.ts +83 -9
  27. package/src/extension/public-execution.ts +37 -4
  28. package/src/extension/rpc.ts +8 -10
  29. package/src/extension/schemas.ts +12 -10
  30. package/src/extension/tool-description.ts +13 -9
  31. package/src/inspectors/herdr/actions.ts +13 -8
  32. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  33. package/src/inspectors/herdr/project-panes.ts +2 -6
  34. package/src/inspectors/herdr/shell-command.ts +16 -0
  35. package/src/intercom/intercom-bridge.ts +9 -5
  36. package/src/intercom/native-supervisor-channel.ts +19 -42
  37. package/src/missions/goal-driver.ts +3 -1
  38. package/src/missions/lifecycle.ts +4 -7
  39. package/src/missions/store.ts +12 -7
  40. package/src/missions/workflow-state.ts +6 -2
  41. package/src/runs/background/active-async-capacity.ts +431 -0
  42. package/src/runs/background/active-run-index.ts +77 -3
  43. package/src/runs/background/async-execution.ts +190 -72
  44. package/src/runs/background/async-job-tracker.ts +5 -0
  45. package/src/runs/background/async-resume.ts +21 -7
  46. package/src/runs/background/async-status-snapshot.ts +277 -0
  47. package/src/runs/background/async-status.ts +17 -6
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/chain-root-attachment.ts +2 -2
  50. package/src/runs/background/completion-replay.ts +11 -1
  51. package/src/runs/background/fleet-view.ts +21 -6
  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-files.ts +437 -0
  55. package/src/runs/background/result-watcher.ts +188 -41
  56. package/src/runs/background/resume-guidance.ts +27 -7
  57. package/src/runs/background/retained-children.ts +75 -18
  58. package/src/runs/background/run-id-resolver.ts +30 -24
  59. package/src/runs/background/run-status.ts +106 -5
  60. package/src/runs/background/scheduled-runs.ts +54 -28
  61. package/src/runs/background/stale-run-reconciler.ts +30 -16
  62. package/src/runs/background/subagent-runner.ts +352 -62
  63. package/src/runs/background/subagent-wait.ts +2 -0
  64. package/src/runs/background/wait-completions.ts +5 -2
  65. package/src/runs/foreground/async-dismiss-action.ts +2 -1
  66. package/src/runs/foreground/chain-execution.ts +53 -2
  67. package/src/runs/foreground/execution.ts +309 -34
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/prompt-audit.ts +172 -0
  70. package/src/runs/foreground/subagent-executor.ts +936 -224
  71. package/src/runs/shared/acceptance.ts +13 -4
  72. package/src/runs/shared/completion-guard.ts +107 -1
  73. package/src/runs/shared/external-cli-runner.ts +4 -0
  74. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  75. package/src/runs/shared/model-fallback.ts +16 -2
  76. package/src/runs/shared/nested-events.ts +66 -62
  77. package/src/runs/shared/orca-progress-tabs.ts +375 -0
  78. package/src/runs/shared/parallel-utils.ts +4 -0
  79. package/src/runs/shared/pi-args.ts +44 -1
  80. package/src/runs/shared/run-fanout-budget.ts +280 -0
  81. package/src/runs/shared/single-output.ts +4 -2
  82. package/src/runs/shared/subagent-control.ts +15 -0
  83. package/src/runs/shared/subagent-prompt-runtime.ts +1 -9
  84. package/src/runs/shared/subagent-startup-retry.ts +12 -0
  85. package/src/runs/shared/task-intent.ts +19 -3
  86. package/src/runs/shared/tool-timeout.ts +93 -0
  87. package/src/runs/shared/worktree.ts +17 -5
  88. package/src/shared/agent-stream-options.ts +5 -0
  89. package/src/shared/artifacts.ts +2 -6
  90. package/src/shared/display-text.ts +50 -0
  91. package/src/shared/node-executable.ts +21 -0
  92. package/src/shared/types.ts +143 -5
  93. package/src/shared/utils.ts +3 -1
  94. package/src/slash/slash-commands.ts +34 -25
  95. package/src/slash/slash-live-state.ts +3 -0
  96. package/src/tui/fleet-status.ts +164 -47
  97. package/src/tui/fleet-transcript.ts +1 -48
  98. package/src/tui/fleet.ts +352 -27
  99. package/src/tui/render.ts +122 -44
  100. package/src/watchdog/permission-arbiter.ts +2 -1
  101. package/src/watchdog/review.ts +4 -3
  102. package/src/workflows/chat-progress.ts +10 -2
  103. package/src/workflows/scripted-workflow.ts +292 -79
@@ -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) {
@@ -6,6 +6,7 @@ import {
6
6
  type ControlNotificationChannel,
7
7
  type ResolvedControlConfig,
8
8
  } from "../../shared/types.ts";
9
+ import { isToolTimeoutExempt } from "./tool-timeout.ts";
9
10
 
10
11
  const CONTROL_EVENT_TYPES: ControlEventType[] = ["active_long_running", "needs_attention"];
11
12
  const CONTROL_NOTIFICATION_CHANNELS: ControlNotificationChannel[] = ["event", "async", "intercom"];
@@ -84,6 +85,18 @@ export function deriveActivityState(input: {
84
85
  return ageMs > input.config.needsAttentionAfterMs ? "needs_attention" : undefined;
85
86
  }
86
87
 
88
+ export function shouldEmitOpenToolAttention(input: {
89
+ config: ResolvedControlConfig;
90
+ currentTool?: string;
91
+ currentToolStartedAt?: number;
92
+ now?: number;
93
+ }): boolean {
94
+ if (!input.config.enabled || !input.currentTool || input.currentToolStartedAt === undefined) return false;
95
+ if (isToolTimeoutExempt(input.currentTool)) return false;
96
+ const now = input.now ?? Date.now();
97
+ return Math.max(0, now - input.currentToolStartedAt) >= input.config.activeNoticeAfterMs;
98
+ }
99
+
87
100
  export function buildControlEvent(input: {
88
101
  type?: ControlEventType;
89
102
  from?: ActivityState;
@@ -196,10 +209,12 @@ export function formatControlNoticeMessage(event: ControlEvent, childIntercomTar
196
209
  const supervisorHint = event.reason === "supervisor_request"
197
210
  ? "Supervisor request: reply to the pending request. If subagent_supervisor pending is empty, check intercom pending because an external intercom tool may own the request."
198
211
  : undefined;
212
+ const facts = formatLongRunningFacts(event);
199
213
  return [
200
214
  `Subagent needs attention: ${event.agent}`,
201
215
  `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
202
216
  `Signal: ${event.message}`,
217
+ facts ? `Facts: ${facts}` : undefined,
203
218
  event.recentFailureSummary ? `Recent failures: ${event.recentFailureSummary}` : undefined,
204
219
  supervisorHint,
205
220
  "Hint: Inspect status first unless the run is clearly blocked. Use steer for a top-level live async child, routed resume for a live nested child, or resume to revive a paused/completed/failed child.",
@@ -580,16 +580,9 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
580
580
  } as unknown as SubagentState;
581
581
  if (typeof pi.registerTool === "function") registerWaitTool(pi, waitState, waitToolEnabled);
582
582
  let nativeSupervisorClientRegistered = false;
583
- let nativeSupervisorFallbackRegistered = false;
584
583
  const registerNativeSupervisorClientOnce = (): void => {
585
584
  if (nativeSupervisorClientRegistered) return;
586
585
  nativeSupervisorClientRegistered = true;
587
- registerNativeSupervisorClient(pi, { includeIntercomFallback: false });
588
- };
589
- const registerNativeSupervisorFallbackOnce = (): void => {
590
- registerNativeSupervisorClientOnce();
591
- if (nativeSupervisorFallbackRegistered) return;
592
- nativeSupervisorFallbackRegistered = true;
593
586
  registerNativeSupervisorClient(pi);
594
587
  };
595
588
  const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx?: ExtensionContext) => unknown) => void;
@@ -597,7 +590,6 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
597
590
  const sessionManager = (ctx as { sessionManager?: Parameters<typeof resolveCurrentSessionId>[0] } | undefined)?.sessionManager;
598
591
  waitState.currentSessionId = sessionManager ? resolveCurrentSessionId(sessionManager) : null;
599
592
  registerNativeSupervisorClientOnce();
600
- if (readRequiredChildTools()?.includes("intercom")) registerNativeSupervisorFallbackOnce();
601
593
  });
602
594
  onRuntimeEvent("agent_start", () => {
603
595
  refreshChildToolDiagnostic(pi);
@@ -650,7 +642,7 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
650
642
 
651
643
  onRuntimeEvent("before_agent_start", async (event: unknown) => {
652
644
  if (!event || typeof event !== "object" || !("systemPrompt" in event) || typeof event.systemPrompt !== "string") return undefined;
653
- registerNativeSupervisorFallbackOnce();
645
+ registerNativeSupervisorClientOnce();
654
646
  const intercomSessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();
655
647
  if (intercomSessionName && typeof pi.setSessionName === "function") {
656
648
  pi.setSessionName(intercomSessionName);
@@ -12,6 +12,7 @@ export const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500] as const;
12
12
  export const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
13
13
 
14
14
  const SIGKILL_PROCESS_SIGNAL_ERROR = formatProcessSignalError("SIGKILL");
15
+ const EXTENSION_REGISTRATION_CONFLICT_PATTERN = /Failed to load extension\b[^\n]*:\s*(?:Tool|Flag)\s+"[^"]+"\s+conflicts with\b/i;
15
16
 
16
17
  export interface SubagentStartupFailureEvidence {
17
18
  exitCode: number | null | undefined;
@@ -31,6 +32,17 @@ export interface SubagentStartupFailureEvidence {
31
32
  turnBudgetExceeded?: boolean;
32
33
  }
33
34
 
35
+ export function formatSubagentExtensionConflictError(
36
+ error: string | undefined,
37
+ input: { agent: string; ambientExtensionsEnabled: boolean },
38
+ ): string | undefined {
39
+ if (!error || !input.ambientExtensionsEnabled || !EXTENSION_REGISTRATION_CONFLICT_PATTERN.test(error)) return error;
40
+ const settings = JSON.stringify({
41
+ subagents: { agentOverrides: { [input.agent]: { extensions: [] } } },
42
+ });
43
+ return `${error}\n\nSubagent startup loaded conflicting ambient Pi extensions. Retry this run after disabling ambient extension discovery for agent ${JSON.stringify(input.agent)} in project .pi/settings.json: ${settings}. Replace the empty array with only the required extension entry paths when this agent needs extension tools.`;
44
+ }
45
+
34
46
  function hasUsage(usage: Usage): boolean {
35
47
  return usage.input !== 0
36
48
  || usage.output !== 0
@@ -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));
@@ -0,0 +1,93 @@
1
+ export const TOOL_TIMEOUT_ENV = "PI_SUBAGENT_TOOL_TIMEOUT_MS";
2
+
3
+ /** Maximum delay a Node.js timer accepts without overflow. */
4
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
5
+
6
+ export const DEFAULT_FAST_TOOL_TIMEOUT_MS = 300_000;
7
+
8
+ export const DEFAULT_FAST_TOOL_TIMEOUT_TOOLS = new Set([
9
+ "read",
10
+ "grep",
11
+ "find",
12
+ "ls",
13
+ "edit",
14
+ "write",
15
+ "structured_output",
16
+ ]);
17
+
18
+ /** Tools whose normal job can be to wait for a person or another run. */
19
+ export const TOOL_TIMEOUT_EXEMPT_TOOLS = new Set(["contact_supervisor", "intercom", "subagent_wait"]);
20
+
21
+ // Backward-compatible export name for existing callers/tests.
22
+ export const TOOL_TIMEOUT_ALLOWLIST = TOOL_TIMEOUT_EXEMPT_TOOLS;
23
+
24
+ export function isToolTimeoutExempt(toolName: string | undefined): boolean {
25
+ return toolName !== undefined && TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName);
26
+ }
27
+
28
+ export function defaultToolTimeoutMs(toolName: string | undefined): number | undefined {
29
+ return toolName !== undefined && DEFAULT_FAST_TOOL_TIMEOUT_TOOLS.has(toolName)
30
+ ? DEFAULT_FAST_TOOL_TIMEOUT_MS
31
+ : undefined;
32
+ }
33
+
34
+ export function effectiveToolTimeoutMs(toolName: string | undefined, configuredToolTimeoutMs: number | undefined): number | undefined {
35
+ if (isToolTimeoutExempt(toolName)) return undefined;
36
+ return configuredToolTimeoutMs ?? defaultToolTimeoutMs(toolName);
37
+ }
38
+
39
+ export function formatToolTimeoutMessage(toolName: string, timeoutMs: number): string {
40
+ return `Tool '${toolName}' exceeded its timeout of ${timeoutMs}ms.`;
41
+ }
42
+
43
+ export function toolTimeoutCallKey(event: { toolCallId?: unknown; toolName?: unknown }, fallbackId: number): string {
44
+ return typeof event.toolCallId === "string" && event.toolCallId.length > 0
45
+ ? `id:${event.toolCallId}`
46
+ : `anon:${String(event.toolName ?? "tool")}:${fallbackId}`;
47
+ }
48
+
49
+ export interface ToolTimeoutResolutionInput {
50
+ /** Per-call value from the subagent tool params (highest precedence). */
51
+ callValue?: unknown;
52
+ /** Agent frontmatter default (second precedence). */
53
+ agentValue?: number;
54
+ /** Global extension config.toolTimeoutMs (third precedence). */
55
+ configValue?: unknown;
56
+ /** PI_SUBAGENT_TOOL_TIMEOUT_MS environment override (lowest precedence). */
57
+ envValue?: string | undefined;
58
+ }
59
+
60
+ /** Resolve the configured hard timeout. Default fast-tool timeouts apply later per tool name. */
61
+ export function resolveToolTimeoutMs(input: ToolTimeoutResolutionInput): { toolTimeoutMs?: number; error?: string } {
62
+ const candidates: Array<{ label: string; value: unknown }> = [
63
+ { label: "toolTimeoutMs", value: input.callValue },
64
+ { label: "agent.toolTimeoutMs", value: input.agentValue },
65
+ { label: "config.toolTimeoutMs", value: input.configValue },
66
+ ];
67
+ let winner: { label: string; value: unknown } | undefined;
68
+ for (const candidate of candidates) {
69
+ if (candidate.value === undefined) continue;
70
+ winner = candidate;
71
+ break;
72
+ }
73
+ if (winner === undefined && input.envValue !== undefined && input.envValue.trim() !== "") {
74
+ winner = { label: TOOL_TIMEOUT_ENV, value: input.envValue };
75
+ }
76
+ if (winner === undefined) return {};
77
+
78
+ let raw: unknown = winner.value;
79
+ let parsed: number;
80
+ if (winner.label === TOOL_TIMEOUT_ENV && typeof raw === "string") {
81
+ parsed = Number(raw);
82
+ if (raw.trim() !== "" && !Number.isNaN(parsed)) raw = parsed;
83
+ }
84
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > MAX_TIMER_DELAY_MS) {
85
+ return { error: `${winner.label} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.` };
86
+ }
87
+ return { toolTimeoutMs: raw };
88
+ }
89
+
90
+ /** Read the environment override without requiring callers to know the name. */
91
+ export function toolTimeoutFromEnv(env: NodeJS.ProcessEnv = process.env): string | undefined {
92
+ return env[TOOL_TIMEOUT_ENV];
93
+ }
@@ -4,6 +4,7 @@ import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { resolveAuthorityDecision, type AuthorityPolicyConfig } from "../../policy/authority.ts";
6
6
  import { PROJECT_SUBAGENTS_RELATIVE_DIR } from "../../shared/artifacts.ts";
7
+ import { getAgentDir } from "../../shared/utils.ts";
7
8
 
8
9
  export interface WorktreeSetup {
9
10
  cwd: string;
@@ -149,11 +150,17 @@ function resolveRepoState(cwd: string): RepoState {
149
150
 
150
151
  function normalizeComparableCwd(cwd: string): string {
151
152
  const resolved = path.resolve(cwd);
152
- try {
153
- return fs.realpathSync(resolved);
154
- } catch {
155
- // Use the unresolved absolute path when realpath resolution is unavailable.
156
- return resolved;
153
+ let existing = resolved;
154
+ const missingSegments: string[] = [];
155
+ while (true) {
156
+ try {
157
+ return path.join(fs.realpathSync(existing), ...missingSegments.reverse());
158
+ } catch {
159
+ const parent = path.dirname(existing);
160
+ if (parent === existing) return resolved;
161
+ missingSegments.push(path.basename(existing));
162
+ existing = parent;
163
+ }
157
164
  }
158
165
  }
159
166
 
@@ -196,6 +203,11 @@ function resolveWorktreeBaseDir(configuredBaseDir: string | undefined, repoRoot:
196
203
 
197
204
  const expanded = trimmed.startsWith("~/") ? path.join(os.homedir(), trimmed.slice(2)) : trimmed;
198
205
  const resolved = path.isAbsolute(expanded) ? expanded : path.resolve(repoRoot, expanded);
206
+ const extensionsDir = normalizeComparableCwd(path.join(getAgentDir(), "extensions"));
207
+ const relativeToExtensions = path.relative(extensionsDir, normalizeComparableCwd(resolved));
208
+ if (!relativeToExtensions || (!relativeToExtensions.startsWith(`..${path.sep}`) && relativeToExtensions !== ".." && !path.isAbsolute(relativeToExtensions))) {
209
+ throw new Error(`worktree base directory cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
210
+ }
199
211
  try {
200
212
  fs.mkdirSync(resolved, { recursive: true });
201
213
  } catch (error) {
@@ -0,0 +1,5 @@
1
+ import type { StreamFn } from "@earendil-works/pi-agent-core";
2
+
3
+ export function agentStreamOptions(streamFn: StreamFn): { streamFunction: StreamFn; streamFn: StreamFn } {
4
+ return { streamFunction: streamFn, streamFn };
5
+ }
@@ -65,10 +65,6 @@ function patternMatchesArtifactPath(pattern: string, artifactPath: string): bool
65
65
  || globMatchesPath(normalized, artifactPath);
66
66
  }
67
67
 
68
- function patternMatchesProjectArtifacts(pattern: string): boolean {
69
- return PROJECT_ARTIFACT_PATHS.some((artifactPath) => patternMatchesArtifactPath(pattern, artifactPath));
70
- }
71
-
72
68
  function ignoreFileExcludesProjectArtifacts(filePath: string): boolean {
73
69
  if (!fs.existsSync(filePath)) return false;
74
70
  try {
@@ -144,7 +140,7 @@ export function getProjectChainRunsDir(cwd: string): string {
144
140
 
145
141
  export function getChainRunsDir(
146
142
  projectCwd: string,
147
- dirPreference: ArtifactDirPreference = "project",
143
+ dirPreference: ArtifactDirPreference = "session",
148
144
  ): string {
149
145
  switch (dirPreference) {
150
146
  case "project":
@@ -160,7 +156,7 @@ export function getChainRunsDir(
160
156
  export function getArtifactsDir(
161
157
  sessionFile: string | null,
162
158
  projectCwd?: string,
163
- dirPreference: ArtifactDirPreference = "project",
159
+ dirPreference: ArtifactDirPreference = "session",
164
160
  ): string {
165
161
  switch (dirPreference) {
166
162
  case "session":