pi-subagents 0.55.0 → 0.57.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 (97) hide show
  1. package/CHANGELOG.md +81 -3
  2. package/agents/claude-code-writer.md +15 -0
  3. package/agents/claude-code.md +15 -0
  4. package/agents/codex-exec-writer.md +15 -0
  5. package/agents/codex-exec.md +15 -0
  6. package/agents/cursor-agent-writer.md +14 -0
  7. package/agents/cursor-agent.md +14 -0
  8. package/docs/agents.md +111 -15
  9. package/docs/configuration.md +37 -0
  10. package/docs/extension-api.md +2 -2
  11. package/docs/models.md +6 -0
  12. package/docs/observability.md +8 -7
  13. package/docs/tool-reference.md +11 -1
  14. package/docs/workflows.md +20 -0
  15. package/package.json +1 -1
  16. package/skills/pi-subagents/references/execution-controls.md +1 -1
  17. package/src/agents/agent-management.ts +13 -5
  18. package/src/agents/agent-refinements.ts +4 -4
  19. package/src/agents/agent-serializer.ts +2 -0
  20. package/src/agents/agents.ts +242 -49
  21. package/src/agents/builtin-names.ts +6 -0
  22. package/src/agents/runtime-agent-registry.ts +8 -2
  23. package/src/api/preflight.ts +22 -3
  24. package/src/extension/config.ts +70 -0
  25. package/src/extension/doctor.ts +3 -3
  26. package/src/extension/index.ts +18 -4
  27. package/src/extension/public-execution.ts +29 -13
  28. package/src/extension/rpc.ts +20 -5
  29. package/src/extension/schemas.ts +9 -3
  30. package/src/extension/tool-description.ts +11 -9
  31. package/src/inspectors/herdr/actions.ts +2 -1
  32. package/src/inspectors/herdr/inspector-runner.ts +2 -10
  33. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  34. package/src/integrations/herdr-status.ts +46 -3
  35. package/src/runs/background/active-async-capacity.ts +77 -10
  36. package/src/runs/background/async-execution.ts +148 -27
  37. package/src/runs/background/async-job-tracker.ts +5 -0
  38. package/src/runs/background/async-resume.ts +3 -0
  39. package/src/runs/background/async-retention.ts +20 -3
  40. package/src/runs/background/async-status.ts +5 -0
  41. package/src/runs/background/chain-root-attachment.ts +15 -1
  42. package/src/runs/background/fleet-view.ts +16 -10
  43. package/src/runs/background/inspect-rpc.ts +8 -8
  44. package/src/runs/background/result-files.ts +27 -14
  45. package/src/runs/background/result-watcher.ts +9 -5
  46. package/src/runs/background/run-status.ts +33 -6
  47. package/src/runs/background/scheduled-runs.ts +7 -1
  48. package/src/runs/background/subagent-runner.ts +254 -49
  49. package/src/runs/background/wait-completions.ts +4 -0
  50. package/src/runs/foreground/execution.ts +107 -16
  51. package/src/runs/foreground/foreground-control.ts +6 -0
  52. package/src/runs/foreground/foreground-history.ts +25 -3
  53. package/src/runs/foreground/subagent-executor.ts +324 -84
  54. package/src/runs/foreground/workflow-detach-reconcile.ts +31 -7
  55. package/src/runs/shared/acceptance.ts +10 -5
  56. package/src/runs/shared/agent-contract.ts +1 -1
  57. package/src/runs/shared/child-protocol.ts +21 -7
  58. package/src/runs/shared/claude-code-adapter.ts +129 -0
  59. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  60. package/src/runs/shared/completion-guard.ts +3 -2
  61. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  62. package/src/runs/shared/dynamic-fanout.ts +1 -1
  63. package/src/runs/shared/extension-bindings.ts +78 -0
  64. package/src/runs/shared/external-cli-contract.ts +167 -0
  65. package/src/runs/shared/external-cli-preflight.ts +122 -0
  66. package/src/runs/shared/external-cli-runner.ts +349 -54
  67. package/src/runs/shared/fast-mode-extension.ts +10 -0
  68. package/src/runs/shared/model-exclusions.ts +59 -8
  69. package/src/runs/shared/model-fallback.ts +25 -8
  70. package/src/runs/shared/mutation-evidence.ts +150 -0
  71. package/src/runs/shared/nested-events.ts +3 -1
  72. package/src/runs/shared/nested-render.ts +2 -2
  73. package/src/runs/shared/parallel-utils.ts +3 -0
  74. package/src/runs/shared/pi-args.ts +47 -0
  75. package/src/runs/shared/process-signal.ts +13 -0
  76. package/src/runs/shared/run-history.ts +21 -1
  77. package/src/runs/shared/structured-output.ts +18 -4
  78. package/src/runs/shared/subagent-prompt-runtime.ts +9 -5
  79. package/src/shared/fork-context.ts +21 -0
  80. package/src/shared/formatters.ts +7 -1
  81. package/src/shared/launch-contract.ts +6 -0
  82. package/src/shared/pruned-fork.ts +450 -0
  83. package/src/shared/session-file-trust.ts +19 -0
  84. package/src/shared/session-tokens.ts +14 -3
  85. package/src/shared/settings.ts +16 -3
  86. package/src/shared/shortcuts.ts +17 -0
  87. package/src/shared/types.ts +166 -9
  88. package/src/shared/workflow-child-permit.ts +116 -0
  89. package/src/slash/delegation-adapters.ts +0 -1
  90. package/src/slash/slash-commands.ts +8 -6
  91. package/src/tui/fleet-status.ts +27 -10
  92. package/src/tui/fleet-transcript.ts +11 -5
  93. package/src/tui/fleet.ts +28 -13
  94. package/src/tui/render.ts +47 -21
  95. package/src/workflows/scripted-workflow.ts +298 -30
  96. package/src/workflows/workflow-child-summary.ts +117 -0
  97. package/src/workflows/workflow-receipt.ts +119 -4
