@xzzpig/pi-subagents 0.7.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  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 +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -0,0 +1,129 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { parseExternalCliJsonlEvent, type ExternalCliParser, type ExternalCliParserProgress, type ExternalCliParserTerminal } from "./external-cli-runner.ts";
4
+ import type { ExternalCliPreflightSpec } from "./external-cli-preflight.ts";
5
+
6
+ const MAX_FINAL_MESSAGE_BYTES = 1024 * 1024;
7
+ const MAX_EVENT_TYPE_LENGTH = 128;
8
+
9
+ export const CODEX_EXEC_ADAPTER_ID = "codex-exec" as const;
10
+ export const CODEX_EXEC_WRITER_ADAPTER_ID = "codex-exec-writer" as const;
11
+ export const CODEX_EXEC_ENV_ALLOWLIST = [
12
+ "PATH",
13
+ "HOME",
14
+ "USERPROFILE",
15
+ "CODEX_HOME",
16
+ "CODEX_API_KEY",
17
+ "OPENAI_API_KEY",
18
+ "HTTP_PROXY",
19
+ "HTTPS_PROXY",
20
+ "NO_PROXY",
21
+ "http_proxy",
22
+ "https_proxy",
23
+ "no_proxy",
24
+ "SSL_CERT_FILE",
25
+ "SSL_CERT_DIR",
26
+ ] as const;
27
+
28
+ function eventError(event: Record<string, unknown>, fallback: string): string {
29
+ const error = event.error;
30
+ if (typeof error === "string" && error.trim()) return error.trim().slice(0, 4_096);
31
+ if (error && typeof error === "object" && !Array.isArray(error)) {
32
+ const message = (error as Record<string, unknown>).message;
33
+ if (typeof message === "string" && message.trim()) return message.trim().slice(0, 4_096);
34
+ }
35
+ const message = event.message;
36
+ return typeof message === "string" && message.trim() ? message.trim().slice(0, 4_096) : fallback;
37
+ }
38
+
39
+ export function createCodexExecJsonlParser(finalMessagePath: string): ExternalCliParser {
40
+ let eventCount = 0;
41
+ let terminal: ExternalCliParserTerminal | undefined;
42
+ return {
43
+ parseLine(line): ExternalCliParserProgress {
44
+ const event = parseExternalCliJsonlEvent(line, "Codex exec", MAX_EVENT_TYPE_LENGTH);
45
+ if (terminal) throw new Error("Codex exec emitted an event after its terminal state.");
46
+ eventCount += 1;
47
+ if (event.type === "turn.completed") terminal = { state: "completed" };
48
+ else if (event.type === "turn.failed") terminal = { state: "failed", error: eventError(event, "Codex exec reported turn.failed.") };
49
+ else if (event.type === "error") terminal = { state: "failed", error: eventError(event, "Codex exec reported an error event.") };
50
+ return { phase: terminal ? terminal.state : "streaming", eventCount };
51
+ },
52
+ finish(): ExternalCliParserTerminal | undefined {
53
+ if (!terminal || terminal.state === "failed") return terminal;
54
+ let descriptor: number;
55
+ try { descriptor = fs.openSync(finalMessagePath, "r"); }
56
+ catch (error) { throw new Error(`Codex exec did not write its final-message artifact: ${error instanceof Error ? error.message : String(error)}`); }
57
+ try {
58
+ const stat = fs.fstatSync(descriptor);
59
+ if (!stat.isFile()) throw new Error("Codex exec final-message artifact is not a file.");
60
+ if (stat.size > MAX_FINAL_MESSAGE_BYTES) throw new Error("Codex exec final-message artifact exceeded its byte limit.");
61
+ const content = Buffer.alloc(stat.size);
62
+ let bytesRead = 0;
63
+ while (bytesRead < content.length) {
64
+ const count = fs.readSync(descriptor, content, bytesRead, content.length - bytesRead, bytesRead);
65
+ if (count === 0) break;
66
+ bytesRead += count;
67
+ }
68
+ const output = content.subarray(0, bytesRead).toString("utf-8").trim();
69
+ if (!output) throw new Error("Codex exec final-message artifact is empty.");
70
+ return { state: "completed", output };
71
+ } finally { fs.closeSync(descriptor); }
72
+ },
73
+ };
74
+ }
75
+
76
+ export function resolveCodexExecLaunch(input: {
77
+ adapter: typeof CODEX_EXEC_ADAPTER_ID | typeof CODEX_EXEC_WRITER_ADAPTER_ID;
78
+ command: string;
79
+ asyncDir: string;
80
+ stepIndex: number;
81
+ /** Test-only executable prefix for a fake Codex process. */
82
+ commandPrefixArgs?: readonly string[];
83
+ }): {
84
+ command: string;
85
+ args: string[];
86
+ finalOutputPath: string;
87
+ promptFilePath?: undefined;
88
+ temporaryDirectories?: undefined;
89
+ environment: { allowlist: readonly string[] };
90
+ preflight: ExternalCliPreflightSpec;
91
+ parser: ExternalCliParser;
92
+ } {
93
+ const writer = input.adapter === CODEX_EXEC_WRITER_ADAPTER_ID;
94
+ const finalMessagePath = path.join(input.asyncDir, `external-${input.stepIndex}.final-message.txt`);
95
+ fs.rmSync(finalMessagePath, { force: true });
96
+ const prefix = [...(input.commandPrefixArgs ?? [])];
97
+ const args = [
98
+ ...prefix,
99
+ "exec",
100
+ "--json",
101
+ "--color", "never",
102
+ "--ephemeral",
103
+ "--ignore-user-config",
104
+ "--ignore-rules",
105
+ "--skip-git-repo-check",
106
+ "-s", writer ? "workspace-write" : "read-only",
107
+ "-c", 'approval_policy="never"',
108
+ "--output-last-message", finalMessagePath,
109
+ "-",
110
+ ];
111
+ return {
112
+ command: input.command,
113
+ args,
114
+ finalOutputPath: finalMessagePath,
115
+ environment: { allowlist: CODEX_EXEC_ENV_ALLOWLIST },
116
+ preflight: {
117
+ id: input.adapter,
118
+ versionArgs: [...prefix, "--version"],
119
+ helpArgs: [...prefix, "exec", "--help"],
120
+ validate(result) {
121
+ if (!/^codex-cli \d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(result.version)) throw new Error(`Unsupported Codex version response: ${JSON.stringify(result.version)}.`);
122
+ for (const required of ["Run Codex non-interactively", "--json", "--output-last-message", "--ephemeral", "--ignore-user-config", "--ignore-rules", "--skip-git-repo-check", "--sandbox", writer ? "workspace-write" : "read-only", "--config"]) {
123
+ if (!result.help.includes(required)) throw new Error(`Codex exec help does not document required option ${JSON.stringify(required)}.`);
124
+ }
125
+ },
126
+ },
127
+ parser: createCodexExecJsonlParser(finalMessagePath),
128
+ };
129
+ }
@@ -0,0 +1,89 @@
1
+ import type {
2
+ FileMutationEffect,
3
+ SettlementDiagnostic,
4
+ TrackedMutationEvidence,
5
+ } from "../../shared/types.ts";
6
+ import type { CompletionMutationGuardResult } from "./completion-guard.ts";
7
+
8
+ export const MISSING_IMPLEMENTATION_MUTATION_MESSAGE = "Subagent completed without making edits for an implementation task.";
9
+ export const MISSING_IMPLEMENTATION_MUTATION_ERROR = `${MISSING_IMPLEMENTATION_MUTATION_MESSAGE}\nIt appears to have returned planning or scratchpad output instead of applying changes.`;
10
+
11
+ export interface CompletionEvidencePlan {
12
+ guardTriggered: boolean;
13
+ guardBlocked: boolean;
14
+ mutationExpected: boolean;
15
+ mutationAttempted: boolean;
16
+ fileMutation?: FileMutationEffect;
17
+ legacyFailureError?: string;
18
+ }
19
+
20
+ export function planCompletionEvidence(input: {
21
+ guard?: CompletionMutationGuardResult;
22
+ guardTriggered?: boolean;
23
+ completionGuardEnabled: boolean;
24
+ mutationCapable: boolean;
25
+ implementationMutationExpected: boolean;
26
+ mutationAttemptObserved: boolean;
27
+ mutationEvidence?: TrackedMutationEvidence;
28
+ arbiterRescued?: boolean;
29
+ agentContractV1: boolean;
30
+ }): CompletionEvidencePlan {
31
+ const guardBlocked = input.guard?.blocked === true;
32
+ const guardTriggered = input.guardTriggered
33
+ ?? (input.guard?.triggered === true && !input.mutationAttemptObserved);
34
+ const mutationExpected = input.guard?.expectedMutation
35
+ ?? (input.completionGuardEnabled && input.mutationCapable && input.implementationMutationExpected);
36
+ const mutationAttempted = input.guard?.attemptedMutation === true || input.mutationAttemptObserved;
37
+ const fileMutation = input.guard
38
+ ? {
39
+ status: guardBlocked
40
+ ? "blocked" as const
41
+ : input.guard.expectedMutation
42
+ ? guardTriggered
43
+ ? "missing" as const
44
+ : input.arbiterRescued
45
+ ? "not-applicable" as const
46
+ : "observed" as const
47
+ : "not-applicable" as const,
48
+ expected: input.guard.expectedMutation,
49
+ attempted: guardBlocked ? false : mutationAttempted,
50
+ ...(input.mutationEvidence ? { evidence: input.mutationEvidence } : {}),
51
+ ...(guardBlocked && input.guard.message ? { message: input.guard.message } : {}),
52
+ ...(guardTriggered ? { message: MISSING_IMPLEMENTATION_MUTATION_MESSAGE } : {}),
53
+ ...(input.arbiterRescued ? { resolvedBy: "llm-intent-arbiter" as const } : {}),
54
+ }
55
+ : undefined;
56
+ return {
57
+ guardTriggered,
58
+ guardBlocked,
59
+ mutationExpected,
60
+ mutationAttempted,
61
+ fileMutation,
62
+ legacyFailureError: guardTriggered && !input.agentContractV1
63
+ ? MISSING_IMPLEMENTATION_MUTATION_ERROR
64
+ : undefined,
65
+ };
66
+ }
67
+
68
+ export function projectSettlementDiagnostic(
69
+ plan: Pick<CompletionEvidencePlan, "guardTriggered" | "guardBlocked" | "mutationExpected" | "mutationAttempted">,
70
+ input: {
71
+ terminalFailed: boolean;
72
+ finalTextPresent: boolean;
73
+ mutationObserved: boolean;
74
+ requiredOutput?: SettlementDiagnostic["requiredOutput"];
75
+ afterCompactionSettlement?: boolean;
76
+ },
77
+ ): SettlementDiagnostic | undefined {
78
+ if (!input.terminalFailed && !plan.guardTriggered && !plan.guardBlocked) return undefined;
79
+ return {
80
+ finalTextPresent: input.finalTextPresent,
81
+ mutation: {
82
+ expected: plan.mutationExpected,
83
+ attempted: plan.mutationAttempted,
84
+ observed: input.mutationObserved,
85
+ },
86
+ ...(input.requiredOutput ? { requiredOutput: input.requiredOutput } : {}),
87
+ afterCompactionSettlement: input.afterCompactionSettlement === true,
88
+ };
89
+ }
@@ -1,6 +1,7 @@
1
1
  import type { Message } from "@earendil-works/pi-ai";
