@xzzpig/pi-subagents 0.1.0 → 0.3.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 (108) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +4 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +343 -0
  5. package/docs/configuration.md +395 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +121 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +198 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +53 -23
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/preflight.ts +1 -1
  22. package/src/api/project-panes.ts +30 -0
  23. package/src/extension/config.ts +54 -1
  24. package/src/extension/doctor.ts +40 -0
  25. package/src/extension/fanout-child.ts +5 -4
  26. package/src/extension/index.ts +114 -38
  27. package/src/extension/public-execution.ts +35 -4
  28. package/src/extension/rpc.ts +10 -15
  29. package/src/extension/schemas.ts +33 -11
  30. package/src/extension/subagent-guide.ts +39 -0
  31. package/src/extension/tool-description.ts +38 -18
  32. package/src/inspectors/herdr/actions.ts +11 -2
  33. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  34. package/src/inspectors/herdr/project-panes.ts +459 -63
  35. package/src/intercom/intercom-bridge.ts +7 -2
  36. package/src/intercom/native-supervisor-channel.ts +102 -4
  37. package/src/missions/actions.ts +25 -2
  38. package/src/missions/lifecycle.ts +25 -9
  39. package/src/missions/store.ts +89 -7
  40. package/src/missions/types.ts +33 -0
  41. package/src/missions/workflow-state.ts +25 -15
  42. package/src/runs/background/active-async-capacity.ts +431 -0
  43. package/src/runs/background/active-run-index.ts +46 -0
  44. package/src/runs/background/async-execution.ts +158 -71
  45. package/src/runs/background/async-job-tracker.ts +297 -133
  46. package/src/runs/background/async-resume.ts +37 -5
  47. package/src/runs/background/async-status.ts +39 -5
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/completion-replay.ts +267 -0
  50. package/src/runs/background/control-channel.ts +95 -54
  51. package/src/runs/background/fleet-view.ts +18 -5
  52. package/src/runs/background/owned-process-tree.ts +104 -0
  53. package/src/runs/background/process-terminal.ts +17 -3
  54. package/src/runs/background/result-watcher.ts +113 -10
  55. package/src/runs/background/resume-guidance.ts +53 -0
  56. package/src/runs/background/retained-children.ts +14 -6
  57. package/src/runs/background/run-status.ts +119 -5
  58. package/src/runs/background/scheduled-runs.ts +25 -1
  59. package/src/runs/background/stale-run-reconciler.ts +12 -24
  60. package/src/runs/background/subagent-runner.ts +127 -41
  61. package/src/runs/background/subagent-wait.ts +5 -2
  62. package/src/runs/background/wait-completions.ts +39 -5
  63. package/src/runs/background/wait-subscriptions.ts +21 -5
  64. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  65. package/src/runs/foreground/async-steering-action.ts +7 -8
  66. package/src/runs/foreground/chain-execution.ts +40 -2
  67. package/src/runs/foreground/execution.ts +97 -19
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/foreground-history.ts +137 -0
  70. package/src/runs/foreground/prompt-audit.ts +172 -0
  71. package/src/runs/foreground/subagent-executor.ts +1274 -243
  72. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  73. package/src/runs/shared/acceptance.ts +13 -4
  74. package/src/runs/shared/completion-guard.ts +17 -1
  75. package/src/runs/shared/dynamic-fanout.ts +1 -1
  76. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  77. package/src/runs/shared/model-fallback.ts +8 -4
  78. package/src/runs/shared/model-scope.ts +12 -2
  79. package/src/runs/shared/parallel-utils.ts +3 -0
  80. package/src/runs/shared/pi-args.ts +44 -1
  81. package/src/runs/shared/run-fanout-budget.ts +280 -0
  82. package/src/runs/shared/single-output.ts +4 -2
  83. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  84. package/src/runs/shared/task-intent.ts +19 -3
  85. package/src/runs/shared/worktree.ts +20 -7
  86. package/src/shared/agent-stream-options.ts +5 -0
  87. package/src/shared/artifacts.ts +17 -21
  88. package/src/shared/display-text.ts +150 -0
  89. package/src/shared/file-coalescer.ts +9 -0
  90. package/src/shared/fork-context.ts +13 -0
  91. package/src/shared/formatters.ts +4 -6
  92. package/src/shared/node-executable.ts +21 -0
  93. package/src/shared/prompt-resources.ts +51 -0
  94. package/src/shared/settings.ts +15 -2
  95. package/src/shared/types.ts +158 -4
  96. package/src/shared/utf8.ts +11 -0
  97. package/src/shared/utils.ts +46 -34
  98. package/src/slash/prompt-workflows.ts +2 -15
  99. package/src/slash/slash-commands.ts +22 -2
  100. package/src/tui/fleet-status.ts +29 -17
  101. package/src/tui/fleet-transcript.ts +1 -48
  102. package/src/tui/fleet.ts +362 -37
  103. package/src/tui/render.ts +235 -71
  104. package/src/watchdog/change-signature.ts +4 -3
  105. package/src/watchdog/permission-arbiter.ts +2 -1
  106. package/src/watchdog/review.ts +4 -3
  107. package/src/workflows/chat-progress.ts +8 -2
  108. package/src/workflows/scripted-workflow.ts +273 -20