@@ -13,7 +13,9 @@ import {
13
13
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
14
14
  import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
15
15
  import { resolveAsyncResumeTarget } from "../background/async-resume.ts";
16
+ import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
16
17
  import { readWorkflowReceipt, workflowReceiptPath, writeWorkflowReceipt, type WorkflowReceipt } from "../../workflows/workflow-receipt.ts";
18
+ import { workflowChildSummary } from "../../workflows/workflow-child-summary.ts";
17
19
 
18
20
  function cloneWorkflowStatus(status: AsyncStatus): AsyncStatus {
19
21
  return {
@@ -23,13 +25,16 @@ function cloneWorkflowStatus(status: AsyncStatus): AsyncStatus {
23
25
  };
24
26
  }
25
27
 
26
- function childSucceeded(result: Pick<SingleResult, "exitCode" | "error">): boolean {
27
- return result.exitCode === 0 && !result.error;
28
+ function childSucceeded(result: Pick<SingleResult, "exitCode" | "error" | "interrupted">): boolean {
29
+ return result.exitCode === 0 && !result.error && !result.interrupted;
28
30
  }
29
31
 
32
+ const UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION = "unsupported-continuation: detached workflow child settled, but JavaScript workflow continuation was not persisted. Resume the workflow explicitly instead of treating the completed child as top-level workflow completion.";
33
+ const INTERRUPTED_DETACHED_CHILD = "Interrupted. Waiting for explicit next action.";
34
+
30
35
  export function applyDetachedChildToPausedWorkflow(
31
36
  status: AsyncStatus,
32
- input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "sessionFile">; workflowKey?: string },
37
+ input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "interrupted" | "sessionFile">; workflowKey?: string },
33
38
  ): AsyncStatus | undefined {
34
39
  if (status.mode !== "workflow" || status.state !== "paused") return undefined;
35
40
  const next = cloneWorkflowStatus(status);
@@ -37,6 +42,7 @@ export function applyDetachedChildToPausedWorkflow(
37
42
  ?? (input.workflowKey ? next.steps?.find((candidate) => candidate.workflowKey === input.workflowKey) : undefined);
38
43
  if (!step) return undefined;
39
44
  const succeeded = childSucceeded(input.result);
45
+ const failedSiblingError = next.steps?.find((candidate) => candidate !== step && candidate.status === "failed" && candidate.error)?.error;
40
46
  const updatedAt = Date.now();
41
47
  step.status = succeeded ? "completed" : "failed";
42
48
  step.endedAt = updatedAt;
@@ -45,11 +51,16 @@ export function applyDetachedChildToPausedWorkflow(
45
51
  delete step.currentToolStartedAt;
46
52
  if (input.result.sessionFile) step.sessionFile = input.result.sessionFile;
47
53
  if (succeeded) delete step.error;
54
+ else if (input.result.interrupted) step.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
48
55
  else if (input.result.error) step.error = input.result.error;
49
56
  next.lastUpdate = updatedAt;
50
57
  const promoted = promotePausedWorkflowIfSettled(next);
51
- if (promoted?.state === "failed" && input.result.error) promoted.error = input.result.error;
52
- return promoted ?? next;
58
+ if (promoted?.state === "failed" && input.result.interrupted && !failedSiblingError) promoted.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
59
+ else if (promoted?.state === "failed" && input.result.error) promoted.error = input.result.error;
60
+ const resolved = promoted ?? next;
61
+ const workflowState = resolved.state === "complete" ? "completed" : resolved.state === "paused" ? "paused" : resolved.state === "stopped" ? "stopped" : "failed";
62
+ resolved.workflowChildren = workflowChildSummary({ parentToolCallId: resolved.toolCallId ?? resolved.runId, workflowRunId: resolved.runId, workflowState, inventoryComplete: true, trace: resolved.workflow?.trace, steps: resolved.steps });
63
+ return resolved;
53
64
  }
54
65
 
55
66
  export function promotePausedWorkflowIfSettled(status: AsyncStatus): AsyncStatus | undefined {
@@ -63,10 +74,11 @@ export function promotePausedWorkflowIfSettled(status: AsyncStatus): AsyncStatus
63
74
  const failed = next.steps.some((candidate) => candidate.status === "failed");
64
75
  const updatedAt = Date.now();
65
76
  next.lastUpdate = updatedAt;
66
- next.state = failed ? "failed" : "complete";
77
+ next.state = "failed";
67
78
  next.endedAt = updatedAt;
68
79
  delete next.activityState;
69
- if (!failed) delete next.error;
80
+ if (failed) return next;
81
+ next.error = UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION;
70
82
  return next;
71
83
  }
72
84
 
@@ -83,6 +95,7 @@ function workflowResultChildren(status: AsyncStatus, childRunId: string, result:
83
95
  output,
84
96
  outputState: output.trim() ? "present" : "absent",
85
97
  detached: undefined,
98
+ ...(result.interrupted ? { interrupted: true } : {}),
86
99
  ...(result.error ? { error: result.error } : {}),
87
100
  };
88
101
  });
@@ -94,6 +107,7 @@ function workflowResultChildren(status: AsyncStatus, childRunId: string, result:
94
107
  success: step.status === "completed" || step.status === "complete",
95
108
  output: step.runId === childRunId ? output : "",
96
109
  outputState: step.runId === childRunId && output.trim() ? "present" : "absent",
110
+ ...(step.runId === childRunId && result.interrupted ? { interrupted: true } : {}),
97
111
  ...(step.error ? { error: step.error } : {}),
98
112
  }));
