@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
+ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
4
5
 
5
6
  export const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
6
7
  export const PI_SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
@@ -23,9 +24,13 @@ export function findPiPackageRootFromEntry(
23
24
  }
24
25
 
25
26
  export function resolveInstalledPiPackageRoot(): string | undefined {
26
- return findPiPackageRootFromEntry(
27
- fileURLToPath(import.meta.resolve(PI_CODING_AGENT_PACKAGE)),
28
- );
27
+ try {
28
+ return findPiPackageRootFromEntry(
29
+ fileURLToPath(import.meta.resolve(PI_CODING_AGENT_PACKAGE)),
30
+ );
31
+ } catch {
32
+ return undefined;
33
+ }
29
34
  }
30
35
 
31
36
  export function resolvePiPackageRoot(): string | undefined {
@@ -58,12 +63,21 @@ interface PiSpawnCommand {
58
63
  args: string[];
59
64
  }
60
65
 
66
+ interface PiPackageJson {
67
+ name?: unknown;
68
+ bin?: string | Record<string, string>;
69
+ }
70
+
71
+ function isNodeScriptPath(filePath: string): boolean {
72
+ return /\.(?:mjs|cjs|js)$/i.test(filePath);
73
+ }
74
+
61
75
  function isRunnableNodeScript(
62
76
  filePath: string,
63
77
  existsSync: (filePath: string) => boolean,
64
78
  ): boolean {
65
79
  if (!existsSync(filePath)) return false;
66
- return /\.(?:mjs|cjs|js)$/i.test(filePath);
80
+ return isNodeScriptPath(filePath);
67
81
  }
68
82
 
69
83
  function normalizePath(filePath: string): string {
@@ -75,6 +89,23 @@ function isStandalonePiExecutable(execPath: string): boolean {
75
89
  return /^pi(?:\.exe)?$/i.test(executableName ?? "");
76
90
  }
77
91
 
92
+ function resolvePiCliScriptFromPackageJson(
93
+ packageJsonPath: string,
94
+ readFileSync: (filePath: string, encoding: "utf-8") => string,
95
+ existsSync: (filePath: string) => boolean,
96
+ ): string | undefined {
97
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as PiPackageJson;
98
+ if (packageJson.name !== PI_CODING_AGENT_PACKAGE) return undefined;
99
+ const binField = packageJson.bin;
100
+ const binPath =
101
+ typeof binField === "string"
102
+ ? binField
103
+ : (binField?.pi ?? Object.values(binField ?? {})[0]);
104
+ if (!binPath) return undefined;
105
+ const candidate = path.resolve(path.dirname(packageJsonPath), binPath);
106
+ return isRunnableNodeScript(candidate, existsSync) ? candidate : undefined;
107
+ }
108
+
78
109
  export function resolvePiCliScript(
79
110
  deps: PiSpawnDeps = {},
80
111
  ): string | undefined {
@@ -84,6 +115,7 @@ export function resolvePiCliScript(
84
115
  deps.readFileSync ??
85
116
  ((filePath, encoding) => fs.readFileSync(filePath, encoding));
86
117
  const argv1 = deps.argv1 ?? process.argv[1];
118
+ const env = deps.env ?? process.env;
87
119
 
88
120
  if (argv1) {
89
121
  const argvPath = normalizePath(argv1);
@@ -99,38 +131,28 @@ export function resolvePiCliScript(
99
131
  }
100
132
  }
101
133
 
102
- try {
103
- const resolvePackageJson =
104
- deps.resolvePackageJson ??
105
- (() => {
106
- const root = deps.piPackageRoot ?? resolvePiPackageRoot();
107
- if (root) return path.join(root, "package.json");
108
- const packageRoot = deps.resolvePackageEntry
109
- ? findPiPackageRootFromEntry(deps.resolvePackageEntry())
110
- : resolveInstalledPiPackageRoot();
111
- if (!packageRoot)
112
- throw new Error(
113
- `Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`,
114
- );
115
- return path.join(packageRoot, "package.json");
116
- });
117
- const packageJsonPath = resolvePackageJson();
118
- const packageJson = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as {
119
- bin?: string | Record<string, string>;
120
- };
121
- const binField = packageJson.bin;
122
- const binPath =
123
- typeof binField === "string"
124
- ? binField
125
- : (binField?.pi ?? Object.values(binField ?? {})[0]);
126
- if (!binPath) return undefined;
127
- const candidate = path.resolve(path.dirname(packageJsonPath), binPath);
128
- if (isRunnableNodeScript(candidate, existsSync)) {
129
- return candidate;
134
+ const packageJsonCandidates: Array<() => string | undefined> = [];
135
+ if (deps.resolvePackageJson) packageJsonCandidates.push(deps.resolvePackageJson);
136
+ for (const root of [deps.piPackageRoot, env[PI_CODING_AGENT_PACKAGE_ROOT_ENV], resolvePiPackageRoot()]) {
137
+ const trimmed = root?.trim();
138
+ if (trimmed) packageJsonCandidates.push(() => path.join(trimmed, "package.json"));
139
+ }
140
+ packageJsonCandidates.push(() => {
141
+ const packageRoot = deps.resolvePackageEntry
142
+ ? findPiPackageRootFromEntry(deps.resolvePackageEntry())
143
+ : resolveInstalledPiPackageRoot();
144
+ return packageRoot ? path.join(packageRoot, "package.json") : undefined;
145
+ });
146
+
147
+ for (const candidatePackageJson of packageJsonCandidates) {
148
+ try {
149
+ const packageJsonPath = candidatePackageJson();
150
+ if (!packageJsonPath) continue;
151
+ const candidate = resolvePiCliScriptFromPackageJson(packageJsonPath, readFileSync, existsSync);
152
+ if (candidate) return candidate;
153
+ } catch {
154
+ // Keep resolving; callers decide whether a PATH fallback is safe.
130
155
  }
131
- } catch {
132
- // Verified CLI resolution is optional; falling back to `pi` lets PATH handle execution.
133
- return undefined;
134
156
  }
135
157
 
136
158
  return undefined;
@@ -140,9 +162,16 @@ export function getPiSpawnCommand(
140
162
  args: string[],
141
163
  deps: PiSpawnDeps = {},
142
164
  ): PiSpawnCommand {
165
+ const platform = deps.platform ?? process.platform;
143
166
  const env = deps.env ?? process.env;
144
167
  const piBinary = env[PI_SUBAGENT_PI_BINARY_ENV]?.trim();
145
168
  if (piBinary) {
169
+ if (platform === "win32" && isNodeScriptPath(piBinary)) {
170
+ return {
171
+ command: deps.execPath ?? process.execPath,
172
+ args: [piBinary, ...args],
173
+ };
174
+ }
146
175
  return { command: piBinary, args };
147
176
  }
148
177
 
@@ -158,6 +187,11 @@ export function getPiSpawnCommand(
158
187
  args: [piCliPath, ...args],
159
188
  };
160
189
  }
190
+ if (platform === "win32") {
191
+ throw new Error(
192
+ `Could not resolve the Pi CLI on Windows. Set ${PI_SUBAGENT_PI_BINARY_ENV} or ensure ${PI_CODING_AGENT_PACKAGE} is installed.`,
193
+ );
194
+ }
161
195
 
162
196
  return { command: "pi", args };
163
197
  }
@@ -2,6 +2,22 @@ export function formatProcessSignalError(signal: string): string {
2
2
  return `Subagent process terminated by signal ${signal}.`;
3
3
  }
4
4
 
5
+ export function formatMidToolExitError(input: {
6
+ toolName: string;
7
+ exitCode?: number | null;
8
+ processSignal?: string | null;
9
+ }): string {
10
+ if (input.exitCode === undefined && !input.processSignal) {
11
+ return `Subagent session ended during '${input.toolName}' tool execution before the tool completed. Earlier assistant output is not a terminal result.`;
12
+ }
13
+ const terminal = [`exit ${input.exitCode ?? "unknown"}`, ...(input.processSignal ? [`signal ${input.processSignal}`] : [])].join(", ");
14
+ return `Subagent process exited during '${input.toolName}' tool execution (${terminal}) before the tool completed. Earlier assistant output is not a terminal result.`;
15
+ }
16
+
17
+ export function isOrdinaryToolForMidToolExit(toolName: string): boolean {
18
+ return toolName !== "intercom" && toolName !== "contact_supervisor";
19
+ }
20
+
5
21
  export function isUnexplainedProcessSignal(input: {
6
22
  processSignal?: string | null;
7
23
  interrupted?: boolean;
@@ -9,7 +9,6 @@ import {
9
9
  type RunFanoutRejection,
10
10
  } from "../../shared/types.ts";
11
11
 
12
- export const RUN_FANOUT_BUDGET_ENV = "PI_SUBAGENT_RUN_FANOUT_BUDGET";
13
12
  const RUN_FANOUT_ROOT = path.join(TEMP_ROOT_DIR, "run-fanout-budgets");
14
13
 
15
14
  interface ManifestV1 {
@@ -124,18 +123,6 @@ export function readRunFanoutBudgetDescriptor(asyncDir: string | undefined): Run
124
123
  }
125
124
  }
126
125
 
127
- export function encodeRunFanoutBudgetDescriptor(descriptor: RunFanoutBudgetDescriptor): string {
128
- return Buffer.from(JSON.stringify(validateRunFanoutBudgetDescriptor(descriptor)), "utf-8").toString("base64url");
129
- }
130
-
131
- export function decodeRunFanoutBudgetDescriptor(encoded: string | undefined): RunFanoutBudgetDescriptor | undefined {
132
- if (!encoded) return undefined;
133
- try {
134
- return validateRunFanoutBudgetDescriptor(JSON.parse(Buffer.from(encoded, "base64url").toString("utf-8")));
135
- } catch (error) {
136
- throw new Error(`Invalid inherited run fan-out budget: ${error instanceof Error ? error.message : String(error)}`);
137
- }
138
- }
139
126
 
140
127
  interface AdmissionLockOwner {
141
128
  pid: number;
@@ -2,6 +2,9 @@ import { createHash } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { getAgentDir } from "../../shared/utils.ts";
5
+ import { isUnexplainedProcessSignal } from "./process-signal.ts";
6
+
7
+ export type RunOutcome = "completed" | "failed" | "timed_out" | "stopped" | "interrupted";
5
8
 
6
9
  export interface RunEntry {
7
10
  agent: string;
@@ -9,6 +12,7 @@ export interface RunEntry {
9
12
  taskHash?: string;
10
13
  ts: number;
11
14
  status: "ok" | "error";
15
+ outcome?: RunOutcome;
12
16
  duration: number;
13
17
  exit?: number;
14
18
  }
@@ -129,14 +133,30 @@ function appendPrivateHistoryLine(historyPath: string, line: string): void {
129
133
  }
130
134
  }
131
135
 
132
- export function recordRun(agent: string, task: string, exitCode: number, durationMs: number): void {
136
+ export function recordRun(
137
+ agent: string,
138
+ task: string,
139
+ exitCode: number,
140
+ durationMs: number,
141
+ terminal: { interrupted?: boolean; processSignal?: string | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean } = {},
142
+ ): void {
133
143
  try {
144
+ const outcome: RunOutcome = terminal.stopped
145
+ ? "stopped"
146
+ : terminal.interrupted
147
+ ? "interrupted"
148
+ : terminal.timedOut
149
+ ? "timed_out"
150
+ : exitCode !== 0 && isUnexplainedProcessSignal(terminal)
151
+ ? "stopped"
152
+ : exitCode === 0 ? "completed" : "failed";
134
153
  const entry: RunEntry = {
135
154
  agent,
136
155
  task: REDACTED_TASK,
137
156
  taskHash: hashTask(task),
138
157
  ts: Math.floor(Date.now() / 1000),
139
158
  status: exitCode === 0 ? "ok" : "error",
159
+ outcome,
140
160
  duration: durationMs,
141
161
  ...(exitCode !== 0 ? { exit: exitCode } : {}),
142
162
  };
@@ -1,13 +1,8 @@
1
- import * as fs from "node:fs";
2
- import * as path from "node:path";
3
1
  import type { RuntimeAcknowledgedChildExtensionsV1 } from "../../shared/types.ts";
4
2
 
5
3
  export const RUNTIME_EXTENSION_ACK_EVENT = "subagent:acknowledge-extension";
6
- export const RUNTIME_EXTENSION_ACK_PATH_ENV = "PI_SUBAGENT_RUNTIME_ACKNOWLEDGED_EXTENSIONS";
7
4
  export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_IDS = 32;
8
5
  export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_ID_LENGTH = 128;
9
- // Generous bound for a valid capture (32 ids x 128 chars plus envelope); larger files are child misbehavior.
10
- export const MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_FILE_BYTES = 64 * 1024;
11
6
 
12
7
  export function isRuntimeAcknowledgedExtensionId(value: unknown): value is string {
13
8
  return typeof value === "string"
@@ -47,25 +42,3 @@ export function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAc
47
42
  : 0;
48
43
  return { ...projected, omitted: projected.omitted + omitted };
49
44
  }
50
-
51
- export function readRuntimeAcknowledgedExtensions(filePath: string | undefined): RuntimeAcknowledgedChildExtensionsV1 | undefined {
52
- if (!filePath) return undefined;
53
- try {
54
- if (fs.statSync(filePath).size > MAX_RUNTIME_ACKNOWLEDGED_EXTENSION_FILE_BYTES) return undefined;
55
- const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
56
- return sanitizeRuntimeAcknowledgedExtensions(parsed);
57
- } catch {
58
- return undefined;
59
- }
60
- }
61
-
62
- export function writeRuntimeAcknowledgedExtensions(filePath: string, ids: Iterable<unknown>): void {
63
- const projection = projectRuntimeAcknowledgedExtensions(ids);
64
- try {
65
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
66
- if (projection) fs.writeFileSync(filePath, JSON.stringify(projection), { mode: 0o600 });
67
- else fs.rmSync(filePath, { force: true });
68
- } catch {
69
- // Runtime acknowledgement is best-effort observability only.
70
- }
71
- }
@@ -0,0 +1,85 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { SANDBOX_DIAGNOSTICS_PATH_ENV } from "./sandbox-startup-diagnostics.ts";
5
+
6
+ const SANDBOX_PROFILE_ENV = "PI_SUBAGENT_SANDBOX_PROFILE";
7
+ const SANDBOX_STARTUP_ACK_PATH_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_PATH";
8
+ const SANDBOX_STARTUP_ACK_TOKEN_ENV = "PI_SUBAGENT_SANDBOX_STARTUP_ACK_TOKEN";
9
+ const MAX_ACK_BYTES = 4096;
10
+
11
+ function startupAcknowledgementError(profile: string, ackPath: string | undefined, token: string | undefined): string | undefined {
12
+ if (!ackPath || !token) {
13
+ return `Sandbox profile '${profile}' is missing its required startup acknowledgement channel.`;
14
+ }
15
+ try {
16
+ const stat = fs.lstatSync(ackPath);
17
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_ACK_BYTES) {
18
+ return `Sandbox profile '${profile}' did not produce a valid startup acknowledgement.`;
19
+ }
20
+ const parsed: unknown = JSON.parse(fs.readFileSync(ackPath, "utf-8"));
21
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
22
+ return `Sandbox profile '${profile}' did not produce a valid startup acknowledgement.`;
23
+ }
24
+ const acknowledgement = parsed as { version?: unknown; profile?: unknown; token?: unknown };
25
+ if (acknowledgement.version !== 1 || acknowledgement.profile !== profile || acknowledgement.token !== token) {
26
+ return `Sandbox profile '${profile}' did not acknowledge successful startup.`;
27
+ }
28
+ return undefined;
29
+ } catch {
30
+ return `Sandbox profile '${profile}' did not acknowledge successful startup.`;
31
+ }
32
+ }
33
+
34
+ export default function registerSandboxProfileGuard(pi: ExtensionAPI): void {
35
+ // Env values are captured at registration, inside the launch env window; the
36
+ // host restores transient sandbox keys after the session is created.
37
+ const profile = process.env[SANDBOX_PROFILE_ENV];
38
+ if (!profile) return;
39
+ const ackPath = process.env[SANDBOX_STARTUP_ACK_PATH_ENV];
40
+ const token = process.env[SANDBOX_STARTUP_ACK_TOKEN_ENV];
41
+ const diagnosticsPath = process.env[SANDBOX_DIAGNOSTICS_PATH_ENV];
42
+ let validated = false;
43
+
44
+ // The guard owns the acknowledgement check, so it is also the component that
45
+ // knows the child was refused before its first turn. Publish that reason for
46
+ // the launcher instead of leaving the caller with an empty session.
47
+ const publishDiagnostic = (reason: string): void => {
48
+ if (!diagnosticsPath) return;
49
+ try {
50
+ fs.mkdirSync(path.dirname(diagnosticsPath), { recursive: true, mode: 0o700 });
51
+ fs.writeFileSync(
52
+ diagnosticsPath,
53
+ JSON.stringify({ version: 1, profile, reason }),
54
+ { mode: 0o600 },
55
+ );
56
+ } catch {
57
+ // The stderr diagnostic below remains the fallback channel.
58
+ }
59
+ };
60
+
61
+ const check = (): string | undefined => {
62
+ if (validated) return undefined;
63
+ const failure = startupAcknowledgementError(profile, ackPath, token);
64
+ if (!failure) validated = true;
65
+ return failure;
66
+ };
67
+
68
+ const clearAcknowledgement = (): void => {
69
+ if (!ackPath || !validated) return;
70
+ try { fs.rmSync(ackPath, { force: true }); } catch { /* best effort */ }
71
+ };
72
+
73
+ pi.on("input", (_event, ctx: ExtensionContext) => {
74
+ const failure = check();
75
+ if (failure) {
76
+ process.stderr.write(`pi-subagents: ${failure}\n`);
77
+ publishDiagnostic(failure);
78
+ if (ctx.hasUI) ctx.ui.notify(failure, "error");
79
+ else process.exitCode = 1;
80
+ return { action: "handled" as const };
81
+ }
82
+ clearAcknowledgement();
83
+ return undefined;
84
+ });
85
+ }
@@ -0,0 +1,54 @@
1
+ import * as fs from "node:fs";
2
+
3
+ /**
4
+ * A child extension that refuses to start (for example a required sandbox
5
+ * profile that cannot initialize) blocks the first model turn, so the child
6
+ * session ends with no messages and no tool result to inspect. The launcher
7
+ * hands the extension this path through the transient launch environment and
8
+ * reads it back, so the caller sees the real reason instead of an invented
9
+ * empty-output message.
10
+ */
11
+ export const SANDBOX_DIAGNOSTICS_PATH_ENV = "PI_SUBAGENT_SANDBOX_DIAGNOSTICS_PATH";
12
+
13
+ const MAX_DIAGNOSTIC_BYTES = 8192;
14
+
15
+ export interface SandboxStartupDiagnostic {
16
+ version: 1;
17
+ profile?: string;
18
+ reason: string;
19
+ }
20
+
21
+ /**
22
+ * Read the startup diagnostic a blocked child extension wrote. The file is
23
+ * treated as untrusted input: only a bounded, well-formed record is accepted.
24
+ */
25
+ export function readSandboxStartupDiagnostic(
26
+ diagnosticsPath: string | undefined,
27
+ ): SandboxStartupDiagnostic | undefined {
28
+ if (!diagnosticsPath) return undefined;
29
+ try {
30
+ const stat = fs.lstatSync(diagnosticsPath);
31
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > MAX_DIAGNOSTIC_BYTES) return undefined;
32
+ const parsed: unknown = JSON.parse(fs.readFileSync(diagnosticsPath, "utf-8"));
33
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
34
+ const record = parsed as { version?: unknown; profile?: unknown; reason?: unknown };
35
+ if (record.version !== 1) return undefined;
36
+ if (typeof record.reason !== "string" || !record.reason.trim()) return undefined;
37
+ const profile = typeof record.profile === "string" && record.profile.trim() ? record.profile : undefined;
38
+ const diagnostic: SandboxStartupDiagnostic = { version: 1, reason: record.reason.trim() };
39
+ if (profile !== undefined) diagnostic.profile = profile;
40
+ return diagnostic;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ /** Best-effort removal so a stale diagnostic cannot describe a later attempt. */
47
+ export function clearSandboxStartupDiagnostic(diagnosticsPath: string | undefined): void {
48
+ if (!diagnosticsPath) return;
49
+ try {
50
+ fs.rmSync(diagnosticsPath, { force: true });
51
+ } catch {
52
+ // Best effort: the diagnostics directory lives in the transient temp root.
53
+ }
54
+ }
@@ -8,6 +8,17 @@ export interface SingleOutputSnapshot {
8
8
  exists: boolean;
9
9
  mtimeMs?: number;
10
10
  size?: number;
11
+ error?: string;
12
+ }
13
+
14
+ function missingFileStatError(error: unknown): boolean {
15
+ const code = (error as NodeJS.ErrnoException | undefined)?.code;
16
+ return code === "ENOENT" || code === "ENOTDIR";
17
+ }
18
+
19
+ function snapshotFromStatError(error: unknown): SingleOutputSnapshot {
20
+ if (missingFileStatError(error)) return { exists: false };
21
+ return { exists: false, error: error instanceof Error ? error.message : String(error) };
11
22
  }
12
23
 
13
24
  /**
@@ -96,6 +107,23 @@ function formatOutputPathInstruction(outputPath: string, capabilities?: OutputIn
96
107
  ].join("\n");
97
108
  }
98
109
 
110
+ export function requestedOutputPathFromTask(task: string): string | undefined {
111
+ for (const line of task.split(/\r?\n/).reverse()) {
112
+ const match = line.match(/^\s*(?:Write your findings to(?: exactly this path)?:|The runtime will persist it to exactly this path:)\s*(.+?)\s*$/i);
113
+ if (!match?.[1]) continue;
114
+ const requested = match[1].trim();
115
+ return requested.startsWith("`") && requested.endsWith("`") ? requested.slice(1, -1) : requested;
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ export function outputPathMappingFromTask(task: string, savedPath: string | undefined): { requestedPath: string; savedPath: string } | undefined {
121
+ const requestedPath = requestedOutputPathFromTask(task);
122
+ if (!requestedPath || !savedPath) return undefined;
123
+ if (path.isAbsolute(requestedPath) && path.normalize(requestedPath) === path.normalize(savedPath)) return undefined;
124
+ return { requestedPath, savedPath };
125
+ }
126
+
99
127
  export function injectSingleOutputInstruction(task: string, outputPath: string | undefined, capabilities?: OutputInstructionCapabilities): string {
100
128
  if (!outputPath) return task;
101
129
  return `${task}\n\n---\n**Output:**\n${formatOutputPathInstruction(outputPath, capabilities)}`;
@@ -144,23 +172,67 @@ export function validateFileOnlyOutputMode(outputMode: OutputMode | undefined, o
144
172
  return undefined;
145
173
  }
146
174
 
175
+ export function resolveSingleOutputClaimPath(outputPath: string): string {
176
+ let existing = path.resolve(outputPath);
177
+ const missingSegments: string[] = [];
178
+ while (!fs.existsSync(existing)) {
179
+ missingSegments.unshift(path.basename(existing));
180
+ const parent = path.dirname(existing);
181
+ if (parent === existing) break;
182
+ existing = parent;
183
+ }
184
+ return path.join(fs.realpathSync(existing), ...missingSegments);
185
+ }
186
+
187
+ function outputClaimError(outputPath: string, expectedClaimPath: string | undefined): string | undefined {
188
+ if (expectedClaimPath && resolveSingleOutputClaimPath(outputPath) !== expectedClaimPath) return "Output path changed after it was claimed.";
189
+ return undefined;
190
+ }
191
+
147
192
  export function captureSingleOutputSnapshot(outputPath: string | undefined): SingleOutputSnapshot | undefined {
148
193
  if (!outputPath) return undefined;
149
194
  try {
150
195
  const stat = fs.statSync(outputPath);
151
196
  return { exists: true, mtimeMs: stat.mtimeMs, size: stat.size };
152
- } catch {
153
- // The snapshot is advisory; resolveSingleOutput reports concrete read/write failures.
154
- return { exists: false };
197
+ } catch (error) {
198
+ return snapshotFromStatError(error);
199
+ }
200
+ }
201
+
202
+ function inspectSingleOutputChange(
203
+ outputPath: string,
204
+ beforeRun: SingleOutputSnapshot | undefined,
205
+ ): { changed: boolean; error?: string } {
206
+ if (beforeRun?.error) return { changed: false, error: beforeRun.error };
207
+ try {
208
+ const stat = fs.statSync(outputPath);
209
+ return {
210
+ changed: !beforeRun?.exists || stat.mtimeMs !== beforeRun.mtimeMs || stat.size !== beforeRun.size,
211
+ };
212
+ } catch (error) {
213
+ if (missingFileStatError(error)) return { changed: false };
214
+ return { changed: false, error: error instanceof Error ? error.message : String(error) };
155
215
  }
156
216
  }
157
217
 
218
+ export function hasSingleOutputChangedSinceSnapshot(
219
+ outputPath: string | undefined,
220
+ beforeRun: SingleOutputSnapshot | undefined,
221
+ ): boolean | undefined {
222
+ if (!outputPath) return undefined;
223
+ const inspected = inspectSingleOutputChange(outputPath, beforeRun);
224
+ return inspected.error ? undefined : inspected.changed;
225
+ }
226
+
158
227
  function persistSingleOutput(
159
228
  outputPath: string | undefined,
160
229
  fullOutput: string,
161
- ): { savedPath?: string; error?: string } {
230
+ expectedClaimPath?: string,
231
+ ): { savedPath?: string; error?: string; fatalError?: boolean } {
162
232
  if (!outputPath) return {};
163
233
  try {
234
+ const claimError = outputClaimError(outputPath, expectedClaimPath);
235
+ if (claimError) return { error: claimError, fatalError: true };
164
236
  fs.mkdirSync(path.dirname(outputPath), { recursive: true });
165
237
  fs.writeFileSync(outputPath, fullOutput, "utf-8");
166
238
  return { savedPath: outputPath };
@@ -173,26 +245,21 @@ export function resolveSingleOutput(
173
245
  outputPath: string | undefined,
174
246
  fallbackOutput: string,
175
247
  beforeRun: SingleOutputSnapshot | undefined,
176
- ): { fullOutput: string; savedPath?: string; saveError?: string } {
248
+ expectedClaimPath?: string,
249
+ ): { fullOutput: string; savedPath?: string; saveError?: string; fatalError?: boolean } {
177
250
  if (!outputPath) return { fullOutput: fallbackOutput };
251
+ const claimError = outputClaimError(outputPath, expectedClaimPath);
252
+ if (claimError) return { fullOutput: fallbackOutput, saveError: claimError, fatalError: true };
178
253
 
179
- let changedSinceStart = false;
180
- try {
181
- const stat = fs.statSync(outputPath);
182
- changedSinceStart = !beforeRun?.exists
183
- || stat.mtimeMs !== beforeRun.mtimeMs
184
- || stat.size !== beforeRun.size;
185
- } catch (error) {
186
- const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined;
187
- if (code !== "ENOENT" && code !== "ENOTDIR") {
188
- return {
189
- fullOutput: fallbackOutput,
190
- saveError: `Failed to inspect output file: ${error instanceof Error ? error.message : String(error)}`,
191
- };
192
- }
254
+ const changedSinceStart = inspectSingleOutputChange(outputPath, beforeRun);
255
+ if (changedSinceStart.error) {
256
+ return {
257
+ fullOutput: fallbackOutput,
258
+ saveError: `Failed to inspect output file: ${changedSinceStart.error}`,
259
+ };
193
260
  }
194
261
 
195
- if (changedSinceStart) {
262
+ if (changedSinceStart.changed) {
196
263
  try {
197
264
  return { fullOutput: fs.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
198
265
  } catch (error) {
@@ -203,9 +270,9 @@ export function resolveSingleOutput(
203
270
  }
204
271
  }
205
272
 
206
- const save = persistSingleOutput(outputPath, fallbackOutput);
273
+ const save = persistSingleOutput(outputPath, fallbackOutput, expectedClaimPath);
207
274
  if (save.savedPath) return { fullOutput: fallbackOutput, savedPath: save.savedPath };
208
- return { fullOutput: fallbackOutput, saveError: save.error };
275
+ return { fullOutput: fallbackOutput, saveError: save.error, ...(save.fatalError ? { fatalError: true } : {}) };
209
276
  }
210
277
 
211
278
  export function finalizeSingleOutput(params: {