@ferris1225/pi-subagents 4.3.30 → 4.3.32

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.
@@ -28,19 +28,19 @@ import {
28
28
  type SubagentLiveEvent,
29
29
  } from "./rpc-control.ts";
30
30
 
31
- export { asPlainTextRpcPrompt, terminateProcessTree };
32
-
33
- export const DEPTH_ENV_VAR = "PI_SUBAGENT_DEPTH";
34
- export const SUBAGENT_KILL_GRACE_MS = 5_000;
31
+ const DEPTH_ENV_VAR = "PI_SUBAGENT_DEPTH";
32
+ /** Every tool of an MCP server shares this prefix, whatever its exposure. */
33
+ const MCP_TOOL_PREFIX = "mcp__";
34
+ const SUBAGENT_KILL_GRACE_MS = 5_000;
35
35
  /** ACK budget after the child is known to be reading RPC. */
36
- export const RPC_COMMAND_TIMEOUT_MS = 30_000;
36
+ const RPC_COMMAND_TIMEOUT_MS = 30_000;
37
37
 
38
38
  /** clear_queue is stop-path hygiene ahead of the abort: give it its own short
39
39
  * budget so a hung response cannot eat into the abort-settle window. */
40
40
  const RPC_CLEAR_QUEUE_TIMEOUT_MS = 2_000;
41
41
  /** Time allowed for the child to boot and answer get_state. */
42
- export const RPC_READY_TIMEOUT_MS = 60_000;
43
- export const RPC_ABORT_SETTLE_TIMEOUT_MS = 5_000;
42
+ const RPC_READY_TIMEOUT_MS = 60_000;
43
+ const RPC_ABORT_SETTLE_TIMEOUT_MS = 5_000;
44
44
  /** Retained stderr tail. A chatty or crash-looping child must not grow parent
45
45
  * memory without bound, and the tail carries the decisive diagnostic. */
46
46
  export const RPC_STDERR_MAX_CHARS = 32_000;
@@ -88,7 +88,7 @@ export function sessionExists(sessionDir: string, sessionId: string): boolean {
88
88
  }
89
89
 
90
90
  /** Resolve how to invoke the same pi build as the current process. */