99
113
  }
@@ -119,6 +133,7 @@ function publishedWorkflowResult(status: AsyncStatus, childRunId: string, result
119
133
  timestamp: Date.now(),
120
134
  results: workflowResultChildren(status, childRunId, result, existing?.results),
121
135
  workflow: status.workflow,
136
+ workflowChildren: status.workflowChildren,
122
137
  reconciledFromDetachedChild: childRunId,
123
138
  ...(receipt ? { workflowReceipt: { path: path.join(asyncDir, "workflow-receipt.json"), receipt } } : {}),
124
139
  asyncDir,
@@ -145,6 +160,12 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
145
160
  resumability = { state: "not-resumable", reason: error instanceof Error ? error.message : String(error) };
146
161
  }
147
162
  const outputReference = result.savedOutputPath ?? result.outputReference?.path ?? entry.outputReference;
163
+ const childStatus = readStatus(path.join(DIRS.async, childRunId));
164
+ const externalStep = childStatus?.steps?.length === 1 && childStatus.steps[0]?.runner?.type === "external-cli" ? childStatus.steps[0] : undefined;
165
+ const externalRunner = normalizeExternalCliRunnerStatus(result.runner?.type === "external-cli" ? result.runner : externalStep?.runner);
166
+ const externalProcess = result.externalProcess ?? externalStep?.externalProcess;
167
+ const externalAdapter = externalRunner ? externalCliReceiptMetadata({ runner: externalRunner, externalProcess, outputReference }) : entry.externalAdapter;
168
+ if (externalAdapter) resumability = { state: "not-resumable", reason: externalAdapter.nonResumableReason };
148
169
  const updatedEntry: WorkflowReceipt["entries"][string] = resumability.state === "resumable"
