@vicary/pi-subagents 0.87.0 → 0.88.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-75LVXBSA.js → chunk-2HKPEANZ.js} +114 -49
  6. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  7. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  8. package/bundle/{chunk-XV7RTWTS.js → chunk-4ZQBZDF3.js} +21 -6
  9. package/bundle/{chunk-LZKVUWIY.js → chunk-5EMPFFO4.js} +30 -5
  10. package/bundle/{chunk-OOE3R7IQ.js → chunk-6CG2VAG4.js} +2 -2
  11. package/bundle/{chunk-HDICKROY.js → chunk-7OX6O7DQ.js} +31 -14
  12. package/bundle/{chunk-Z4TR7MK6.js → chunk-AZPP3G4N.js} +14 -5
  13. package/bundle/{chunk-PUSTU4Q7.js → chunk-BKISQ5CJ.js} +130 -49
  14. package/bundle/{chunk-NMYBVCGP.js → chunk-CGWNA6EJ.js} +75 -44
  15. package/bundle/{chunk-PGU4TZV3.js → chunk-CPSUJHZE.js} +417 -455
  16. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  17. package/bundle/{chunk-SIAQXPJ4.js → chunk-D32H53HM.js} +21 -9
  18. package/bundle/{chunk-YEXKJJVS.js → chunk-DSHQWGHO.js} +4 -4
  19. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  20. package/bundle/{chunk-O7A26O6B.js → chunk-IYT7X46U.js} +6 -4
  21. package/bundle/{chunk-NJTSXIMG.js → chunk-JQTHG2ID.js} +12 -12
  22. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  23. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  24. package/bundle/{chunk-2NY5PCKQ.js → chunk-LV3CPYXJ.js} +4 -4
  25. package/bundle/{chunk-2D2DQGC2.js → chunk-PYKBTBY6.js} +27 -10
  26. package/bundle/{chunk-M2VBGET6.js → chunk-RMZAAXIR.js} +7 -2
  27. package/bundle/{chunk-HTI7DD5D.js → chunk-V7SZMS6W.js} +2 -2
  28. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  29. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  30. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  31. package/bundle/chunk-YDZ7BZD5.js +523 -0
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +9 -9
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/required-child-extensions.js +1 -1
  38. package/docs/agents.md +4 -2
  39. package/docs/configuration.md +4 -2
  40. package/docs/observability.md +2 -0
  41. package/docs/tool-reference.md +4 -1
  42. package/docs/workflows.md +3 -1
  43. package/package.json +3 -3
  44. package/skills/pi-subagents/SKILL.md +8 -2
  45. package/src/agents/agent-management.d.ts +1 -0
  46. package/src/agents/agent-management.js +12 -4
  47. package/src/agents/agents.d.ts +1 -0
  48. package/src/agents/agents.js +2 -2
  49. package/src/extension/config.d.ts +9 -0
  50. package/src/extension/config.js +13 -0
  51. package/src/extension/index.d.ts +1 -1
  52. package/src/extension/index.js +47 -23
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/subagent-launch-tool.d.ts +6 -2
  56. package/src/extension/subagent-launch-tool.js +13 -9
  57. package/src/extension/tool-activation.js +20 -3
  58. package/src/runs/background/async-resume.js +2 -1
  59. package/src/runs/background/async-retention.d.ts +0 -2
  60. package/src/runs/background/async-retention.js +11 -5
  61. package/src/runs/background/async-status.d.ts +2 -0
  62. package/src/runs/background/async-status.js +4 -0
  63. package/src/runs/background/run-child-session.d.ts +2 -2
  64. package/src/runs/background/run-child-session.js +4 -7
  65. package/src/runs/background/stale-run-reconciler.js +17 -8
  66. package/src/runs/background/steering.d.ts +2 -11
  67. package/src/runs/background/steering.js +11 -6
  68. package/src/runs/background/subagent-runner.d.ts +0 -2
  69. package/src/runs/background/subagent-runner.js +73 -58
  70. package/src/runs/foreground/async-steering-action.js +24 -9
  71. package/src/runs/foreground/execution.js +32 -15
  72. package/src/runs/foreground/prompt-audit.js +1 -0
  73. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  74. package/src/runs/foreground/subagent-executor.js +17 -21
  75. package/src/runs/shared/async-status-projection.d.ts +2 -0
  76. package/src/runs/shared/async-status-projection.js +10 -0
  77. package/src/runs/shared/child-launch.js +6 -3
  78. package/src/runs/shared/child-session.d.ts +1 -1
  79. package/src/runs/shared/child-session.js +24 -30
  80. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  81. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -5
  82. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -15
  83. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  84. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  85. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  86. package/src/shared/artifacts.d.ts +1 -0
  87. package/src/shared/artifacts.js +107 -9
  88. package/src/shared/compaction-interruption.d.ts +9 -0
  89. package/src/shared/compaction-interruption.js +47 -0
  90. package/src/shared/parent-wake.d.ts +3 -2
  91. package/src/shared/parent-wake.js +14 -3
  92. package/src/shared/reported-progress.d.ts +1 -0
  93. package/src/shared/reported-progress.js +12 -0
  94. package/src/shared/required-child-extensions.d.ts +2 -0
  95. package/src/shared/required-child-extensions.js +27 -0
  96. package/src/shared/status-format.d.ts +1 -0
  97. package/src/shared/status-format.js +1 -1
  98. package/src/shared/types.d.ts +9 -0
  99. package/src/shared/utils.d.ts +3 -1
  100. package/src/shared/utils.js +4 -0
  101. package/src/tui/fleet.d.ts +7 -2
  102. package/src/tui/fleet.js +22 -0
  103. package/src/tui/render.js +33 -2
  104. package/src/watchdog/permission-arbiter.js +1 -0
  105. package/src/watchdog/review.d.ts +0 -5
  106. package/src/watchdog/review.js +2 -1
  107. package/src/workflows/workflow-script-worker.js +3 -1
  108. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -38,21 +38,26 @@ export function resolveMcpDirectToolResolution(mcpDirectTools, cwd = process.cwd
38
38
  const resolvedConfig = Object.keys(runtimeServers).length > 0
39
39
  ? mergeConfigs(config, { mcpServers: runtimeServers })
40
40
  : config;
41
- validateSelectedServerDefinitions(resolvedConfig, selectors);
41
+ const enabledSelectors = selectors.filter((selector) => resolvedConfig.mcpServers[selector.split("/", 1)[0]]?.disabled !== true);
42
+ validateSelectedServerDefinitions(resolvedConfig, enabledSelectors);
42
43
  const runtime = Object.keys(runtimeServers).length > 0
43
44
  ? { mcpConfig: resolvedConfig, runtimeServerNames: Object.keys(runtimeServers) }
44
45
  : {};
46
+ if (enabledSelectors.length === 0)
47
+ return { selections: [], unresolvedSelectors: [], ...runtime };
45
48
  const cache = loadMetadataCache();
46
49
  if (!cache)
47
- return { selections: [], unresolvedSelectors: selectors, ...runtime };
50
+ return { selections: [], unresolvedSelectors: enabledSelectors, ...runtime };
48
51
  const validMetadata = {};
49
52
  for (const [serverName, definition] of Object.entries(resolvedConfig.mcpServers)) {
53
+ if (definition.disabled === true)
54
+ continue;
50
55
  const serverCache = cache.servers[serverName];
51
56
  if (isServerCacheValid(serverCache, definition))
52
57
  validMetadata[serverName] = serverCache;
53
58
  }
54
59
  const grant = planMcpDirectToolGrant({
55
- selectors,
60
+ selectors: enabledSelectors,
56
61
  servers: resolvedConfig.mcpServers,
57
62
  metadata: validMetadata,
58
63
  toolPrefix: resolvedConfig.settings?.toolPrefix,
@@ -63,9 +68,6 @@ export function resolveMcpDirectToolResolution(mcpDirectTools, cwd = process.cwd
63
68
  ...runtime,
64
69
  };
65
70
  }
66
- export function resolveMcpDirectToolSelections(mcpDirectTools, cwd = process.cwd(), runtimeSnapshotHost) {
67
- return resolveMcpDirectToolResolution(mcpDirectTools, cwd, runtimeSnapshotHost).selections;
68
- }
69
71
  /**
70
72
  * pi-mcp-adapter keeps priority whenever it is loaded. 2.x registers /mcp, so Pi does not load its
71
73
  * built-in MCP. 3.x always registers /mcp-adapter and leaves /mcp to the built-in MCP.
@@ -116,11 +118,12 @@ export function formatUnresolvedBuiltinMcpSelectors(agentName, selectors) {
116
118
  }
117
119
  /**
118
120
  * Selected servers that only an extension registered, which a child without ambient extensions
119
- * never has. A server of the same name in an `mcp.json` the child reads takes precedence; like Pi,
120
- * the project file is read only when the project is trusted.
121
+ * never has unless the registering extension is one the child loads (`loadedByChild`). A server of
122
+ * the same name in an `mcp.json` the child reads takes precedence; like Pi, the project file is read
123
+ * only when the project is trusted.
121
124
  */
122
- export function extensionOnlyMcpServers(selections, host, cwd, projectTrusted) {
123
- const registered = new Set(host.getMcpServers?.().map(({ name }) => name));
125
+ export function extensionOnlyMcpServers(selections, host, cwd, projectTrusted, loadedByChild) {
126
+ const registered = new Set(host.getMcpServers?.().filter(({ extensionPath }) => !loadedByChild(extensionPath)).map(({ name }) => name));
124
127
  const servers = [...new Set(selections.map(({ selector }) => selector.split("/")[0]))].filter((server) => registered.has(server));
125
128
  if (servers.length === 0)
126
129
  return [];
@@ -301,11 +304,22 @@ function parseSettings(value) {
301
304
  function mergeConfigs(base, next) {
302
305
  const imports = [...(base.imports ?? []), ...(next.imports ?? [])];
303
306
  return {
304
- mcpServers: { ...base.mcpServers, ...next.mcpServers },
307
+ mcpServers: mergeServerDefinitions(base.mcpServers, next.mcpServers),
305
308
  imports: imports.length ? [...new Set(imports)] : undefined,
306
309
  settings: next.settings ? { ...base.settings, ...next.settings } : base.settings,
307
310
  };
308
311
  }
312
+ function mergeServerDefinitions(base, next) {
313
+ const servers = { ...base };
314
+ for (const [name, definition] of Object.entries(next)) {
315
+ const previous = base[name];
316
+ if (previous && Object.keys(definition).every((key) => key === "disabled"))
317
+ servers[name] = { ...previous, ...definition };
318
+ else
319
+ servers[name] = previous?.disabled === undefined ? definition : { disabled: previous.disabled, ...definition };
320
+ }
321
+ return servers;
322
+ }
309
323
  function expandImports(config, cwd) {
310
324
  if (!config.imports?.length)
311
325
  return config;
@@ -329,7 +343,7 @@ function expandImports(config, cwd) {
329
343
  return {
330
344
  imports: config.imports,
331
345
  settings: config.settings,
332
- mcpServers: { ...importedServers, ...config.mcpServers },
346
+ mcpServers: mergeServerDefinitions(importedServers, config.mcpServers),
333
347
  };
334
348
  }
335
349
  function resolveImportPath(importKind, cwd) {
@@ -349,9 +363,6 @@ function extractServers(config, kind) {
349
363
  : obj.mcpServers;
350
364
  return parseServerEntries(servers);
351
365
  }
352
- export function resolveMcpDirectToolNames(mcpDirectTools, cwd = process.cwd()) {
353
- return resolveMcpDirectToolSelections(mcpDirectTools, cwd).map((selection) => selection.name);
354
- }
355
366
  function validateSelectedServerDefinitions(config, selectors) {
356
367
  const { servers, tools } = parseMcpDirectToolSelectors(selectors);
357
368
  for (const serverName of new Set([...servers, ...tools.keys()])) {
@@ -298,11 +298,19 @@ export function modelBefore(messages, forkedAt) {
298
298
  * parent's prompt, so its own versions of these sections are not repeated in its task message.
299
299
  */
300
300
  const LOADOUT_SECTIONS = new Set(["tools", "rules", "docs", "skills", "advertised_subagents", "mcp_servers", "project_context"]);
301
+ /** The `<project_instructions path="…">` blocks Pi writes into a `project_context` section, by path. */
302
+ function projectInstructionBlocks(section) {
303
+ const blocks = new Map();
304
+ for (const match of (section ?? "").matchAll(/<project_instructions\s+path=(["'])(.*?)\1\s*>[\s\S]*?<\/project_instructions>/gi))
305
+ blocks.set(match[2], match[0]);
306
+ return blocks;
307
+ }
301
308
  /**
302
309
  * The child's own instructions, which a fork sends in its task message instead of its system
303
310
  * prompt: the text its own system messages (`own`) add, the sections it changed except the loadout
304
- * ones, the tools it can call, and its boundary. `parent` is the inherited system messages and
305
- * `child` the whole request.
311
+ * ones, the project instruction files the parent's prompt lacks (a child that works in another
312
+ * folder has that folder's AGENTS.md), the tools it can call, and its boundary. `parent` is the
313
+ * inherited system messages and `child` the whole request.
306
314
  */
307
315
  function forkInstructions(input) {
308
316
  const parent = getCurrentSystemMessage(input.parent);
@@ -318,6 +326,10 @@ function forkInstructions(input) {
318
326
  if (!LOADOUT_SECTIONS.has(name) && value && parent?.sections?.[name] !== value)
319
327
  parts.push(value);
320
328
  }
329
+ const parentFiles = projectInstructionBlocks(parent?.sections?.project_context);
330
+ const missingFiles = [...projectInstructionBlocks(child?.sections?.project_context)].filter(([filePath]) => !parentFiles.has(filePath)).map(([, block]) => block);
331
+ if (missingFiles.length > 0)
332
+ parts.push(["Project instructions for your working folder, which the parent's prompt does not include:", ...missingFiles].join("\n\n"));
321
333
  if (input.boundary)
322
334
  parts.push(input.boundary);
323
335
  return `<subagent_instructions>\n${parts.join("\n\n")}\n</subagent_instructions>`;
@@ -0,0 +1,16 @@
1
+ /** A child making one of these calls is blocked on its supervisor's reply, not working. */
2
+ export declare function isBlockingSupervisorTool(toolName: string | undefined, args: unknown): boolean;
3
+ /** A one-shot timer whose countdown stops while any key holds it paused. */
4
+ export interface PausableTimer {
5
+ pause(key: string): void;
6
+ resume(key: string): void;
7
+ remainingMs(): number;
8
+ clear(): void;
9
+ }
10
+ export declare function startPausableTimer(delayMs: number, onFire: () => void): PausableTimer;
11
+ export declare function pauseForSupervisorWait(timer: PausableTimer | undefined, event: {
12
+ type?: string;
13
+ toolCallId?: unknown;
14
+ toolName?: string;
15
+ args?: unknown;
16
+ }): void;
@@ -0,0 +1,61 @@
1
+ /** A child making one of these calls is blocked on its supervisor's reply, not working. */
2
+ export function isBlockingSupervisorTool(toolName, args) {
3
+ if (!args || typeof args !== "object")
4
+ return false;
5
+ const call = args;
6
+ if (toolName === "contact_supervisor")
7
+ return call.reason === "need_decision" || call.reason === "interview_request";
8
+ return toolName === "intercom" && call.action === "ask";
9
+ }
10
+ export function startPausableTimer(delayMs, onFire) {
11
+ let remaining = Math.max(0, delayMs);
12
+ // Monotonic clock: a system clock change must not shorten or extend the budget.
13
+ let runningSince;
14
+ let timer;
15
+ let done = false;
16
+ const pausedBy = new Set();
17
+ const remainingMs = () => runningSince === undefined ? remaining : Math.max(0, remaining - (performance.now() - runningSince));
18
+ const run = () => {
19
+ runningSince = performance.now();
20
+ timer = setTimeout(() => {
21
+ done = true;
22
+ runningSince = undefined;
23
+ remaining = 0;
24
+ onFire();
25
+ }, remaining);
26
+ timer.unref?.();
27
+ };
28
+ const stop = () => {
29
+ clearTimeout(timer);
30
+ remaining = remainingMs();
31
+ runningSince = undefined;
32
+ };
33
+ run();
34
+ return {
35
+ pause(key) {
36
+ if (done)
37
+ return;
38
+ if (pausedBy.size === 0)
39
+ stop();
40
+ pausedBy.add(key);
41
+ },
42
+ resume(key) {
43
+ if (done || !pausedBy.delete(key) || pausedBy.size > 0)
44
+ return;
45
+ run();
46
+ },
47
+ remainingMs,
48
+ clear() {
49
+ done = true;
50
+ stop();
51
+ },
52
+ };
53
+ }
54
+ export function pauseForSupervisorWait(timer, event) {
55
+ if (!timer || typeof event.toolCallId !== "string")
56
+ return;
57
+ if (event.type === "tool_execution_start" && isBlockingSupervisorTool(event.toolName, event.args))
58
+ timer.pause(event.toolCallId);
59
+ else if (event.type === "tool_execution_end")
60
+ timer.resume(event.toolCallId);
61
+ }
@@ -20,3 +20,4 @@ export declare function writeMetadata(filePath: string, metadata: object): void;
20
20
  export declare function appendJsonl(filePath: string, line: string): void;
21
21
  export declare function cleanupOldArtifacts(dir: string, maxAgeDays: number): void;
22
22
  export declare function cleanupAllArtifactDirs(maxAgeDays: number): void;
23
+ export declare function missingForkCopyNote(sessionFile: string): string;
@@ -1,8 +1,12 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { CHAIN_RUNS_DIR, TEMP_ARTIFACTS_DIR } from "./types.js";
4
- import { getAgentDir } from "./utils.js";
3
+ import { CHAIN_RUNS_DIR, DIRS, TEMP_ARTIFACTS_DIR } from "./types.js";
4
+ import { getAgentDir, readStatus } from "./utils.js";
5
+ import { acquireSessionLease } from "../runs/shared/session-lease.js";
5
6
  const CLEANUP_MARKER_FILE = ".last-cleanup";
7
+ // Pi lists only directories under its sessions root, so a marker file there is invisible to it.
8
+ const FORK_CLEANUP_MARKER_FILE = ".pi-subagents-fork-cleanup";
9
+ const DAY_MS = 24 * 60 * 60 * 1000;
6
10
  // Kept worktrees can outlive cleanupDays; their handoff record and the patches it points to must stay with them.
7
11
  const RETAINED_ARTIFACT_DIRS = new Set(["handoffs", "worktree-diffs"]);
8
12
  export const PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
@@ -223,13 +227,9 @@ export function cleanupOldArtifacts(dir, maxAgeDays) {
223
227
  return;
224
228
  const markerPath = path.join(dir, CLEANUP_MARKER_FILE);
225
229
  const now = Date.now();
226
- if (fs.existsSync(markerPath)) {
227
- const stat = fs.statSync(markerPath);
228
- if (now - stat.mtimeMs < 24 * 60 * 60 * 1000)
229
- return;
230
- }
231
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000;
232
- const cutoff = now - maxAgeMs;
230
+ if (ranWithinDay(markerPath, now))
231
+ return;
232
+ const cutoff = now - maxAgeDays * DAY_MS;
233
233
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
234
234
  if (entry.name === CLEANUP_MARKER_FILE || (entry.isDirectory() && RETAINED_ARTIFACT_DIRS.has(entry.name)))
235
235
  continue;
@@ -271,6 +271,9 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
271
271
  // skip cleanup instead of failing extension startup.
272
272
  return;
273
273
  }
274
+ const forkMarkerPath = path.join(sessionsBase, FORK_CLEANUP_MARKER_FILE);
275
+ const now = Date.now();
276
+ const pruneForks = maxAgeDays > 0 && !ranWithinDay(forkMarkerPath, now);
274
277
  for (const dir of dirs) {
275
278
  const artifactsDir = path.join(sessionsBase, dir, "subagent-artifacts");
276
279
  try {
@@ -280,5 +283,100 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
280
283
  // Session cleanup is best-effort. Keep going so one unreadable session dir
281
284
  // does not block cleanup for the rest.
282
285
  }
286
+ if (pruneForks)
287
+ removeOldForkCopies(path.join(sessionsBase, dir), now - maxAgeDays * DAY_MS);
288
+ }
289
+ if (!pruneForks)
290
+ return;
291
+ try {
292
+ fs.writeFileSync(forkMarkerPath, String(now));
293
+ }
294
+ catch {
295
+ // Without the marker the next load scans again; cleanup must not fail startup.
296
+ }
297
+ }
298
+ function ranWithinDay(markerPath, now) {
299
+ try {
300
+ return now - fs.statSync(markerPath).mtimeMs < DAY_MS;
283
301
  }
302
+ catch {
303
+ return false;
304
+ }
305
+ }
306
+ function removeOldForkCopies(projectDir, cutoff) {
307
+ let sessions;
308
+ try {
309
+ sessions = fs.readdirSync(projectDir, { withFileTypes: true });
310
+ }
311
+ catch {
312
+ return;
313
+ }
314
+ for (const session of sessions) {
315
+ if (!session.isDirectory())
316
+ continue;
317
+ const forksDir = path.join(projectDir, session.name, "forks");
318
+ let runIds;
319
+ try {
320
+ // Never follow a symlinked forks folder: the deletes below would land in its target.
321
+ if (!fs.lstatSync(forksDir).isDirectory())
322
+ continue;
323
+ runIds = fs.readdirSync(forksDir);
324
+ }
325
+ catch {
326
+ continue;
327
+ }
328
+ for (const runId of runIds) {
329
+ const runDir = path.join(forksDir, runId);
330
+ const leases = [];
331
+ try {
332
+ const sessionFiles = idleSessionFiles(runDir, cutoff);
333
+ if (!sessionFiles || asyncRunActive(runId))
334
+ continue;
335
+ // A resumed run writes into its old copy under a new run id and holds that file's session lease.
336
+ // Holding the leases while deleting means a resume elsewhere finds either the lease taken or the file gone.
337
+ for (const file of sessionFiles)
338
+ leases.push(acquireSessionLease({ sessionFile: file, runId: "fork-cleanup", sourceRunId: runId }));
339
+ fs.rmSync(runDir, { recursive: true, force: true });
340
+ }
341
+ catch {
342
+ // Best-effort like artifact cleanup: a leased copy, or an entry that vanishes or can't be read, is left for the next pass.
343
+ }
344
+ finally {
345
+ for (const lease of leases)
346
+ lease.release();
347
+ }
348
+ }
349
+ }
350
+ }
351
+ // Undefined when anything inside, including a nested fork's copy, was written since cutoff: that keeps the whole folder.
352
+ function idleSessionFiles(entryPath, cutoff, files = []) {
353
+ const stat = fs.lstatSync(entryPath);
354
+ if (stat.mtimeMs >= cutoff)
355
+ return undefined;
356
+ if (!stat.isDirectory()) {
357
+ if (stat.isFile() && entryPath.endsWith(".jsonl"))
358
+ files.push(entryPath);
359
+ return files;
360
+ }
361
+ for (const name of fs.readdirSync(entryPath)) {
362
+ if (!idleSessionFiles(path.join(entryPath, name), cutoff, files))
363
+ return undefined;
364
+ }
365
+ return files;
366
+ }
367
+ // An async run waiting on a long tool call or a reply can leave its session file untouched for a long time.
368
+ function asyncRunActive(runId) {
369
+ try {
370
+ const state = readStatus(path.join(DIRS.async, runId))?.state;
371
+ return state === "queued" || state === "running";
372
+ }
373
+ catch {
374
+ // A status that can't be read may still belong to a live run.
375
+ return true;
376
+ }
377
+ }
378
+ export function missingForkCopyNote(sessionFile) {
379
+ if (path.basename(path.dirname(path.dirname(sessionFile))) !== "forks")
380
+ return "";
381
+ return ". It was a forked child's copy of the parent session; such copies are deleted once nothing has written to them for artifactConfig.cleanupDays days (default 7).";
284
382
  }
@@ -0,0 +1,9 @@
1
+ export declare function installCompactionInterruptionCapture(sessionClass: {
2
+ prototype: object;
3
+ }): void;
4
+ /** A manual compaction of this session is in progress, until compact() returns. */
5
+ export declare function compactionInProgress(sessionManager: object): boolean;
6
+ /** A manual compaction of this session that aborted an active run is in progress. */
7
+ export declare function compactionInterruptedRun(sessionManager: object): boolean;
8
+ /** True once, for the aborted end of the run the compaction interrupted; a later run's abort is the user's. */
9
+ export declare function takeCompactionAbort(sessionManager: object): boolean;
@@ -0,0 +1,47 @@
1
+ // Pi's manual compaction (/compact, RPC, ctx.compact()) aborts the active run before any hook runs, and its
2
+ // events do not say whether it interrupted one. Record that in AgentSession.compact, their shared entry point.
3
+ const stateSymbol = Symbol.for("pi-subagents.compaction-interruption.v1");
4
+ const wrappedSymbol = Symbol.for("pi-subagents.compaction-interruption.v1.wrapped");
5
+ // Shared with the wrapper an earlier extension instance installed before a reload.
6
+ const globalStore = globalThis;
7
+ const compactions = globalStore[stateSymbol] ??= new WeakMap();
8
+ export function installCompactionInterruptionCapture(sessionClass) {
9
+ const prototype = sessionClass.prototype;
10
+ const original = prototype.compact;
11
+ if (original[wrappedSymbol])
12
+ return;
13
+ const compact = async function (...args) {
14
+ const manager = this.sessionManager;
15
+ const compaction = compactions.get(manager) ?? { calls: 0, interrupted: false, abortPending: false };
16
+ compactions.set(manager, compaction);
17
+ compaction.calls += 1;
18
+ // Overlapping calls share the record: a later idle call must not erase an earlier interruption.
19
+ if (this.isStreaming)
20
+ compaction.interrupted = compaction.abortPending = true;
21
+ try {
22
+ return await original.apply(this, args);
23
+ }
24
+ finally {
25
+ if (--compaction.calls === 0)
26
+ compactions.delete(manager);
27
+ }
28
+ };
29
+ compact[wrappedSymbol] = true;
30
+ prototype.compact = compact;
31
+ }
32
+ /** A manual compaction of this session is in progress, until compact() returns. */
33
+ export function compactionInProgress(sessionManager) {
34
+ return compactions.has(sessionManager);
35
+ }
36
+ /** A manual compaction of this session that aborted an active run is in progress. */
37
+ export function compactionInterruptedRun(sessionManager) {
38
+ return compactions.get(sessionManager)?.interrupted === true;
39
+ }
40
+ /** True once, for the aborted end of the run the compaction interrupted; a later run's abort is the user's. */
41
+ export function takeCompactionAbort(sessionManager) {
42
+ const compaction = compactions.get(sessionManager);
43
+ if (!compaction?.abortPending)
44
+ return false;
45
+ compaction.abortPending = false;
46
+ return true;
47
+ }
@@ -10,6 +10,7 @@ export interface ParentWake {
10
10
  * Returns true when the message was only appended (held, or another wake is already starting
11
11
  * the run): Pi emits no extension message_start for it.
12
12
  * After userAborted() and until the next run starts, a turn-triggering message is only appended.
13
+ * So it is during a manual compaction, which Pi does not guard against a new run; takeDeferredWake() reports it.
13
14
  */
14
15
  sendMessage(...args: Parameters<ExtensionAPI["sendMessage"]>): boolean;
15
16
  /** True from an idle wake until its run starts or the session shuts down. Past the deadline it holds only while the parent is busy, which may still be the wake's preflight (for example compacting). */
@@ -18,9 +19,9 @@ export interface ParentWake {
18
19
  agentStarted(): void;
19
20
  /** The user stopped the parent run: hold wakes until the next run starts. */
20
21
  userAborted(): void;
21
- /** A deliberate resume (manual compaction) drops the hold without touching the shared wake reservation. */
22
- releaseHold(): void;
23
22
  isHeld(): boolean;
23
+ /** True once if a wake was only appended because a manual compaction was in progress. */
24
+ takeDeferredWake(): boolean;
24
25
  sessionShutdown(reason: string | undefined): void;
25
26
  }
26
27
  export declare function createParentWake(pi: Pick<ExtensionAPI, "sendMessage">, now?: () => number): ParentWake;
@@ -1,3 +1,4 @@
1
+ import { compactionInProgress } from "./compaction-interruption.js";
1
2
  /** Ends a waking notice that reports results. */
2
3
  export const COMPLETION_ACTION = "Read the saved results above and resume the already-authorized parent task, or report completion. If approval is required, explicitly ask the user. Do not silently yield, rerun completed work, or infer new authorization.";
3
4
  /** Ends a waking notice that reports a problem or a run state rather than results. */
@@ -14,6 +15,7 @@ export function createParentWake(pi, now = Date.now) {
14
15
  // Captured at bind: Pi's ctx throws once stale, which it can be by session_shutdown.
15
16
  let session;
16
17
  let held = false;
18
+ let deferred = false;
17
19
  // Look the reservation up on every access: another extension may have created this session's entry.
18
20
  const reservation = () => {
19
21
  // Pi can shut an extension down before session_start binds it; an unbound wake reserved nothing.
@@ -42,6 +44,11 @@ export function createParentWake(pi, now = Date.now) {
42
44
  pi.sendMessage(message, { triggerTurn: false });
43
45
  return true;
44
46
  }
47
+ if (session && compactionInProgress(session.manager)) {
48
+ deferred = true;
49
+ pi.sendMessage(message, { triggerTurn: false });
50
+ return true;
51
+ }
45
52
  if (ctx.isIdle())
46
53
  reservation().sentAt = now();
47
54
  pi.sendMessage(message, options);
@@ -51,15 +58,19 @@ export function createParentWake(pi, now = Date.now) {
51
58
  bindSession(context) {
52
59
  ctx = context;
53
60
  session = { manager: context.sessionManager, id: context.sessionManager.getSessionId() };
54
- held = false;
61
+ held = deferred = false;
55
62
  },
56
63
  agentStarted() {
57
64
  reservation().sentAt = undefined;
58
- held = false;
65
+ held = deferred = false;
59
66
  },
60
67
  userAborted: () => { held = true; },
61
- releaseHold: () => { held = false; },
62
68
  isHeld: () => held,
69
+ takeDeferredWake() {
70
+ const wasDeferred = deferred;
71
+ deferred = false;
72
+ return wasDeferred;
73
+ },
63
74
  sessionShutdown(reason) {
64
75
  if (reason !== "reload")
65
76
  reservation().sentAt = undefined;
@@ -0,0 +1 @@
1
+ export declare function extractReportedProgress(toolName: string, args: unknown): string | undefined;
@@ -0,0 +1,12 @@
1
+ import { sanitizeDisplayText } from "./display-text.js";
2
+ const MAX_REPORTED_PROGRESS_LENGTH = 512;
3
+ export function extractReportedProgress(toolName, args) {
4
+ if (toolName !== "contact_supervisor" || typeof args !== "object" || args === null)
5
+ return undefined;
6
+ const call = args;
7
+ if (call.reason !== "progress_update" || typeof call.message !== "string")
8
+ return undefined;
9
+ const firstLine = call.message.split(/\r?\n/, 1)[0] ?? "";
10
+ const sanitized = sanitizeDisplayText(firstLine).replace(/^(?:progress|update):\s*/i, "");
11
+ return sanitized ? sanitized.slice(0, MAX_REPORTED_PROGRESS_LENGTH) : undefined;
12
+ }
@@ -28,6 +28,8 @@ export declare function assertRequiredChildExtensionsAdmitted(snapshots: Readonl
28
28
  runnerType?: string;
29
29
  machine?: string;
30
30
  }): void;
31
+ /** Maps a path to the identity of the required extension file it names, or undefined. A required path that can't be stat'ed matches only its own spelling. */
32
+ export declare function createRequiredChildExtensionIdentity(requiredPaths: Iterable<string>): (extensionPath: string) => string | undefined;
31
33
  export declare function hasMandatoryRequiredChildExtensions(snapshot: RequiredChildExtensionSnapshot | undefined): snapshot is RequiredChildExtensionSnapshot;
32
34
  /** Persist a run's mandatory snapshot so append-step admits against it; writes nothing without a mandatory entry. */
33
35
  export declare function writeRetainedRequiredChildExtensions(asyncDir: string, snapshot: RequiredChildExtensionSnapshot): void;
@@ -87,6 +87,33 @@ export function assertRequiredChildExtensionsAdmitted(snapshots, launch) {
87
87
  if (route)
88
88
  throw new Error(`Agent '${launch.agent}' cannot run on ${route}: the host requires child extensions (${ids.join(", ")}) for every runner, and only local native Pi children load them.`);
89
89
  }
90
+ function childExtensionFileIdentity(extensionPath) {
91
+ if (!path.isAbsolute(extensionPath))
92
+ return undefined;
93
+ try {
94
+ const stat = fs.statSync(extensionPath, { bigint: true });
95
+ return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;
96
+ }
97
+ catch {
98
+ return undefined;
99
+ }
100
+ }
101
+ /** Maps a path to the identity of the required extension file it names, or undefined. A required path that can't be stat'ed matches only its own spelling. */
102
+ export function createRequiredChildExtensionIdentity(requiredPaths) {
103
+ const aliases = new Map([...requiredPaths].map((extensionPath) => [extensionPath, childExtensionFileIdentity(extensionPath) ?? extensionPath]));
104
+ const identities = new Set(aliases.values());
105
+ return (extensionPath) => {
106
+ const known = aliases.get(extensionPath);
107
+ if (known !== undefined)
108
+ return known;
109
+ const identity = childExtensionFileIdentity(extensionPath);
110
+ if (identity === undefined || !identities.has(identity))
111
+ return undefined;
112
+ // Retain the alias even if the extension removes its file before reporting a failure.
113
+ aliases.set(extensionPath, identity);
114
+ return identity;
115
+ };
116
+ }
90
117
  export function hasMandatoryRequiredChildExtensions(snapshot) {
91
118
  return snapshot?.some((entry) => entry.requireForAllRunners) === true;
92
119
  }
@@ -1,5 +1,6 @@
1
1
  import type { ActivityState, AsyncJobStep } from "./types.ts";
2
2
  type StepStatusLike = Pick<AsyncJobStep, "status">;
3
+ export declare function formatActivityAge(ms: number): string;
3
4
  export declare function formatActivityLabel(lastActivityAt: number | undefined, activityState?: ActivityState, now?: number): string | undefined;
4
5
  export declare function aggregateStepStatus(steps: StepStatusLike[]): AsyncJobStep["status"];
5
6
  export declare function formatAgentRunningLabel(count: number): string;
@@ -1,4 +1,4 @@
1
- function formatActivityAge(ms) {
1
+ export function formatActivityAge(ms) {
2
2
  if (ms < 1000)
3
3
  return "now";
4
4
  if (ms < 60000)
@@ -668,6 +668,7 @@ export interface ScheduleOrigin {
668
668
  }
669
669
  export type SteeringActionState = "delivered" | "scheduled" | "pending" | "partial" | "recovered" | "failed";
670
670
  export type SteeringTargetState = "scheduled" | "pending" | "routed" | "queued" | "delivered" | "late" | "failed" | "recovered";
671
+ export type SteeringFailureKind = "rejected" | "unconsumed";
671
672
  export interface SteeringTargetStatus {
672
673
  index: number;
673
674
  state: SteeringTargetState;
@@ -676,6 +677,7 @@ export interface SteeringTargetStatus {
676
677
  lateDeliveredAt?: number;
677
678
  failedAt?: number;
678
679
  recoveredAt?: number;
680
+ failureKind?: SteeringFailureKind;
679
681
  reason?: string;
680
682
  replacementRunId?: string;
681
683
  }
@@ -700,6 +702,7 @@ export interface SteeringStatus {
700
702
  export interface SteerActionTarget {
701
703
  index: number;
702
704
  state: SteeringTargetState;
705
+ failureKind?: SteeringFailureKind;
703
706
  deliveredAt?: number;
704
707
  lateDeliveredAt?: number;
705
708
  reason?: string;
@@ -887,6 +890,8 @@ export interface AgentProgress {
887
890
  /** Human-readable display name for the child's session, when derived at launch. */
888
891
  sessionName?: string;
889
892
  status: "pending" | "running" | "completed" | "failed" | "detached";
893
+ progressText?: string;
894
+ progressUpdatedAt?: number;
890
895
  activityState?: ActivityState;
891
896
  task: string;
892
897
  skills?: string[];
@@ -1543,6 +1548,8 @@ export interface NestedStepSummary {
1543
1548
  /** Human-readable display name for the child session, when derived at launch. */
1544
1549
  sessionName?: string;
1545
1550
  status: "pending" | "running" | "complete" | "completed" | "failed" | "partial" | "paused" | "stopped" | "rejected";
1551
+ progressText?: string;
1552
+ progressUpdatedAt?: number;
1546
1553
  model?: string;
1547
1554
  thinking?: string;
1548
1555
  sessionFile?: string;
@@ -1995,6 +2002,8 @@ export interface AsyncStatus {
1995
2002
  endMs: number;
1996
2003
  }>;
1997
2004
  recentOutput?: string[];
2005
+ progressText?: string;
2006
+ progressUpdatedAt?: number;
1998
2007
  turnCount?: number;
1999
2008
  toolCount?: number;
2000
2009
  startedAt?: number;
@@ -1,4 +1,4 @@
1
- import type { Message, Usage as PiUsage } from "@earendil-works/pi-ai";
1
+ import type { Message, StopReason, Usage as PiUsage } from "@earendil-works/pi-ai";
2
2
  import type { AgentProgress, AsyncStatus, Details, DisplayItem, ErrorInfo, SingleResult, ToolCallSummary, Usage } from "./types.ts";
3
3
  export declare const PI_CODING_AGENT_PACKAGE_ROOT_ENV = "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT";
4
4
  export declare const PROMPT_REDACTED = "[prompt redacted]";
@@ -27,6 +27,8 @@ export declare function assistantMessageError(message: {
27
27
  }): string | undefined;
28
28
  export declare function getFinalOutput(messages: Message[]): string;
29
29
  export declare function getSingleResultOutput(result: Pick<SingleResult, "finalOutput" | "messages">): string;
30
+ export declare const TRUNCATED_RESPONSE_ERROR = "Response was truncated: the model reached its maximum output length.";
31
+ export declare function getTerminalAssistantStopReason(messages: Message[]): StopReason | undefined;
30
32
  export declare function getDisplayItems(messages: Message[] | undefined): DisplayItem[];
31
33
  export declare function sumResultsUsage(results: SingleResult[]): Usage;
32
34
  export declare function toAgentToolUsage(usage: Usage): PiUsage;
@@ -288,6 +288,10 @@ export function getFinalOutput(messages) {
288
288
  export function getSingleResultOutput(result) {
289
289
  return result.finalOutput ?? getFinalOutput(result.messages ?? []);
290
290
  }
291
+ export const TRUNCATED_RESPONSE_ERROR = "Response was truncated: the model reached its maximum output length.";
292
+ export function getTerminalAssistantStopReason(messages) {
293
+ return messages.findLast((message) => message.role === "assistant")?.stopReason;
294
+ }
291
295
  export function getDisplayItems(messages) {
292
296
  if (!messages || messages.length === 0)
293
297
  return [];