pi-subagents 0.31.1 → 0.33.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 (60) hide show
  1. package/CHANGELOG.md +67 -4
  2. package/README.md +219 -40
  3. package/install.mjs +2 -1
  4. package/package.json +3 -2
  5. package/skills/pi-subagents/SKILL.md +71 -10
  6. package/src/agents/agent-management.ts +179 -2
  7. package/src/agents/agent-memory.ts +254 -0
  8. package/src/agents/agent-serializer.ts +11 -0
  9. package/src/agents/agents.ts +193 -19
  10. package/src/agents/chain-serializer.ts +27 -2
  11. package/src/extension/config.ts +27 -4
  12. package/src/extension/doctor.ts +1 -7
  13. package/src/extension/fanout-child.ts +3 -2
  14. package/src/extension/index.ts +70 -41
  15. package/src/extension/rpc.ts +369 -0
  16. package/src/extension/schemas.ts +54 -10
  17. package/src/extension/tool-description.ts +200 -0
  18. package/src/intercom/intercom-bridge.ts +21 -253
  19. package/src/intercom/native-supervisor-channel.ts +510 -0
  20. package/src/runs/background/async-execution.ts +187 -38
  21. package/src/runs/background/async-job-tracker.ts +88 -2
  22. package/src/runs/background/async-status.ts +67 -10
  23. package/src/runs/background/chain-root-attachment.ts +34 -4
  24. package/src/runs/background/completion-batcher.ts +166 -0
  25. package/src/runs/background/control-channel.ts +156 -1
  26. package/src/runs/background/fleet-view.ts +515 -0
  27. package/src/runs/background/notify.ts +161 -44
  28. package/src/runs/background/result-watcher.ts +1 -2
  29. package/src/runs/background/run-id-resolver.ts +3 -2
  30. package/src/runs/background/run-status.ts +167 -6
  31. package/src/runs/background/scheduled-runs.ts +514 -0
  32. package/src/runs/background/stale-run-reconciler.ts +28 -1
  33. package/src/runs/background/subagent-runner.ts +840 -127
  34. package/src/runs/background/wait.ts +353 -0
  35. package/src/runs/foreground/chain-execution.ts +123 -27
  36. package/src/runs/foreground/execution.ts +174 -27
  37. package/src/runs/foreground/subagent-executor.ts +569 -81
  38. package/src/runs/shared/acceptance.ts +45 -22
  39. package/src/runs/shared/dynamic-fanout.ts +2 -2
  40. package/src/runs/shared/model-fallback.ts +171 -20
  41. package/src/runs/shared/model-scope.ts +128 -0
  42. package/src/runs/shared/nested-events.ts +89 -0
  43. package/src/runs/shared/parallel-utils.ts +50 -1
  44. package/src/runs/shared/pi-args.ts +35 -4
  45. package/src/runs/shared/pi-spawn.ts +52 -20
  46. package/src/runs/shared/single-output.ts +2 -0
  47. package/src/runs/shared/subagent-prompt-runtime.ts +110 -4
  48. package/src/runs/shared/tool-budget.ts +74 -0
  49. package/src/runs/shared/turn-budget.ts +52 -0
  50. package/src/runs/shared/worktree.ts +28 -5
  51. package/src/shared/artifacts.ts +16 -1
  52. package/src/shared/atomic-json.ts +15 -2
  53. package/src/shared/child-transcript.ts +212 -0
  54. package/src/shared/fork-context.ts +133 -22
  55. package/src/shared/settings.ts +3 -1
  56. package/src/shared/types.ts +197 -4
  57. package/src/shared/utils.ts +99 -14
  58. package/src/slash/prompt-workflows.ts +330 -0
  59. package/src/slash/slash-commands.ts +133 -2
  60. package/src/tui/render.ts +32 -12
@@ -38,6 +38,7 @@ export interface RunnerSubagentStep {
38
38
  };
39
39
  structuredOutputSchema?: import("../../shared/types.ts").JsonSchemaObject;
40
40
  effectiveAcceptance?: import("../../shared/types.ts").ResolvedAcceptanceConfig;
41
+ toolBudget?: import("../../shared/types.ts").ResolvedToolBudget;
41
42
  }
42
43
 