149
170
  ? {
150
171
  ...entry,
@@ -153,6 +174,7 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
153
174
  latestRunId: entry.latestRunId ?? childRunId,
154
175
  resumability,
155
176
  ...(outputReference ? { outputReference } : {}),
177
+ ...(externalAdapter ? { externalAdapter } : {}),
156
178
  }
157
179
  : {
158
180
  ...entry,
@@ -160,6 +182,7 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
160
182
  ...(step.context ? { resolvedContext: step.context } : {}),
161
183
  resumability,
162
184
  ...(outputReference ? { outputReference } : {}),
185
+ ...(externalAdapter ? { externalAdapter } : {}),
163
186
  };
164
187
  const next: WorkflowReceipt = {
165
188
  ...receipt,
@@ -168,6 +191,7 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
168
191
  ...receipt.entries,
169
192
  [key]: updatedEntry,
170
193
  },
194
+ workflowChildren: status.workflowChildren,
171
195
  };
172
196
  writeWorkflowReceipt(asyncDir, next);
173
197
  return next;
@@ -404,7 +404,7 @@ function acceptanceRequiresChildReport(acceptance: ResolvedAcceptanceConfig): bo
404
404
  return acceptance.criteria.length > 0 || acceptance.evidence.length > 0;
405
405
  }
406
406
 
407
- export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, options: { reportOptional?: boolean } = {}): string {
407
+ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, options: { reportOptional?: boolean; structuredOutput?: boolean } = {}): string {
408
408
  if (acceptance.level === "none") return "";
409
409
  if (options.reportOptional && !acceptanceRequiresChildReport(acceptance)) return "";
410
410
  const lines = [
@@ -431,13 +431,15 @@ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, opt
431
431
  }
432
432
  lines.push(
433
433
  "",
434
- "Finish with a fenced JSON block tagged `acceptance-report` in this shape:",
434
+ options.structuredOutput
435
+ ? "Include an `acceptanceReport` object in your final `structured_output` tool call in this shape:"
436
+ : "Finish with a fenced JSON block tagged `acceptance-report` in this shape:",
435
437
  "Use empty arrays when no items apply; array fields contain strings unless object entries are shown.",
436
438
  "Empty-string entries (`[\"\"]`) are ignored; use `[]` when nothing applies.",
437
439
  "`criteriaSatisfied[].status` must be exactly one of: satisfied, not-satisfied, not-applicable.",
438
440
  "`commandsRun[].result` must be exactly one of: passed, failed, not-run.",
439
441
  "`manualNotes` and `notes` are optional strings; an empty string means no note and does not satisfy `manual-notes` evidence.",
440
- "```acceptance-report",
442
+ ...(options.structuredOutput ? [] : ["```acceptance-report"]),
441
443
  JSON.stringify({
442
444
  criteriaSatisfied: acceptance.criteria
443
445
  .filter((criterion) => criterion.severity !== "recommended")
@@ -452,7 +454,7 @@ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, opt
452
454
  reviewFindings: ["blocker: file.ts:12 - issue found, or no blockers"],
453
455
  manualNotes: "anything else the parent should know",
454
456
  }, null, 2),
455
- "```",
457
+ ...(options.structuredOutput ? [] : ["```"]),
456
458
  );
457
459
  return lines.join("\n");
458
460
  }