2
+ import type { AcceptanceRole, TrackedMutationEvidence } from "../../shared/types.ts";
2
3
  import { isMutatingTool } from "./long-running-guard.ts";
3
- import { expectsImplementationMutation } from "./task-intent.ts";
4
+ import { classifyTaskMutationIntent, expectsImplementationMutation, taskMayMutate } from "./task-intent.ts";
4
5
 
5
6
  export { expectsImplementationMutation };
6
7
 
@@ -14,6 +15,7 @@ const READ_ONLY_BUILTIN_TOOLS = new Set([
14
15
  "get_search_content",
15
16
  "intercom",
16
17
  "contact_supervisor",
18
+ "structured_output",
17
19
  ]);
18
20
 
19
21
  // Cursor native edit/write often land as thinking traces (inactive_trace /
@@ -22,7 +24,7 @@ const READ_ONLY_BUILTIN_TOOLS = new Set([
22
24
  const CURSOR_FILE_MUTATION_THINKING =
23
25
  /(?:^|\n)\s*Cursor (?:edit|write)\s*:/i;
24
26
 
25
- const REVIVED_TASK_PREFIX = /^You are reviving a previous subagent conversation\.\n\nOriginal run: .+\nOriginal agent: .+(?:\nOriginal session file: .+)?\n\nUse the stored session context as background\. Answer the orchestrator's follow-up below\. Do not assume the original child process is still alive\.\n\nFollow-up:\n/;
27
+ const REVIVED_TASK_PREFIX = /^You are reviving a previous subagent conversation\.\n\nOriginal run: .+\nOriginal agent: .+(?:\nOriginal session file: .+)?\n\nUse the stored session context as background\. Answer the orchestrator's follow-up below\. Do not assume the original child session is still running\.\n\nFollow-up:\n/;
26
28
  const IMPLEMENTATION_CHALLENGE_FOLLOW_UP_PATTERN = /^(?:Run )?implementation challenge pass (?:one|two|\d+)(?:\s+and implement any better current[- ]scope change\.?|\s+for the accepted candidate\.\s+Reconsider it and implement any better current[- ]scope change\.?)?$/i;
27
29
  const NO_BETTER_CHANGE_NEEDED_PATTERN = /^\s*no (?:better|further|additional) (?:current[- ]scope )?(?:code |source |file )?(?:change|changes|edit|edits|patch|patches) (?:is|are) needed\b/i;
28
30
  const KEPT_CURRENT_IMPLEMENTATION_PATTERN = /\b(?:kept (?:the )?current (?:implementation|candidate|shape)|(?:the )?current (?:implementation|candidate|shape) was kept)\b/i;
@@ -45,12 +47,17 @@ interface CompletionMutationGuardInput {
45
47
  messages: Message[];
46
48
  tools?: string[];
47
49
  mcpDirectTools?: string[];
50
+ mutationTools?: string[];
51
+ toolAvailabilityError?: string;
52
+ mutationEvidence?: TrackedMutationEvidence;
48
53
  }
49
54
 
50
- interface CompletionMutationGuardResult {
55
+ export interface CompletionMutationGuardResult {
51
56
  expectedMutation: boolean;
52
57
  attemptedMutation: boolean;
53
58
  triggered: boolean;
59
+ blocked: boolean;
60
+ message?: string;
54
61
  }
55
62
 
56
63
  interface ReportSentence {
@@ -64,6 +71,40 @@ export function hasMutationToolCapability(tools: string[] | undefined, mcpDirect
64
71
  return !tools.every((tool) => READ_ONLY_BUILTIN_TOOLS.has(tool));
65
72
  }
66
73
 
74
+ function hasBuiltinMutationTool(tools: string[] | undefined): boolean {
75
+ return tools === undefined || tools.some((tool) => !READ_ONLY_BUILTIN_TOOLS.has(tool));
76
+ }
77
+
78
+ function isWriterRole(agent: string, acceptanceRole: AcceptanceRole | undefined): boolean {
79
+ return acceptanceRole === "writer"
80
+ || (acceptanceRole === undefined && /\bworker\b/i.test(agent));
81
+ }
82
+
83
+ const WRITER_DELIVERY_PATTERN = /\b(?:address|resolve|work)\s+(?:backlog\s+)?(?:item|issue)\b|\b(?:land|ship)\s+(?:the\s+)?(?:change|changes|fix|feature|implementation)\b/i;
84
+
85
+ export function validateImplementationToolContract(input: {
86
+ agent: string;
87
+ task: string;
88
+ tools?: string[];
89
+ mcpDirectTools?: string[];
90
+ configuredExtensions?: string[];
91
+ requestedTools?: string[];
92
+ acceptanceRole?: AcceptanceRole;
93
+ completionGuard?: boolean;
94
+ }): string | undefined {
95
+ if (input.completionGuard === false) return undefined;
96
+ const requestedMutationTools = input.requestedTools?.filter((tool) => !READ_ONLY_BUILTIN_TOOLS.has(tool)) ?? [];
97
+ const declaredMutationToolsWereRemoved = requestedMutationTools.length > 0 && !hasBuiltinMutationTool(input.tools);
98
+ const configuredExtensionCapability = (input.configuredExtensions?.length ?? 0) > 0 && !declaredMutationToolsWereRemoved;
99
+ if (hasMutationToolCapability(input.tools, input.mcpDirectTools) || configuredExtensionCapability) return undefined;
100
+ const intent = classifyTaskMutationIntent(input.agent, input.task);
101
+ if (intent.kind === "read-only") return undefined;
102
+ const writerTaskMayMutate = isWriterRole(input.agent, input.acceptanceRole)
103
+ && (taskMayMutate(input.task) || WRITER_DELIVERY_PATTERN.test(input.task));
104
+ if (intent.kind !== "implementation" && !writerTaskMayMutate && !declaredMutationToolsWereRemoved) return undefined;
105
+ return `Agent '${input.agent}' was given an implementation task, but its tool allowlist has no mutation-capable tools. Add bash, edit, write, or another mutation-capable tool to the agent, or use a read-only task/agent.`;
106
+ }
107
+
67
108
  function hasCheckpointMutationEvidence(message: Message): boolean {
68
109
  const record = message as unknown as {
69
110
  role?: string;
@@ -88,7 +129,7 @@ function hasCheckpointMutationEvidence(message: Message): boolean {
88
129
  && data.beforeCommit !== data.afterCommit;
89
130
  }
90
131
 
91
- export function hasMutationToolCall(messages: Message[]): boolean {
132
+ export function hasMutationToolCall(messages: Message[], mutationTools?: readonly string[]): boolean {
92
133
  for (const message of messages) {
93
134
  if (hasCheckpointMutationEvidence(message)) return true;
94
135
  if (message.role !== "assistant") continue;
@@ -98,7 +139,7 @@ export function hasMutationToolCall(messages: Message[]): boolean {
98
139
  const args = typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments)
99
140
  ? part.arguments as Record<string, unknown>
100
141
  : {};
101
- if (isMutatingTool(part.name, args)) return true;
142
+ if (isMutatingTool(part.name, args, mutationTools)) return true;
102
143
  }
103
144
  }
104
145
  return false;
@@ -187,15 +228,25 @@ function reportsNoBetterChallengeChange(messages: Message[]): boolean {
187
228
  }
188
229
 
189
230
  export function evaluateCompletionMutationGuard(input: CompletionMutationGuardInput): CompletionMutationGuardResult {
231
+ if (input.toolAvailabilityError && expectsImplementationMutation(input.agent, input.task)) {
232
+ return {
233
+ expectedMutation: true,
234
+ attemptedMutation: false,
235
+ triggered: false,
236
+ blocked: true,
237
+ message: input.toolAvailabilityError,
238
+ };
239
+ }
190
240
  const expectedMutation = hasMutationToolCapability(input.tools, input.mcpDirectTools)
191
241
  ? expectsImplementationMutation(input.agent, input.task)
192
242
  : false;
193
- const attemptedMutation = hasMutationToolCall(input.messages);
243
+ const attemptedMutation = hasMutationToolCall(input.messages, input.mutationTools) || input.mutationEvidence?.attemptedMutation === true;
194
244
  const noEditChallengeComplete = isImplementationChallengeTask(input.task)
195
245
  && reportsNoBetterChallengeChange(input.messages);
196
246
  return {
197
247
  expectedMutation,
198
248
  attemptedMutation,
199
249
  triggered: expectedMutation && !attemptedMutation && !noEditChallengeComplete,
250
+ blocked: false,
200
251
  };
201
252
  }
@@ -0,0 +1,114 @@
1
+ import * as path from "node:path";
2
+ import { parseExternalCliJsonlEvent, type ExternalCliParser, type ExternalCliParserProgress, type ExternalCliParserTerminal } from "./external-cli-runner.ts";
3
+ import type { ExternalCliPreflightSpec } from "./external-cli-preflight.ts";
4
+
5
+ const MAX_EVENT_TYPE_LENGTH = 128;
6
+ const MAX_ERROR_LENGTH = 4_096;
7
+ const MAX_OVERSIZED_TOOL_CALL_BYTES = 1024 * 1024;
8
+
9
+ export const CURSOR_AGENT_ADAPTER_ID = "cursor-agent" as const;
10
+ export const CURSOR_AGENT_WRITER_ADAPTER_ID = "cursor-agent-writer" as const;
11
+ export const CURSOR_AGENT_ENV_ALLOWLIST = [
12
+ "PATH",
13
+ "HOME",
14
+ "USERPROFILE",
15
+ "CURSOR_API_KEY",
16
+ "HTTP_PROXY",
17
+ "HTTPS_PROXY",
18
+ "NO_PROXY",
19
+ "http_proxy",
20
+ "https_proxy",
21
+ "no_proxy",
22
+ "SSL_CERT_FILE",
23
+ "SSL_CERT_DIR",
24
+ ] as const;
25
+
26
+ function terminalError(event: Record<string, unknown>): string {
27
+ for (const value of [event.result, event.error, event.message]) {
28
+ if (typeof value === "string" && value.trim()) return value.trim().slice(0, MAX_ERROR_LENGTH);
29
+ }
30
+ const subtype = typeof event.subtype === "string" && event.subtype ? event.subtype : "unknown";
31
+ return `Cursor Agent reported terminal result ${subtype}.`;
32
+ }
33
+
34
+ export function createCursorAgentJsonlParser(): ExternalCliParser {
35
+ let eventCount = 0;
36
+ let terminal: ExternalCliParserTerminal | undefined;
37
+ return {
38
+ parseLine(line): ExternalCliParserProgress {
39
+ const event = parseExternalCliJsonlEvent(line, "Cursor Agent", MAX_EVENT_TYPE_LENGTH);
40
+ if (terminal) throw new Error("Cursor Agent emitted an event after its terminal state.");
41
+ eventCount += 1;
42
+ if (event.type === "error") terminal = { state: "failed", error: terminalError(event) };
43
+ else if (event.type === "result") {
44
+ if (event.subtype === "success" && event.is_error === false && typeof event.result === "string" && event.result.trim()) {
45
+ terminal = { state: "completed", output: event.result.trim() };
46
+ } else terminal = { state: "failed", error: terminalError(event) };
47
+ }
48
+ return { phase: terminal ? terminal.state : "streaming", eventCount };
49
+ },
50
+ skipOversizedLine(prefix, byteLength): ExternalCliParserProgress | undefined {
51
+ if (terminal || byteLength > MAX_OVERSIZED_TOOL_CALL_BYTES || !/^\s*\{\s*"type"\s*:\s*"tool_call"\s*,/.test(prefix)) return undefined;
52
+ eventCount += 1;
53
+ return { phase: "streaming", eventCount };
54
+ },
55
+ finish(): ExternalCliParserTerminal | undefined {
56
+ return terminal;
57
+ },
58
+ };
59
+ }
60
+
61
+ export function resolveCursorAgentLaunch(input: {
62
+ adapter: typeof CURSOR_AGENT_ADAPTER_ID | typeof CURSOR_AGENT_WRITER_ADAPTER_ID;
63
+ command: string;
64
+ cwd: string;
65
+ asyncDir: string;
66
+ stepIndex: number;
67
+ /** Test-only executable prefix for a fake Cursor Agent process. */
68
+ commandPrefixArgs?: readonly string[];
69
+ }): {
70
+ command: string;
71
+ args: string[];
72
+ finalOutputPath?: undefined;
73
+ promptFilePath: string;
74
+ temporaryDirectories: string[];
75
+ environment: { allowlist: readonly string[] };
76
+ preflight: ExternalCliPreflightSpec;
77
+ parser: ExternalCliParser;
78
+ } {
79
+ const writer = input.adapter === CURSOR_AGENT_WRITER_ADAPTER_ID;
80
+ const promptDirectory = path.join(input.asyncDir, `external-${input.stepIndex}.cursor-prompt`);
81
+ const promptFilePath = path.join(promptDirectory, "handoff.txt");
82
+ const promptRelative = path.relative(input.cwd, promptDirectory);
83
+ const promptOutsideWorkspace = promptRelative.startsWith("..") || path.isAbsolute(promptRelative);
84
+ const prefix = [...(input.commandPrefixArgs ?? [])];
85
+ const args = [
86
+ ...prefix,
87
+ "-p",
88
+ "--output-format", "stream-json",
89
+ ...(writer ? [] : ["--mode", "ask"]),
90
+ "--sandbox", "enabled",
91
+ "--workspace", input.cwd,
92
+ ...(promptOutsideWorkspace ? ["--add-dir", promptDirectory] : []),
93
+ `Read the complete handoff from the private file at ${promptFilePath}. Follow it and return only the final answer.`,
94
+ ];
95
+ return {
96
+ command: input.command,
97
+ args,
98
+ promptFilePath,
99
+ temporaryDirectories: [promptDirectory],
100
+ environment: { allowlist: CURSOR_AGENT_ENV_ALLOWLIST },
101
+ preflight: {
102
+ id: input.adapter,
103
+ versionArgs: [...prefix, "--version"],
104
+ helpArgs: [...prefix, "--help"],
105
+ validate(result) {
106
+ if (!/^\d{4}\.\d{2}\.\d{2}-[0-9a-f]+$/.test(result.version)) throw new Error(`Unsupported Cursor Agent version response: ${JSON.stringify(result.version)}.`);
107
+ for (const required of ["Start the Cursor Agent", "--print", "stream-json", "--sandbox <mode>", "enabled", "--workspace <path-or-name>", "--add-dir <path>", ...(writer ? ["all tools", "including write and shell"] : ["--mode <mode>", "ask:", "read-only"])]) {
108
+ if (!result.help.includes(required)) throw new Error(`Cursor Agent help does not document required option ${JSON.stringify(required)}.`);
109
+ }
110
+ },
111
+ },
112
+ parser: createCursorAgentJsonlParser(),
113
+ };
114
+ }
@@ -46,12 +46,12 @@ const DYNAMIC_STEP_KEYS = new Set(["expand", "parallel", "collect", "concurrency
46
46
  const RUNNER_DYNAMIC_STEP_KEYS = new Set([...DYNAMIC_STEP_KEYS, "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "sessionFiles", "thinkingOverrides"]);
47
47
  const DYNAMIC_EXPAND_KEYS = new Set(["from", "item", "key", "maxItems", "onEmpty"]);
48
48
  const DYNAMIC_EXPAND_FROM_KEYS = new Set(["output", "path"]);
49
- const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outputSchema", "cwd", "output", "outputMode", "reads", "progress", "skill", "model", "toolBudget", "acceptance", "agentContract", "gateOn"]);
49
+ const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outputSchema", "cwd", "output", "outputMode", "reads", "progress", "skill", "model", "fast", "toolBudget", "acceptance", "agentContract", "gateOn"]);
50
50
  const RUNNER_DYNAMIC_PARALLEL_KEYS = new Set([
51
51
  ...DYNAMIC_PARALLEL_KEYS,
52
- "outputName", "structured", "inheritProjectContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled",
53
- "structuredOutput", "structuredOutputSchema", "tools", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "capabilityCeiling", "completionGuard", "systemPrompt",
54
- "systemPromptMode", "thinking", "modelCandidates", "sessionFile", "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "parentSessionId", "launchResolvedExtensions",
52
+ "outputName", "structured", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled", "waitToolDefaultTimeoutMs",
53
+ "structuredOutput", "structuredOutputSchema", "tools", "excludeTools", "allowNestedSubagents", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "capabilityCeiling", "completionGuard", "systemPrompt",
54
+ "systemPromptMode", "thinking", "modelCandidates", "sessionFile", "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "parentSessionId", "launchResolvedExtensions", "requestedCwd",
55
55
  ]);
56
56
  const DYNAMIC_COLLECT_KEYS = new Set(["as", "outputSchema"]);
57
57
 
@@ -0,0 +1,78 @@
1
+ export const PI_SUBAGENT_EXTENSION_BINDINGS_ENV = "PI_SUBAGENT_EXTENSION_BINDINGS";
2
+ export const MAX_EXTENSION_BINDING_NAMESPACES = 16;
3
+ export const MAX_EXTENSION_BINDINGS_BYTES = 16 * 1024;
4
+ export const MAX_EXTENSION_BINDINGS_DEPTH = 16;
5
+ export const MAX_EXTENSION_BINDINGS_PROPERTIES = 256;
6
+
7
+ const EXTENSION_BINDING_NAMESPACE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]{0,62})\/[1-9][0-9]{0,8}$/;
8
+
9
+ export type ExtensionBindingJson = null | boolean | number | string | ReadonlyArray<ExtensionBindingJson> | { readonly [key: string]: ExtensionBindingJson };
10
+ export type ExtensionBindings = Readonly<Record<string, ExtensionBindingJson>>;
11
+
12
+ export interface NormalizedExtensionBindings {
13
+ value: ExtensionBindings;
14
+ json: string;
15
+ }
16
+
17
+ function canonicalizeJson(value: unknown, path: string, depth: number, seen: Set<object>, propertyCount: { value: number }): ExtensionBindingJson {
18
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
19
+ if (typeof value === "number") {
20
+ if (!Number.isFinite(value)) throw new Error(`${path} must contain only finite JSON numbers.`);
21
+ return value;
22
+ }
23
+ if (typeof value !== "object") throw new Error(`${path} must contain only plain JSON values.`);
24
+ if (depth > MAX_EXTENSION_BINDINGS_DEPTH) throw new Error(`${path} exceeds the maximum nesting depth of ${MAX_EXTENSION_BINDINGS_DEPTH}.`);
25
+ if (seen.has(value)) throw new Error(`${path} must not contain cycles.`);
26
+ seen.add(value);
27
+ try {
28
+ if (Array.isArray(value)) {
29
+ const output: ExtensionBindingJson[] = [];
30
+ for (let index = 0; index < value.length; index++) {
31
+ if (!Object.prototype.hasOwnProperty.call(value, index)) throw new Error(`${path} must not contain sparse arrays.`);
32
+ output.push(canonicalizeJson(value[index], `${path}[${index}]`, depth + 1, seen, propertyCount));
33
+ }
34
+ return Object.freeze(output);
35
+ }
36
+ const prototype = Object.getPrototypeOf(value);
37
+ if (prototype !== Object.prototype && prototype !== null) throw new Error(`${path} must contain only plain JSON objects.`);
38
+ if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path} must not contain symbol keys.`);
39
+ const descriptors = Object.getOwnPropertyDescriptors(value);
40
+ const output: Record<string, ExtensionBindingJson> = {};
41
+ for (const key of Object.keys(descriptors).sort()) {
42
+ const descriptor = descriptors[key]!;
43
+ if (!descriptor.enumerable || !("value" in descriptor)) throw new Error(`${path}.${key} must be an enumerable data property.`);
44
+ propertyCount.value += 1;
45
+ if (propertyCount.value > MAX_EXTENSION_BINDINGS_PROPERTIES) throw new Error(`extensionBindings exceeds ${MAX_EXTENSION_BINDINGS_PROPERTIES} total properties.`);
46
+ Object.defineProperty(output, key, { value: canonicalizeJson(descriptor.value, `${path}.${key}`, depth + 1, seen, propertyCount), enumerable: true, writable: false, configurable: false });
47
+ }
48
+ return Object.freeze(output);
49
+ } finally {
50
+ seen.delete(value);
51
+ }
52
+ }
53
+
54
+ export function normalizeExtensionBindings(input: unknown): NormalizedExtensionBindings | undefined {
55
+ if (input === undefined) return undefined;
56
+ if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("extensionBindings must be a plain JSON object.");
57
+ const prototype = Object.getPrototypeOf(input);
58
+ if (prototype !== Object.prototype && prototype !== null) throw new Error("extensionBindings must be a plain JSON object.");
59
+ const keys = Object.keys(input);
60
+ if (keys.length > MAX_EXTENSION_BINDING_NAMESPACES) throw new Error(`extensionBindings supports at most ${MAX_EXTENSION_BINDING_NAMESPACES} namespaces.`);
61
+ for (const key of keys) {
62
+ if (!EXTENSION_BINDING_NAMESPACE.test(key)) throw new Error(`extensionBindings namespace '${key}' must use a package-like name followed by '/<positive-version>'.`);
63
+ }
64
+ const value = canonicalizeJson(input, "extensionBindings", 0, new Set(), { value: 0 }) as ExtensionBindings;
65
+ const json = JSON.stringify(value);
66
+ const bytes = Buffer.byteLength(json, "utf8");
67
+ if (bytes > MAX_EXTENSION_BINDINGS_BYTES) throw new Error(`extensionBindings canonical JSON is ${bytes} bytes; maximum is ${MAX_EXTENSION_BINDINGS_BYTES}.`);
68
+ return { value, json };
69
+ }
70
+
71
+ export function encodeExtensionBindings(input: ExtensionBindings | undefined): string | undefined {
72
+ return input === undefined ? undefined : normalizeExtensionBindings(input)!.json;
73
+ }
74
+
75
+ export function omitExtensionBindingsEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
76
+ const { [PI_SUBAGENT_EXTENSION_BINDINGS_ENV]: _extensionBindings, ...sanitized } = env;
77
+ return sanitized;
78
+ }