91
- export function getPiInvocation(args: string[]): { command: string; args: string[] } {
91
+ function getPiInvocation(args: string[]): { command: string; args: string[] } {
92
92
  const currentScript = process.argv[1];
93
93
  const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
94
94
  if (currentScript && !isBunVirtualScript && existsSync(currentScript)) {
@@ -100,7 +100,7 @@ export function getPiInvocation(args: string[]): { command: string; args: string
100
100
  return { command: "pi", args };
101
101
  }
102
102
 
103
- export function extractToolErrorText(content: unknown): string {
103
+ function extractToolErrorText(content: unknown): string {
104
104
  const parts = Array.isArray(content) ? content : [];
105
105
  const text = parts
106
106
  .filter(
@@ -161,7 +161,7 @@ export function renderChildRetryPolicySource(modelRef?: string): string {
161
161
  * stream adapter with its registered API implementation while forcing
162
162
  * maxRetries=0. It uses Pi's public extension and pi-ai compatibility APIs, so
163
163
  * it works in Node and standalone/Bun builds without touching user settings. */
164
- export async function writeChildRetryPolicyExtension(
164
+ async function writeChildRetryPolicyExtension(
165
165
  scratchRoot: string,
166
166
  modelRef?: string,
167
167
  ): Promise<ChildRetryPolicyExtension> {
@@ -181,7 +181,7 @@ export async function writeChildRetryPolicyExtension(
181
181
 
182
182
  /** Hand the agent body to the child as a file rather than inline argv text.
183
183
  * `--append-system-prompt` takes either, but a system prompt is unbounded — a
184
- * custom agent can carry a whole spec — while Windows caps a command line at
184
+ * role can carry a whole spec — while Windows caps a command line at
185
185
  * 32767 characters, so inlining turns a long agent into an opaque spawn failure.
186
186
  * The file lives in the run's scratch dir and is removed when the attempt ends. */
187
187
  async function writePromptToTempFile(
@@ -288,36 +288,76 @@ export interface RunRpcAttemptOptions {
288
288
  rpcCommandTimeoutMs?: number;
289
289
  }
290
290
 
291
- /** Run one persistent RPC child until a stable `agent_settled` or control action. */
292
- export async function runRpcAgentAttempt(options: RunRpcAttemptOptions): Promise<RpcSingleResult> {
293
- const { agent, agentName, task, thinkingLevel, idleTimeoutMs, signal, onLive, control } = options;
294
- const args: string[] = ["--mode", "rpc", "--exclude-tools", SUBAGENT_TOOL_NAMES.join(",")];
291
+ export interface ChildLaunchOptions {
292
+ agent: Pick<AgentConfig, "model" | "tools">;
293
+ thinkingLevel: ThinkingLevel;
294
+ sessionDir?: string;
295
+ sessionId?: string;
296
+ /** The session directory already holds the session being resumed. */
297
+ resumeExistingSession?: boolean;
298
+ /** Appended system prompt file, when the role carries one. */
299
+ promptPath?: string;
300
+ retryPolicyPath: string;
301
+ }
302
+
303
+ /** Command line for one child attempt.
304
+ *
305
+ * An explicit role list is a strict intersection of the parent's tools, but pi
306
+ * keeps MCP tools unless a `--tools` entry names one, so a list that names none
307
+ * has to exclude them by pattern. Scout depends on that: its read-only boundary
308
+ * must not leak an MCP writer. */
309
+ export function buildChildLaunchArgs(options: ChildLaunchOptions): string[] {
310
+ const { agent, thinkingLevel } = options;
311
+ const excludedTools: string[] = [...SUBAGENT_TOOL_NAMES];
312
+ const args: string[] = ["--mode", "rpc"];
295
313
  if (options.sessionDir && options.sessionId) {
296
314
  args.push("--session-dir", options.sessionDir);
297
- args.push(sessionExists(options.sessionDir, options.sessionId) ? "--session" : "--session-id", options.sessionId);
315
+ args.push(options.resumeExistingSession ? "--session" : "--session-id", options.sessionId);
298
316
  } else {
299
317
  args.push("--no-session");
300
318
  }
301
319
  if (agent.model) args.push("--model", agent.model);
302
320
  args.push("--thinking", thinkingLevel);
303
321
  if (agent.tools) {
304
- if (agent.tools.length > 0) args.push("--tools", agent.tools.join(","));
305
- else args.push("--no-tools");
322
+ if (agent.tools.length > 0) {
323
+ args.push("--tools", agent.tools.join(","));
324
+ if (!agent.tools.some((tool) => tool.startsWith(MCP_TOOL_PREFIX))) excludedTools.push(`${MCP_TOOL_PREFIX}*`);
325
+ } else {
326
+ args.push("--no-tools");
327
+ }
306
328
  }
329
+ args.push("--exclude-tools", excludedTools.join(","));
330
+ if (options.promptPath) args.push("--append-system-prompt", options.promptPath);
331
+ args.push("--extension", options.retryPolicyPath);
332
+ return args;
333
+ }
307
334
 
335
+ /** Run one persistent RPC child until a stable `agent_settled` or control action. */
336
+ export async function runRpcAgentAttempt(options: RunRpcAttemptOptions): Promise<RpcSingleResult> {
337
+ const { agent, agentName, task, thinkingLevel, idleTimeoutMs, signal, onLive, control } = options;
308
338
  let tmpPromptDir: string | null = null;
309
339
  let tmpPromptPath: string | null = null;
310
340
  if (agent.systemPrompt.trim()) {
311
341
  const tmp = await writePromptToTempFile(options.scratchRoot, agent.name, agent.systemPrompt);
312
342
  tmpPromptDir = tmp.dir;
313
343
  tmpPromptPath = tmp.filePath;
314
- args.push("--append-system-prompt", tmpPromptPath);
315
344
  }
316
345
 
317
346
  let retryPolicy: ChildRetryPolicyExtension;
347
+ let args: string[];
318
348
  try {
319
349
  retryPolicy = await writeChildRetryPolicyExtension(options.scratchRoot, agent.model);
320
- args.push("--extension", retryPolicy.filePath);
350
+ args = buildChildLaunchArgs({
351
+ agent,
352
+ thinkingLevel,
353
+ sessionDir: options.sessionDir,
354
+ sessionId: options.sessionId,
355
+ resumeExistingSession: Boolean(
356
+ options.sessionDir && options.sessionId && sessionExists(options.sessionDir, options.sessionId),
357
+ ),
358
+ promptPath: tmpPromptPath ?? undefined,
359
+ retryPolicyPath: retryPolicy.filePath,
360
+ });
321
361
  } catch (error) {
322
362
  if (tmpPromptDir) await rm(tmpPromptDir, { recursive: true, force: true }).catch(() => undefined);
323
363
  throw error;
@@ -24,45 +24,34 @@ import {
24
24
  } from "./rpc-control.ts";
25
25
  import {
26
26
  currentSubagentDepth,
27
- DEPTH_ENV_VAR,
28
- extractToolErrorText,
29
- getPiInvocation,
30
27
  isRpcCommandTimeoutError,
31
28
  runRpcAgentAttempt,
32
29
  sessionExists,
33
- writeChildRetryPolicyExtension,
34
- SUBAGENT_KILL_GRACE_MS,
35
30
  } from "./rpc-run.ts";
36
31
  import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
37
32
 
38
33
  export {
39
34
  currentSubagentDepth,
40
- DEPTH_ENV_VAR,
41
- extractToolErrorText,
42
- getPiInvocation,
43
- isRpcCommandTimeoutError,
44
35
  RpcRunControl,
45
36
  sessionExists,
46
- SUBAGENT_KILL_GRACE_MS,
47
- writeChildRetryPolicyExtension,
48
37
  };
49
38
  export type { SubagentLiveEvent, UsageStats };
50
39
 
51
- export const SUBAGENT_THINKING_LEVEL: ThinkingLevel = DEFAULT_THINKING_LEVEL;
40
+ const SUBAGENT_THINKING_LEVEL: ThinkingLevel = DEFAULT_THINKING_LEVEL;
52
41
  /** 0 disables the watchdog; dispatch supplies the configured timeout. */
53
- export const SUBAGENT_DEFAULT_IDLE_TIMEOUT_MS = 0;
42
+ const SUBAGENT_DEFAULT_IDLE_TIMEOUT_MS = 0;
54
43
  /** Base delays cover Pi's stale-lock window and leave headroom beyond the
55
44
  * default four-way launch fan-out. Additive jitter below reduces the chance
56
45
  * that contenders retry in the same lockstep waves. */
57
- export const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500, 3000, 6000] as const;
58
- export const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
59
- export const MAX_SUBAGENT_STARTUP_RETRY_JITTER_MS = 1000;
46
+ const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500, 3000, 6000] as const;
47
+ const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
48
+ const MAX_SUBAGENT_STARTUP_RETRY_JITTER_MS = 1000;
60
49
 
61
50
  function normalizeStartupRetryDelay(delayMs: number): number {
62
51
  return Number.isFinite(delayMs) && delayMs > 0 ? delayMs : 0;
63
52
  }
64
53
 
65
- export function addStartupRetryJitter(delayMs: number, randomValue = Math.random()): number {
54
+ function addStartupRetryJitter(delayMs: number, randomValue = Math.random()): number {
66
55
  const baseDelay = Math.floor(normalizeStartupRetryDelay(delayMs));
67
56
  if (baseDelay === 0) return 0;
68
57
  const boundedRandom = Number.isFinite(randomValue) ? Math.max(0, Math.min(1, randomValue)) : 0;
@@ -80,7 +69,7 @@ export interface SubagentDetails {
80
69
  /** Text of the newest assistant message that has any. A final answer may be
81
70
  * split into several text blocks (for example around interleaved thinking);
82
71
  * returning only the first block silently dropped the rest of the result. */
83
- export function getFinalOutput(messages: Message[]): string {
72
+ function getFinalOutput(messages: Message[]): string {
84
73
  for (let i = messages.length - 1; i >= 0; i--) {
85
74
  const msg = messages[i];
86
75
  if (msg.role !== "assistant") continue;
@@ -113,13 +102,13 @@ export function truncateResultOutput(output: string, maxLines: number): Truncate
113
102
  return { text: kept.join("\n"), truncated: true, shownLines: kept.length, totalLines, widthClipped };
114
103
  }
115
104
 
116
- export const RESULT_ARTIFACT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
117
- export const RESULT_ARTIFACT_MAX_FILES_PER_PROJECT = 50;
105
+ const RESULT_ARTIFACT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
106
+ const RESULT_ARTIFACT_MAX_FILES_PER_PROJECT = 50;
118
107
  // Explicit current prefix plus the strict timestamp/token convention used by 1.1.0.
119
108
  const RESULT_ARTIFACT_NAME = /^(?:pi-subagent-\d{13,}-[0-9a-f]{12}|\d{13,}-[a-z0-9]{6})-[\w.-]+\.md$/;
120
109
 
121
110
  /** Name of the single internal-state root under the pi agent directory. */
122
- export const PROJECT_ROOTS_DIR_NAME = "ferris-pi-subagents";
111
+ const PROJECT_ROOTS_DIR_NAME = "ferris-pi-subagents";
123
112
 
124
113
  export function getSubagentsRoot(configPath: string): string {
125
114
  return join(dirname(configPath), PROJECT_ROOTS_DIR_NAME);
@@ -142,7 +131,7 @@ interface ResultArtifactRetentionOptions {
142
131
  * results directory, newest kept first. Unknown files and symlinks are never
143
132
  * touched. Runs on every artifact write, so an active project stays bounded
144
133
  * without ever deleting the result the current completion just linked. */
145
- export function pruneResultArtifacts(
134
+ function pruneResultArtifacts(
146
135
  resultsDir: string,
147
136
  options: ResultArtifactRetentionOptions = {},
148
137
  ): void {
@@ -196,7 +185,7 @@ export function sweepProjectResultArtifacts(
196
185
  }
197
186
  }
198
187
 
199
- export function resultArtifactProjectKey(cwd?: string): string {
188
+ function resultArtifactProjectKey(cwd?: string): string {
200
189
  if (!cwd) return "default";
201
190
  let canonical: string;
202
191
  try {
@@ -289,11 +278,11 @@ export function isRetryableStartupFailure(result: SingleResult, durationMs: numb
289
278
  return true;
290
279
  }
291
280
 
292
- export function formatStartupRetryExhaustedError(model: string, attempts: number): string {
281
+ function formatStartupRetryExhaustedError(model: string, attempts: number): string {
293
282
  return `Subagent failed to start after ${attempts} attempt${attempts === 1 ? "" : "s"} on ${model}: the child failed before its initial RPC prompt was dispatched and produced no model, tool, output, or usage activity. Main handles this phase; inspect launch diagnostics instead of redispatching it.`;
294
283
  }
295
284
 
296
- export async function waitForStartupRetry(delayMs: number, signal?: AbortSignal): Promise<boolean> {
285
+ async function waitForStartupRetry(delayMs: number, signal?: AbortSignal): Promise<boolean> {
297
286
  const normalizedDelay = normalizeStartupRetryDelay(delayMs);
298
287
  if (normalizedDelay === 0) return !signal?.aborted;
299
288
  if (!signal) {
@@ -366,14 +355,14 @@ export function buildResumePrompt(task: string, reason: string): string {
366
355
  /** Create a fresh private session directory under the given root. The owner
367
356
  * marker is what lets a later load tell a session this process still owns from
368
357
  * one a crash abandoned. */
369
- export async function createSessionDir(root: string): Promise<string> {
358
+ async function createSessionDir(root: string): Promise<string> {
370
359
  await mkdir(root, { recursive: true });
371
360
  const dir = await mkdtemp(join(root, "pi-subagent-session-"));
372
361
  writeTempOwnerMarker(dir);
373
362
  return dir;
374
363
  }
375
364
 
376
- export function buildFallbackResumeReason(fromModel?: string): string {
365
+ function buildFallbackResumeReason(fromModel?: string): string {
377
366
  return fromModel
378
367
  ? `the selected model (${fromModel}) failed at the model/provider level, so the current main model is continuing`
379
368
  : "the selected model failed at the model/provider level, so the current main model is continuing";
@@ -444,7 +433,7 @@ function signalAbortDisposition(options: RunSingleOptions, base: SingleResult):
444
433
  }
445
434
 
446
435
  /** Spawn one RPC attempt and wait for stable settlement. */
447
- export async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult> {
436
+ async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult> {
448
437
  const {
449
438
  agent,
450
439
  agentName,
@@ -27,9 +27,8 @@ export type CommandRunner = (
27
27
  ) => Promise<CommandResult>;
28
28
 
29
29
  export const GIT_COMMAND_TIMEOUT_MS = 120_000;
30
- export const GIT_COMMAND_KILL_GRACE_MS = 2_000;
30
+ const GIT_COMMAND_KILL_GRACE_MS = 2_000;
31
31
  export const GIT_OUTPUT_MAX_BYTES = 64 * 1024 * 1024;
32
- export const WORKTREE_PATCH_MAX_BYTES = GIT_OUTPUT_MAX_BYTES;
33
32
 
34
33
  /** Default argument-safe runner. Output is bounded before binary patches enter
35
34
  * memory, and timeout/abort terminates the complete checkout-filter process tree. */
@@ -9,7 +9,7 @@ import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
9
9
  import { managedRecoveryGroup, samePath } from "./managed-paths.ts";
10
10
  import { removeWorktreeGroup, type WorktreeFinalization } from "./worktree.ts";
11
11
 
12
- export const RECOVERY_MANIFEST_FILE_NAME = "pi-subagents-recovery.json";
12
+ const RECOVERY_MANIFEST_FILE_NAME = "pi-subagents-recovery.json";
13
13
  const RECOVERY_MANIFEST_VERSION = 1;
14
14
 
15
15
  export interface RecoveryRecord {
@@ -43,7 +43,7 @@ const DURABLE_SUBDIRS = ["sessions", "worktrees"] as const;
43
43
 
44
44
  /** Unmarked directories (crash before the marker write) must outlive this age
45
45
  * before removal. */
46
- export const UNMARKED_TEMP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
46
+ const UNMARKED_TEMP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
47
47
 
48
48
  interface TempOwner {
49
49
  pid: number;
@@ -138,7 +138,7 @@ function directoryAgeMs(entry: Dirent, dir: string, now: number): number | undef
138
138
 
139
139
  /** Remove dead-owner and old-unmarked directories under `rootDir`.
140
140
  * Returns how many directories were removed. */
141
- export function sweepOrphanTempDirs(
141
+ function sweepOrphanTempDirs(
142
142
  rootDir: string,
143
143
  options: SweepOptions = {},
144
144
  ): number {
@@ -116,11 +116,8 @@ export interface WorktreeIsolation {
116
116
  finalize(): Promise<WorktreeFinalization>;
117
117
  }
118
118
 
119
- export class WorktreeSetupError extends Error {
120
- constructor(
121
- message: string,
122
- readonly retainedPaths: readonly string[] = [],
123
- ) {
119
+ class WorktreeSetupError extends Error {
120
+ constructor(message: string) {
124
121
  super(message);
125
122
  this.name = "WorktreeSetupError";
126
123
  }
@@ -276,7 +273,7 @@ export async function resolveRepositoryRoot(
276
273
  }
277
274
 
278
275
  /** Resolve and validate the Git repository/worktree that contains cwd. */
279
- export async function resolveWorktreeTarget(
276
+ async function resolveWorktreeTarget(
280
277
  cwd: string,
281
278
  runner: CommandRunner = runCommand,
282
279
  ): Promise<WorktreeTarget> {
@@ -308,23 +305,41 @@ class GitWorktreeIsolation implements WorktreeIsolation {
308
305
  private discardPromise?: Promise<void>;
309
306
  /** Full workspace checkpoint retained for manual recovery. */
310
307
  private continuationCheckpoint?: WorktreeCheckpoint;
308
+ readonly originalCwd: string;
309
+ readonly originalRoot: string;
310
+ readonly cwd: string;
311
+ readonly worktreePath: string;
312
+ readonly tempDir: string;
313
+ readonly patchPath: string;
314
+ readonly head: string;
315
+ private readonly runner: CommandRunner;
316
+ /** A restored base may represent work already integrated into the parent. */
317
+ readonly integrationBaseHead: string;
311
318
 
312
319
  constructor(
313
- readonly originalCwd: string,
314
- readonly originalRoot: string,
315
- readonly cwd: string,
316
- readonly worktreePath: string,
317
- readonly tempDir: string,
318
- readonly patchPath: string,
319
- readonly head: string,
320
- private readonly runner: CommandRunner,
321
- /** A restored base may represent work already integrated into the parent. */
322
- readonly integrationBaseHead: string = head,
320
+ originalCwd: string,
321
+ originalRoot: string,
322
+ cwd: string,
323
+ worktreePath: string,
324
+ tempDir: string,
325
+ patchPath: string,
326
+ head: string,
327
+ runner: CommandRunner,
328
+ integrationBaseHead: string = head,
323
329
  restored?: {
324
330
  state: WorktreeIsolation["state"];
325
331
  checkpoint?: WorktreeCheckpoint;
326
332
  },
327
333
  ) {
334
+ this.originalCwd = originalCwd;
335
+ this.originalRoot = originalRoot;
336
+ this.cwd = cwd;
337
+ this.worktreePath = worktreePath;
338
+ this.tempDir = tempDir;
339
+ this.patchPath = patchPath;
340
+ this.head = head;
341
+ this.runner = runner;
342
+ this.integrationBaseHead = integrationBaseHead;
328
343
  if (restored) {
329
344
  this.currentState = restored.state;
330
345
  if (restored.checkpoint) this.continuationCheckpoint = cloneCheckpoint(restored.checkpoint);
@@ -648,7 +663,6 @@ export async function createWorktreeIsolation(
648
663
  const cause = error instanceof Error ? error.message : String(error);
649
664
  throw new WorktreeSetupError(
650
665
  `Could not create isolated Git worktree: ${cause}${rollbackErrors.length > 0 ? ` Rollback errors: ${rollbackErrors.join("; ")}` : ""}${retainedPaths.length > 0 ? ` Retained artifacts: ${retainedPaths.join(", ")}` : ""}`,
651
- retainedPaths,
652
666
  );
653
667
  }
654
668
  }
@@ -14,7 +14,7 @@ export interface CompletionBatchTimings {
14
14
  maxWaitMs: number;
15
15
  }
16
16
 
17
- export const DEFAULT_COMPLETION_BATCH_TIMINGS: CompletionBatchTimings = {
17
+ const DEFAULT_COMPLETION_BATCH_TIMINGS: CompletionBatchTimings = {
18
18
  debounceMs: 150,
19
19
  maxWaitMs: 1_000,
20
20
  };
@@ -34,7 +34,7 @@ import {
34
34
  worktreeSnapshot,
35
35
  } from "../isolation/worktree.ts";
36
36
 
37
- export const THREADS_MANIFEST_FILE_NAME = "pi-subagents-threads.json";
37
+ const THREADS_MANIFEST_FILE_NAME = "pi-subagents-threads.json";
38
38
  const THREADS_MANIFEST_VERSION = 1;
39
39
 
40
40
  /** Project directories whose newest file has not been touched for this long
@@ -98,7 +98,7 @@ export interface ThreadRecord {
98
98
  }
99
99
 
100
100
  /** Approximate timestamp of the machine's current boot. */
101
- export function currentBootId(now = Date.now()): number {
101
+ function currentBootId(now = Date.now()): number {
102
102
  return Math.round(now - uptime() * 1_000);
103
103
  }
104
104
 
@@ -475,7 +475,7 @@ export async function pruneThreadRecords(
475
475
 
476
476
  /** Paths a thread manifest still references; combined with recovery references by
477
477
  * startup retention before any durable directory is swept. */
478
- export function referencedDurablePaths(records: readonly ThreadRecord[]): Set<string> {
478
+ function referencedDurablePaths(records: readonly ThreadRecord[]): Set<string> {
479
479
  const paths = new Set<string>();
480
480
  for (const record of records) {
481
481
  if (record.sessionDir) paths.add(record.sessionDir);
@@ -8,7 +8,7 @@
8
8
  * to every registration site, so state stays in one place without globals.
9
9
  */
10
10
 
11
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
+ import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
12
12
  import type { PhaseScope } from "../delegation/phase-scope.ts";
13
13
  import { rmSync } from "node:fs";
14
14
  import { resolveSubagentConcurrency, BackgroundTaskQueue } from "../execution/background.ts";
@@ -76,6 +76,10 @@ export interface SubagentRuntime {
76
76
  backgroundQueue: BackgroundTaskQueue;
77
77
  /** Live parent tool names from ExtensionAPI, read again for each child launch. */
78
78
  getActiveTools: () => string[];
79
+ /** Live metadata for the registered tools, read again for each child launch.
80
+ * Read-only role policy and write capability come from it, never from a
81
+ * hardcoded list of extension or MCP tool names. */
82
+ getToolInfos: () => ToolInfo[];
79
83
  /** False after session_shutdown; guards delivery and queue work. */
80
84
  sessionActive: boolean;
81
85
  /** Resolves when the load-time durable restore pass has finished. Everything
@@ -137,6 +141,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
137
141
  configPath,
138
142
  backgroundQueue,
139
143
  getActiveTools: () => pi.getActiveTools(),
144
+ getToolInfos: () => pi.getAllTools(),
140
145
  sessionActive: true,
141
146
  durableRestore: Promise.resolve(),
142
147
  restoredRunIds: [],
@@ -10,7 +10,7 @@
10
10
  import { join, resolve } from "node:path";
11
11
  import { isWriteCapableAgent, resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
12
12
  import type { CompletionMessageItem } from "./completion.ts";
13
- import { loadConfig } from "../configuration/config.ts";
13
+ import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
14
14
  import { dispatchFailedResult, failedStartResult, formatCompletionBlock, modelLevelTakeoverNote, queuedResult } from "../presentation/format.ts";
15
15
  import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
16
16
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
@@ -96,8 +96,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
96
96
  const runConfig = baseEnvironment.config;
97
97
  const discoveredAgent = baseEnvironment.agents.find((candidate) => candidate.name === agentName);
98
98
  if (!discoveredAgent) return failedStartResult(agentName, task, `Unknown agent: "${agentName}".`);
99
+ // Admission reads the catalog once; each child launch reads the live one
100
+ // again, like the active tool set, so a server that connected meanwhile
101
+ // is classified by its own annotations.
102
+ const toolInfos = runtime.getToolInfos();
99
103
  const resolveLiveAgentTools = (candidate: AgentConfig): AgentConfig =>
100
- resolveAgentTools({ ...candidate, tools: discoveredAgent.tools }, runtime.getActiveTools());
104
+ resolveAgentTools(candidate, runtime.getActiveTools(), runtime.getToolInfos());
101
105
  const agent = resolveLiveAgentTools(discoveredAgent);
102
106
  const originalCwd = resolve(cwd ?? runCtx.cwd);
103
107
  let phaseId: string | undefined;
@@ -108,8 +112,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
108
112
  } catch (error) {
109
113
  return failedStartResult(agentName, task, error instanceof Error ? error.message : String(error));
110
114
  }
111
- const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent);
112
- if (isolation === "worktree" && !isWorktreeCapableAgent(agent)) {
115
+ const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent, toolInfos);
116
+ if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
113
117
  return {
114
118
  ...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
115
119
  isolation,
@@ -223,14 +227,13 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
223
227
  // queued behind the concurrency limit. Re-resolve the route at actual
224
228
  // start so /subagents-setup edits apply to not-yet-started runs.
225
229
  let activeRoute = route;
226
- let activeIdleTimeoutMs = runConfig.idleTimeoutSec * 1000;
230
+ const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
227
231
  try {
228
232
  const startConfig = await loadConfig(runtime.configPath);
229
233
  const resolvedStart = resolveDispatchModelRoute(agent, startConfig, runCtx);
230
234
  activeRoute = isolation === "worktree"
231
235
  ? { ...resolvedStart, agent: withWorktreeSystemPrompt(resolvedStart.agent) }
232
236
  : resolvedStart;
233
- activeIdleTimeoutMs = startConfig.idleTimeoutSec * 1000;
234
237
  monitor.setModel(runId, activeRoute.agent.model);
235
238
  monitor.setThinking(runId, activeRoute.thinkingLevel);
236
239
  } catch {
@@ -343,7 +346,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
343
346
  );
344
347
  runtime.registerRunResult(runId, result);
345
348
 
346
- const block = formatCompletionBlock(result, runConfig.maxResultLines, {
349
+ const block = formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
347
350
  resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? originalCwd),
348
351
  });
349
352
  const completion: CompletionMessageItem = {
@@ -452,7 +455,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
452
455
  runCtx.ui.notify(`✗ ${crashed.agent} dispatch failed: ${notifyDetail(crashed.errorMessage, "dispatch crashed")}`, "error");
453
456
  runtime.publishRunCompletion(runId, {
454
457
  agent: crashed.agent,
455
- block: formatCompletionBlock(crashed, runConfig.maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, crashed.projectCwd ?? originalCwd) }),
458
+ block: formatCompletionBlock(crashed, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, crashed.projectCwd ?? originalCwd) }),
456
459
  usage: crashed.usage,
457
460
  }, true);
458
461
  } catch {
@@ -3,7 +3,7 @@
3
3
  import { realpath } from "node:fs/promises";
4
4
  import { join, resolve } from "node:path";
5
5
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
- import { isWriteCapableAgent, type AgentConfig } from "../delegation/agents.ts";
6
+ import { isWriteCapableAgent, type AgentConfig, type ToolMetadata } from "../delegation/agents.ts";
7
7
  import type { PhaseScope } from "../delegation/phase-scope.ts";
8
8
  import { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
9
9
  import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord } from "./durable.ts";
@@ -138,8 +138,8 @@ export function withWorktreeSystemPrompt(agent: AgentConfig): AgentConfig {
138
138
  }
139
139
 
140
140
  /** Only write-capable agents can run in an isolated worktree. */
141
- export function isWorktreeCapableAgent(agent: AgentConfig): boolean {
142
- return isWriteCapableAgent(agent);
141
+ export function isWorktreeCapableAgent(agent: AgentConfig, toolInfos?: readonly ToolMetadata[]): boolean {
142
+ return isWriteCapableAgent(agent, toolInfos);
143
143
  }
144
144
 
145
145
  export interface DispatchEnvironment {
@@ -191,7 +191,7 @@ export function resolveDispatchModelRoute(
191
191
  availableRefs: availableModels.map(modelRef),
192
192
  });
193
193
  // A `/subagents-setup` override wins; otherwise the role default. No
194
- // per-call or frontmatter thinking.
194
+ // per-call thinking.
195
195
  const preferred =
196
196
  config.agentThinkingLevels[agent.name] ?? roleThinkingLevel(agent.name);
197
197
  const thinkingLevelForModel = (ref?: string): ThinkingLevel => {
@@ -4,7 +4,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { Text } from "@earendil-works/pi-tui";
5
5
  import { existsSync } from "node:fs";
6
6
  import { Type } from "typebox";
7
- import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
7
+ import { DEFAULT_MAX_RESULT_LINES } from "../configuration/config.ts";
8
8
  import { removeThreadRecord } from "./durable.ts";
9
9
  import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
10
10
  import { emptyUsage } from "../execution/rpc-control.ts";
@@ -146,8 +146,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
146
146
 
147
147
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
148
148
  await runtime.durableRestore;
149
- // Claim every target before awaiting process cleanup or configuration I/O.
150
- const configPromise = loadConfig(runtime.configPath).catch(() => undefined);
151
149
  const completionResults: SingleResult[] = [];
152
150
  const candidateIds = params.all === true
153
151
  ? [...new Set([
@@ -331,10 +329,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
331
329
  stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
332
330
  }
333
331
  if (completionResults.length > 0) {
334
- const maxResultLines = (await configPromise)?.maxResultLines ?? DEFAULT_MAX_RESULT_LINES;
335
332
  runtime.sendCompletionGroup(completionResults.map((result) => ({
336
333
  agent: result.agent,
337
- block: formatCompletionBlock(result, maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
334
+ block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
338
335
  triggerTurn: true,
339
336
  usage: result.usage,
340
337
  })));
@@ -1,10 +1,9 @@
1
1
  /** Session-start recovery, stale-model cleanup, and progress-surface installation. */
2
2
 
3
3
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
- import { existsSync } from "node:fs";
5
4
  import { loadConfig, saveConfig } from "../configuration/config.ts";
6
5
  import { availableModelsInScope, filterUnavailableModelOverrides } from "../configuration/models.ts";
7
- import { offerFirstRunSetup } from "../configuration/setup.ts";
6
+ import { ensureDefaultConfig } from "../configuration/setup.ts";
8
7
  import { announceRecoveryRecords, relocateRecoveryManifest } from "../isolation/recovery.ts";
9
8
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
10
9
  import { installActiveRunsWidget } from "./widget.ts";
@@ -35,7 +34,7 @@ async function removeUnavailableAgentModels(
35
34
 
36
35
  export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime): void {
37
36
  pi.on("session_start", async (_event, ctx) => {
38
- const firstRun = !existsSync(runtime.configPath);
37
+ await ensureDefaultConfig(ctx, runtime.configPath);
39
38
  await relocateRecoveryManifest(runtime.configPath);
40
39
  await announceRecoveryRecords(runtime.configPath, ctx);
41
40
  await removeUnavailableAgentModels(ctx, runtime);
@@ -53,7 +52,6 @@ export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime
53
52
  // The active-run widget is TUI-only.
54
53
  if (ctx.mode !== "tui") return;
55
54
  installActiveRunsWidget(ctx);
56
- if (firstRun) await offerFirstRunSetup(ctx, runtime.configPath);
57
55
  });
58
56
 
59
57
  // Compaction failures are otherwise silent in long orchestration sessions