@@ -1272,6 +1274,7 @@ export async function evaluateAcceptance(input: {
1272
1274
  */
1273
1275
  fileOutput?: { content: string; path: string; authoritative?: boolean };
1274
1276
  report?: AcceptanceReport;
1277
+ reportError?: string;
1275
1278
  reviewResult?: AcceptanceReviewResult;
1276
1279
  signal?: AbortSignal;
1277
1280
  abortMessage?: string;
@@ -1293,7 +1296,9 @@ export async function evaluateAcceptance(input: {
1293
1296
  };
1294
1297
  if (acceptance.level === "none") return ledger;
1295
1298
 
1296
- const parsed = input.report
1299
+ const parsed = input.reportError
1300
+ ? { error: input.reportError }
1301
+ : input.report
1297
1302
  ? (() => {
1298
1303
  const validation = validateAcceptanceReport(input.report);
1299
1304
  return validation.report
@@ -12,7 +12,7 @@ export function buildExecutionProjection(result: Pick<SingleResult, "exitCode" |
12
12
  return { status: "stopped", success: false, exitCode: result.exitCode, stopped: true, ...(result.error ? { error: result.error } : {}) };
13
13
  }
14
14
  if (result.interrupted) {
15
- return { status: "paused", success: true, exitCode: result.exitCode, interrupted: true, ...(result.error ? { error: result.error } : {}) };
15
+ return { status: "paused", success: false, exitCode: result.exitCode, interrupted: true, ...(result.error ? { error: result.error } : {}) };
16
16
  }
17
17
  const success = result.exitCode === 0 && !result.error && !result.timedOut;
18
18
  return {
@@ -218,6 +218,7 @@ function createPiAggregateProjection(): OversizedLineProjection {
218
218
  if (!valid || token || stack.length !== 0 || rootState !== "end") return undefined;
219
219
  if (eventType === "turn_end") return '{"type":"turn_end"}';
220
220
  if (eventType === "agent_end" && typeof willRetry === "boolean") return JSON.stringify({ type: "agent_end", willRetry });
221
+ if (eventType === "compaction_end" && typeof willRetry === "boolean") return JSON.stringify({ type: "compaction_end", willRetry });
221
222
  return undefined;
222
223
  },
223
224
  };
@@ -225,14 +226,15 @@ function createPiAggregateProjection(): OversizedLineProjection {
225
226
 
226
227
  /**
227
228
  * Pi JSON mode emits granular message/tool events followed by aggregate
228
- * `turn_end` and `agent_end` events that duplicate those payloads. Parallel
229
- * image reads can make one aggregate record exceed the child line limit even
230
- * though every granular event was valid. Replace only syntactically valid,
231
- * redundant records with the lifecycle fields the runners consume.
229
+ * `turn_end`, `agent_end`, and `compaction_end` events that can duplicate
230
+ * large payloads. Parallel image reads can make one aggregate record exceed
231
+ * the child line limit even though every granular event was valid. Replace
232
+ * only syntactically valid, redundant records with the lifecycle fields the
233
+ * runners consume.
232
234
  */
233
235
  export const PI_AGGREGATE_EVENT_PROJECTOR: OversizedLineProjector = {
234
236
  accepts(prefix) {
235
- return prefix.startsWith('{"type":"turn_end"') || prefix.startsWith('{"type":"agent_end"');
237
+ return prefix.startsWith('{"type":"turn_end"') || prefix.startsWith('{"type":"agent_end"') || prefix.startsWith('{"type":"compaction_end"');
236
238
  },
237
239
  create: createPiAggregateProjection,
238
240
  };
@@ -393,9 +395,21 @@ export function createBoundedByteTail(maxBytes = MAX_CHILD_STDERR_BYTES): {
393
395
 
394
396
  export type ChildLifecycleAction = "start-drain" | "cancel-drain" | "none";
395
397
 
396
- export function projectChildLifecycle(event: { type?: string; willRetry?: unknown }, terminalAssistantStop = false): ChildLifecycleAction {
398
+ export interface ChildLifecycleState {
399
+ compactionRetryActive: boolean;
400
+ }
401
+
402
+ export function projectChildLifecycle(event: { type?: string; willRetry?: unknown }, terminalAssistantStop = false, state?: ChildLifecycleState): ChildLifecycleAction {
403
+ if (event.type === "compaction_end") {
404
+ if (state) state.compactionRetryActive = event.willRetry === true;
405
+ return event.willRetry === true ? "cancel-drain" : "none";
406
+ }
407
+ if (event.type === "agent_start" || event.type === "auto_retry_start") {
408
+ if (state) state.compactionRetryActive = false;
409
+ }
397
410
  if (event.type === "agent_end" && event.willRetry === true) return "cancel-drain";
398
- if (event.type === "agent_settled") return "start-drain";
411
+ if (event.type === "agent_end" && state) state.compactionRetryActive = false;
412
+ if (event.type === "agent_settled") return state?.compactionRetryActive ? "none" : "start-drain";
399
413
  if (terminalAssistantStop) return "start-drain";
400
414
  return "none";
401
415
  }
@@ -0,0 +1,129 @@
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
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)? \(Claude Code\)$/.test(result.version)) throw new Error(`Unsupported Claude Code version response: ${JSON.stringify(result.version)}.`);
122
+ 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"]) {
123
+ if (!result.help.includes(required)) throw new Error(`Claude Code help does not document required option ${JSON.stringify(required)}.`);
124
+ }
125
+ },
126
+ },
127
+ parser: createClaudeCodeJsonlParser(),
128
+ };
129
+ }
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Message } from "@earendil-works/pi-ai";
2
- import type { AcceptanceRole } from "../../shared/types.ts";
2
+ import type { AcceptanceRole, TrackedMutationEvidence } from "../../shared/types.ts";
3
3
  import { isMutatingTool } from "./long-running-guard.ts";