43
44
  export interface ParallelStepGroup {
@@ -55,6 +56,8 @@ export interface DynamicRunnerGroup {
55
56
  failFast?: boolean;
56
57
  phase?: string;
57
58
  label?: string;
59
+ sessionFiles?: (string | undefined)[];
60
+ thinkingOverrides?: (string | undefined)[];
58
61
  effectiveAcceptance?: import("../../shared/types.ts").ResolvedAcceptanceConfig;
59
62
  }
60
63
 
@@ -82,10 +85,47 @@ export function flattenSteps(steps: RunnerStep[]): RunnerSubagentStep[] {
82
85
  return flat;
83
86
  }
84
87
 
88
+ export const DEFAULT_GLOBAL_CONCURRENCY_LIMIT = 20;
89
+
90
+ /**
91
+ * A promise-based semaphore for limiting concurrent access across multiple
92
+ * mapConcurrent calls within a single run. Enforces a global cap on the total
93
+ * number of subagent tasks executing simultaneously, regardless of each step's
94
+ * per-step concurrency limit.
95
+ */
96
+ export class Semaphore {
97
+ private available: number;
98
+ private readonly queue: Array<() => void> = [];
99
+
100
+ constructor(limit: number) {
101
+ this.available = Math.max(1, Math.floor(limit) || 1);
102
+ }
103
+
104
+ acquire(): Promise<void> {
105
+ if (this.available > 0) {
106
+ this.available--;
107
+ return Promise.resolve();
108
+ }
109
+ return new Promise<void>((resolve) => {
110
+ this.queue.push(resolve);
111
+ });
112
+ }
113
+
114
+ release(): void {
115
+ const next = this.queue.shift();
116
+ if (next) {
117
+ next();
118
+ } else {
119
+ this.available++;
120
+ }
121
+ }
122
+ }
123
+
85
124
  export async function mapConcurrent<T, R>(
86
125
  items: T[],
87
126
  limit: number,
88
127
  fn: (item: T, i: number) => Promise<R>,
128
+ globalSemaphore?: Semaphore,
89
129
  ): Promise<R[]> {
90
130
  const safeLimit = Math.max(1, Math.floor(limit) || 1);
91
131
  const results: R[] = new Array(items.length);
@@ -94,7 +134,16 @@ export async function mapConcurrent<T, R>(
94
134
  async function worker(_workerIndex: number): Promise<void> {
95
135
  while (next < items.length) {
96
136
  const i = next++;
97
- results[i] = await fn(items[i], i);
137
+ if (globalSemaphore) {
138
+ await globalSemaphore.acquire();
139
+ try {
140
+ results[i] = await fn(items[i], i);
141
+ } finally {
142
+ globalSemaphore.release();
143
+ }
144
+ } else {
145
+ results[i] = await fn(items[i], i);
146
+ }
98
147
  }
99
148
  }
100
149
 
@@ -5,7 +5,8 @@ import { fileURLToPath } from "node:url";
5
5
  import { encodeNestedPathEnv, parseNestedPathEnv, type NestedPathEntry } from "./nested-path.ts";
6
6
  import { resolveMcpDirectToolNames } from "./mcp-direct-tool-allowlist.ts";
7
7
  import { STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV } from "./structured-output.ts";
8
- import type { JsonSchemaObject } from "../../shared/types.ts";
8
+ import { TEMP_ROOT_DIR, type JsonSchemaObject, type ResolvedToolBudget } from "../../shared/types.ts";
9
+ import { TOOL_BUDGET_ENV, encodeToolBudgetEnv } from "./tool-budget.ts";
9
10
 
10
11
  const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh"];
11
12
  const TASK_ARG_LIMIT = 8000;
@@ -13,6 +14,8 @@ const PROMPT_RUNTIME_EXTENSION_PATH = path.join(path.dirname(fileURLToPath(impor
13
14
  const FANOUT_CHILD_EXTENSION_PATH = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "extension", "fanout-child.ts");
14
15
  export const SUBAGENT_CHILD_ENV = "PI_SUBAGENT_CHILD";
15
16
  export const SUBAGENT_ORCHESTRATOR_TARGET_ENV = "PI_SUBAGENT_ORCHESTRATOR_TARGET";
17
+ export const SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV = "PI_SUBAGENT_ORCHESTRATOR_SESSION_ID";
18
+ export const SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV = "PI_SUBAGENT_SUPERVISOR_CHANNEL_DIR";
16
19
  export const SUBAGENT_RUN_ID_ENV = "PI_SUBAGENT_RUN_ID";
17
20
  export const SUBAGENT_CHILD_AGENT_ENV = "PI_SUBAGENT_CHILD_AGENT";
18
21
  export const SUBAGENT_CHILD_INDEX_ENV = "PI_SUBAGENT_CHILD_INDEX";
@@ -26,6 +29,7 @@ export const SUBAGENT_PARENT_DEPTH_ENV = "PI_SUBAGENT_PARENT_DEPTH";
26
29
  export const SUBAGENT_PARENT_PATH_ENV = "PI_SUBAGENT_PARENT_PATH";
27
30
  export const SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV = "PI_SUBAGENT_PARENT_CAPABILITY_TOKEN";
28
31
  export const SUBAGENT_PARENT_SESSION_ENV = "PI_SUBAGENT_PARENT_SESSION";
32
+ export const SUBAGENT_STEER_INBOX_ENV = "PI_SUBAGENT_STEER_INBOX";
29
33
 
30
34
  interface BuildPiArgsInput {
31
35
  parentSessionId?: string;
@@ -60,11 +64,13 @@ interface BuildPiArgsInput {
60
64
  parentDepth?: number;
61
65
  parentPath?: NestedPathEntry[];
62
66
  parentCapabilityToken?: string;
67
+ steerInboxDir?: string;
63
68
  structuredOutput?: {
64
69
  schema: JsonSchemaObject;
65
70
  schemaPath: string;
66
71
  outputPath: string;
67
72
  };
73
+ toolBudget?: ResolvedToolBudget;
68
74
  }
69
75
 
70
76
  interface BuildPiArgsResult {
@@ -73,10 +79,20 @@ interface BuildPiArgsResult {
73
79
  tempDir?: string;
74
80
  }
75
81
 
76
- export function applyThinkingSuffix(model: string | undefined, thinking: string | undefined): string | undefined {
77
- if (!model || !thinking || thinking === "off") return model;
82
+ function sanitizeSupervisorChannelSegment(value: string): string {
83
+ return value.trim().replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "unknown";
84
+ }
85
+
86
+ function supervisorChannelDir(runId: string, agent: string, childIndex: number): string {
87
+ return path.join(TEMP_ROOT_DIR, "supervisor-channels", `${sanitizeSupervisorChannelSegment(runId)}-${sanitizeSupervisorChannelSegment(agent)}-${childIndex}`);
88
+ }
89
+
90
+ export function applyThinkingSuffix(model: string | undefined, thinking: string | undefined, replaceExisting = false): string | undefined {
91
+ if (!model || !thinking) return model;
78
92
  const colonIdx = model.lastIndexOf(":");
79
- if (colonIdx !== -1 && THINKING_LEVELS.includes(model.substring(colonIdx + 1))) return model;
93
+ if (colonIdx !== -1 && THINKING_LEVELS.includes(model.substring(colonIdx + 1))) {
94
+ return replaceExisting ? `${model.slice(0, colonIdx)}:${thinking}` : model;
95
+ }
80
96
  return `${model}:${thinking}`;
81
97
  }
82
98
 
@@ -204,6 +220,16 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
204
220
  if (input.orchestratorIntercomTarget) {
205
221
  env[SUBAGENT_ORCHESTRATOR_TARGET_ENV] = input.orchestratorIntercomTarget;
206
222
  }
223
+ if (input.parentSessionId) {
224
+ env[SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV] = input.parentSessionId;
225
+ }
226
+ if (input.orchestratorIntercomTarget && input.parentSessionId && input.runId && input.childAgentName) {
227
+ const childIndex = input.childIndex ?? 0;
228
+ const channelDir = supervisorChannelDir(input.runId, input.childAgentName, childIndex);
229
+ fs.mkdirSync(path.join(channelDir, "requests"), { recursive: true });
230
+ fs.mkdirSync(path.join(channelDir, "replies"), { recursive: true });
231
+ env[SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV] = channelDir;
232
+ }
207
233
  if (input.runId) {
208
234
  env[SUBAGENT_RUN_ID_ENV] = input.runId;
209
235
  }
@@ -222,6 +248,11 @@ export function buildPiArgs(input: BuildPiArgsInput): BuildPiArgsResult {
222
248
  env[STRUCTURED_OUTPUT_CAPTURE_ENV] = input.structuredOutput.outputPath;
223
249
  env[STRUCTURED_OUTPUT_SCHEMA_ENV] = input.structuredOutput.schemaPath;
224
250
  }
251
+ if (input.steerInboxDir) {
252
+ env[SUBAGENT_STEER_INBOX_ENV] = input.steerInboxDir;
253
+ }
254
+ const encodedToolBudget = encodeToolBudgetEnv(input.toolBudget);
255
+ if (encodedToolBudget) env[TOOL_BUDGET_ENV] = encodedToolBudget;
225
256
 
226
257
  env[SUBAGENT_PARENT_SESSION_ENV] = input.parentSessionId ?? process.env[SUBAGENT_PARENT_SESSION_ENV] ?? "";
227
258
 
@@ -3,13 +3,18 @@ import * as path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
 
5
5
  export const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
6
+ export const PI_SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
6
7
 
7
- export function findPiPackageRootFromEntry(entryPoint: string): string | undefined {
8
+ export function findPiPackageRootFromEntry(
9
+ entryPoint: string,
10
+ ): string | undefined {
8
11
  let dir = path.dirname(entryPoint);
9
12
  while (dir !== path.dirname(dir)) {
10
13
  const packageJsonPath = path.join(dir, "package.json");
11
14
  if (fs.existsSync(packageJsonPath)) {
12
- const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as { name?: unknown };
15
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as {
16
+ name?: unknown;
17
+ };
13
18
  if (pkg.name === PI_CODING_AGENT_PACKAGE) return dir;
14
19
  }
15
20
  dir = path.dirname(dir);
@@ -18,13 +23,17 @@ export function findPiPackageRootFromEntry(entryPoint: string): string | undefin
18
23
  }
19
24
 
20
25
  export function resolveInstalledPiPackageRoot(): string | undefined {
21
- return findPiPackageRootFromEntry(fileURLToPath(import.meta.resolve(PI_CODING_AGENT_PACKAGE)));
26
+ return findPiPackageRootFromEntry(
27
+ fileURLToPath(import.meta.resolve(PI_CODING_AGENT_PACKAGE)),
28
+ );
22
29
  }
23
30
 
24
31
  export function resolvePiPackageRoot(): string | undefined {
25
32
  try {
26
33
  const entry = process.argv[1];
27
- return entry ? findPiPackageRootFromEntry(fs.realpathSync(entry)) : undefined;
34
+ return entry
35
+ ? findPiPackageRootFromEntry(fs.realpathSync(entry))
36
+ : undefined;
28
37
  } catch {
29
38
  // process.argv[1] probing is best-effort; callers can fall back to PATH/package resolution.
30
39
  return undefined;
@@ -40,6 +49,7 @@ export interface PiSpawnDeps {
40
49
  resolvePackageJson?: () => string;
41
50
  resolvePackageEntry?: () => string;
42
51
  piPackageRoot?: string;
52
+ env?: NodeJS.ProcessEnv;
43
53
  }
44
54
 
45
55
  interface PiSpawnCommand {
@@ -47,7 +57,10 @@ interface PiSpawnCommand {
47
57
  args: string[];
48
58
  }
49
59
 
50
- function isRunnableNodeScript(filePath: string, existsSync: (filePath: string) => boolean): boolean {
60
+ function isRunnableNodeScript(
61
+ filePath: string,
62
+ existsSync: (filePath: string) => boolean,
63
+ ): boolean {
51
64
  if (!existsSync(filePath)) return false;
52
65
  return /\.(?:mjs|cjs|js)$/i.test(filePath);
53
66
  }
@@ -56,9 +69,13 @@ function normalizePath(filePath: string): string {
56
69
  return path.isAbsolute(filePath) ? filePath : path.resolve(filePath);
57
70
  }
58
71
 
59
- export function resolveWindowsPiCliScript(deps: PiSpawnDeps = {}): string | undefined {
72
+ export function resolveWindowsPiCliScript(
73
+ deps: PiSpawnDeps = {},
74
+ ): string | undefined {
60
75
  const existsSync = deps.existsSync ?? fs.existsSync;
61
- const readFileSync = deps.readFileSync ?? ((filePath, encoding) => fs.readFileSync(filePath, encoding));
76
+ const readFileSync =
77
+ deps.readFileSync ??
78
+ ((filePath, encoding) => fs.readFileSync(filePath, encoding));
62
79
  const argv1 = deps.argv1 ?? process.argv[1];
63
80
 
64
81
  if (argv1) {
@@ -69,23 +86,29 @@ export function resolveWindowsPiCliScript(deps: PiSpawnDeps = {}): string | unde
69
86
  }
70
87
 
71
88
  try {
72
- const resolvePackageJson = deps.resolvePackageJson ?? (() => {
73
- const root = deps.piPackageRoot ?? resolvePiPackageRoot();
74
- if (root) return path.join(root, "package.json");
75
- const packageRoot = deps.resolvePackageEntry
76
- ? findPiPackageRootFromEntry(deps.resolvePackageEntry())
77
- : resolveInstalledPiPackageRoot();
78
- if (!packageRoot) throw new Error(`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`);
79
- return path.join(packageRoot, "package.json");
80
- });
89
+ const resolvePackageJson =
90
+ deps.resolvePackageJson ??
91
+ (() => {
92
+ const root = deps.piPackageRoot ?? resolvePiPackageRoot();
93
+ if (root) return path.join(root, "package.json");
94
+ const packageRoot = deps.resolvePackageEntry
95
+ ? findPiPackageRootFromEntry(deps.resolvePackageEntry())
96
+ : resolveInstalledPiPackageRoot();
97
+ if (!packageRoot)
98
+ throw new Error(
99
+ `Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`,
100
+ );
101
+ return path.join(packageRoot, "package.json");
102
+ });
81
103
  const packageJsonPath = resolvePackageJson();
82
104
  const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as {
83
105
  bin?: string | Record<string, string>;
84
106
  };
85
107
  const binField = packageJson.bin;
86
- const binPath = typeof binField === "string"
87
- ? binField
88
- : binField?.pi ?? Object.values(binField ?? {})[0];
108
+ const binPath =
109
+ typeof binField === "string"
110
+ ? binField
111
+ : (binField?.pi ?? Object.values(binField ?? {})[0]);
89
112
  if (!binPath) return undefined;
90
113
  const candidate = path.resolve(path.dirname(packageJsonPath), binPath);
91
114
  if (isRunnableNodeScript(candidate, existsSync)) {
@@ -99,7 +122,16 @@ export function resolveWindowsPiCliScript(deps: PiSpawnDeps = {}): string | unde
99
122
  return undefined;
100
123
  }
101
124
 
102
- export function getPiSpawnCommand(args: string[], deps: PiSpawnDeps = {}): PiSpawnCommand {
125
+ export function getPiSpawnCommand(
126
+ args: string[],
127
+ deps: PiSpawnDeps = {},
128
+ ): PiSpawnCommand {
129
+ const env = deps.env ?? process.env;
130
+ const piBinary = env[PI_SUBAGENT_PI_BINARY_ENV]?.trim();
131
+ if (piBinary) {
132
+ return { command: piBinary, args };
133
+ }
134
+
103
135
  const platform = deps.platform ?? process.platform;
104
136
  if (platform === "win32") {
105
137
  const piCliPath = resolveWindowsPiCliScript(deps);
@@ -22,9 +22,11 @@ export function resolveSingleOutputPath(
22
22
  output: string | boolean | undefined,
23
23
  runtimeCwd: string,
24
24
  requestedCwd?: string,
25
+ relativeBaseDir?: string,
25
26
  ): string | undefined {
26
27
  if (typeof output !== "string" || !output || output === "false" || output === "true") return undefined;
27
28
  if (path.isAbsolute(output)) return output;
29
+ if (relativeBaseDir) return path.resolve(relativeBaseDir, output);
28
30
  const baseCwd = requestedCwd
29
31
  ? (path.isAbsolute(requestedCwd) ? requestedCwd : path.resolve(runtimeCwd, requestedCwd))
30
32
  : runtimeCwd;
@@ -1,9 +1,12 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
- import { SUBAGENT_FANOUT_CHILD_ENV } from "./pi-args.ts";
4
+ import { registerNativeSupervisorClient } from "../../intercom/native-supervisor-channel.ts";
5
+ import { consumeSteerRequestsFromDir, writeSteerRequestToDir, type SteerRequest } from "../background/control-channel.ts";
6
+ import { SUBAGENT_FANOUT_CHILD_ENV, SUBAGENT_STEER_INBOX_ENV } from "./pi-args.ts";
5
7
  import { STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV, validateStructuredOutputValue } from "./structured-output.ts";
6
- import type { JsonSchemaObject } from "../../shared/types.ts";
8
+ import { TOOL_BUDGET_ENV, decodeToolBudgetEnv, shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.ts";
9
+ import type { JsonSchemaObject, ResolvedToolBudget } from "../../shared/types.ts";
7
10
 
8
11
  const SUBAGENT_INHERIT_PROJECT_CONTEXT_ENV = "PI_SUBAGENT_INHERIT_PROJECT_CONTEXT";
9
12
  const SUBAGENT_INHERIT_SKILLS_ENV = "PI_SUBAGENT_INHERIT_SKILLS";
@@ -20,7 +23,7 @@ export const CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS = [
20
23
  "The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.",
21
24
  "Ignore prior parent-only orchestration instructions in inherited conversation history.",
22
25
  "Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.",
23
- "If you need to edit files, call the actual edit/write tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.",
26
+ "If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.",
24
27
  ].join("\n");
25
28
 
26
29
  export const CHILD_FANOUT_BOUNDARY_INSTRUCTIONS = [
@@ -29,7 +32,7 @@ export const CHILD_FANOUT_BOUNDARY_INSTRUCTIONS = [
29
32
  "You may use the `subagent` tool only for the fanout work explicitly requested in this task.",
30
33
  "Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.",
31
34
  "The maxSubagentDepth cap still applies and may block further fanout.",
32
- "If you need to edit files, call the actual edit/write tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.",
35
+ "If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.",
33
36
  ].join("\n");
34
37
 
35
38
  const PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([
@@ -155,7 +158,110 @@ export function stripParentOnlySubagentMessages(messages: unknown[]): unknown[]
155
158
  return changed ? filtered : messages;
156
159
  }
157
160
 
161
+ export function formatSteerMessage(request: SteerRequest): string {
162
+ return [
163
+ "Mid-run steering from the parent orchestrator:",
164
+ "",
165
+ request.message,
166
+ "",
167
+ "Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.",
168
+ ].join("\n");
169
+ }
170
+
171
+ function registerToolBudget(pi: ExtensionAPI, budget: ResolvedToolBudget | undefined): void {
172
+ if (!budget) return;
173
+ let toolCount = 0;
174
+ let softNudged = false;
175
+ const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: "steer" }) => unknown }).sendUserMessage;
176
+ const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: { toolName?: string }) => unknown) => void;
177
+ onRuntimeEvent("tool_call", (event) => {
178
+ const toolName = typeof event.toolName === "string" ? event.toolName : "tool";
179
+ toolCount++;
180
+ if (budget.soft !== undefined && toolCount >= budget.soft && !softNudged) {
181
+ softNudged = true;
182
+ try {
183
+ sendUserMessage?.(toolBudgetSoftNudge(budget, toolCount), { deliverAs: "steer" });
184
+ } catch {
185
+ // Budget nudges are advisory; blocking below remains authoritative.
186
+ }
187
+ }
188
+ if (!shouldBlockToolForBudget(budget, toolName, toolCount)) return undefined;
189
+ return { block: true, reason: toolBudgetBlockedMessage(budget, toolName, toolCount) };
190
+ });
191
+ }
192
+
193
+ function registerSteeringInbox(pi: ExtensionAPI): void {
194
+ const steerInbox = process.env[SUBAGENT_STEER_INBOX_ENV]?.trim();
195
+ if (!steerInbox) return;
196
+ const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: "steer" }) => unknown }).sendUserMessage;
197
+ if (typeof sendUserMessage !== "function") return;
198
+
199
+ let canSteer = false;
200
+ let disposed = false;
201
+ let flushing = false;
202
+ let started = false;
203
+ let watcher: fs.FSWatcher | undefined;
204
+ let interval: NodeJS.Timeout | undefined;
205
+ const flush = (): void => {
206
+ if (disposed || flushing || !canSteer) return;
207
+ flushing = true;
208
+ try {
209
+ const requests = consumeSteerRequestsFromDir(steerInbox);
210
+ for (let index = 0; index < requests.length; index++) {
211
+ const request = requests[index]!;
212
+ try {
213
+ sendUserMessage(formatSteerMessage(request), { deliverAs: "steer" });
214
+ } catch {
215
+ for (const pending of requests.slice(index)) writeSteerRequestToDir(steerInbox, pending);
216
+ break;
217
+ }
218
+ }
219
+ } finally {
220
+ flushing = false;
221
+ }
222
+ };
223
+ const start = (): void => {
224
+ if (started || disposed) return;
225
+ try {
226
+ fs.mkdirSync(steerInbox, { recursive: true });
227
+ } catch {
228
+ return;
229
+ }
230
+ started = true;
231
+ try {
232
+ watcher = fs.watch(steerInbox, () => flush());
233
+ watcher.on("error", () => {});
234
+ } catch {
235
+ watcher = undefined;
236
+ }
237
+ interval = setInterval(flush, 250);
238
+ interval.unref?.();
239
+ };
240
+ const activate = (): undefined => {
241
+ start();
242
+ canSteer = true;
243
+ flush();
244
+ return undefined;
245
+ };
246
+
247
+ const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown) => unknown) => void;
248
+ onRuntimeEvent("session_start", () => start());
249
+ for (const eventName of ["message_start", "message_update", "message_end", "tool_execution_start", "tool_execution_end", "turn_end"] as const) {
250
+ onRuntimeEvent(eventName, activate);
251
+ }
252
+ onRuntimeEvent("session_shutdown", () => {
253
+ disposed = true;
254
+ try {
255
+ watcher?.close();
256
+ } catch {}
257
+ if (interval) clearInterval(interval);
258
+ });
259
+ }
260
+
158
261
  export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
262
+ registerSteeringInbox(pi);
263
+ registerToolBudget(pi, decodeToolBudgetEnv(process.env[TOOL_BUDGET_ENV]));
264
+ registerNativeSupervisorClient(pi);
159
265
  const structuredOutputPath = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV];
160
266
  const structuredSchemaPath = process.env[STRUCTURED_OUTPUT_SCHEMA_ENV];
161
267
  if (structuredOutputPath && structuredSchemaPath) {
@@ -0,0 +1,74 @@
1
+ import type { ResolvedToolBudget, ToolBudgetConfig, ToolBudgetState } from "../../shared/types.ts";
2
+
3
+ export const DEFAULT_TOOL_BUDGET_BLOCK = ["read", "grep", "find", "ls"] as const;
4
+ export const TOOL_BUDGET_ENV = "PI_SUBAGENT_TOOL_BUDGET";
5
+
6
+ export function normalizeToolBudgetBlock(block: ToolBudgetConfig["block"] | undefined): "*" | string[] {
7
+ if (block === "*") return "*";
8
+ if (block === undefined) return [...DEFAULT_TOOL_BUDGET_BLOCK];
9
+ return [...new Set(block.map((tool) => tool.trim()).filter(Boolean))];
10
+ }
11
+
12
+ export function validateToolBudgetConfig(raw: unknown, label = "toolBudget"): { budget?: ResolvedToolBudget; error?: string } {
13
+ if (raw === undefined) return {};
14
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { error: `${label} must be an object with hard and optional soft/block.` };
15
+ const value = raw as ToolBudgetConfig;
16
+ if (typeof value.hard !== "number" || !Number.isInteger(value.hard) || value.hard < 1) {
17
+ return { error: `${label}.hard must be an integer >= 1.` };
18
+ }
19
+ if (value.soft !== undefined && (typeof value.soft !== "number" || !Number.isInteger(value.soft) || value.soft < 1)) {
20
+ return { error: `${label}.soft must be an integer >= 1 when provided.` };
21
+ }
22
+ if (value.soft !== undefined && value.soft > value.hard) {
23
+ return { error: `${label}.soft must be <= ${label}.hard.` };
24
+ }
25
+ if (value.block !== undefined && value.block !== "*") {
26
+ if (!Array.isArray(value.block)) return { error: `${label}.block must be "*" or an array of tool names.` };
27
+ if (value.block.length === 0) return { error: `${label}.block must contain at least one tool name.` };
28
+ for (const item of value.block) {
29
+ if (typeof item !== "string" || !item.trim()) return { error: `${label}.block must contain non-empty tool names.` };
30
+ }
31
+ }
32
+ return { budget: { hard: value.hard, ...(value.soft !== undefined ? { soft: value.soft } : {}), block: normalizeToolBudgetBlock(value.block) } };
33
+ }
34
+
35
+ export function initialToolBudgetState(budget: ResolvedToolBudget): ToolBudgetState {
36
+ return { ...budget, toolCount: 0, outcome: "within-budget" };
37
+ }
38
+
39
+ export function toolBudgetState(budget: ResolvedToolBudget, toolCount: number, blockedTool?: string): ToolBudgetState {
40
+ const overHard = toolCount > budget.hard;
41
+ const overSoft = budget.soft !== undefined && toolCount >= budget.soft;
42
+ return {
43
+ ...budget,
44
+ toolCount,
45
+ outcome: overHard ? "hard-blocked" : overSoft ? "soft-reached" : "within-budget",
46
+ ...(overSoft ? { softReachedAt: budget.soft } : {}),
47
+ ...(overHard ? { hardReachedAt: budget.hard, blockedTool } : {}),
48
+ };
49
+ }
50
+
51
+ export function shouldBlockToolForBudget(budget: ResolvedToolBudget, toolName: string, nextToolCount: number): boolean {
52
+ if (nextToolCount <= budget.hard) return false;
53
+ return budget.block === "*" || budget.block.includes(toolName);
54
+ }
55
+
56
+ export function toolBudgetSoftNudge(budget: ResolvedToolBudget, toolCount: number): string {
57
+ return `Tool budget soft limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (soft ${budget.soft}, hard ${budget.hard}). Stop starting new browsing/search work and finalize from the context you already have.`;
58
+ }
59
+
60
+ export function toolBudgetBlockedMessage(budget: ResolvedToolBudget, toolName: string, toolCount: number): string {
61
+ return `Tool budget hard limit reached after ${toolCount} tool call${toolCount === 1 ? "" : "s"} (hard ${budget.hard}). The '${toolName}' tool is blocked so you can finalize from the context you already have.`;
62
+ }
63
+
64
+ export function encodeToolBudgetEnv(budget: ResolvedToolBudget | undefined): string | undefined {
65
+ return budget ? JSON.stringify(budget) : undefined;
66
+ }
67
+
68
+ export function decodeToolBudgetEnv(value: string | undefined): ResolvedToolBudget | undefined {
69
+ if (!value?.trim()) return undefined;
70
+ const parsed = JSON.parse(value) as unknown;
71
+ const normalized = validateToolBudgetConfig(parsed, TOOL_BUDGET_ENV);
72
+ if (normalized.error) throw new Error(normalized.error);
73
+ return normalized.budget;
74
+ }
@@ -0,0 +1,52 @@
1
+ import type { ResolvedTurnBudget, TurnBudgetState } from "../../shared/types.ts";
2
+
3
+ export const DEFAULT_TURN_BUDGET_GRACE_TURNS = 1;
4
+
5
+ export function appendTurnBudgetSystemPrompt(systemPrompt: string, budget: ResolvedTurnBudget | undefined): string {
6
+ if (!budget) return systemPrompt;
7
+ const grace = budget.graceTurns === 1 ? "1 additional assistant turn" : `${budget.graceTurns} additional assistant turns`;
8
+ const block = [
9
+ "## Turn budget",
10
+ `This child run has a soft budget of ${budget.maxTurns} assistant turn${budget.maxTurns === 1 ? "" : "s"}.`,
11
+ `After that, ${grace} may be allowed only for a final wrap-up.`,
12
+ "When you approach or reach the soft budget, stop starting new tool work and return the final answer immediately.",
13
+ "This runner uses process-mode execution, so live steering after launch may be unavailable; treat this instruction as the wrap-up request.",
14
+ "If you continue past the soft budget plus grace turns, the supervisor may abort the process and return only partial output.",
15
+ ].join("\n");
16
+ return systemPrompt.trim() ? `${systemPrompt.trim()}\n\n${block}` : block;
17
+ }
18
+
19
+ export function turnBudgetSoftNote(budget: ResolvedTurnBudget, turnCount: number): string {
20
+ return `Turn budget wrap-up was requested after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns}, grace ${budget.graceTurns}). Process-mode live steering is unavailable, so the child was warned at launch to wrap up by this budget. Output may be partial.`;
21
+ }
22
+
23
+ export function turnBudgetExceededMessage(budget: ResolvedTurnBudget, turnCount: number): string {
24
+ return `Subagent exceeded turn budget after ${turnCount} assistant turn${turnCount === 1 ? "" : "s"} (soft limit ${budget.maxTurns} + grace ${budget.graceTurns}).`;
25
+ }
26
+
27
+ export function formatTurnBudgetOutput(message: string, output: string): string {
28
+ return output.trim()
29
+ ? `${message}\n\nPartial output before turn-budget abort:\n${output}`
30
+ : message;
31
+ }
32
+
33
+ export function initialTurnBudgetState(budget: ResolvedTurnBudget): TurnBudgetState {
34
+ return { ...budget, outcome: "within-budget", turnCount: 0 };
35
+ }
36
+
37
+ export function turnBudgetState(budget: ResolvedTurnBudget, turnCount: number, exceeded: boolean): TurnBudgetState {
38
+ return {
39
+ ...budget,
40
+ turnCount,
41
+ outcome: exceeded ? "exceeded" : "wrap-up-requested",
42
+ wrapUpRequestedAtTurn: budget.maxTurns,
43
+ ...(exceeded ? { exceededAtTurn: turnCount } : {}),
44
+ };
45
+ }
46
+
47
+ export function shouldAbortForTurnBudget(budget: ResolvedTurnBudget, turnCount: number, terminalAssistantStop: boolean): boolean {
48
+ const hardLimit = budget.maxTurns + budget.graceTurns;
49
+ if (turnCount < hardLimit) return false;
50
+ if (turnCount > hardLimit) return true;
51
+ return !terminalAssistantStop;
52
+ }
@@ -43,6 +43,7 @@ interface WorktreeSetupHookConfig {
43
43
  interface CreateWorktreesOptions {
44
44
  agents?: string[];
45
45
  setupHook?: WorktreeSetupHookConfig;
46
+ baseDir?: string;
46
47
  }
47
48
 
48
49
  interface ResolvedWorktreeSetupHook {
@@ -152,8 +153,26 @@ function buildWorktreeBranch(runId: string, index: number): string {
152
153
  return `pi-parallel-${runId}-${index}`;
153
154
  }
154
155
 
155
- function buildWorktreePath(runId: string, index: number): string {
156
- return path.join(os.tmpdir(), `pi-worktree-${runId}-${index}`);
156
+ function resolveWorktreeBaseDir(configuredBaseDir: string | undefined, repoRoot: string): string {
157
+ const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
158
+ if (rawBaseDir === undefined) return os.tmpdir();
159
+
160
+ const trimmed = rawBaseDir.trim();
161
+ if (!trimmed) throw new Error("worktree base directory cannot be empty");
162
+
163
+ const expanded = trimmed.startsWith("~/") ? path.join(os.homedir(), trimmed.slice(2)) : trimmed;
164
+ const resolved = path.isAbsolute(expanded) ? expanded : path.resolve(repoRoot, expanded);
165
+ try {
166
+ fs.mkdirSync(resolved, { recursive: true });
167
+ } catch (error) {
168
+ const message = error instanceof Error ? error.message : String(error);
169
+ throw new Error(`failed to create worktree base directory ${resolved}: ${message}`);
170
+ }
171
+ return resolved;
172
+ }
173
+
174
+ function buildWorktreePath(baseDir: string, runId: string, index: number): string {
175
+ return path.join(baseDir, `pi-worktree-${runId}-${index}`);
157
176
  }
158
177
 
159
178
  function resolveRepoCwdRelative(cwd: string): string {
@@ -168,9 +187,10 @@ function resolveRepoCwdRelative(cwd: string): string {
168
187
  return normalizedPrefix === "." ? "" : normalizedPrefix;
169
188
  }
170
189
 
171
- export function resolveExpectedWorktreeAgentCwd(cwd: string, runId: string, index: number): string {
190
+ export function resolveExpectedWorktreeAgentCwd(cwd: string, runId: string, index: number, baseDir?: string): string {
172
191
  const cwdRelative = resolveRepoCwdRelative(cwd);
173
- const worktreePath = buildWorktreePath(runId, index);
192
+ const repoRoot = runGitChecked(cwd, ["rev-parse", "--show-toplevel"]).trim();
193
+ const worktreePath = buildWorktreePath(resolveWorktreeBaseDir(baseDir, repoRoot), runId, index);
174
194
  return cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath;
175
195
  }
176
196
 
@@ -320,9 +340,10 @@ function createSingleWorktree(
320
340
  baseCommit: string,
321
341
  setupHook: ResolvedWorktreeSetupHook | undefined,
322
342
  agent: string | undefined,
343
+ baseDir: string,
323
344
  ): WorktreeInfo {
324
345
  const branch = buildWorktreeBranch(runId, index);
325
- const worktreePath = buildWorktreePath(runId, index);
346
+ const worktreePath = buildWorktreePath(baseDir, runId, index);
326
347
  const add = runGit(toplevel, ["worktree", "add", worktreePath, "-b", branch, "HEAD"]);
327
348
  if (add.status !== 0) {
328
349
  const message = add.stderr.trim() || add.stdout.trim() || `failed to create worktree ${worktreePath}`;
@@ -492,6 +513,7 @@ function hasWorktreeChanges(diff: WorktreeDiff): boolean {
492
513
  export function createWorktrees(cwd: string, runId: string, count: number, options?: CreateWorktreesOptions): WorktreeSetup {
493
514
  const repo = resolveRepoState(cwd);
494
515
  const setupHook = resolveWorktreeSetupHook(repo.toplevel, options?.setupHook);
516
+ const baseDir = resolveWorktreeBaseDir(options?.baseDir, repo.toplevel);
495
517
  const worktrees: WorktreeInfo[] = [];
496
518
 
497
519
  try {
@@ -504,6 +526,7 @@ export function createWorktrees(cwd: string, runId: string, count: number, optio
504
526
  repo.baseCommit,
505
527
  setupHook,
506
528
  options?.agents?.[index],
529
+ baseDir,
507
530
  ));
508
531
  }
509
532
  } catch (error) {