@xzzpig/pi-subagents 0.18.0 → 0.19.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 (95) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +1 -1
  3. package/docs/agents.md +18 -12
  4. package/docs/configuration.md +66 -9
  5. package/docs/extension-api.md +5 -4
  6. package/docs/missions.md +13 -13
  7. package/docs/models.md +2 -2
  8. package/docs/observability.md +2 -2
  9. package/docs/standalone-background.md +1 -1
  10. package/docs/tool-reference.md +63 -86
  11. package/docs/workflows.md +170 -172
  12. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  13. package/package.json +6 -6
  14. package/prompts/review-loop.md +1 -1
  15. package/skills/council-mode/SKILL.md +1 -1
  16. package/skills/pi-subagents/SKILL.md +12 -5
  17. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
  18. package/skills/pi-subagents/references/execution-controls.md +68 -67
  19. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  20. package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
  21. package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
  22. package/src/agents/advertised-agent-prompt.ts +21 -41
  23. package/src/agents/agent-management.ts +2 -2
  24. package/src/agents/agents.ts +7 -0
  25. package/src/api/preflight.ts +67 -62
  26. package/src/extension/config.ts +12 -4
  27. package/src/extension/control-notices.ts +3 -0
  28. package/src/extension/doctor.ts +1 -0
  29. package/src/extension/fanout-child.ts +12 -3
  30. package/src/extension/herdr-pi-bridge.ts +2 -0
  31. package/src/extension/index.ts +68 -159
  32. package/src/extension/public-execution.ts +69 -35
  33. package/src/extension/reply-workflow-script.ts +58 -0
  34. package/src/extension/rpc.ts +29 -10
  35. package/src/extension/schemas.ts +36 -133
  36. package/src/extension/tool-activation.ts +57 -108
  37. package/src/extension/tool-description.ts +62 -27
  38. package/src/extension/upgrade-notice.ts +40 -0
  39. package/src/integrations/herdr-status.ts +19 -3
  40. package/src/intercom/native-supervisor-channel.ts +4 -1
  41. package/src/runs/background/async-execution.ts +58 -53
  42. package/src/runs/background/async-job-tracker.ts +63 -22
  43. package/src/runs/background/async-retention.ts +46 -16
  44. package/src/runs/background/await-async-run.ts +76 -0
  45. package/src/runs/background/chain-root-attachment.ts +4 -4
  46. package/src/runs/background/control-channel.ts +18 -2
  47. package/src/runs/background/notify.ts +5 -0
  48. package/src/runs/background/run-child-session.ts +4 -1
  49. package/src/runs/background/run-status.ts +6 -0
  50. package/src/runs/background/runner-aliases.ts +30 -2
  51. package/src/runs/background/runner-child-launch.ts +3 -0
  52. package/src/runs/background/scheduled-runs.ts +5 -5
  53. package/src/runs/background/subagent-runner.ts +15 -1
  54. package/src/runs/foreground/async-stop-action.ts +17 -3
  55. package/src/runs/foreground/execution.ts +130 -125
  56. package/src/runs/foreground/subagent-executor.ts +487 -288
  57. package/src/runs/shared/async-status-projection.ts +5 -0
  58. package/src/runs/shared/child-launch.ts +15 -2
  59. package/src/runs/shared/child-session.ts +92 -6
  60. package/src/runs/shared/child-tool-plan.ts +15 -3
  61. package/src/runs/shared/dynamic-fanout.ts +1 -1
  62. package/src/runs/shared/mcp-config-sources.ts +2 -1
  63. package/src/runs/shared/mcp-direct-tool-allowlist.ts +103 -11
  64. package/src/runs/shared/model-resolution.ts +29 -9
  65. package/src/runs/shared/model-scope.ts +28 -9
  66. package/src/runs/shared/nested-events.ts +55 -55
  67. package/src/runs/shared/parallel-utils.ts +2 -0
  68. package/src/runs/shared/pi-spawn.ts +7 -95
  69. package/src/runs/shared/subagent-prompt-runtime.ts +2 -0
  70. package/src/runs/shared/worktree.ts +1 -1
  71. package/src/shared/disabled-features.ts +123 -0
  72. package/src/shared/extension-context.ts +13 -0
  73. package/src/shared/model-info.ts +9 -0
  74. package/src/shared/settings.ts +1 -1
  75. package/src/shared/types.ts +21 -0
  76. package/src/slash/prompt-template-bridge.ts +2 -2
  77. package/src/slash/slash-commands.ts +10 -5
  78. package/src/slash/subagents-admin.ts +24 -24
  79. package/src/tui/fleet-status.ts +14 -6
  80. package/src/tui/fleet.ts +14 -2
  81. package/src/tui/render.ts +113 -52
  82. package/src/tui/running-tone.ts +28 -0
  83. package/src/watchdog/diff-tool.ts +23 -9
  84. package/src/watchdog/register-child.ts +3 -3
  85. package/src/watchdog/register-main.ts +3 -3
  86. package/src/watchdog/review.ts +2 -2
  87. package/src/watchdog/turn-delta.ts +1 -1
  88. package/src/workflows/chat-progress.ts +2 -2
  89. package/src/workflows/scripted-workflow.ts +117 -37
  90. package/src/workflows/structured-workflow-scripts.ts +177 -0
  91. package/src/workflows/workflow-checklist.ts +6 -0
  92. package/src/workflows/workflow-receipt.ts +8 -2
  93. package/src/workflows/workflow-resources.ts +37 -12
  94. package/src/workflows/workflow-reuse.ts +120 -0
  95. package/src/workflows/workflow-revival.ts +123 -0
