@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
@@ -0,0 +1,133 @@
1
+ import { parseExternalCliJsonlEvent, type ExternalCliParser, type ExternalCliParserProgress, type ExternalCliParserTerminal } from "./external-cli-runner.ts";
2
+ import type { ExternalCliPreflightSpec } from "./external-cli-preflight.ts";
3
+
4
+ const MAX_EVENT_TYPE_LENGTH = 128;
5
+ const MAX_ERROR_LENGTH = 4_096;
6
+
7
+ export const CLAUDE_CODE_ADAPTER_ID = "claude-code" as const;
8
+ export const CLAUDE_CODE_WRITER_ADAPTER_ID = "claude-code-writer" as const;
9
+ export const CLAUDE_CODE_WRITER_TOOLS = "Read,Write,Edit,Glob,Grep" as const;
10
+ export const CLAUDE_CODE_ENV_ALLOWLIST = [
11
+ "PATH",
12
+ "HOME",
13
+ "USERPROFILE",
14
+ "USER",
15
+ "LOGNAME",
16
+ "TMPDIR",
17
+ "CLAUDE_CONFIG_DIR",
18
+ "ANTHROPIC_API_KEY",
19
+ "ANTHROPIC_AUTH_TOKEN",
20
+ "ANTHROPIC_BASE_URL",
21
+ "CLAUDE_CODE_OAUTH_TOKEN",
22
+ "CLAUDE_CODE_USE_BEDROCK",
23
+ "CLAUDE_CODE_USE_VERTEX",
24
+ "CLAUDE_CODE_USE_FOUNDRY",
25
+ "AWS_PROFILE",
26
+ "AWS_REGION",
27
+ "AWS_DEFAULT_REGION",
28
+ "AWS_ACCESS_KEY_ID",
29
+ "AWS_SECRET_ACCESS_KEY",
30
+ "AWS_SESSION_TOKEN",
31
+ "AWS_BEARER_TOKEN_BEDROCK",
32
+ "GOOGLE_APPLICATION_CREDENTIALS",
33
+ "CLOUD_ML_REGION",
34
+ "ANTHROPIC_VERTEX_PROJECT_ID",
35
+ "HTTP_PROXY",
36
+ "HTTPS_PROXY",
37
+ "NO_PROXY",
38
+ "http_proxy",
39
+ "https_proxy",
40
+ "no_proxy",
41
+ "SSL_CERT_FILE",
42
+ "SSL_CERT_DIR",
43
+ ] as const;
44
+
45
+ function terminalError(event: Record<string, unknown>): string {
46
+ for (const value of [event.error, event.result]) {
47
+ if (typeof value === "string" && value.trim()) return value.trim().slice(0, MAX_ERROR_LENGTH);
48
+ }
49
+ if (Array.isArray(event.errors)) {
50
+ const messages = event.errors.filter((value): value is string => typeof value === "string" && Boolean(value.trim()));
51
+ if (messages.length > 0) return messages.join("; ").slice(0, MAX_ERROR_LENGTH);
52
+ }
53
+ const subtype = typeof event.subtype === "string" && event.subtype ? event.subtype : "unknown";
54
+ return `Claude Code reported terminal result ${subtype}.`;
55
+ }
56
+
57
+ export function createClaudeCodeJsonlParser(): ExternalCliParser {
58
+ let eventCount = 0;
59
+ let terminal: ExternalCliParserTerminal | undefined;
60
+ return {
61
+ parseLine(line): ExternalCliParserProgress {
62
+ const event = parseExternalCliJsonlEvent(line, "Claude Code", MAX_EVENT_TYPE_LENGTH);
63
+ if (terminal && event.type === "result") throw new Error("Claude Code emitted a duplicate terminal result.");
64
+ eventCount += 1;
65
+ if (!terminal && event.type === "result") {
66
+ if (event.subtype === "success" && event.is_error === false && typeof event.result === "string" && event.result.trim()) {
67
+ terminal = { state: "completed", output: event.result.trim() };
68
+ } else {
69
+ terminal = { state: "failed", error: terminalError(event) };
70
+ }
71
+ }
72
+ return { phase: terminal ? terminal.state : "streaming", eventCount };
73
+ },
74
+ finish(): ExternalCliParserTerminal | undefined {
75
+ return terminal;
76
+ },
77
+ };
78
+ }
79
+
80
+ export function resolveClaudeCodeLaunch(input: {
81
+ adapter: typeof CLAUDE_CODE_ADAPTER_ID | typeof CLAUDE_CODE_WRITER_ADAPTER_ID;
82
+ command: string;
83
+ /** Test-only executable prefix for a fake Claude Code process. */
84
+ commandPrefixArgs?: readonly string[];
85
+ }): {
86
+ command: string;
87
+ args: string[];
88
+ finalOutputPath?: undefined;
89
+ promptFilePath?: undefined;
90
+ temporaryDirectories?: undefined;
91
+ environment: { allowlist: readonly string[] };
92
+ preflight: ExternalCliPreflightSpec;
93
+ parser: ExternalCliParser;
94
+ } {
95
+ const writer = input.adapter === CLAUDE_CODE_WRITER_ADAPTER_ID;
96
+ const prefix = [...(input.commandPrefixArgs ?? [])];
97
+ const args = [
98
+ ...prefix,
99
+ "-p",
100
+ "--input-format", "text",
101
+ "--output-format", "stream-json",
102
+ "--verbose",
103
+ "--permission-mode", writer ? "acceptEdits" : "plan",
104
+ "--tools", writer ? CLAUDE_CODE_WRITER_TOOLS : "",
105
+ "--strict-mcp-config",
106
+ "--mcp-config", '{"mcpServers":{}}',
107
+ "--setting-sources", "user",
108
+ "--no-session-persistence",
109
+ "--disable-slash-commands",
110
+ "--no-chrome",
111
+ ];
112
+ return {
113
+ command: input.command,
114
+ args,
115
+ environment: { allowlist: CLAUDE_CODE_ENV_ALLOWLIST },
116
+ preflight: {
117
+ id: input.adapter,
118
+ versionArgs: [...prefix, "--version"],
119
+ helpArgs: [...prefix, "--help"],
120
+ validate(result) {
121
+ // Claude Code now publishes both semver (`2.1.259 (Claude Code)`) and
122
+ // calendar/platform (`2026.4.24 macos-arm64 (2026-04-27)`) versions.
123
+ // The launch flags are validated from --help below, so only require a
124
+ // recognizable release identifier here rather than one display format.
125
+ if (!/^(?:\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)? \(Claude Code\)|\d{4}\.\d{1,2}\.\d{1,2} [A-Za-z0-9._-]+ \(\d{4}-\d{2}-\d{2}\))$/.test(result.version)) throw new Error(`Unsupported Claude Code version response: ${JSON.stringify(result.version)}.`);
126
+ for (const required of ["Claude Code - starts an interactive session", "--print", "--input-format", "stream-json", "--verbose", "--permission-mode", writer ? "acceptEdits" : "plan", "--tools", "--strict-mcp-config", "--mcp-config", "--setting-sources", "--no-session-persistence", "--disable-slash-commands", "--no-chrome"]) {
127
+ if (!result.help.includes(required)) throw new Error(`Claude Code help does not document required option ${JSON.stringify(required)}.`);
128
+ }
129
+ },
130
+ },
131
+ parser: createClaudeCodeJsonlParser(),
132
+ };
133
+ }
@@ -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
+ }
@@ -24,7 +24,7 @@ const READ_ONLY_BUILTIN_TOOLS = new Set([
24
24
  const CURSOR_FILE_MUTATION_THINKING =
25
25
  /(?:^|\n)\s*Cursor (?:edit|write)\s*:/i;
26
26
 
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 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/;
28
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;
29
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;
30
30
  const KEPT_CURRENT_IMPLEMENTATION_PATTERN = /\b(?:kept (?:the )?current (?:implementation|candidate|shape)|(?:the )?current (?:implementation|candidate|shape) was kept)\b/i;
@@ -47,11 +47,12 @@ interface CompletionMutationGuardInput {
47
47
  messages: Message[];
48
48
  tools?: string[];
49
49
  mcpDirectTools?: string[];
50
+ mutationTools?: string[];
50
51
  toolAvailabilityError?: string;
51
52
  mutationEvidence?: TrackedMutationEvidence;
52
53
  }
53
54
 
54
- interface CompletionMutationGuardResult {
55
+ export interface CompletionMutationGuardResult {
55
56
  expectedMutation: boolean;
56
57
  attemptedMutation: boolean;
57
58
  triggered: boolean;
@@ -128,7 +129,7 @@ function hasCheckpointMutationEvidence(message: Message): boolean {
128
129
  && data.beforeCommit !== data.afterCommit;
129
130
  }
130
131
 
131
- export function hasMutationToolCall(messages: Message[]): boolean {
132
+ export function hasMutationToolCall(messages: Message[], mutationTools?: readonly string[]): boolean {
132
133
  for (const message of messages) {
133
134
  if (hasCheckpointMutationEvidence(message)) return true;
134
135
  if (message.role !== "assistant") continue;
@@ -138,7 +139,7 @@ export function hasMutationToolCall(messages: Message[]): boolean {
138
139
  const args = typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments)
139
140
  ? part.arguments as Record<string, unknown>
140
141
  : {};
141
- if (isMutatingTool(part.name, args)) return true;
142
+ if (isMutatingTool(part.name, args, mutationTools)) return true;
142
143
  }
143
144
  }
144
145
  return false;
@@ -239,7 +240,7 @@ export function evaluateCompletionMutationGuard(input: CompletionMutationGuardIn
239
240
  const expectedMutation = hasMutationToolCapability(input.tools, input.mcpDirectTools)
240
241
  ? expectsImplementationMutation(input.agent, input.task)
241
242
  : false;
242
- const attemptedMutation = hasMutationToolCall(input.messages) || input.mutationEvidence?.attemptedMutation === true;
243
+ const attemptedMutation = hasMutationToolCall(input.messages, input.mutationTools) || input.mutationEvidence?.attemptedMutation === true;
243
244
  const noEditChallengeComplete = isImplementationChallengeTask(input.task)
244
245
  && reportsNoBetterChallengeChange(input.messages);
245
246
  return {
@@ -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
+ }
@@ -49,9 +49,9 @@ const DYNAMIC_EXPAND_FROM_KEYS = new Set(["output", "path"]);
49
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