@xzzpig/pi-subagents 0.8.0 → 0.9.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 (218) hide show
  1. package/CHANGELOG.md +443 -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 +151 -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 +5 -4
  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 +370 -114
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +12 -2
  35. package/src/agents/agents.ts +919 -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 +31 -20
  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 +48 -18
  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 +57 -21
  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 +2 -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 +366 -128
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +45 -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 +189 -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 +676 -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 +468 -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 +1172 -400
  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 +314 -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 +342 -0
  115. package/src/runs/shared/child-tool-plan.ts +540 -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 +142 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +38 -48
  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 +15 -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/single-output.ts +89 -22
  149. package/src/runs/shared/structured-output.ts +49 -9
  150. package/src/runs/shared/subagent-control.ts +6 -2
  151. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  152. package/src/runs/shared/task-intent.ts +21 -7
  153. package/src/runs/shared/tool-availability.ts +18 -62
  154. package/src/runs/shared/tool-budget.ts +0 -14
  155. package/src/runs/shared/tool-timeout.ts +1 -1
  156. package/src/runs/shared/workflow-graph.ts +16 -0
  157. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  158. package/src/runs/shared/worktree.ts +571 -62
  159. package/src/shared/atomic-json.ts +3 -1
  160. package/src/shared/child-session-name.ts +46 -0
  161. package/src/shared/extension-context.ts +24 -0
  162. package/src/shared/fork-context.ts +21 -12
  163. package/src/shared/fork-session-cwd.ts +27 -0
  164. package/src/shared/formatters.ts +18 -3
  165. package/src/shared/jsonl-writer.ts +11 -0
  166. package/src/shared/launch-contract.ts +8 -1
  167. package/src/shared/pruned-fork.ts +450 -0
  168. package/src/shared/session-file-trust.ts +19 -0
  169. package/src/shared/session-tokens.ts +14 -3
  170. package/src/shared/settings.ts +19 -105
  171. package/src/shared/shortcuts.ts +17 -0
  172. package/src/shared/thinking-ceiling.ts +0 -6
  173. package/src/shared/types.ts +524 -70
  174. package/src/shared/utils.ts +60 -93
  175. package/src/shared/workflow-child-permit.ts +207 -0
  176. package/src/slash/delegation-adapters.ts +1 -9
  177. package/src/slash/delegation-request.ts +0 -4
  178. package/src/slash/prompt-template-bridge.ts +37 -1
  179. package/src/slash/slash-bridge.ts +1 -2
  180. package/src/slash/slash-commands.ts +383 -116
  181. package/src/slash/slash-live-state.ts +22 -11
  182. package/src/slash/subagents-admin.ts +29 -12
  183. package/src/tui/fleet-native-transcript.ts +4 -0
  184. package/src/tui/fleet-status.ts +217 -82
  185. package/src/tui/fleet-transcript.ts +11 -5
  186. package/src/tui/fleet.ts +54 -28
  187. package/src/tui/render-helpers.ts +31 -0
  188. package/src/tui/render.ts +1429 -163
  189. package/src/watchdog/change-signature.ts +40 -1
  190. package/src/watchdog/child-status.ts +54 -34
  191. package/src/watchdog/diff-tool.ts +77 -0
  192. package/src/watchdog/emission-guard.ts +5 -3
  193. package/src/watchdog/guidance.ts +20 -0
  194. package/src/watchdog/register-child.ts +28 -25
  195. package/src/watchdog/register-main.ts +10 -9
  196. package/src/watchdog/render.ts +4 -5
  197. package/src/watchdog/review.ts +15 -4
  198. package/src/watchdog/rules.ts +70 -0
  199. package/src/watchdog/runtime.ts +75 -92
  200. package/src/watchdog/scope.ts +0 -11
  201. package/src/watchdog/settings.ts +48 -104
  202. package/src/watchdog/turn-delta.ts +1 -1
  203. package/src/watchdog/types.ts +18 -32
  204. package/src/watchdog/warning-format.ts +0 -1
  205. package/src/workflows/chat-progress.ts +7 -3
  206. package/src/workflows/host-command.ts +235 -0
  207. package/src/workflows/scripted-workflow.ts +988 -59
  208. package/src/workflows/workflow-checklist.ts +439 -0
  209. package/src/workflows/workflow-child-summary.ts +121 -0
  210. package/src/workflows/workflow-preflight.ts +297 -0
  211. package/src/workflows/workflow-receipt.ts +232 -6
  212. package/src/workflows/workflow-resources.ts +150 -0
  213. package/src/workflows/workflow-settlement.ts +246 -0
  214. package/src/runs/shared/child-protocol.ts +0 -401
  215. package/src/runs/shared/pi-args.ts +0 -935
  216. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  217. package/src/runs/shared/turn-budget.ts +0 -98
  218. 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