@@ -12,7 +12,7 @@ import { createCapacityResilientJsonWriter } from "../../shared/capacity-resilie
12
12
  import { isStorageCapacityError } from "../../shared/file-system-retry.ts";
13
13
  import { updateActiveRunIndex } from "./active-run-index.ts";
14
14
  import { createChildTranscriptWriter, type ChildTranscriptWriter } from "../../shared/child-transcript.ts";
15
- import { closeSteerInbox, consumeInterruptRequest, consumeSteerRequests, consumeStopRequestPayloads, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, watchAsyncControlInbox, type SteerRequest, type StopRequest } from "./control-channel.ts";
15
+ import { closeSteerInbox, closeStopInbox, consumeInterruptRequest, consumeSteerRequests, consumeStopRequestPayloads, deliverInterruptRequest, deliverStopRequest, deliverTimeoutRequest, watchAsyncControlInbox, type SteerRequest, type StopRequest } from "./control-channel.ts";
16
16
  import { appendJsonl as appendRawJsonl, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata } from "../../shared/artifacts.ts";
17
17
  import { PI_CODING_AGENT_PACKAGE, resolveInstalledPiPackageRoot } from "../shared/pi-spawn.ts";
18
18
  import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
@@ -190,6 +190,8 @@ export interface SubagentRunConfig {
190
190
  childSessionFactoryModule?: string;
191
191
  /** The launching executor's own child runtime when it was itself an in-process child. */
192
192
  inheritedChildRuntime?: InheritedChildRuntime;
193
+ /** The launching session's project trust; undefined keeps Pi's default for hosts without trust. */
194
+ projectTrusted?: boolean;
193
195
  worktreeSetupHook?: string;
194
196
  worktreeSetupHookTimeoutMs?: number;
195
197
  worktreeBaseDir?: string;
@@ -685,6 +687,7 @@ interface SingleStepContext {
685
687
  childSessions: ChildSessionFactory;
686
688
  /** The launching executor's own child runtime; nested route, depth, and ceilings come from here. */
687
689
  inheritedChildRuntime?: InheritedChildRuntime;
690
+ projectTrusted?: boolean;
688
691
  registerInterrupt?: (interrupt: (() => void) | undefined) => void;
689
692
  registerTimeout?: (interrupt: (() => void) | undefined) => void;
690
693
  registerStop?: (stop: (() => void) | undefined) => void;
@@ -830,6 +833,7 @@ export async function runSingleStepInner(
830
833
  fast: step.fast,
831
834
  model: step.model,
832
835
  mcpDirectTools: step.mcpDirectTools,
836
+ builtinMcpTools: step.builtinMcpTools,
833
837
  cwd: step.cwd ?? ctx.cwd,
834
838
  requireReadTool: Boolean(step.skills?.length),
835
839
  structuredOutput: Boolean(effectiveStructuredOutput),
@@ -1164,6 +1168,7 @@ export async function runSingleStepInner(
1164
1168
  fast: step.fast,
1165
1169
  model: step.model,
1166
1170
  mcpDirectTools: step.mcpDirectTools,
1171
+ builtinMcpTools: step.builtinMcpTools,
1167
1172
  cwd: step.cwd ?? ctx.cwd,
1168
1173
  requireReadTool: Boolean(step.skills?.length),
1169
1174
  structuredOutput: Boolean(effectiveStructuredOutput),
@@ -3739,6 +3744,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
3739
3744
  artifactsDir, artifactConfig, id,
3740
3745
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
3741
3746
  outputFile: path.join(asyncDir, `output-${fi}.log`),
3747
+ projectTrusted: config.projectTrusted,
3742
3748
  piPackageRoot: config.piPackageRoot,
3743
3749
  childSessions,
3744
3750
  inheritedChildRuntime: config.inheritedChildRuntime,
@@ -4153,6 +4159,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4153
4159
  sessionDir: taskSessionDir,
4154
4160
  artifactsDir, artifactConfig, id,
4155
4161
  flatIndex: fi, flatStepCount: Math.max(statusPayload.steps.length, 1),
4162
+ projectTrusted: config.projectTrusted,
4156
4163
  outputFile: path.join(asyncDir, `output-${fi}.log`),
4157
4164
  piPackageRoot: config.piPackageRoot,
4158
4165
  childSessions,
@@ -4543,6 +4550,7 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4543
4550
  outputs: statusPayload.mode === "single" ? undefined : outputs,
4544
4551
  sessionDir: config.sessionDir,
4545
4552
  artifactsDir, artifactConfig, id,
4553
+ projectTrusted: config.projectTrusted,
4546
4554
  flatIndex, flatStepCount: Math.max(statusPayload.steps.length, 1),
4547
4555
  outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
4548
4556
  piPackageRoot: config.piPackageRoot,
@@ -4890,6 +4898,12 @@ requestedModel: step.requestedModel, contextOverflow: step.contextOverflow,
4890
4898
  timedOut = true;
4891
4899
  }
4892
4900
  disposeControlInbox();
4901
+ try {
4902
+ closeStopInbox(asyncDir);
4903
+ } catch (error) {
4904
+ // Result publication must not depend on the marker; without it a late stop is accepted as before.
4905
+ appendJsonl(eventsPath, JSON.stringify({ type: "subagent.run.stop_inbox_close_failed", ts: Date.now(), runId: id, message: error instanceof Error ? error.message : String(error) }));
4906
+ }
4893
4907
  for (const request of consumeStopRequestPayloads(asyncDir)) stopChildStep(request);
4894
4908
  const signalTerminated = !stopped && !timedOut && !interrupted && results.some((result) => result.exitCode !== 0 && isUnexplainedProcessSignal(omitUndefinedProperties({
4895
4909
  processSignal: result.processSignal,
@@ -4,11 +4,12 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
5
  import { DIRS, type AsyncStatus, type Details, type SubagentState } from "../../shared/types.ts";
6
6
  import { updateActiveRunIndex } from "../background/active-run-index.ts";
7
- import { deliverStopRequest } from "../background/control-channel.ts";
7
+ import { deliverStopRequest, stopInboxClosedPath } from "../background/control-channel.ts";
8
8
  import { readProcessTerminal } from "../background/process-terminal.ts";
9
9
  import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
10
10
  import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
11
- import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
11
+ import { readStatus } from "../../shared/utils.ts";
12
+ import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
12
13
 
13
14
  function getAsyncStopTarget(
14
15
  state: SubagentState,
@@ -108,6 +109,18 @@ export function stopAsyncRun(
108
109
  childId?: string,
109
110
  ): AgentToolResult<Details> | null {
110
111
  const target = getAsyncStopTarget(state, runId, location);
112
+ // An async workflow runs in this process: it has no runner to read a stop request, so stop it through its controller.
113
+ const workflowRunId = target?.asyncId ?? runId;
114
+ const workflowController = childId === undefined && workflowRunId ? state.workflowControllers?.get(workflowRunId) : undefined;
115
+ const workflowAsyncDir = workflowController && workflowRunId ? target?.asyncDir ?? state.asyncJobs.get(workflowRunId)?.asyncDir : undefined;
116
+ const workflowStatus = workflowAsyncDir ? readStatus(workflowAsyncDir) : undefined;
117
+ // Controllers outlive a session switch; a workflow owned by another session falls through to the ownership check below.
118
+ const foreignWorkflow = Boolean(state.currentSessionId && workflowStatus && workflowStatus.sessionId !== state.currentSessionId);
119
+ if (workflowController && workflowRunId && !foreignWorkflow) {
120
+ if (workflowStatus) stopStoppableAsyncStatusChildren(workflowStatus, state.workflowChildStops?.get(workflowRunId), "Workflow stopped.");
121
+ workflowController.abort(new Error("Workflow stopped."));
122
+ return { content: [{ type: "text", text: `Stop requested for async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
123
+ }
111
124
  if (!target) return null;
112
125
  const status = reconcileAsyncRun(target.asyncDir, { kill }).status;
113
126
  if (state.currentSessionId && status?.sessionId !== state.currentSessionId) {
@@ -145,7 +158,8 @@ export function stopAsyncRun(
145
158
  }
146
159
  }
147
160
  try {
148
- deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
161
+ // A paused run whose runner closed its inbox can only be sealed from exact exit proof below.
162
+ if (!(pausedWholeRun && fs.existsSync(stopInboxClosedPath(target.asyncDir)))) deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
149
163
  if (pausedWholeRun) {
150
164
  const failure = sealPausedRun(target.asyncDir, status);
151
165
  if (failure) {
@@ -158,7 +158,7 @@ function persistSingleResultMetadata(input: {
158
158
  toolCount: target.progressSummary?.toolCount,
159
159
  error: target.error,
160
160
  agentContract: target.agentContract,
161
- sandbox: target.sandbox,
161
+ sandbox: target.sandbox,
162
162
  launchContractDigest: target.launchContractDigest,
163
163
  launchResolvedExtensions: target.launchResolvedExtensions,
164
164
  runtimeAcknowledgedExtensions: target.runtimeAcknowledgedExtensions,
@@ -380,8 +380,8 @@ async function runSingleAttempt(
380
380
  })
381
381
  : undefined;
382
382
  const permissionRules = resolvePermissionRules(options.permissions, agent.permissions);
383
- const sandbox = options.sandbox ?? agent.sandbox;
384
- const permissionProfile = options.permissionProfile ?? agent.permissionProfile;
383
+ const sandbox = options.sandbox ?? agent.sandbox;
384
+ const permissionProfile = options.permissionProfile ?? agent.permissionProfile;
385
385
  const permissionAuditPath = permissionRules && options.artifactsDir
386
386
  ? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
387
387
  : undefined;
@@ -426,10 +426,10 @@ const permissionProfile = options.permissionProfile ?? agent.permissionProfile;
426
426
  toolBudget: options.toolBudget,
427
427
  permissionRules,
428
428
  permissionAuditPath,
429
- sandbox,
430
- permissionProfile,
431
- projectTrusted: options.projectTrusted,
432
- trustedProjectCwd: options.trustedProjectCwd,
429
+ sandbox,
430
+ permissionProfile,
431
+ projectTrusted: options.projectTrusted,
432
+ trustedProjectCwd: options.trustedProjectCwd,
433
433
  childWatchdog,
434
434
  // registerChildWatchdog returns before reading the sink when no watchdog exists.
435
435
  watchdogStatus: childWatchdog ? (event) => onWatchdogStatus?.(event) : undefined,
@@ -458,12 +458,12 @@ trustedProjectCwd: options.trustedProjectCwd,
458
458
  ...(fast !== undefined ? { fast } : {}),
459
459
  ...(resolvedThinking ? { thinking: resolvedThinking } : {}),
460
460
  systemPrompt: effectiveSystemPrompt,
461
- systemPromptMode: agent.systemPromptMode,
462
- inheritProjectContext: agent.inheritProjectContext,
463
- inheritGlobalContext: agent.inheritGlobalContext,
464
- inheritSkills: agent.inheritSkills,
465
- sandbox,
466
- permissionProfile,
461
+ systemPromptMode: agent.systemPromptMode,
462
+ inheritProjectContext: agent.inheritProjectContext,
463
+ inheritGlobalContext: agent.inheritGlobalContext,
464
+ inheritSkills: agent.inheritSkills,
465
+ sandbox,
466
+ permissionProfile,
467
467
  skills: shared.resolvedSkillNames ?? [],
468
468
  toolPlan,
469
469
  ...(options.outputPath ? { outputPath: options.outputPath } : {}),
@@ -477,8 +477,8 @@ permissionProfile,
477
477
  task: shared.originalTask ?? task,
478
478
  ...(childSessionName ? { sessionName: childSessionName } : {}),
479
479
  ...(options.agentContract ? { agentContract: options.agentContract } : {}),
480
- ...(sandbox ? { sandbox } : {}),
481
- ...(permissionProfile ? { permissionProfile } : {}),
480
+ ...(sandbox ? { sandbox } : {}),
481
+ ...(permissionProfile ? { permissionProfile } : {}),
482
482
  launchContractDigest,
483
483
  launchResolvedExtensions,
484
484
  exitCode: 0,
@@ -801,11 +801,11 @@ permissionProfile,
801
801
 
802
802
  let activeLongRunningNotified = false;
803
803
  let pendingToolResult: { tool: string; path?: string; mutates: boolean; startedAt?: number } | undefined;
804
- // Pi host versions may represent one tool result as either a dedicated
805
- // tool_result_end event or a message_end whose message role is toolResult.
806
- // Remember correlated ids so normalizing both forms cannot duplicate output.
807
- const handledToolResultIds = new Set<string>();
808
- const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
804
+ // Pi host versions may represent one tool result as either a dedicated
805
+ // tool_result_end event or a message_end whose message role is toolResult.
806
+ // Remember correlated ids so normalizing both forms cannot duplicate output.
807
+ const handledToolResultIds = new Set<string>();
808
+ const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
809
809
  type ActiveToolCall = { key: string; tool: string; args: string; startedAt: number; path?: string };
810
810
  let activeToolSequence = 0;
811
811
  const activeToolCalls = new Map<string, ActiveToolCall>();
@@ -983,68 +983,71 @@ const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
983
983
  emitUpdateSnapshot(output || "(running...)");
984
984
  };
985
985
 
986
- // Fork: shared, id-deduplicated tool-result completion. Pi hosts may
987
- // deliver the same result either as a tool_result_end event or as a
988
- // message_end whose message role is toolResult; both funnel through here
989
- // so one result updates budget, output, and mutating-failure state once.
990
- const handleToolResult = (message: Message, completion: { toolCallId?: unknown; toolName?: unknown }, now: number): void => {
991
- const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
992
- const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
993
- if (callId) {
994
- if (handledToolResultIds.has(callId)) return;
995
- if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
996
- const oldest = handledToolResultIds.values().next().value;
997
- if (typeof oldest === "string") handledToolResultIds.delete(oldest);
998
- }
999
- handledToolResultIds.add(callId);
1000
- }
1001
- result.messages!.push(message);
1002
- const resultText = extractTextFromContent(message.content);
1003
- // The result event's own tool name is authoritative; the single pending slot can
1004
- // describe a different, overlapping call and serves only as a fallback.
1005
- const blockedTool = (typeof completion.toolName === "string" && completion.toolName.length > 0
1006
- ? completion.toolName
1007
- : undefined) ?? pendingToolResult?.tool;
1008
- if (options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool)) {
1009
- result.toolBudgetBlocked = true;
1010
- result.toolBudget = toolBudgetState(
1011
- options.toolBudget,
1012
- Math.max(progress.toolCount, options.toolBudget.hard + 1),
1013
- blockedTool,
1014
- );
1015
- }
1016
- appendRecentOutput(progress, resultText.split("\n").slice(-10));
1017
- const toolSnapshot = pendingToolResult;
1018
- pendingToolResult = undefined;
1019
- if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
1020
- recordMutatingFailure(mutatingFailures, {
1021
- tool: toolSnapshot.tool,
1022
- path: toolSnapshot.path,
1023
- error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
1024
- ts: now,
1025
- }, mutatingFailureWindowMs);
1026
- if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
1027
- emitNeedsAttention(now, {
1028
- message: `${agent.name} needs attention after repeated mutating tool failures`,
1029
- reason: "tool_failures",
1030
- currentTool: toolSnapshot.tool,
1031
- currentPath: toolSnapshot.path,
1032
- currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
1033
- recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
1034
- });
1035
- }
1036
- } else if (toolSnapshot?.mutates) {
1037
- resetMutatingFailureState(mutatingFailures);
1038
- }
1039
- fireUpdate();
1040
- };
986
+ // Fork: shared, id-deduplicated tool-result completion. Pi hosts may
987
+ // deliver the same result either as a tool_result_end event or as a
988
+ // message_end whose message role is toolResult; both funnel through here
989
+ // so one result updates budget, output, and mutating-failure state once.
990
+ const handleToolResult = (message: Message, completion: { toolCallId?: unknown; toolName?: unknown }, now: number): void => {
991
+ const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
992
+ const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
993
+ if (callId) {
994
+ if (handledToolResultIds.has(callId)) return;
995
+ if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
996
+ const oldest = handledToolResultIds.values().next().value;
997
+ if (typeof oldest === "string") handledToolResultIds.delete(oldest);
998
+ }
999
+ handledToolResultIds.add(callId);
1000
+ }
1001
+ result.messages!.push(message);
1002
+ const resultText = extractTextFromContent(message.content);
1003
+ // The result event's own tool name is authoritative; the single pending slot can
1004
+ // describe a different, overlapping call and serves only as a fallback.
1005
+ const blockedTool = (typeof completion.toolName === "string" && completion.toolName.length > 0
1006
+ ? completion.toolName
1007
+ : undefined) ?? pendingToolResult?.tool;
1008
+ if (options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool)) {
1009
+ result.toolBudgetBlocked = true;
1010
+ result.toolBudget = toolBudgetState(
1011
+ options.toolBudget,
1012
+ Math.max(progress.toolCount, options.toolBudget.hard + 1),
1013
+ blockedTool,
1014
+ );
1015
+ }
1016
+ appendRecentOutput(progress, resultText.split("\n").slice(-10));
1017
+ const toolSnapshot = pendingToolResult;
1018
+ pendingToolResult = undefined;
1019
+ if (toolSnapshot?.mutates && didMutatingToolFail(resultText)) {
1020
+ recordMutatingFailure(mutatingFailures, {
1021
+ tool: toolSnapshot.tool,
1022
+ path: toolSnapshot.path,
1023
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
1024
+ ts: now,
1025
+ }, mutatingFailureWindowMs);
1026
+ if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
1027
+ emitNeedsAttention(now, {
1028
+ message: `${agent.name} needs attention after repeated mutating tool failures`,
1029
+ reason: "tool_failures",
1030
+ currentTool: toolSnapshot.tool,
1031
+ currentPath: toolSnapshot.path,
1032
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
1033
+ recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
1034
+ });
1035
+ }
1036
+ } else if (toolSnapshot?.mutates) {
1037
+ resetMutatingFailureState(mutatingFailures);
1038
+ }
1039
+ fireUpdate();
1040
+ };
1041
1041
 
1042
1042
  const processEvent = (evt: ChildSessionEvent & { message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown }) => {
1043
1043
  if (lifecycleFinished) return;
1044
1044
  jsonlWriter.writeLine(JSON.stringify(projectChildSessionEventForJson(evt)));
1045
1045
  shared.transcriptWriter?.writeChildEvent(evt);
1046
1046
  shared.orcaProgressTab?.event(evt);
1047
- if (evt.type === "compaction_start") compactionStartedReceived = true;
1047
+ if (evt.type === "compaction_start") {
1048
+ compactionStartedReceived = true;
1049
+ if (agentSettledReceived) afterCompactionSettlement = true;
1050
+ }
1048
1051
  if (evt.type === "compaction_end" && evt.willRetry === true) {
1049
1052
  compactionStartedReceived = false;
1050
1053
  afterCompactionSettlement = false;
@@ -1141,11 +1144,11 @@ fireUpdate();
1141
1144
  }
1142
1145
 
1143
1146
  if (evt.type === "message_end" && evt.message) {
1144
- if (evt.message.role === "toolResult") {
1145
- // Fork: hosts that deliver tool results as message_end instead of
1146
- // tool_result_end reach the same deduplicated completion path.
1147
- handleToolResult(evt.message, evt, now);
1148
- } else {
1147
+ if (evt.message.role === "toolResult") {
1148
+ // Fork: hosts that deliver tool results as message_end instead of
1149
+ // tool_result_end reach the same deduplicated completion path.
1150
+ handleToolResult(evt.message, evt, now);
1151
+ } else {
1149
1152
  result.messages!.push(evt.message);
1150
1153
  if (childWatchdog) {
1151
1154
  const next = applyChildWatchdogMessage(childWatchdogState, evt.message);
@@ -1176,36 +1179,36 @@ handleToolResult(evt.message, evt, now);
1176
1179
  progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
1177
1180
  }
1178
1181
  projectCompleteUsage();
1179
- if (evt.message.model) {
1180
- progress.model = evt.message.model;
1181
- if (!result.model) result.model = evt.message.model;
1182
- if (expectedModelForVerification && !hasToolCall) {
1183
- const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases);
1184
- if (modelVerificationError && !result.error) result.error = modelVerificationError;
1182
+ if (evt.message.model) {
1183
+ progress.model = evt.message.model;
1184
+ if (!result.model) result.model = evt.message.model;
1185
+ if (expectedModelForVerification && !hasToolCall) {
1186
+ const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels, options.modelResponseAliases);
1187
+ if (modelVerificationError && !result.error) result.error = modelVerificationError;
1188
+ }
1189
+ }
1190
+ if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1191
+ else if (hasToolCall && evt.message.stopReason === "toolUse") {
1192
+ // A recovered request can finish via a terminating tool, without a text stop.
1193
+ assistantError = undefined;
1194
+ }
1195
+ const assistantText = extractTextFromContent(evt.message.content);
1196
+ appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1197
+ // Final assistant message: start the settle drain window.
1198
+ if (terminalAssistantStop) {
1199
+ if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1200
+ cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1201
+ clearAllToolTimeouts();
1202
+ activeToolCalls.clear();
1203
+ activeToolKeysByName.clear();
1204
+ refreshCurrentTool();
1205
+ applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1185
1206
  }
1186
1207
  }
1187
- if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
1188
- else if (hasToolCall && evt.message.stopReason === "toolUse") {
1189
- // A recovered request can finish via a terminating tool, without a text stop.
1190
- assistantError = undefined;
1191
- }
1192
- const assistantText = extractTextFromContent(evt.message.content);
1193
- appendRecentOutput(progress, assistantText.split("\n").slice(-10));
1194
- // Final assistant message: start the settle drain window.
1195
- if (terminalAssistantStop) {
1196
- if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
1197
- cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
1198
- clearAllToolTimeouts();
1199
- activeToolCalls.clear();
1200
- activeToolKeysByName.clear();
1201
- refreshCurrentTool();
1202
- applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
1203
- }
1208
+ updateActivityState(now);
1209
+ fireUpdate();
1204
1210
  }
1205
- updateActivityState(now);
1206
- fireUpdate();
1207
1211
  }
1208
- }
1209
1212
 
1210
1213
  if (evt.type === "tool_result_end" && evt.message) {
1211
1214
  const toolResultCompletion = {
@@ -1222,16 +1225,16 @@ handleToolResult(evt.message, evt, now);
1222
1225
  });
1223
1226
  refreshCurrentTool();
1224
1227
  }
1225
- // Fork: the shared, id-deduplicated tail (message push, budget,
1226
- // mutating-failure tracking, output) lives in handleToolResult; hosts
1227
- // may deliver the same result via message_end(role=toolResult).
1228
- handleToolResult(evt.message, evt, now);
1228
+ // Fork: the shared, id-deduplicated tail (message push, budget,
1229
+ // mutating-failure tracking, output) lives in handleToolResult; hosts
1230
+ // may deliver the same result via message_end(role=toolResult).
1231
+ handleToolResult(evt.message, evt, now);
1229
1232
  }
1230
1233
  };
1231
- // SAFETY: this callback is only ever invoked with child-watchdog status events
1232
- // (declared as ChildWatchdogStatusEvent above); those carry the session-event
1233
- // fields `processEvent` needs, and `processEvent` re-validates the shape with
1234
- // `isChildWatchdogStatusEvent` before touching watchdog-specific fields.
1234
+ // SAFETY: this callback is only ever invoked with child-watchdog status events
1235
+ // (declared as ChildWatchdogStatusEvent above); those carry the session-event
1236
+ // fields `processEvent` needs, and `processEvent` re-validates the shape with
1237
+ // `isChildWatchdogStatusEvent` before touching watchdog-specific fields.
1235
1238
  onWatchdogStatus = (event) => processEvent(event as unknown as Parameters<typeof processEvent>[0]);
1236
1239
 
1237
1240
  fireUpdate();
@@ -1364,6 +1367,8 @@ handleToolResult(evt.message, evt, now);
1364
1367
  if (!closeError && (abortedBySignal || session?.shutDown) && !result.interrupted && !result.timedOut) {
1365
1368
  closeError = session?.shutDown ? "Subagent stopped because the parent session shut down." : STOPPED_BEFORE_COMPLETION_ERROR;
1366
1369
  }
1370
+ // A workflow child ended by the workflow's abort signal was stopped, not failed.
1371
+ if (options.abortedAsStopped && abortedBySignal && !session?.shutDown && !result.interrupted && !result.timedOut) result.stopped = true;
1367
1372
  if (!closeError && forced && !forcedDrainAfterFinalSuccess) {
1368
1373
  closeError = "Subagent session did not settle after it was aborted.";
1369
1374
  }
@@ -1534,17 +1539,17 @@ handleToolResult(evt.message, evt, now);
1534
1539
  && hasEmptyTerminalAssistantResponse(messages)
1535
1540
  && (progress.toolCount > 0 || Boolean(finalText?.trim()));
1536
1541
  if ((missingOutput || terminalEmptyAfterUsefulWork) && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
1537
- // A startup guard can block the first turn, which leaves no message to
1538
- // inspect. Prefer the reason the blocked child published.
1539
- const sandboxDiagnostic = readSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1542
+ // A startup guard can block the first turn, which leaves no message to
1543
+ // inspect. Prefer the reason the blocked child published.
1544
+ const sandboxDiagnostic = readSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1540
1545
  result.exitCode = 1;
1541
- if (sandboxDiagnostic) {
1542
- result.error = sandboxDiagnostic.reason;
1543
- result.startupBlocked = true;
1544
- clearSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1545
- } else {
1546
- result.error = formatEmptyTerminalAssistantResponseError(messages);
1547
- }
1546
+ if (sandboxDiagnostic) {
1547
+ result.error = sandboxDiagnostic.reason;
1548
+ result.startupBlocked = true;
1549
+ clearSandboxStartupDiagnostic(launch.sandboxDiagnosticsPath);
1550
+ } else {
1551
+ result.error = formatEmptyTerminalAssistantResponseError(messages);
1552
+ }
1548
1553
  } else if (errInfo.hasError) {
1549
1554
  result.exitCode = errInfo.exitCode ?? 1;
1550
1555
  result.error = errInfo.details