@@ -2,7 +2,9 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
- import { listAsyncRuns } from "./async-status.ts";
5
+ import { listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
6
+ import { formatResumeFirstFailedRunDetail } from "./resume-guidance.ts";
7
+ import { readCompletionReplay } from "./completion-replay.ts";
6
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
7
9
  import {
8
10
  DIRS,
@@ -13,6 +15,7 @@ import {
13
15
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
14
16
  SUBAGENT_RESULT_INTERCOM_EVENT,
15
17
  type SubagentState,
18
+ type WaitCompletion,
16
19
  type WaitSubscriptionRecord,
17
20
  } from "../../shared/types.ts";
18
21
 
@@ -61,7 +64,7 @@ function parseRecord(value: unknown): WaitSubscriptionRecord | undefined {
61
64
  return record as WaitSubscriptionRecord;
62
65
  }
63
66
 
64
- function needsAttention(run: ReturnType<typeof listAsyncRuns>[number]): boolean {
67
+ function needsAttention(run: AsyncRunSummary): boolean {
65
68
  return run.activityState === "needs_attention" || run.steps.some((step) => step.activityState === "needs_attention");
66
69
  }
67
70
 
@@ -103,7 +106,7 @@ export function createWaitSubscriptionManager(
103
106
  unresolvedRestoredForegroundTokens.delete(record.token);
104
107
  };
105
108
 
106
- const settle = (record: WaitSubscriptionRecord, outcome: string, detail: string) => {
109
+ const settle = (record: WaitSubscriptionRecord, outcome: string, detail: string, completion?: WaitCompletion) => {
107
110
  if (disposed || state.currentSessionId !== record.sessionId) return;
108
111
  try {
109
112
  remove(record);
@@ -116,7 +119,12 @@ export function createWaitSubscriptionManager(
116
119
  customType: "subagent-wait-subscription",
117
120
  content: `Wait subscription ${record.token} fired for run ${record.runId}: ${outcome}. ${detail}`,
118
121
  display: true,
119
- details: { token: record.token, runId: record.runId, outcome },
122
+ details: {
123
+ token: record.token,
124
+ runId: record.runId,
125
+ outcome,
126
+ ...(completion ? { completions: [completion] } : {}),
127
+ },
120
128
  }, { triggerTurn: true });
121
129
  } catch (error) {
122
130
  console.error(`Failed to deliver wait subscription '${record.token}' after clearing it:`, error);
@@ -166,7 +174,15 @@ export function createWaitSubscriptionManager(
166
174
  return;
167
175
  }
168
176
  if (run.state !== "queued" && run.state !== "running") {
169
- settle(record, run.state === "complete" ? "completed" : run.state, "Inspect the run status for its final output.");
177
+ let completion: WaitCompletion | undefined;
178
+ try {
179
+ completion = readCompletionReplay(resultsDir, record.runId, { sessionId: record.sessionId, now: now() })?.completion;
180
+ } catch (error) {
181
+ console.error(`Failed to read completion replay for wait subscription '${record.token}':`, error);
182
+ }
183
+ const detail = formatResumeFirstFailedRunDetail(run) ?? "Inspect the run status for its final output.";
184
+ const archiveDetail = completion?.archivePath ? ` Completion archive: ${completion.archivePath}.` : "";
185
+ settle(record, run.state === "complete" ? "completed" : run.state, `${detail}${archiveDetail}`, completion);
170
186
  }
171
187
  };
172
188
 
@@ -0,0 +1,85 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
+ import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
6
+ import { readStatus } from "../../shared/utils.ts";
7
+ import { updateActiveRunIndex } from "../background/active-run-index.ts";
8
+ import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
9
+
10
+ export function dismissRecoveredWorkflow(
11
+ state: SubagentState,
12
+ location: { asyncDir: string | null; resolvedId?: string },
13
+ ): AgentToolResult<Details> {
14
+ const asyncDir = location.asyncDir;
15
+ const runId = location.resolvedId ?? (asyncDir ? path.basename(asyncDir) : "requested");
16
+ if (!asyncDir) {
17
+ return {
18
+ content: [{ type: "text", text: `Recovered workflow '${runId}' has no disk status to dismiss.` }],
19
+ isError: true,
20
+ details: { mode: "management", results: [] },
21
+ };
22
+ }
23
+ const status = readStatus(asyncDir);
24
+ if (!status || status.mode !== "workflow") {
25
+ return {
26
+ content: [{ type: "text", text: `Run '${runId}' is not a recovered workflow.` }],
27
+ isError: true,
28
+ details: { mode: "management", results: [] },
29
+ };
30
+ }
31
+ if (!state.currentSessionId || status.sessionId !== state.currentSessionId) {
32
+ return {
33
+ content: [{ type: "text", text: `Recovered workflow '${runId}' was not found in the active session.` }],
34
+ isError: true,
35
+ details: { mode: "management", results: [] },
36
+ };
37
+ }
38
+ if (state.workflowControllers?.has(status.runId) || state.workflowControllers?.has(runId)) {
39
+ return {
40
+ content: [{ type: "text", text: `Workflow '${runId}' still has a live controller and cannot be dismissed.` }],
41
+ isError: true,
42
+ details: { mode: "management", results: [] },
43
+ };
44
+ }
45
+ if (status.state !== "running") {
46
+ return {
47
+ content: [{ type: "text", text: `Recovered workflow '${runId}' is ${status.state}, not running.` }],
48
+ isError: true,
49
+ details: { mode: "management", results: [] },
50
+ };
51
+ }
52
+ let latestStatus = status;
53
+ const resultPath = path.join(DIRS.results, `${status.runId}.json`);
54
+ if (fs.existsSync(resultPath)) {
55
+ const reconciled = reconcileAsyncRun(asyncDir).status;
56
+ if (reconciled && reconciled.state !== "running") {
57
+ return {
58
+ content: [{ type: "text", text: `Recovered workflow '${runId}' is ${reconciled.state}, not running.` }],
59
+ isError: true,
60
+ details: { mode: "management", results: [] },
61
+ };
62
+ }
63
+ if (reconciled) latestStatus = reconciled;
64
+ }
65
+
66
+ const dismissed = { ...latestStatus, displayDismissedAt: Date.now() };
67
+ writeAtomicJson(path.join(asyncDir, "status.json"), dismissed);
68
+ const repaired = reconcileAsyncRun(asyncDir).status;
69
+ if (repaired && repaired.state !== "running") {
70
+ return {
71
+ content: [{ type: "text", text: `Recovered workflow '${runId}' is ${repaired.state}, not running.` }],
72
+ isError: true,
73
+ details: { mode: "management", results: [] },
74
+ };
75
+ }
76
+ updateActiveRunIndex(asyncDir, "complete");
77
+ state.asyncJobs.delete(status.runId);
78
+ state.asyncJobs.delete(runId);
79
+ state.fleetJobs?.delete(status.runId);
80
+ state.fleetJobs?.delete(runId);
81
+ return {
82
+ content: [{ type: "text", text: `Dismissed recovered workflow ${status.runId} from the display. No running work was terminated.` }],
83
+ details: { mode: "management", results: [] },
84
+ };
85
+ }
@@ -173,7 +173,7 @@ export async function steerAsyncRun(input: {
173
173
  return { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: preCommitResult } };
174
174
  }
175
175
  try {
176
- deliverInterruptRequest({ asyncDir, pid: latest?.pid ?? status.pid, kill: input.kill, source: "steering-recovery" });
176
+ deliverInterruptRequest({ asyncDir, source: "steering-recovery" });
177
177
  } catch (error) {
178
178
  fs.rmSync(markerPath, { force: true });
179
179
  fs.rmSync(claimPath, { force: true });
@@ -219,15 +219,14 @@ export async function steerAsyncRun(input: {
219
219
  const limits = remainingSteeringRecoveryLimits(recoveryTarget.recoveryDescriptor, paused);
220
220
  const revived = await input.recover(limits);
221
221
  if (revived.isError || !revived.details.asyncId) throw new Error(revived.content[0]?.type === "text" ? revived.content[0].text : "Replacement launch failed; source run remains paused.");
222
- const sourceStatus = readStatus(asyncDir);
223
- const targetIndex = input.index ?? status.steps?.findIndex((step) => step.status === "running") ?? -1;
224
- if (sourceStatus?.state === "paused" && sourceStatus.steering && targetIndex >= 0) {
225
- updateSteeringTarget(sourceStatus.steering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
226
- const stepSteering = sourceStatus.steps?.[targetIndex]?.steering;
222
+ const targetIndex = input.index ?? paused.steering?.recent.find((request) => request.id === requestId)?.targets[0]?.index ?? status.steps?.findIndex((step) => step.status === "running") ?? -1;
223
+ if (paused.steering && targetIndex >= 0) {
224
+ updateSteeringTarget(paused.steering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
225
+ const stepSteering = paused.steps?.[targetIndex]?.steering;
227
226
  if (stepSteering) updateSteeringTarget(stepSteering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
228
- writeAtomicJson(path.join(asyncDir, "status.json"), sourceStatus);
227
+ writeAtomicJson(path.join(asyncDir, "status.json"), paused);
229
228
  }
230
- const recovered = sourceStatus?.steering ? actionResultFromSteeringStatus(sourceStatus.steering, status.runId, requestId, revived.details.asyncId) : undefined;
229
+ const recovered = paused.steering ? actionResultFromSteeringStatus(paused.steering, status.runId, requestId, revived.details.asyncId) : undefined;
231
230
  appendSteeringNotice("recovered", `Steering recovered for run ${status.runId}; replacement ${revived.details.asyncId} launched.`);
232
231
  return { content: [{ type: "text", text: `Steering recovered for async run ${status.runId}; replacement ${revived.details.asyncId} launched after the source paused.` }], details: { mode: "management", results: [], steering: recovered ?? { requestId, state: "recovered", sourceRunId: status.runId, replacementRunId: revived.details.asyncId, deliveryStatus: "delivered", targets: [{ index: input.index ?? 0, state: "recovered" }] } } };
233
232
  } catch (error) {
@@ -34,6 +34,8 @@ import {
34
34
  import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
35
35
  import { INTERCOM_BRIDGE_MARKER } from "../../intercom/intercom-bridge.ts";
36
36
  import { runSync } from "./execution.ts";
37
+ import { createTaskMutationArbiter } from "../shared/llm-intent-arbiter.ts";
38
+ import { workflowForegroundSteeringLaunchOptions } from "./workflow-foreground-steering.ts";
37
39
  import {
38
40
  beginForegroundChild,
39
41
  finishForegroundChild,
@@ -41,6 +43,7 @@ import {
41
43
  settleForegroundSchedulingOwner,
42
44
  updateForegroundChild,
43
45
  } from "./foreground-control.ts";
46
+ import { updateLiveEffectivePrompt } from "./prompt-audit.ts";
44
47
  import { buildChainSummary } from "../../shared/formatters.ts";
45
48
  import { compactForegroundDetails, getSingleResultOutput, mapConcurrent, resolveChildCwd, sumResultsCost, sumResultsUsage } from "../../shared/utils.ts";
46
49
  import { DEFAULT_GLOBAL_CONCURRENCY_LIMIT, Semaphore } from "../shared/parallel-utils.ts";
@@ -70,6 +73,7 @@ import {
70
73
  type ResolvedControlConfig,
71
74
  type ResolvedTurnBudget,
72
75
  type ResolvedToolBudget,
76
+ type RunFanoutBudgetDescriptor,
73
77
  type SingleResult,
74
78
  type ToolBudgetConfig,
75
79
  type ChainCheckpointState,
@@ -85,6 +89,7 @@ import { ChainOutputValidationError, outputEntryFromResult, resolveOutputReferen
85
89
  import { createStructuredOutputRuntime } from "../shared/structured-output.ts";
86
90
  import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection, type DynamicCollectedResult } from "../shared/dynamic-fanout.ts";
87
91
  import { acceptanceFailureMessage, aggregateAcceptanceReport, evaluateAcceptance, resolveEffectiveAcceptance } from "../shared/acceptance.ts";
92
+ import { claimRunFanoutBatch, RunFanoutLimitError } from "../shared/run-fanout-budget.ts";
88
93
  import { isAgentContractV1 } from "../shared/agent-contract.ts";
89
94
  import type { ChainOutputMap } from "../../shared/types.ts";
90
95
  import { validateToolBudgetConfig } from "../shared/tool-budget.ts";
@@ -166,6 +171,7 @@ interface ParallelChainRunInput {
166
171
  configToolBudget?: ToolBudgetConfig;
167
172
  globalSemaphore?: Semaphore;
168
173
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
174
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
169
175
  permissions?: PermissionConfig;
170
176
  dynamic?: boolean;
171
177
  }
@@ -367,7 +373,11 @@ async function runParallelChainTasks(input: ParallelChainRunInput): Promise<Sing
367
373
  beginForegroundChild(input.foregroundControl, {
368
374
  index: childIndex,
369
375
  agent: task.agent,
370
- description: cleanTask.trim(),
376
+ authoredTask: cleanTask,
377
+ effectivePrompt: taskStr,
378
+ cwd: taskCwd,
379
+ ...(outputPath ? { outputPath } : {}),
380
+ description: `${task.agent} child`,
371
381
  ...(effectiveModel ? { model: effectiveModel } : {}),
372
382
  ...(thinking ? { thinking } : {}),
373
383
  interrupt: () => {
@@ -387,7 +397,10 @@ async function runParallelChainTasks(input: ParallelChainRunInput): Promise<Sing
387
397
  result = await runSync(input.ctx.cwd, input.agents, task.agent, taskStr, {
388
398
  permissions: input.permissions,
389
399
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
400
+ llmIntentArbiter: createTaskMutationArbiter(input.ctx),
401
+ ...workflowForegroundSteeringLaunchOptions(input.foregroundControl, childIndex),
390
402
  capabilityCeiling: input.capabilityCeiling,
403
+ runFanoutBudget: input.runFanoutBudget ? { ...input.runFanoutBudget, parentPath: `${input.runFanoutBudget.parentPath ? `${input.runFanoutBudget.parentPath}/` : ""}chain[${input.stepIndex}]${input.dynamic ? `.expand[${taskIndex}]` : `.parallel[${taskIndex}]`}` } : undefined,
391
404
  context: input.contextForAgent?.(task.agent),
392
405
  cwd: taskCwd,
393
406
  signal: input.signal,
@@ -420,6 +433,7 @@ async function runParallelChainTasks(input: ParallelChainRunInput): Promise<Sing
420
433
  agentContract,
421
434
  acceptance: task.acceptance,
422
435
  acceptanceContext: { mode: "chain", dynamic: input.dynamic && task.acceptance === undefined },
436
+ onEffectivePrompt: input.foregroundControl ? (prompt) => updateLiveEffectivePrompt(input.foregroundControl!, childIndex, prompt) : undefined,
423
437
  timeoutMs: input.timeoutMs,
424
438
  deadlineAt: input.deadlineAt,
425
439
  turnBudget: input.turnBudget,
@@ -538,6 +552,7 @@ interface ChainExecutionParams {
538
552
  /** Global cap on simultaneously-running tasks within this chain. Defaults to DEFAULT_GLOBAL_CONCURRENCY_LIMIT. */
539
553
  globalConcurrencyLimit?: number;
540
554
  capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
555
+ runFanoutBudget?: RunFanoutBudgetDescriptor;
541
556
  }
542
557
 
543
558
  interface ChainExecutionResult {
@@ -874,6 +889,7 @@ ${step.message}` : ""}` }],
874
889
  configToolBudget: params.configToolBudget,
875
890
  globalSemaphore,
876
891
  permissions: params.permissions,
892
+ runFanoutBudget: params.runFanoutBudget,
877
893
  });
878
894
  globalTaskIndex += step.parallel.length;
879
895
 
@@ -1000,6 +1016,19 @@ ${step.message}` : ""}` }],
1000
1016
  return buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
1001
1017
  }
1002
1018
 
1019
+ try {
1020
+ if (params.runFanoutBudget) claimRunFanoutBatch(params.runFanoutBudget, materialized.parallel.map((_, itemIndex) => `chain[${stepIndex}].expand[${itemIndex}]`));
1021
+ } catch (error) {
1022
+ const message = error instanceof Error ? error.message : String(error);
1023
+ dynamicGroupStatuses[stepIndex] = { status: "failed", error: message };
1024
+ const result = buildChainExecutionErrorResult(message, makeDetailsInput({ currentStepIndex: stepIndex, currentFlatIndex: globalTaskIndex }));
1025
+ if (error instanceof RunFanoutLimitError) {
1026
+ result.details.runFanoutBudget = error.snapshot;
1027
+ result.details.runFanoutRejection = error.rejection;
1028
+ }
1029
+ return result;
1030
+ }
1031
+
1003
1032
  dynamicChildren[stepIndex] = materialized.items.map((item, itemIndex) => ({
1004
1033
  agent: step.parallel.agent,
1005
1034
  label: materialized.parallel[itemIndex]?.label,
@@ -1135,6 +1164,7 @@ ${step.message}` : ""}` }],
1135
1164
  configToolBudget: params.configToolBudget,
1136
1165
  globalSemaphore,
1137
1166
  permissions: params.permissions,
1167
+ runFanoutBudget: params.runFanoutBudget,
1138
1168
  dynamic: true,
1139
1169
  });
1140
1170
  globalTaskIndex = dynamicStartIndex + reservedDynamicItems;
@@ -1330,7 +1360,11 @@ ${step.message}` : ""}` }],
1330
1360
  beginForegroundChild(foregroundControl, {
1331
1361
  index: childIndex,
1332
1362
  agent: seqStep.agent,
1333
- description: cleanTask.trim(),
1363
+ authoredTask: cleanTask,
1364
+ effectivePrompt: stepTask,
1365
+ cwd,
1366
+ ...(outputPath ? { outputPath } : {}),
1367
+ description: `${seqStep.agent} child`,
1334
1368
  ...(effectiveModel ? { model: effectiveModel } : {}),
1335
1369
  ...(thinking ? { thinking } : {}),
1336
1370
  interrupt: () => {
@@ -1367,7 +1401,10 @@ ${step.message}` : ""}` }],
1367
1401
  r = await runSync(ctx.cwd, agents, seqStep.agent, stepTask, {
1368
1402
  permissions: params.permissions,
1369
1403
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
1404
+ llmIntentArbiter: createTaskMutationArbiter(ctx),
1405
+ ...workflowForegroundSteeringLaunchOptions(params.foregroundControl, childIndex),
1370
1406
  capabilityCeiling: params.capabilityCeiling,
1407
+ runFanoutBudget: params.runFanoutBudget ? { ...params.runFanoutBudget, parentPath: `${params.runFanoutBudget.parentPath ? `${params.runFanoutBudget.parentPath}/` : ""}chain[${stepIndex}]` } : undefined,
1371
1408
  context: params.contextForAgent?.(seqStep.agent),
1372
1409
  cwd: resolveChildCwd(cwd ?? ctx.cwd, seqStep.cwd),
1373
1410
  signal,
@@ -1400,6 +1437,7 @@ ${step.message}` : ""}` }],
1400
1437
  agentContract,
1401
1438
  acceptance: seqStep.acceptance,
1402
1439
  acceptanceContext: { mode: "chain" },
1440
+ onEffectivePrompt: foregroundControl ? (prompt) => updateLiveEffectivePrompt(foregroundControl, childIndex, prompt) : undefined,
1403
1441
  timeoutMs: params.timeoutMs,
1404
1442
  deadlineAt,
1405
1443
  turnBudget: params.turnBudget,
@@ -8,6 +8,7 @@ import * as path from "node:path";
8
8
  import type { Message } from "@earendil-works/pi-ai";
9
9
  import type { AgentConfig } from "../../agents/agents.ts";
10
10
  import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
11
+ import { alignForkedSessionCwd } from "../../shared/fork-context.ts";
11
12
  import {
12
13
  ensureArtifactsDir,
13
14
  formatOutputArtifactContent,
@@ -53,18 +54,19 @@ import {
53
54
  import { buildSkillInjection, resolveSkillsWithFallback } from "../../agents/skills.ts";
54
55
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
55
56
  import { evaluateCompletionMutationGuard } from "../shared/completion-guard.ts";
57
+ import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
56
58
  import { getPiSpawnCommand } from "../shared/pi-spawn.ts";
57
59
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
58
60
  import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
59
61
  import { resolvePermissionRules } from "../shared/permissions.ts";
60
- import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
62
+ import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, type SubagentTaskDelivery } from "../shared/pi-args.ts";
61
63
  import { readRuntimeAcknowledgedExtensions } from "../shared/runtime-acknowledged-extensions.ts";
62
64
  import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV } from "../shared/capability-ceiling.ts";
63
65
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
64
66
  import { MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput } from "../shared/structured-output.ts";
65
67
  import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
66
68
  import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
67
- import { captureSingleOutputSnapshot, extractChildWrittenOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
69
+ import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
68
70
  import {
69
71
  buildModelCandidates,
70
72
  formatModelAttemptNote,
@@ -89,6 +91,7 @@ import {
89
91
  summarizeRecentMutatingFailures,
90
92
  } from "../shared/long-running-guard.ts";
91
93
  import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
94
+ import { PROMPT_REDACTED } from "../../shared/utils.ts";
92
95
  import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
93
96
  import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
94
97
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
@@ -116,6 +119,12 @@ function withRunContext<T extends SingleResult>(result: T, context: RunSyncOptio
116
119
  return result;
117
120
  }
118
121
 
122
+ function redactResultPrompt<T extends SingleResult>(result: T): T {
123
+ result.task = PROMPT_REDACTED;
124
+ if (result.progress) result.progress.task = PROMPT_REDACTED;
125
+ return result;
126
+ }
127
+
119
128
  function sumUsage(target: Usage, source: Usage): void {
120
129
  target.input += source.input;
121
130
  target.output += source.output;
@@ -138,7 +147,7 @@ function persistSingleResultMetadata(input: {
138
147
  writeMetadata(input.metadataPath, {
139
148
  runId: input.runId,
140
149
  agent: input.agent,
141
- task: input.task,
150
+ task: PROMPT_REDACTED,
142
151
  exitCode: target.exitCode,
143
152
  processSignal: target.processSignal,
144
153
  usage: target.usage,
@@ -230,6 +239,7 @@ function stripAcceptanceReportsFromMessages(messages: Message[] | undefined): vo
230
239
  function snapshotProgress(progress: AgentProgress): AgentProgress {
231
240
  return {
232
241
  ...progress,
242
+ task: PROMPT_REDACTED,
233
243
  skills: progress.skills ? [...progress.skills] : undefined,
234
244
  recentTools: boundStreamedRecentTools(progress.recentTools),
235
245
  recentOutput: boundStreamedRecentOutput(progress.recentOutput),
@@ -239,6 +249,7 @@ function snapshotProgress(progress: AgentProgress): AgentProgress {
239
249
  function snapshotResult(result: SingleResult, progress: AgentProgress): SingleResult {
240
250
  return {
241
251
  ...result,
252
+ task: PROMPT_REDACTED,
242
253
  messages: result.outputMode === "file-only" && result.savedOutputPath ? undefined : result.messages ? [...result.messages] : undefined,
243
254
  usage: { ...result.usage },
244
255
  skills: result.skills ? [...result.skills] : undefined,
@@ -290,6 +301,7 @@ async function runSingleAttempt(
290
301
  attemptNotes: string[];
291
302
  outputSnapshot?: SingleOutputSnapshot;
292
303
  originalTask?: string;
304
+ taskDelivery?: SubagentTaskDelivery;
293
305
  },
294
306
  ): Promise<SingleResult> {
295
307
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
@@ -311,6 +323,7 @@ async function runSingleAttempt(
311
323
  const { args, env: sharedEnv, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit } = buildPiArgs({
312
324
  baseArgs: ["--mode", "json", "-p"],
313
325
  task,
326
+ taskDelivery: shared.taskDelivery,
314
327
  sessionEnabled: shared.sessionEnabled,
315
328
  sessionDir: options.sessionDir,
316
329
  sessionFile: options.sessionFile,
@@ -336,7 +349,11 @@ async function runSingleAttempt(
336
349
  parentControlInbox: options.nestedRoute?.controlInbox,
337
350
  parentRootRunId: options.nestedRoute?.rootRunId,
338
351
  parentCapabilityToken: options.nestedRoute?.capabilityToken,
352
+ runFanoutBudget: options.runFanoutBudget,
339
353
  parentSessionId: options.parentSessionId,
354
+ steerInboxDir: options.steerInboxDir,
355
+ steerCapabilityPath: options.steerCapabilityPath,
356
+ steerAckDir: options.steerAckDir,
340
357
  structuredOutput: options.structuredOutput,
341
358
  toolBudget: options.toolBudget,
342
359
  allowZeroToolBudget: options.allowZeroToolBudget,
@@ -1273,15 +1290,38 @@ async function runSingleAttempt(
1273
1290
  mcpDirectTools: agent.mcpDirectTools,
1274
1291
  })
1275
1292
  : undefined;
1276
- const completionGuardTriggered = completionGuard?.triggered === true && !observedMutationAttempt;
1293
+ let completionGuardTriggered = completionGuard?.triggered === true && !observedMutationAttempt;
1294
+ // The classifier is deliberately narrow, so a read-only review task can
1295
+ // still be misread as implementation. Arbitrate BEFORE any failure side
1296
+ // effect is published (effects, exit code, progress, notifications,
1297
+ // acceptance, output persistence): only a confident read-only verdict
1298
+ // rescues, and the task text alone is evidence — never the child's own
1299
+ // final message.
1300
+ let arbiterRescued = false;
1301
+ if (completionGuardTriggered) {
1302
+ const arbitration = await arbitrateCompletionGuardRescue({
1303
+ guardTriggered: true,
1304
+ task: shared.originalTask ?? task,
1305
+ arbiter: options.llmIntentArbiter,
1306
+ });
1307
+ completionGuardTriggered = arbitration.triggered;
1308
+ arbiterRescued = arbitration.rescued;
1309
+ }
1277
1310
  if (completionGuard) {
1278
1311
  result.effects = {
1279
1312
  ...(result.effects ?? {}),
1280
1313
  fileMutation: {
1281
- status: completionGuard.expectedMutation ? completionGuardTriggered ? "missing" : "observed" : "not-applicable",
1314
+ status: completionGuard.expectedMutation
1315
+ ? completionGuardTriggered
1316
+ ? "missing"
1317
+ : arbiterRescued
1318
+ ? "not-applicable"
1319
+ : "observed"
1320
+ : "not-applicable",
1282
1321
  expected: completionGuard.expectedMutation,
1283
1322
  attempted: completionGuard.attemptedMutation || observedMutationAttempt,
1284
1323
  ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1324
+ ...(arbiterRescued ? { resolvedBy: "llm-intent-arbiter" } : {}),
1285
1325
  },
1286
1326
  };
1287
1327
  }
@@ -1351,7 +1391,7 @@ async function runSyncCompletion(
1351
1391
  };
1352
1392
  const agent = agents.find((a) => a.name === agentName);
1353
1393
  if (!agent) {
1354
- return withRunContext({
1394
+ return redactResultPrompt(withRunContext({
1355
1395
  index: options.index ?? 0,
1356
1396
  agent: agentName,
1357
1397
  task,
@@ -1359,12 +1399,12 @@ async function runSyncCompletion(
1359
1399
  messages: [],
1360
1400
  usage: emptyUsage(),
1361
1401
  error: `Unknown agent: ${agentName}`,
1362
- }, options.context);
1402
+ }, options.context));
1363
1403
  }
1364
1404
  try {
1365
1405
  assertAgentAllowedByCapabilityCeiling(agent.name, options.capabilityCeiling);
1366
1406
  } catch (error) {
1367
- return withRunContext({
1407
+ return redactResultPrompt(withRunContext({
1368
1408
  index: options.index ?? 0,
1369
1409
  agent: agent.name,
1370
1410
  task,
@@ -1373,11 +1413,11 @@ async function runSyncCompletion(
1373
1413
  usage: emptyUsage(),
1374
1414
  error: error instanceof Error ? error.message : String(error),
1375
1415
  ...(options.capabilityCeiling ? { capabilityCeiling: options.capabilityCeiling } : {}),
1376
- }, options.context);
1416
+ }, options.context));
1377
1417
  }
1378
1418
  const acceptanceErrors = validateAcceptanceInput(options.acceptance);
1379
1419
  if (acceptanceErrors.length > 0) {
1380
- return withRunContext({
1420
+ return redactResultPrompt(withRunContext({
1381
1421
  index: options.index ?? 0,
1382
1422
  agent: agentName,
1383
1423
  task,
@@ -1385,11 +1425,11 @@ async function runSyncCompletion(
1385
1425
  messages: [],
1386
1426
  usage: emptyUsage(),
1387
1427
  error: acceptanceErrors.join(" "),
1388
- }, options.context);
1428
+ }, options.context));
1389
1429
  }
1390
1430
  const outputModeValidationError = validateFileOnlyOutputMode(options.outputMode, options.outputPath, `Single run (${agentName})`);
1391
1431
  if (outputModeValidationError) {
1392
- return withRunContext({
1432
+ return redactResultPrompt(withRunContext({
1393
1433
  index: options.index ?? 0,
1394
1434
  agent: agentName,
1395
1435
  task,
@@ -1398,7 +1438,7 @@ async function runSyncCompletion(
1398
1438
  usage: emptyUsage(),
1399
1439
  outputMode: options.outputMode,
1400
1440
  error: outputModeValidationError,
1401
- }, options.context);
1441
+ }, options.context));
1402
1442
  }
1403
1443
 
1404
1444
  const shareEnabled = options.share === true;
@@ -1415,7 +1455,11 @@ async function runSyncCompletion(
1415
1455
  });
1416
1456
  const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract) });
1417
1457
  const taskWithAcceptance = acceptancePrompt ? `${task}\n${acceptancePrompt}` : task;
1458
+ options.onEffectivePrompt?.(taskWithAcceptance);
1418
1459
  const sessionEnabled = Boolean(options.sessionFile || options.sessionDir) || shareEnabled;
1460
+ if (options.context === "fork" && options.sessionFile && existsSync(options.sessionFile)) {
1461
+ alignForkedSessionCwd(options.sessionFile, options.cwd ?? runtimeCwd);
1462
+ }
1419
1463
  const skillNames = options.skills ?? agent.skills ?? [];
1420
1464
  const skillCwd = options.cwd ?? runtimeCwd;
1421
1465
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
@@ -1426,7 +1470,7 @@ async function runSyncCompletion(
1426
1470
  agent.filePath ? path.dirname(agent.filePath) : skillCwd,
1427
1471
  );
1428
1472
  if (skillNames.some((skill) => skill.trim() === "pi-subagents") && missingSkills.includes("pi-subagents")) {
1429
- return withRunContext({
1473
+ return redactResultPrompt(withRunContext({
1430
1474
  index: options.index ?? 0,
1431
1475
  agent: agentName,
1432
1476
  task,
@@ -1434,7 +1478,7 @@ async function runSyncCompletion(
1434
1478
  messages: [],
1435
1479
  usage: emptyUsage(),
1436
1480
  error: "Skills not found: pi-subagents",
1437
- }, options.context);
1481
+ }, options.context));
1438
1482
  }
1439
1483
  let systemPrompt = agent.systemPrompt?.trim() || "";
1440
1484
  if (resolvedSkills.length > 0) {
@@ -1469,7 +1513,7 @@ async function runSyncCompletion(
1469
1513
  artifactPathsResult = getArtifactPaths(options.artifactsDir, options.runId, agentName, options.index);
1470
1514
  ensureArtifactsDir(options.artifactsDir);
1471
1515
  if (options.artifactConfig?.includeInput !== false) {
1472
- writeArtifact(artifactPathsResult.inputPath, `# Task for ${agentName}\n\n${taskWithAcceptance}`);
1516
+ writeArtifact(artifactPathsResult.inputPath, `# Task for ${agentName}\n\n${PROMPT_REDACTED}; live Prompt Audit only.\n`);
1473
1517
  }
1474
1518
  if (options.artifactConfig?.includeJsonl !== false) {
1475
1519
  jsonlPath = artifactPathsResult.jsonlPath;
@@ -1483,7 +1527,7 @@ async function runSyncCompletion(
1483
1527
  childIndex: options.index,
1484
1528
  cwd: options.cwd ?? runtimeCwd,
1485
1529
  });
1486
- transcriptWriter.writeInitialUserMessage(taskWithAcceptance);
1530
+ transcriptWriter.writeInitialUserMessage(`${PROMPT_REDACTED}; live Prompt Audit only.`);
1487
1531
  }
1488
1532
  }
1489
1533
 
@@ -1519,6 +1563,9 @@ async function runSyncCompletion(
1519
1563
  };
1520
1564
  let lastResult: SingleResult | undefined;
1521
1565
  const modelsToTry = candidates.length > 0 ? candidates : [undefined];
1566
+ // Escalated to "file" after an unexplained zero-activity startup failure so
1567
+ // retries keep the task text out of argv (endpoint pre-exec scans may deny it).
1568
+ let taskDeliveryOverride: SubagentTaskDelivery | undefined;
1522
1569
  modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
1523
1570
  const candidate = modelsToTry[modelIndex];
1524
1571
  for (let startupAttemptIndex = 0; ; startupAttemptIndex++) {
@@ -1537,6 +1584,7 @@ async function runSyncCompletion(
1537
1584
  .filter((modelCandidate): modelCandidate is string => Boolean(modelCandidate)),
1538
1585
  outputSnapshot,
1539
1586
  originalTask: task,
1587
+ taskDelivery: taskDeliveryOverride,
1540
1588
  });
1541
1589
  lastResult = result;
1542
1590
  if (startupAttemptIndex === 0) {
@@ -1605,6 +1653,10 @@ async function runSyncCompletion(
1605
1653
  }
1606
1654
  break modelAttemptsLoop;
1607
1655
  }
1656
+ if (!taskDeliveryOverride && result.processSignal === "SIGKILL") {
1657
+ taskDeliveryOverride = "file";
1658
+ attemptNotes.push("[startup-retry] retrying with file task delivery to keep the task text out of the child process argv.");
1659
+ }
1608
1660
  attempt.error = retryNote;
1609
1661
  attemptNotes.push(retryNote);
1610
1662
  continue;
@@ -1719,13 +1771,39 @@ async function runSyncCompletion(
1719
1771
  stripAcceptanceReportsFromMessages(result.messages);
1720
1772
  if (acceptanceFailure && result.acceptance.explicit && result.exitCode === 0 && !result.interrupted && !result.timedOut && !isAgentContractV1(options.agentContract)) {
1721
1773
  result.exitCode = 1;
1774
+ if (result.savedOutputPath) {
1775
+ result.finalOutput = finalizeSingleOutput({
1776
+ fullOutput: result.finalOutput ?? "",
1777
+ outputPath: options.outputPath,
1778
+ outputMode: result.outputMode,
1779
+ exitCode: result.exitCode,
1780
+ preserveSavedOutput: true,
1781
+ savedPath: result.savedOutputPath,
1782
+ outputReference: result.outputReference,
1783
+ }).displayOutput;
1784
+ artifactOutputByResult.set(result, result.finalOutput);
1785
+ }
1722
1786
  result.error = result.error ? `${result.error}\n${acceptanceFailure}` : acceptanceFailure;
1787
+ if (artifactPathsResult && options.artifactConfig?.enabled !== false && options.artifactConfig?.includeOutput !== false) {
1788
+ try {
1789
+ writeArtifact(artifactPathsResult.outputPath, formatOutputArtifactContent({
1790
+ output: artifactOutputByResult.get(result) ?? result.finalOutput ?? "",
1791
+ error: result.error,
1792
+ transcriptPath: result.transcriptPath,
1793
+ metadataPath: options.artifactConfig?.includeMetadata === false ? undefined : artifactPathsResult.metadataPath,
1794
+ }));
1795
+ } catch (error) {
1796
+ const message = `Artifact output post-processing failed: ${error instanceof Error ? error.message : String(error)}`;
1797
+ result.outputSaveError = result.outputSaveError ? `${result.outputSaveError}\n${message}` : message;
1798
+ }
1799
+ }
1723
1800
  if (result.progress) {
1724
1801
  result.progress.status = "failed";
1725
1802
  result.progress.error = result.error;
1726
1803
  }
1727
1804
  }
1728
1805
  if (isAgentContractV1(options.agentContract)) attachContractProjections(result);
1806
+ redactResultPrompt(result);
1729
1807
  try {
1730
1808
  persistResultMetadata(result);
1731
1809
  } catch (error) {
@@ -1810,7 +1888,7 @@ export async function runSync(
1810
1888
  durationMs: publishedReceipt.progressSummary?.durationMs ?? 0,
1811
1889
  error: failureMessage,
1812
1890
  };
1813
- const failedResult: SingleResult = {
1891
+ const failedResult: SingleResult = redactResultPrompt({
1814
1892
  ...publishedReceipt,
1815
1893
  detached: undefined,
1816
1894
  detachedReason,
@@ -1826,7 +1904,7 @@ export async function runSync(
1826
1904
  acceptance: publishedReceipt.acceptance
1827
1905
  ? buildSkippedAcceptanceLedger(publishedReceipt.acceptance.effectiveAcceptance, { id: "completion-pipeline", message: failureMessage })
1828
1906
  : undefined,
1829
- };
1907
+ });
1830
1908
  if (strictContract) attachContractProjections(failedResult);
1831
1909
  try {
1832
1910
  // Replace the provisional detach receipt metadata with the authoritative