4
4
  import { classifyTaskMutationIntent, expectsImplementationMutation, taskMayMutate } from "./task-intent.ts";
5
5
 
@@ -48,6 +48,7 @@ interface CompletionMutationGuardInput {
48
48
  tools?: string[];
49
49
  mcpDirectTools?: string[];
50
50
  toolAvailabilityError?: string;
51
+ mutationEvidence?: TrackedMutationEvidence;
51
52
  }
52
53
 
53
54
  interface CompletionMutationGuardResult {
@@ -238,7 +239,7 @@ export function evaluateCompletionMutationGuard(input: CompletionMutationGuardIn
238
239
  const expectedMutation = hasMutationToolCapability(input.tools, input.mcpDirectTools)
239
240
  ? expectsImplementationMutation(input.agent, input.task)
240
241
  : false;
241
- const attemptedMutation = hasMutationToolCall(input.messages);
242
+ const attemptedMutation = hasMutationToolCall(input.messages) || input.mutationEvidence?.attemptedMutation === true;
242
243
  const noEditChallengeComplete = isImplementationChallengeTask(input.task)
243
244
  && reportsNoBetterChallengeChange(input.messages);
244
245
  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
+ }
@@ -46,7 +46,7 @@ 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
52
  "outputName", "structured", "inheritProjectContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled",