@xzzpig/pi-subagents 0.2.0 → 0.4.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 (103) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +2 -0
  3. package/agents/oracle.md +7 -5
  4. package/agents/researcher.md +1 -1
  5. package/agents/reviewer.md +2 -2
  6. package/agents/scout.md +1 -1
  7. package/agents/worker.md +1 -1
  8. package/docs/agents.md +3 -0
  9. package/docs/configuration.md +121 -10
  10. package/docs/extension-api.md +36 -0
  11. package/docs/missions.md +5 -3
  12. package/docs/observability.md +43 -3
  13. package/docs/tool-reference.md +20 -3
  14. package/docs/workflows.md +2 -2
  15. package/package.json +4 -4
  16. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  17. package/skills/pi-subagents/references/execution-controls.md +5 -4
  18. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  19. package/skills/pi-subagents/references/prompting-and-roles.md +31 -15
  20. package/src/agents/agent-serializer.ts +2 -0
  21. package/src/agents/agents.ts +46 -15
  22. package/src/api/external-runs.ts +174 -84
  23. package/src/api/preflight.ts +13 -7
  24. package/src/extension/config.ts +59 -0
  25. package/src/extension/doctor.ts +40 -0
  26. package/src/extension/index.ts +83 -9
  27. package/src/extension/public-execution.ts +37 -4
  28. package/src/extension/rpc.ts +8 -10
  29. package/src/extension/schemas.ts +12 -10
  30. package/src/extension/tool-description.ts +13 -9
  31. package/src/inspectors/herdr/actions.ts +13 -8
  32. package/src/inspectors/herdr/inspector-runner.ts +16 -3
  33. package/src/inspectors/herdr/project-panes.ts +2 -6
  34. package/src/inspectors/herdr/shell-command.ts +16 -0
  35. package/src/intercom/intercom-bridge.ts +9 -5
  36. package/src/intercom/native-supervisor-channel.ts +19 -42
  37. package/src/missions/goal-driver.ts +3 -1
  38. package/src/missions/lifecycle.ts +4 -7
  39. package/src/missions/store.ts +12 -7
  40. package/src/missions/workflow-state.ts +6 -2
  41. package/src/runs/background/active-async-capacity.ts +431 -0
  42. package/src/runs/background/active-run-index.ts +77 -3
  43. package/src/runs/background/async-execution.ts +190 -72
  44. package/src/runs/background/async-job-tracker.ts +5 -0
  45. package/src/runs/background/async-resume.ts +21 -7
  46. package/src/runs/background/async-status-snapshot.ts +277 -0
  47. package/src/runs/background/async-status.ts +17 -6
  48. package/src/runs/background/chain-append.ts +33 -15
  49. package/src/runs/background/chain-root-attachment.ts +2 -2
  50. package/src/runs/background/completion-replay.ts +11 -1
  51. package/src/runs/background/fleet-view.ts +21 -6
  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-files.ts +437 -0
  55. package/src/runs/background/result-watcher.ts +188 -41
  56. package/src/runs/background/resume-guidance.ts +27 -7
  57. package/src/runs/background/retained-children.ts +75 -18
  58. package/src/runs/background/run-id-resolver.ts +30 -24
  59. package/src/runs/background/run-status.ts +106 -5
  60. package/src/runs/background/scheduled-runs.ts +54 -28
  61. package/src/runs/background/stale-run-reconciler.ts +30 -16
  62. package/src/runs/background/subagent-runner.ts +352 -62
  63. package/src/runs/background/subagent-wait.ts +2 -0
  64. package/src/runs/background/wait-completions.ts +5 -2
  65. package/src/runs/foreground/async-dismiss-action.ts +2 -1
  66. package/src/runs/foreground/chain-execution.ts +53 -2
  67. package/src/runs/foreground/execution.ts +309 -34
  68. package/src/runs/foreground/foreground-control.ts +12 -0
  69. package/src/runs/foreground/prompt-audit.ts +172 -0
  70. package/src/runs/foreground/subagent-executor.ts +936 -224
  71. package/src/runs/shared/acceptance.ts +13 -4
  72. package/src/runs/shared/completion-guard.ts +107 -1
  73. package/src/runs/shared/external-cli-runner.ts +4 -0
  74. package/src/runs/shared/llm-intent-arbiter.ts +302 -0
  75. package/src/runs/shared/model-fallback.ts +16 -2
  76. package/src/runs/shared/nested-events.ts +66 -62
  77. package/src/runs/shared/orca-progress-tabs.ts +375 -0
  78. package/src/runs/shared/parallel-utils.ts +4 -0
  79. package/src/runs/shared/pi-args.ts +44 -1
  80. package/src/runs/shared/run-fanout-budget.ts +280 -0
  81. package/src/runs/shared/single-output.ts +4 -2
  82. package/src/runs/shared/subagent-control.ts +15 -0
  83. package/src/runs/shared/subagent-prompt-runtime.ts +1 -9
  84. package/src/runs/shared/subagent-startup-retry.ts +12 -0
  85. package/src/runs/shared/task-intent.ts +19 -3
  86. package/src/runs/shared/tool-timeout.ts +93 -0
  87. package/src/runs/shared/worktree.ts +17 -5
  88. package/src/shared/agent-stream-options.ts +5 -0
  89. package/src/shared/artifacts.ts +2 -6
  90. package/src/shared/display-text.ts +50 -0
  91. package/src/shared/node-executable.ts +21 -0
  92. package/src/shared/types.ts +143 -5
  93. package/src/shared/utils.ts +3 -1
  94. package/src/slash/slash-commands.ts +34 -25
  95. package/src/slash/slash-live-state.ts +3 -0
  96. package/src/tui/fleet-status.ts +164 -47
  97. package/src/tui/fleet-transcript.ts +1 -48
  98. package/src/tui/fleet.ts +352 -27
  99. package/src/tui/render.ts +122 -44
  100. package/src/watchdog/permission-arbiter.ts +2 -1
  101. package/src/watchdog/review.ts +4 -3
  102. package/src/workflows/chat-progress.ts +10 -2
  103. package/src/workflows/scripted-workflow.ts +292 -79
@@ -38,6 +38,7 @@ import {
38
38
  buildControlEvent,
39
39
  claimControlNotification,
40
40
  deriveActivityState,
41
+ shouldEmitOpenToolAttention,
41
42
  shouldNotifyControlEvent,
42
43
  } from "../shared/subagent-control.ts";
43
44
  import {
@@ -53,19 +54,22 @@ import {
53
54
  } from "../../shared/utils.ts";
54
55
  import { buildSkillInjection, resolveSkillsWithFallback } from "../../agents/skills.ts";
55
56
  import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
57
+ import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
56
58
  import { evaluateCompletionMutationGuard } from "../shared/completion-guard.ts";
59
+ import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
57
60
  import { getPiSpawnCommand } from "../shared/pi-spawn.ts";
58
61
  import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
62
+ import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
59
63
  import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
60
64
  import { resolvePermissionRules } from "../shared/permissions.ts";
61
- import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan } from "../shared/pi-args.ts";
65
+ import { applyThinkingSuffix, buildPiArgs, cleanupTempDir, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, type SubagentTaskDelivery } from "../shared/pi-args.ts";
62
66
  import { readRuntimeAcknowledgedExtensions } from "../shared/runtime-acknowledged-extensions.ts";
63
67
  import { assertAgentAllowedByCapabilityCeiling, decodeSubagentCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling, SUBAGENT_CAPABILITY_CEILING_ENV } from "../shared/capability-ceiling.ts";
64
68
  import { resolveEffectiveThinking } from "../../shared/model-info.ts";
65
69
  import { MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput } from "../shared/structured-output.ts";
66
70
  import { formatProcessSignalError, isUnexplainedProcessSignal } from "../shared/process-signal.ts";
67
71
  import { readChildToolDiagnosticError } from "../shared/tool-availability.ts";
68
- import { captureSingleOutputSnapshot, extractChildWrittenOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
72
+ import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
69
73
  import {
70
74
  buildModelCandidates,
71
75
  formatModelAttemptNote,
@@ -73,6 +77,7 @@ import {
73
77
  } from "../shared/model-fallback.ts";
74
78
  import {
75
79
  SUBAGENT_STARTUP_RETRY_DELAYS_MS,
80
+ formatSubagentExtensionConflictError,
76
81
  formatSubagentStartupRetryExhaustedError,
77
82
  formatSubagentStartupRetryNote,
78
83
  isRetryableSubagentStartupFailure,
@@ -90,6 +95,7 @@ import {
90
95
  summarizeRecentMutatingFailures,
91
96
  } from "../shared/long-running-guard.ts";
92
97
  import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
98
+ import { PROMPT_REDACTED } from "../../shared/utils.ts";
93
99
  import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
94
100
  import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
95
101
  import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
@@ -117,6 +123,12 @@ function withRunContext<T extends SingleResult>(result: T, context: RunSyncOptio
117
123
  return result;
118
124
  }
119
125
 
126
+ function redactResultPrompt<T extends SingleResult>(result: T): T {
127
+ result.task = PROMPT_REDACTED;
128
+ if (result.progress) result.progress.task = PROMPT_REDACTED;
129
+ return result;
130
+ }
131
+
120
132
  function sumUsage(target: Usage, source: Usage): void {
121
133
  target.input += source.input;
122
134
  target.output += source.output;
@@ -139,7 +151,7 @@ function persistSingleResultMetadata(input: {
139
151
  writeMetadata(input.metadataPath, {
140
152
  runId: input.runId,
141
153
  agent: input.agent,
142
- task: input.task,
154
+ task: PROMPT_REDACTED,
143
155
  exitCode: target.exitCode,
144
156
  processSignal: target.processSignal,
145
157
  usage: target.usage,
@@ -231,6 +243,7 @@ function stripAcceptanceReportsFromMessages(messages: Message[] | undefined): vo
231
243
  function snapshotProgress(progress: AgentProgress): AgentProgress {
232
244
  return {
233
245
  ...progress,
246
+ task: PROMPT_REDACTED,
234
247
  skills: progress.skills ? [...progress.skills] : undefined,
235
248
  recentTools: boundStreamedRecentTools(progress.recentTools),
236
249
  recentOutput: boundStreamedRecentOutput(progress.recentOutput),
@@ -240,6 +253,7 @@ function snapshotProgress(progress: AgentProgress): AgentProgress {
240
253
  function snapshotResult(result: SingleResult, progress: AgentProgress): SingleResult {
241
254
  return {
242
255
  ...result,
256
+ task: PROMPT_REDACTED,
243
257
  messages: result.outputMode === "file-only" && result.savedOutputPath ? undefined : result.messages ? [...result.messages] : undefined,
244
258
  usage: { ...result.usage },
245
259
  skills: result.skills ? [...result.skills] : undefined,
@@ -291,6 +305,8 @@ async function runSingleAttempt(
291
305
  attemptNotes: string[];
292
306
  outputSnapshot?: SingleOutputSnapshot;
293
307
  originalTask?: string;
308
+ taskDelivery?: SubagentTaskDelivery;
309
+ orcaProgressTab?: OrcaProgressTab;
294
310
  },
295
311
  ): Promise<SingleResult> {
296
312
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
@@ -312,6 +328,7 @@ async function runSingleAttempt(
312
328
  const { args, env: sharedEnv, tempDir, toolDiagnosticPath, runtimeAcknowledgedExtensionsPath, capabilityAudit } = buildPiArgs({
313
329
  baseArgs: ["--mode", "json", "-p"],
314
330
  task,
331
+ taskDelivery: shared.taskDelivery,
315
332
  sessionEnabled: shared.sessionEnabled,
316
333
  sessionDir: options.sessionDir,
317
334
  sessionFile: options.sessionFile,
@@ -337,6 +354,7 @@ async function runSingleAttempt(
337
354
  parentControlInbox: options.nestedRoute?.controlInbox,
338
355
  parentRootRunId: options.nestedRoute?.rootRunId,
339
356
  parentCapabilityToken: options.nestedRoute?.capabilityToken,
357
+ runFanoutBudget: options.runFanoutBudget,
340
358
  parentSessionId: options.parentSessionId,
341
359
  steerInboxDir: options.steerInboxDir,
342
360
  steerCapabilityPath: options.steerCapabilityPath,
@@ -657,6 +675,7 @@ async function runSingleAttempt(
657
675
  clearWatchdogTailTimer();
658
676
  clearStdioGuard();
659
677
  clearTimeoutTimers();
678
+ clearAllToolTimeouts();
660
679
  clearTurnBudgetTimers();
661
680
  if (protocolHardKillTimer) {
662
681
  clearTimeout(protocolHardKillTimer);
@@ -681,6 +700,64 @@ async function runSingleAttempt(
681
700
 
682
701
  let activeLongRunningNotified = false;
683
702
  let pendingToolResult: { tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined;
703
+ type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string };
704
+ let activeToolSequence = 0;
705
+ const activeToolCalls = new Map<string, ActiveToolCall>();
706
+ const activeToolKeysByName = new Map<string, string[]>();
707
+ const latestActiveToolCall = (): ActiveToolCall | undefined => [...activeToolCalls.values()].sort((left, right) => right.startedAt - left.startedAt)[0];
708
+ const refreshCurrentTool = (): void => {
709
+ const active = latestActiveToolCall();
710
+ if (!active) {
711
+ progress.currentTool = undefined;
712
+ progress.currentToolArgs = undefined;
713
+ progress.currentToolStartedAt = undefined;
714
+ progress.currentPath = undefined;
715
+ return;
716
+ }
717
+ progress.currentTool = active.tool;
718
+ progress.currentToolArgs = active.args;
719
+ progress.currentToolStartedAt = active.startedAt;
720
+ progress.currentPath = active.path;
721
+ };
722
+ const recordActiveToolCall = (event: { toolCallId?: unknown; toolName: string }, args: Record<string, unknown>, now: number): ActiveToolCall => {
723
+ const key = toolTimeoutCallKey(event, ++activeToolSequence);
724
+ const path = resolveCurrentPath(event.toolName, args);
725
+ const active: ActiveToolCall = {
726
+ key,
727
+ tool: event.toolName,
728
+ args: extractToolArgsPreview(args),
729
+ startedAt: now,
730
+ ...(path !== undefined ? { path } : {}),
731
+ };
732
+ activeToolCalls.set(key, active);
733
+ const keys = activeToolKeysByName.get(active.tool) ?? [];
734
+ keys.push(key);
735
+ activeToolKeysByName.set(active.tool, keys);
736
+ refreshCurrentTool();
737
+ return active;
738
+ };
739
+ const removeActiveToolCallKey = (key: string): ActiveToolCall | undefined => {
740
+ const active = activeToolCalls.get(key);
741
+ if (!active) return undefined;
742
+ activeToolCalls.delete(key);
743
+ const keys = activeToolKeysByName.get(active.tool)?.filter((candidate) => candidate !== key) ?? [];
744
+ if (keys.length > 0) activeToolKeysByName.set(active.tool, keys);
745
+ else activeToolKeysByName.delete(active.tool);
746
+ return active;
747
+ };
748
+ const removeActiveToolCall = (event: { toolCallId?: unknown; toolName?: unknown }): ActiveToolCall | undefined => {
749
+ const key = typeof event.toolCallId === "string" && event.toolCallId.length > 0
750
+ ? `id:${event.toolCallId}`
751
+ : typeof event.toolName === "string"
752
+ ? activeToolKeysByName.get(event.toolName)?.[0]
753
+ : activeToolCalls.size === 1
754
+ ? [...activeToolCalls.keys()][0]
755
+ : undefined;
756
+ return key ? removeActiveToolCallKey(key) : undefined;
757
+ };
758
+ const openToolAttentionTarget = (now: number): ActiveToolCall | undefined => [...activeToolCalls.values()]
759
+ .filter((active) => shouldEmitOpenToolAttention({ config: controlConfig, currentTool: active.tool, currentToolStartedAt: active.startedAt, now }))
760
+ .sort((left, right) => left.startedAt - right.startedAt)[0];
684
761
  const mutatingFailures = createMutatingFailureState();
685
762
  const mutatingFailureWindowMs = 5 * 60_000;
686
763
  const currentToolDurationMs = (now: number) => progress.currentToolStartedAt ? Math.max(0, now - progress.currentToolStartedAt) : undefined;
@@ -798,6 +875,17 @@ async function runSingleAttempt(
798
875
  if (idleState === "needs_attention") {
799
876
  return progress.activityState === "needs_attention" ? false : emitNeedsAttention(now);
800
877
  }
878
+ const toolAttentionTarget = progress.activityState !== "needs_attention" ? openToolAttentionTarget(now) : undefined;
879
+ if (toolAttentionTarget) {
880
+ const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
881
+ return emitNeedsAttention(now, {
882
+ message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1000)}s`,
883
+ reason: "tool_open_threshold",
884
+ currentTool: toolAttentionTarget.tool,
885
+ currentPath: toolAttentionTarget.path,
886
+ currentToolDurationMs: durationMs,
887
+ });
888
+ }
801
889
  const activeReason = nextLongRunningTrigger(controlConfig, {
802
890
  startedAt: startTime,
803
891
  now,
@@ -835,16 +923,18 @@ async function runSingleAttempt(
835
923
  const processLine = (line: string) => {
836
924
  if (!line.trim()) return;
837
925
  jsonlWriter.writeLine(line);
838
- let evt: { type?: string; message?: Message; toolName?: string; args?: unknown; willRetry?: unknown };
926
+ let evt: { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
839
927
  try {
840
- evt = JSON.parse(line) as { type?: string; message?: Message; toolName?: string; args?: unknown; willRetry?: unknown };
928
+ evt = JSON.parse(line) as { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
841
929
  } catch {
842
930
  rawStdoutTail.push(`${line}\n`);
843
931
  shared.transcriptWriter?.writeStdoutLine(line);
932
+ shared.orcaProgressTab?.append(`${line}\n`);
844
933
  // Non-JSON stdout lines are expected; only structured events are parsed.
845
934
  return;
846
935
  }
847
936
  shared.transcriptWriter?.writeChildEvent(evt);
937
+ shared.orcaProgressTab?.event(evt);
848
938
  if (evt.type === "agent_settled") agentSettledReceived = true;
849
939
  applyChildLifecycle(projectChildLifecycle(evt));
850
940
 
@@ -879,6 +969,8 @@ async function runSingleAttempt(
879
969
  const toolArgs = evt.args && typeof evt.args === "object" && !Array.isArray(evt.args)
880
970
  ? evt.args as Record<string, unknown>
881
971
  : {};
972
+ const activeTool = evt.toolName !== undefined ? recordActiveToolCall(evt as { toolCallId?: unknown; toolName: string }, toolArgs, now) : undefined;
973
+ if (evt.toolName !== undefined) armToolTimeout(evt as { toolCallId?: unknown; toolName: string });
882
974
  if (options.structuredOutput && evt.toolName === "structured_output") {
883
975
  structuredOutputToolInvoked = true;
884
976
  structuredOutputMessageStartIndex = result.messages?.length ?? 0;
@@ -890,28 +982,23 @@ async function runSingleAttempt(
890
982
  if (options.toolBudget) {
891
983
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount);
892
984
  }
893
- progress.currentTool = evt.toolName;
894
- progress.currentToolArgs = extractToolArgsPreview(toolArgs);
895
- progress.currentToolStartedAt = now;
896
- progress.currentPath = resolveCurrentPath(evt.toolName, toolArgs);
897
985
  const mutates = isMutatingTool(evt.toolName, toolArgs);
898
986
  observedMutationAttempt = observedMutationAttempt || mutates;
899
- pendingToolResult = { tool: evt.toolName ?? "tool", path: progress.currentPath, mutates, startedAt: now };
987
+ pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
900
988
  fireUpdate();
901
989
  }
902
990
 
903
991
  if (evt.type === "tool_execution_end") {
904
- if (progress.currentTool) {
992
+ clearActiveToolTimeout(evt);
993
+ const endedTool = removeActiveToolCall(evt);
994
+ if (endedTool) {
905
995
  progress.recentTools.push({
906
- tool: progress.currentTool,
907
- args: progress.currentToolArgs || "",
996
+ tool: endedTool.tool,
997
+ args: endedTool.args,
908
998
  endMs: now,
909
999
  });
910
1000
  }
911
- progress.currentTool = undefined;
912
- progress.currentToolArgs = undefined;
913
- progress.currentToolStartedAt = undefined;
914
- progress.currentPath = undefined;
1001
+ refreshCurrentTool();
915
1002
  fireUpdate();
916
1003
  }
917
1004
 
@@ -1009,6 +1096,7 @@ async function runSingleAttempt(
1009
1096
  timeoutTimer = setTimeout(() => {
1010
1097
  if (processClosed || lifecycleFinished || interruptedByControl) return;
1011
1098
  result.timedOut = true;
1099
+ clearAllToolTimeouts();
1012
1100
  result.error = attemptTimeout.message;
1013
1101
  result.finalOutput = attemptTimeout.message;
1014
1102
  progress.status = "failed";
@@ -1030,6 +1118,81 @@ async function runSingleAttempt(
1030
1118
  timeoutTimer.unref?.();
1031
1119
  }
1032
1120
 
1121
+ let toolTimeoutSequence = 0;
1122
+ const activeToolTimeouts = new Map<string, { toolName: string; timer: ReturnType<typeof setTimeout> }>();
1123
+ const activeToolTimeoutKeysByName = new Map<string, string[]>();
1124
+ let toolTimeoutTerminationTimer: ReturnType<typeof setTimeout> | undefined;
1125
+ let toolTimeoutHardKillTimer: ReturnType<typeof setTimeout> | undefined;
1126
+ const removeToolTimeoutKey = (key: string): void => {
1127
+ const active = activeToolTimeouts.get(key);
1128
+ if (!active) return;
1129
+ clearTimeout(active.timer);
1130
+ activeToolTimeouts.delete(key);
1131
+ const keys = activeToolTimeoutKeysByName.get(active.toolName)?.filter((candidate) => candidate !== key) ?? [];
1132
+ if (keys.length > 0) activeToolTimeoutKeysByName.set(active.toolName, keys);
1133
+ else activeToolTimeoutKeysByName.delete(active.toolName);
1134
+ };
1135
+ const clearActiveToolTimeout = (event: { toolCallId?: unknown; toolName?: unknown }): void => {
1136
+ const key = typeof event.toolCallId === "string" && event.toolCallId.length > 0
1137
+ ? `id:${event.toolCallId}`
1138
+ : typeof event.toolName === "string"
1139
+ ? activeToolTimeoutKeysByName.get(event.toolName)?.[0]
1140
+ : activeToolTimeouts.size === 1
1141
+ ? [...activeToolTimeouts.keys()][0]
1142
+ : undefined;
1143
+ if (key) removeToolTimeoutKey(key);
1144
+ };
1145
+ const clearAllToolTimeouts = (): void => {
1146
+ for (const key of [...activeToolTimeouts.keys()]) removeToolTimeoutKey(key);
1147
+ if (toolTimeoutTerminationTimer) {
1148
+ clearTimeout(toolTimeoutTerminationTimer);
1149
+ toolTimeoutTerminationTimer = undefined;
1150
+ }
1151
+ if (toolTimeoutHardKillTimer) {
1152
+ clearTimeout(toolTimeoutHardKillTimer);
1153
+ toolTimeoutHardKillTimer = undefined;
1154
+ }
1155
+ };
1156
+ const terminateForToolTimeout = (message: string): void => {
1157
+ if (processClosed || lifecycleFinished || interruptedByControl) return;
1158
+ result.timedOut = true;
1159
+ result.error = message;
1160
+ result.finalOutput = message;
1161
+ progress.status = "failed";
1162
+ progress.error = message;
1163
+ progress.durationMs = Date.now() - startTime;
1164
+ fireUpdate();
1165
+ trySignalChild(proc, "SIGINT");
1166
+ toolTimeoutTerminationTimer = setTimeout(() => {
1167
+ if (processClosed || lifecycleFinished) return;
1168
+ trySignalChild(proc, "SIGTERM");
1169
+ }, 1000);
1170
+ toolTimeoutTerminationTimer.unref?.();
1171
+ toolTimeoutHardKillTimer = setTimeout(() => {
1172
+ if (processClosed || lifecycleFinished) return;
1173
+ trySignalChild(proc, "SIGKILL");
1174
+ }, 4000);
1175
+ toolTimeoutHardKillTimer.unref?.();
1176
+ };
1177
+ const armToolTimeout = (event: { toolCallId?: unknown; toolName: string }): void => {
1178
+ const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
1179
+ if (timeoutForTool === undefined) return;
1180
+ const elapsed = Date.now() - startTime;
1181
+ const runRemaining = attemptTimeout ? Math.max(0, attemptTimeout.remainingMs - elapsed) : undefined;
1182
+ if (runRemaining !== undefined && timeoutForTool >= runRemaining) return;
1183
+ const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
1184
+ const toolName = event.toolName;
1185
+ const timer = setTimeout(() => {
1186
+ removeToolTimeoutKey(key);
1187
+ terminateForToolTimeout(formatToolTimeoutMessage(toolName, timeoutForTool));
1188
+ }, timeoutForTool);
1189
+ timer.unref?.();
1190
+ activeToolTimeouts.set(key, { toolName, timer });
1191
+ const keys = activeToolTimeoutKeysByName.get(toolName) ?? [];
1192
+ keys.push(key);
1193
+ activeToolTimeoutKeysByName.set(toolName, keys);
1194
+ };
1195
+
1033
1196
  const stderrTail = createBoundedByteTail();
1034
1197
  const failProtocol = (limit: ProtocolOutputLimit): void => {
1035
1198
  if (result.protocolError) return;
@@ -1064,6 +1227,7 @@ async function runSingleAttempt(
1064
1227
  proc.stderr.on("data", (chunk: Buffer) => {
1065
1228
  stderrTail.push(chunk);
1066
1229
  stderrReader.push(chunk);
1230
+ shared.orcaProgressTab?.append(chunk.toString("utf-8"));
1067
1231
  });
1068
1232
  proc.on("exit", () => {
1069
1233
  childExited = true;
@@ -1143,6 +1307,7 @@ async function runSingleAttempt(
1143
1307
  if (result.timedOut) return;
1144
1308
  interruptedByControl = true;
1145
1309
  clearTimeoutTimers();
1310
+ clearAllToolTimeouts();
1146
1311
  progress.status = "running";
1147
1312
  progress.durationMs = Date.now() - startTime;
1148
1313
  result.interrupted = true;
@@ -1188,6 +1353,10 @@ async function runSingleAttempt(
1188
1353
  };
1189
1354
  return result;
1190
1355
  }
1356
+ result.error = formatSubagentExtensionConflictError(result.error, {
1357
+ agent: agent.name,
1358
+ ambientExtensionsEnabled: !launchResolvedExtensions.disableAmbientExtensions,
1359
+ });
1191
1360
  if (result.error && result.exitCode === 0) {
1192
1361
  result.exitCode = 1;
1193
1362
  }
@@ -1277,15 +1446,38 @@ async function runSingleAttempt(
1277
1446
  mcpDirectTools: agent.mcpDirectTools,
1278
1447
  })
1279
1448
  : undefined;
1280
- const completionGuardTriggered = completionGuard?.triggered === true && !observedMutationAttempt;
1449
+ let completionGuardTriggered = completionGuard?.triggered === true && !observedMutationAttempt;
1450
+ // The classifier is deliberately narrow, so a read-only review task can
1451
+ // still be misread as implementation. Arbitrate BEFORE any failure side
1452
+ // effect is published (effects, exit code, progress, notifications,
1453
+ // acceptance, output persistence): only a confident read-only verdict
1454
+ // rescues, and the task text alone is evidence — never the child's own
1455
+ // final message.
1456
+ let arbiterRescued = false;
1457
+ if (completionGuardTriggered) {
1458
+ const arbitration = await arbitrateCompletionGuardRescue({
1459
+ guardTriggered: true,
1460
+ task: shared.originalTask ?? task,
1461
+ arbiter: options.llmIntentArbiter,
1462
+ });
1463
+ completionGuardTriggered = arbitration.triggered;
1464
+ arbiterRescued = arbitration.rescued;
1465
+ }
1281
1466
  if (completionGuard) {
1282
1467
  result.effects = {
1283
1468
  ...(result.effects ?? {}),
1284
1469
  fileMutation: {
1285
- status: completionGuard.expectedMutation ? completionGuardTriggered ? "missing" : "observed" : "not-applicable",
1470
+ status: completionGuard.expectedMutation
1471
+ ? completionGuardTriggered
1472
+ ? "missing"
1473
+ : arbiterRescued
1474
+ ? "not-applicable"
1475
+ : "observed"
1476
+ : "not-applicable",
1286
1477
  expected: completionGuard.expectedMutation,
1287
1478
  attempted: completionGuard.attemptedMutation || observedMutationAttempt,
1288
1479
  ...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
1480
+ ...(arbiterRescued ? { resolvedBy: "llm-intent-arbiter" } : {}),
1289
1481
  },
1290
1482
  };
1291
1483
  }
@@ -1342,7 +1534,7 @@ async function runSingleAttempt(
1342
1534
  /**
1343
1535
  * Run a subagent synchronously (blocking until complete)
1344
1536
  */
1345
- async function runSyncCompletion(
1537
+ async function runSyncCompletionInner(
1346
1538
  runtimeCwd: string,
1347
1539
  agents: AgentConfig[],
1348
1540
  agentName: string,
@@ -1355,7 +1547,7 @@ async function runSyncCompletion(
1355
1547
  };
1356
1548
  const agent = agents.find((a) => a.name === agentName);
1357
1549
  if (!agent) {
1358
- return withRunContext({
1550
+ return redactResultPrompt(withRunContext({
1359
1551
  index: options.index ?? 0,
1360
1552
  agent: agentName,
1361
1553
  task,
@@ -1363,12 +1555,12 @@ async function runSyncCompletion(
1363
1555
  messages: [],
1364
1556
  usage: emptyUsage(),
1365
1557
  error: `Unknown agent: ${agentName}`,
1366
- }, options.context);
1558
+ }, options.context));
1367
1559
  }
1368
1560
  try {
1369
1561
  assertAgentAllowedByCapabilityCeiling(agent.name, options.capabilityCeiling);
1370
1562
  } catch (error) {
1371
- return withRunContext({
1563
+ return redactResultPrompt(withRunContext({
1372
1564
  index: options.index ?? 0,
1373
1565
  agent: agent.name,
1374
1566
  task,
@@ -1377,11 +1569,11 @@ async function runSyncCompletion(
1377
1569
  usage: emptyUsage(),
1378
1570
  error: error instanceof Error ? error.message : String(error),
1379
1571
  ...(options.capabilityCeiling ? { capabilityCeiling: options.capabilityCeiling } : {}),
1380
- }, options.context);
1572
+ }, options.context));
1381
1573
  }
1382
1574
  const acceptanceErrors = validateAcceptanceInput(options.acceptance);
1383
1575
  if (acceptanceErrors.length > 0) {
1384
- return withRunContext({
1576
+ return redactResultPrompt(withRunContext({
1385
1577
  index: options.index ?? 0,
1386
1578
  agent: agentName,
1387
1579
  task,
@@ -1389,11 +1581,29 @@ async function runSyncCompletion(
1389
1581
  messages: [],
1390
1582
  usage: emptyUsage(),
1391
1583
  error: acceptanceErrors.join(" "),
1392
- }, options.context);
1584
+ }, options.context));
1585
+ }
1586
+ const toolTimeout = resolveToolTimeoutMs({
1587
+ callValue: options.toolTimeoutMs,
1588
+ agentValue: agent.defaultToolTimeoutMs,
1589
+ configValue: options.configToolTimeoutMs,
1590
+ envValue: toolTimeoutFromEnv(),
1591
+ });
1592
+ if (toolTimeout.error) {
1593
+ return redactResultPrompt(withRunContext({
1594
+ index: options.index ?? 0,
1595
+ agent: agentName,
1596
+ task,
1597
+ exitCode: 1,
1598
+ messages: [],
1599
+ usage: emptyUsage(),
1600
+ error: toolTimeout.error,
1601
+ }, options.context));
1393
1602
  }
1603
+ options = { ...options, toolTimeoutMs: toolTimeout.toolTimeoutMs };
1394
1604
  const outputModeValidationError = validateFileOnlyOutputMode(options.outputMode, options.outputPath, `Single run (${agentName})`);
1395
1605
  if (outputModeValidationError) {
1396
- return withRunContext({
1606
+ return redactResultPrompt(withRunContext({
1397
1607
  index: options.index ?? 0,
1398
1608
  agent: agentName,
1399
1609
  task,
@@ -1402,7 +1612,7 @@ async function runSyncCompletion(
1402
1612
  usage: emptyUsage(),
1403
1613
  outputMode: options.outputMode,
1404
1614
  error: outputModeValidationError,
1405
- }, options.context);
1615
+ }, options.context));
1406
1616
  }
1407
1617
 
1408
1618
  const shareEnabled = options.share === true;
@@ -1419,6 +1629,7 @@ async function runSyncCompletion(
1419
1629
  });
1420
1630
  const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract) });
1421
1631
  const taskWithAcceptance = acceptancePrompt ? `${task}\n${acceptancePrompt}` : task;
1632
+ options.onEffectivePrompt?.(taskWithAcceptance);
1422
1633
  const sessionEnabled = Boolean(options.sessionFile || options.sessionDir) || shareEnabled;
1423
1634
  if (options.context === "fork" && options.sessionFile && existsSync(options.sessionFile)) {
1424
1635
  alignForkedSessionCwd(options.sessionFile, options.cwd ?? runtimeCwd);
@@ -1433,7 +1644,7 @@ async function runSyncCompletion(
1433
1644
  agent.filePath ? path.dirname(agent.filePath) : skillCwd,
1434
1645
  );
1435
1646
  if (skillNames.some((skill) => skill.trim() === "pi-subagents") && missingSkills.includes("pi-subagents")) {
1436
- return withRunContext({
1647
+ return redactResultPrompt(withRunContext({
1437
1648
  index: options.index ?? 0,
1438
1649
  agent: agentName,
1439
1650
  task,
@@ -1441,7 +1652,7 @@ async function runSyncCompletion(
1441
1652
  messages: [],
1442
1653
  usage: emptyUsage(),
1443
1654
  error: "Skills not found: pi-subagents",
1444
- }, options.context);
1655
+ }, options.context));
1445
1656
  }
1446
1657
  let systemPrompt = agent.systemPrompt?.trim() || "";
1447
1658
  if (resolvedSkills.length > 0) {
@@ -1476,7 +1687,7 @@ async function runSyncCompletion(
1476
1687
  artifactPathsResult = getArtifactPaths(options.artifactsDir, options.runId, agentName, options.index);
1477
1688
  ensureArtifactsDir(options.artifactsDir);
1478
1689
  if (options.artifactConfig?.includeInput !== false) {
1479
- writeArtifact(artifactPathsResult.inputPath, `# Task for ${agentName}\n\n${taskWithAcceptance}`);
1690
+ writeArtifact(artifactPathsResult.inputPath, `# Task for ${agentName}\n\n${PROMPT_REDACTED}; live Prompt Audit only.\n`);
1480
1691
  }
1481
1692
  if (options.artifactConfig?.includeJsonl !== false) {
1482
1693
  jsonlPath = artifactPathsResult.jsonlPath;
@@ -1490,10 +1701,18 @@ async function runSyncCompletion(
1490
1701
  childIndex: options.index,
1491
1702
  cwd: options.cwd ?? runtimeCwd,
1492
1703
  });
1493
- transcriptWriter.writeInitialUserMessage(taskWithAcceptance);
1704
+ transcriptWriter.writeInitialUserMessage(`${PROMPT_REDACTED}; live Prompt Audit only.`);
1494
1705
  }
1495
1706
  }
1496
1707
 
1708
+ const orcaProgressTab = createOrcaProgressTab({
1709
+ cwd: options.cwd ?? runtimeCwd,
1710
+ runId: options.runId,
1711
+ agent: agentName,
1712
+ index: options.index ?? 0,
1713
+ });
1714
+ if (orcaProgressTab) options.onOrcaProgressTabCreated?.(orcaProgressTab);
1715
+
1497
1716
  const persistResultMetadata = (target: SingleResult): void => {
1498
1717
  persistSingleResultMetadata({
1499
1718
  metadataPath: artifactPathsResult?.metadataPath,
@@ -1526,6 +1745,9 @@ async function runSyncCompletion(
1526
1745
  };
1527
1746
  let lastResult: SingleResult | undefined;
1528
1747
  const modelsToTry = candidates.length > 0 ? candidates : [undefined];
1748
+ // Escalated to "file" after an unexplained zero-activity startup failure so
1749
+ // retries keep the task text out of argv (endpoint pre-exec scans may deny it).
1750
+ let taskDeliveryOverride: SubagentTaskDelivery | undefined;
1529
1751
  modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
1530
1752
  const candidate = modelsToTry[modelIndex];
1531
1753
  for (let startupAttemptIndex = 0; ; startupAttemptIndex++) {
@@ -1544,6 +1766,8 @@ async function runSyncCompletion(
1544
1766
  .filter((modelCandidate): modelCandidate is string => Boolean(modelCandidate)),
1545
1767
  outputSnapshot,
1546
1768
  originalTask: task,
1769
+ taskDelivery: taskDeliveryOverride,
1770
+ orcaProgressTab,
1547
1771
  });
1548
1772
  lastResult = result;
1549
1773
  if (startupAttemptIndex === 0) {
@@ -1612,6 +1836,10 @@ async function runSyncCompletion(
1612
1836
  }
1613
1837
  break modelAttemptsLoop;
1614
1838
  }
1839
+ if (!taskDeliveryOverride && result.processSignal === "SIGKILL") {
1840
+ taskDeliveryOverride = "file";
1841
+ attemptNotes.push("[startup-retry] retrying with file task delivery to keep the task text out of the child process argv.");
1842
+ }
1615
1843
  attempt.error = retryNote;
1616
1844
  attemptNotes.push(retryNote);
1617
1845
  continue;
@@ -1726,13 +1954,39 @@ async function runSyncCompletion(
1726
1954
  stripAcceptanceReportsFromMessages(result.messages);
1727
1955
  if (acceptanceFailure && result.acceptance.explicit && result.exitCode === 0 && !result.interrupted && !result.timedOut && !isAgentContractV1(options.agentContract)) {
1728
1956
  result.exitCode = 1;
1957
+ if (result.savedOutputPath) {
1958
+ result.finalOutput = finalizeSingleOutput({
1959
+ fullOutput: result.finalOutput ?? "",
1960
+ outputPath: options.outputPath,
1961
+ outputMode: result.outputMode,
1962
+ exitCode: result.exitCode,
1963
+ preserveSavedOutput: true,
1964
+ savedPath: result.savedOutputPath,
1965
+ outputReference: result.outputReference,
1966
+ }).displayOutput;
1967
+ artifactOutputByResult.set(result, result.finalOutput);
1968
+ }
1729
1969
  result.error = result.error ? `${result.error}\n${acceptanceFailure}` : acceptanceFailure;
1970
+ if (artifactPathsResult && options.artifactConfig?.enabled !== false && options.artifactConfig?.includeOutput !== false) {
1971
+ try {
1972
+ writeArtifact(artifactPathsResult.outputPath, formatOutputArtifactContent({
1973
+ output: artifactOutputByResult.get(result) ?? result.finalOutput ?? "",
1974
+ error: result.error,
1975
+ transcriptPath: result.transcriptPath,
1976
+ metadataPath: options.artifactConfig?.includeMetadata === false ? undefined : artifactPathsResult.metadataPath,
1977
+ }));
1978
+ } catch (error) {
1979
+ const message = `Artifact output post-processing failed: ${error instanceof Error ? error.message : String(error)}`;
1980
+ result.outputSaveError = result.outputSaveError ? `${result.outputSaveError}\n${message}` : message;
1981
+ }
1982
+ }
1730
1983
  if (result.progress) {
1731
1984
  result.progress.status = "failed";
1732
1985
  result.progress.error = result.error;
1733
1986
  }
1734
1987
  }
1735
1988
  if (isAgentContractV1(options.agentContract)) attachContractProjections(result);
1989
+ redactResultPrompt(result);
1736
1990
  try {
1737
1991
  persistResultMetadata(result);
1738
1992
  } catch (error) {
@@ -1742,6 +1996,27 @@ async function runSyncCompletion(
1742
1996
  return result;
1743
1997
  }
1744
1998
 
1999
+ async function runSyncCompletion(
2000
+ runtimeCwd: string,
2001
+ agents: AgentConfig[],
2002
+ agentName: string,
2003
+ task: string,
2004
+ options: RunSyncOptions,
2005
+ ): Promise<SingleResult> {
2006
+ let orcaProgressTab: OrcaProgressTab | undefined;
2007
+ try {
2008
+ const result = await runSyncCompletionInner(runtimeCwd, agents, agentName, task, {
2009
+ ...options,
2010
+ onOrcaProgressTabCreated: (tab) => { orcaProgressTab = tab; },
2011
+ });
2012
+ orcaProgressTab?.finish(result.stopped ? "stopped" : result.exitCode === 0 && !result.error ? "completed" : "failed", result.sessionFile);
2013
+ return result;
2014
+ } catch (error) {
2015
+ orcaProgressTab?.finish("failed");
2016
+ throw error;
2017
+ }
2018
+ }
2019
+
1745
2020
  /**
1746
2021
  * Runs the authoritative completion pipeline independently from the foreground
1747
2022
  * receipt. Detachment is same-runtime only: it does not adopt or daemonize work.
@@ -1817,7 +2092,7 @@ export async function runSync(
1817
2092
  durationMs: publishedReceipt.progressSummary?.durationMs ?? 0,
1818
2093
  error: failureMessage,
1819
2094
  };
1820
- const failedResult: SingleResult = {
2095
+ const failedResult: SingleResult = redactResultPrompt({
1821
2096
  ...publishedReceipt,
1822
2097
  detached: undefined,
1823
2098
  detachedReason,
@@ -1833,7 +2108,7 @@ export async function runSync(
1833
2108
  acceptance: publishedReceipt.acceptance
1834
2109
  ? buildSkippedAcceptanceLedger(publishedReceipt.acceptance.effectiveAcceptance, { id: "completion-pipeline", message: failureMessage })
1835
2110
  : undefined,
1836
- };
2111
+ });
1837
2112
  if (strictContract) attachContractProjections(failedResult);
1838
2113
  try {
1839
2114
  // Replace the provisional detach receipt metadata with the authoritative