- }
@@ -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: {
@@ -5,17 +5,17 @@ import * as path from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
7
7
  import type { JsonSchemaObject } from "../../shared/types.ts";
8
+ import type { ResolvedAcceptanceReportMode } from "./acceptance.ts";
8
9
 
9
- export const STRUCTURED_OUTPUT_SCHEMA_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA";
10
- export const STRUCTURED_OUTPUT_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";
11
- export const STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_ACCEPTANCE_CAPTURE";
12
10
  export const MISSING_STRUCTURED_OUTPUT_CALL_ERROR = "Missing structured_output call; this step has outputSchema and must finish by calling structured_output.";
11
+ export const MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR = "Missing acceptanceReport in structured_output call; acceptance.report is \"on\".";
13
12
 
14
13
  export interface StructuredOutputRuntime {
15
14
  schema: JsonSchemaObject;
16
15
  schemaPath: string;
17
16
  outputPath: string;
18
17
  acceptanceReportPath?: string;
18
+ acceptanceReportRequired?: boolean;
19
19
  }
20
20
 
21
21
  const SCHEMA_MAP_KEYWORDS = ["properties", "patternProperties", "$defs", "definitions", "dependentSchemas"] as const;
@@ -61,14 +61,14 @@ function rewriteLocalJsonPointerRefs(schema: unknown, pointerPrefix: string, inh
61
61
  return rewritten;
62
62
  }
63
63
 
64
- export function createStructuredOutputToolParameters(schema: JsonSchemaObject, options: { acceptanceReport?: boolean } = {}): JsonSchemaObject {
64
+ export function createStructuredOutputToolParameters(schema: JsonSchemaObject, options: { acceptanceReport?: "optional" | "required" } = {}): JsonSchemaObject {
65
65
  return {
66
66
  type: "object",
67
67
  properties: {
68
68
  value: rewriteLocalJsonPointerRefs(schema, "#/properties/value"),
69
69
  ...(options.acceptanceReport ? { acceptanceReport: { type: "object" } } : {}),
70
70
  },
71
- required: ["value"],
71
+ required: ["value", ...(options.acceptanceReport === "required" ? ["acceptanceReport"] : [])],
72
72
  additionalProperties: false,
73
73
  };
74
74
  }
@@ -129,7 +129,7 @@ export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"):
129
129
  }
130
130
  }
131
131
 
132
- export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string, options: { captureAcceptanceReport?: boolean } = {}): StructuredOutputRuntime {
132
+ export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string, options: { acceptanceReport?: ResolvedAcceptanceReportMode } = {}): StructuredOutputRuntime {
133
133
  assertJsonSchemaObject(schema);
134
134
  const rootDir = baseDir ?? os.tmpdir();
135
135
  fs.mkdirSync(rootDir, { recursive: true });
@@ -137,7 +137,14 @@ export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?
137
137
  const schemaPath = path.join(dir, "schema.json");
138
138
  const outputPath = path.join(dir, "output.json");
139
139
  fs.writeFileSync(schemaPath, JSON.stringify(schema), { mode: 0o600 });
140
- return { schema, schemaPath, outputPath, ...(options.captureAcceptanceReport ? { acceptanceReportPath: path.join(dir, "acceptance-report.json") } : {}) };
140
+ return {
141
+ schema,
142
+ schemaPath,
143
+ outputPath,
144
+ ...(options.acceptanceReport && options.acceptanceReport !== "off"
145
+ ? { acceptanceReportPath: path.join(dir, "acceptance-report.json"), acceptanceReportRequired: options.acceptanceReport === "required" }
146
+ : {}),
147
+ };
141
148
  }
142
149
 
143
150
  export async function validateStructuredOutputValue(schema: JsonSchemaObject, value: unknown): Promise<{ status: "valid" } | { status: "invalid"; message: string }> {
@@ -178,14 +185,47 @@ export async function readStructuredOutput(runtime: StructuredOutputRuntime): Pr
178
185
  }
179
186
 
180
187
  export function readStructuredOutputAcceptanceReport(runtime: StructuredOutputRuntime): { value?: unknown; error?: string } {
181
- if (!runtime.acceptanceReportPath || !fs.existsSync(runtime.acceptanceReportPath)) return {};
188
+ if (!runtime.acceptanceReportPath) return {};
189
+ if (!fs.existsSync(runtime.acceptanceReportPath)) {
190
+ return runtime.acceptanceReportRequired ? { error: MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR } : {};
191
+ }
182
192
  try {
183
- return { value: JSON.parse(fs.readFileSync(runtime.acceptanceReportPath, "utf-8")) };
193
+ return { value: JSON.parse(fs.readFileSync(runtime.acceptanceReportPath, "utf-8")) as unknown };
184
194
  } catch (error) {
185
195
  return { error: `Failed to read structured output acceptance report: ${error instanceof Error ? error.message : String(error)}` };
186
196
  }
187
197
  }
188
198
 
199
+ /**
200
+ * Capture callback that persists the structured output (and acceptance report)
201
+ * to the runtime's files, for hosts that read the value back from disk.
202
+ */
203
+ export function createStructuredOutputFileCapture(runtime: StructuredOutputRuntime): (value: unknown, acceptanceReport: unknown | undefined) => void {
204
+ return (value, acceptanceReport) => {
205
+ fs.mkdirSync(path.dirname(runtime.outputPath), { recursive: true });
206
+ if (runtime.acceptanceReportPath && acceptanceReport !== undefined) {
207
+ fs.mkdirSync(path.dirname(runtime.acceptanceReportPath), { recursive: true });
208
+ fs.writeFileSync(runtime.acceptanceReportPath, JSON.stringify(acceptanceReport), { mode: 0o600 });
209
+ } else if (runtime.acceptanceReportPath && fs.existsSync(runtime.acceptanceReportPath)) {
210
+ fs.unlinkSync(runtime.acceptanceReportPath);
211
+ }
212
+ fs.writeFileSync(runtime.outputPath, JSON.stringify(value), { mode: 0o600 });
213
+ };
214
+ }
215
+
216
+ export function clearStructuredOutputCaptures(runtime: StructuredOutputRuntime): string | undefined {
217
+ let cleanupError: string | undefined;
218
+ for (const filePath of [runtime.outputPath, runtime.acceptanceReportPath]) {
219
+ if (!filePath) continue;
220
+ try {
221
+ if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
222
+ } catch (error) {
223
+ cleanupError ??= `Failed to clear stale structured output capture ${filePath}: ${error instanceof Error ? error.message : String(error)}`;
224
+ }
225
+ }
226
+ return cleanupError;
227
+ }
228
+
189
229
  export function cleanupStructuredOutputRuntime(runtime: StructuredOutputRuntime | undefined): void {
190
230
  if (!runtime) return;
191
231
  try {
@@ -45,11 +45,12 @@ export function resolveControlConfig(
45
45
  const enabled = override?.enabled ?? globalConfig?.enabled ?? DEFAULT_CONTROL_CONFIG.enabled;
46
46
  const overrideNeedsAttentionAfterMs = parsePositiveInt(override?.needsAttentionAfterMs);
47
47
  const globalNeedsAttentionAfterMs = parsePositiveInt(globalConfig?.needsAttentionAfterMs);
48
+ const globalNeedsAttentionAfterMsIsExplicit = (globalConfig as Partial<ResolvedControlConfig> | undefined)?.needsAttentionAfterMsIsExplicit ?? globalNeedsAttentionAfterMs !== undefined;
48
49
  const needsAttentionAfterMs = overrideNeedsAttentionAfterMs
49
50
  ?? globalNeedsAttentionAfterMs
50
51
  ?? DEFAULT_CONTROL_CONFIG.needsAttentionAfterMs;
51
52
  const needsAttentionAfterMsIsExplicit = overrideNeedsAttentionAfterMs !== undefined
52
- || globalNeedsAttentionAfterMs !== undefined;
53
+ || globalNeedsAttentionAfterMsIsExplicit;
53
54
  const activeNoticeAfterMs = parsePositiveInt(override?.activeNoticeAfterMs)
54
55
  ?? parsePositiveInt(globalConfig?.activeNoticeAfterMs)
55
56
  ?? DEFAULT_CONTROL_CONFIG.activeNoticeAfterMs;
@@ -98,11 +99,12 @@ export function deriveActivityState(input: {
98
99
  config: ResolvedControlConfig;
99
100
  startedAt: number;
100
101
  lastActivityAt?: number;
102
+ turnCount?: number;
101
103
  currentTool?: string;
102
104
  thinking?: string | false;
103
105
  now?: number;
104
106
  }): ActivityState | undefined {
105
- if (!input.config.enabled || input.currentTool) return undefined;
107
+ if (!input.config.enabled || input.currentTool || (input.turnCount ?? 0) === 0) return undefined;
106
108
  const now = input.now ?? Date.now();
107
109
  const lastActivity = input.lastActivityAt ?? input.startedAt;
108
110
  const ageMs = Math.max(0, now - lastActivity);
@@ -136,6 +138,7 @@ export function buildControlEvent(input: {
136
138
  tokens?: number;
137
139
  toolCount?: number;
138
140
  currentTool?: string;
141
+ toolCallId?: string;
139
142
  currentToolDurationMs?: number;
140
143
  currentPath?: string;
141
144
  elapsedMs?: number;
@@ -168,6 +171,7 @@ export function buildControlEvent(input: {
168
171
  ...(input.tokens !== undefined ? { tokens: input.tokens } : {}),
169
172
  ...(input.toolCount !== undefined ? { toolCount: input.toolCount } : {}),
170
173
  ...(input.currentTool ? { currentTool: input.currentTool } : {}),
174
+ ...(input.toolCallId ? { toolCallId: input.toolCallId } : {}),
171
175
  ...(input.currentToolDurationMs !== undefined ? { currentToolDurationMs: input.currentToolDurationMs } : {}),
172
176
  ...(input.currentPath ? { currentPath: input.currentPath } : {}),
173
177
  ...(elapsedMs !== undefined ? { elapsedMs } : {}),