@xzzpig/pi-subagents 0.8.0 → 0.9.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.
- package/CHANGELOG.md +443 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +151 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +5 -4
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +48 -18
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +57 -21
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +189 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +676 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +468 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1172 -400
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +15 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +8 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +524 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -2,13 +2,12 @@
|
|
|
2
2
|
* Core execution logic for running subagents
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
import {
|
|
6
|
-
import { existsSync, unlinkSync } from "node:fs";
|
|
5
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
7
6
|
import * as path from "node:path";
|
|
8
7
|
import type { Message } from "@earendil-works/pi-ai";
|
|
9
|
-
import type
|
|
8
|
+
import { discoverAgents, formatUnknownAgentError, unknownAgentDiagnosticContext, type AgentConfig } from "../../agents/agents.ts";
|
|
10
9
|
import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
|
|
11
|
-
import { alignForkedSessionCwd } from "../../shared/fork-
|
|
10
|
+
import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.ts";
|
|
12
11
|
import {
|
|
13
12
|
ensureArtifactsDir,
|
|
14
13
|
formatOutputArtifactContent,
|
|
@@ -31,7 +30,6 @@ import {
|
|
|
31
30
|
type AcceptanceLedger,
|
|
32
31
|
type ResolvedAcceptanceConfig,
|
|
33
32
|
truncateOutput,
|
|
34
|
-
getSubagentDepthEnv,
|
|
35
33
|
} from "../../shared/types.ts";
|
|
36
34
|
import {
|
|
37
35
|
DEFAULT_CONTROL_CONFIG,
|
|
@@ -46,8 +44,10 @@ import {
|
|
|
46
44
|
findLatestSessionFile,
|
|
47
45
|
detectSubagentError,
|
|
48
46
|
hasEmptyTerminalAssistantResponse,
|
|
47
|
+
formatEmptyTerminalAssistantResponseError,
|
|
49
48
|
extractToolArgsPreview,
|
|
50
49
|
extractTextFromContent,
|
|
50
|
+
MAX_STREAMED_RECENT_TOOLS,
|
|
51
51
|
boundStreamedRecentTools,
|
|
52
52
|
boundStreamedRecentOutput,
|
|
53
53
|
boundStreamedToolCalls,
|
|
@@ -55,39 +55,32 @@ import {
|
|
|
55
55
|
import { buildSkillInjection, resolveSkillsWithFallback } from "../../agents/skills.ts";
|
|
56
56
|
import { buildAgentMemoryInjection } from "../../agents/agent-memory.ts";
|
|
57
57
|
import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
|
|
58
|
-
import { evaluateCompletionMutationGuard, validateImplementationToolContract } from "../shared/completion-guard.ts";
|
|
58
|
+
import { evaluateCompletionMutationGuard, expectsImplementationMutation, hasMutationToolCapability, validateImplementationToolContract } from "../shared/completion-guard.ts";
|
|
59
|
+
import { planCompletionEvidence } from "../shared/completion-evidence.ts";
|
|
60
|
+
import { planAbortRecovery } from "../shared/abort-recovery.ts";
|
|
59
61
|
import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
|
|
60
|
-
import {
|
|
62
|
+
import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
|
|
61
63
|
import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
|
|
62
64
|
import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
|
|
63
|
-
import { attachPostExitStdioGuard, trySignalChild } from "../../shared/post-exit-stdio-guard.ts";
|
|
64
65
|
import { resolvePermissionRules } from "../shared/permissions.ts";
|
|
65
|
-
import { applyThinkingSuffix,
|
|
66
|
-
import {
|
|
67
|
-
import { assertAgentAllowedByCapabilityCeiling,
|
|
66
|
+
import { applyThinkingSuffix, deriveForkPromptCacheKey } from "../shared/child-tool-plan.ts";
|
|
67
|
+
import { deriveChildSessionName } from "../../shared/child-session-name.ts";
|
|
68
|
+
import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
|
|
68
69
|
import { resolveEffectiveThinking } from "../../shared/model-info.ts";
|
|
69
|
-
import { assertThinkingWithinCeiling,
|
|
70
|
-
import {
|
|
71
|
-
import {
|
|
72
|
-
import {
|
|
70
|
+
import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
|
|
71
|
+
import { MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
|
|
72
|
+
import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/process-signal.ts";
|
|
73
|
+
import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
|
|
73
74
|
import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.ts";
|
|
74
|
-
import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
|
|
75
|
+
import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, injectOutputPathSystemPrompt, resolveSingleOutput, validateFileOnlyOutputMode, type SingleOutputSnapshot } from "../shared/single-output.ts";
|
|
75
76
|
import {
|
|
76
77
|
buildModelCandidates,
|
|
77
78
|
formatSubagentModelVerificationError,
|
|
78
79
|
formatModelAttemptNote,
|
|
79
80
|
isContextOverflow,
|
|
80
|
-
|
|
81
|
+
isRetryableModelFailureAttempt,
|
|
81
82
|
recordRetryableModelFailure,
|
|
82
83
|
} from "../shared/model-fallback.ts";
|
|
83
|
-
import {
|
|
84
|
-
SUBAGENT_STARTUP_RETRY_DELAYS_MS,
|
|
85
|
-
formatSubagentExtensionConflictError,
|
|
86
|
-
formatSubagentStartupRetryExhaustedError,
|
|
87
|
-
formatSubagentStartupRetryNote,
|
|
88
|
-
isRetryableSubagentStartupFailure,
|
|
89
|
-
waitForSubagentStartupRetry,
|
|
90
|
-
} from "../shared/subagent-startup-retry.ts";
|
|
91
84
|
import {
|
|
92
85
|
createMutatingFailureState,
|
|
93
86
|
didMutatingToolFail,
|
|
@@ -102,18 +95,22 @@ import {
|
|
|
102
95
|
import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
|
|
103
96
|
import { PROMPT_REDACTED } from "../../shared/utils.ts";
|
|
104
97
|
import { attachContractProjections, isAgentContractV1 } from "../shared/agent-contract.ts";
|
|
105
|
-
import { appendTurnBudgetSystemPrompt, formatTurnBudgetOutput, initialTurnBudgetState, turnBudgetDecision, turnBudgetDeferredNote, turnBudgetDeferredState, turnBudgetExceededMessage, turnBudgetSoftNote, turnBudgetState } from "../shared/turn-budget.ts";
|
|
106
98
|
import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
|
|
107
99
|
import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
|
|
108
100
|
import { agentDefinitionDigest, launchBindingDigest } from "../../shared/launch-contract.ts";
|
|
109
|
-
import {
|
|
101
|
+
import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.ts";
|
|
102
|
+
import { projectChildLifecycle, type ChildLifecycleAction, type ChildLifecycleState } from "../shared/child-lifecycle.ts";
|
|
110
103
|
import {
|
|
111
104
|
acceptChildWatchdogEvent,
|
|
105
|
+
applyChildWatchdogMessage,
|
|
112
106
|
childWatchdogIsActive,
|
|
113
107
|
isChildWatchdogStatusEvent,
|
|
114
108
|
resolveChildWatchdogConfig,
|
|
115
109
|
type ChildWatchdogStateSnapshot,
|
|
110
|
+
type ChildWatchdogStatusEvent,
|
|
116
111
|
} from "../../watchdog/child-status.ts";
|
|
112
|
+
import { buildInProcessChildLaunch } from "../shared/child-launch.ts";
|
|
113
|
+
import { childSessionFactory, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent } from "../shared/child-session.ts";
|
|
117
114
|
|
|
118
115
|
const artifactOutputByResult = new WeakMap<SingleResult, string>();
|
|
119
116
|
const acceptanceOutputByResult = new WeakMap<SingleResult, string>();
|
|
@@ -281,8 +278,8 @@ function snapshotResult(result: SingleResult, progress: AgentProgress): SingleRe
|
|
|
281
278
|
/**
|
|
282
279
|
* Streaming variant of snapshotResult for `onUpdate` progress events: it drops the
|
|
283
280
|
* unbounded `messages` transcript in favour of compact tool-call summaries so a
|
|
284
|
-
* single `tool_execution_update`
|
|
285
|
-
*
|
|
281
|
+
* single `tool_execution_update` event stays small; the parent records every
|
|
282
|
+
* one in its transcript and `events.jsonl`. Non-streaming consumers such as
|
|
286
283
|
* foreground detach receipts and terminal consumers use snapshotResult directly.
|
|
287
284
|
*/
|
|
288
285
|
function snapshotStreamResult(result: SingleResult, progress: AgentProgress): SingleResult {
|
|
@@ -292,6 +289,61 @@ function snapshotStreamResult(result: SingleResult, progress: AgentProgress): Si
|
|
|
292
289
|
return snapshot;
|
|
293
290
|
}
|
|
294
291
|
|
|
292
|
+
interface StructuredDelegationProgressState {
|
|
293
|
+
currentTool?: string;
|
|
294
|
+
currentToolArgs?: string;
|
|
295
|
+
recentOutput: string[];
|
|
296
|
+
recentTools: Array<{ tool: string; args: string }>;
|
|
297
|
+
activityState?: AgentProgress["activityState"];
|
|
298
|
+
model?: string;
|
|
299
|
+
toolCount: number;
|
|
300
|
+
tokens: number;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function captureStructuredDelegationProgressState(progress: AgentProgress, result: SingleResult): StructuredDelegationProgressState {
|
|
304
|
+
return {
|
|
305
|
+
currentTool: progress.currentTool,
|
|
306
|
+
currentToolArgs: progress.currentToolArgs,
|
|
307
|
+
recentOutput: [...progress.recentOutput],
|
|
308
|
+
recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
|
|
309
|
+
activityState: progress.activityState,
|
|
310
|
+
model: progress.model ?? result.model,
|
|
311
|
+
toolCount: progress.toolCount,
|
|
312
|
+
tokens: progress.tokens,
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function structuredDelegationProgressChanged(
|
|
317
|
+
previous: StructuredDelegationProgressState,
|
|
318
|
+
progress: AgentProgress,
|
|
319
|
+
result: SingleResult,
|
|
320
|
+
): boolean {
|
|
321
|
+
if (previous.currentTool !== progress.currentTool
|
|
322
|
+
|| previous.currentToolArgs !== progress.currentToolArgs
|
|
323
|
+
|| previous.activityState !== progress.activityState
|
|
324
|
+
|| previous.model !== (progress.model ?? result.model)
|
|
325
|
+
|| previous.toolCount !== progress.toolCount
|
|
326
|
+
|| previous.tokens !== progress.tokens
|
|
327
|
+
|| previous.recentOutput.length !== progress.recentOutput.length) return true;
|
|
328
|
+
for (let index = 0; index < progress.recentOutput.length; index++) {
|
|
329
|
+
if (previous.recentOutput[index] !== progress.recentOutput[index]) return true;
|
|
330
|
+
}
|
|
331
|
+
const recentToolsStart = Math.max(0, progress.recentTools.length - MAX_STREAMED_RECENT_TOOLS);
|
|
332
|
+
if (previous.recentTools.length !== progress.recentTools.length - recentToolsStart) return true;
|
|
333
|
+
for (let index = recentToolsStart; index < progress.recentTools.length; index++) {
|
|
334
|
+
const previousTool = previous.recentTools[index - recentToolsStart];
|
|
335
|
+
const currentTool = progress.recentTools[index];
|
|
336
|
+
if (previousTool?.tool !== currentTool?.tool || previousTool?.args !== currentTool?.args) return true;
|
|
337
|
+
}
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
|
|
342
|
+
type AbortRecoverySingleResult = SingleResult & { [AFTER_COMPACTION_SETTLEMENT]?: true };
|
|
343
|
+
|
|
344
|
+
const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
|
|
345
|
+
|
|
346
|
+
|
|
295
347
|
async function runSingleAttempt(
|
|
296
348
|
runtimeCwd: string,
|
|
297
349
|
agent: AgentConfig,
|
|
@@ -310,7 +362,6 @@ async function runSingleAttempt(
|
|
|
310
362
|
attemptNotes: string[];
|
|
311
363
|
outputSnapshot?: SingleOutputSnapshot;
|
|
312
364
|
originalTask?: string;
|
|
313
|
-
taskDelivery?: SubagentTaskDelivery;
|
|
314
365
|
orcaProgressTab?: OrcaProgressTab;
|
|
315
366
|
launchWarnings: { emitted: boolean };
|
|
316
367
|
verifyModel: boolean;
|
|
@@ -321,6 +372,10 @@ async function runSingleAttempt(
|
|
|
321
372
|
assertThinkingWithinCeiling({ model: modelArg, configThinking: effectiveThinking, ceiling: options.thinkingCeiling, agent: agent.name, runId: options.runId });
|
|
322
373
|
const expectedModelForVerification = shared.verifyModel ? modelArg : undefined;
|
|
323
374
|
const resolvedThinking = resolveEffectiveThinking(modelArg, effectiveThinking);
|
|
375
|
+
// Display name for the child session: applied inside the child through its
|
|
376
|
+
// runtime config and echoed back on the result payload so hosts can label
|
|
377
|
+
// this run without reading the child's session file.
|
|
378
|
+
const childSessionName = deriveChildSessionName({ agent: agent.name, task: shared.originalTask ?? task });
|
|
324
379
|
const watchdogConfig = resolveWatchdogConfig(options.cwd ?? runtimeCwd);
|
|
325
380
|
const childWatchdog = watchdogConfig.ok
|
|
326
381
|
? resolveChildWatchdogConfig({
|
|
@@ -334,75 +389,59 @@ async function runSingleAttempt(
|
|
|
334
389
|
const permissionAuditPath = permissionRules && options.artifactsDir
|
|
335
390
|
? path.join(options.artifactsDir, "permission-audit", `${options.runId}-${options.index ?? 0}.jsonl`)
|
|
336
391
|
: undefined;
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
task,
|
|
340
|
-
taskDelivery: shared.taskDelivery,
|
|
392
|
+
let onWatchdogStatus: ((event: ChildWatchdogStatusEvent) => void) | undefined;
|
|
393
|
+
const launch = buildInProcessChildLaunch({
|
|
341
394
|
sessionEnabled: shared.sessionEnabled,
|
|
342
395
|
sessionDir: options.sessionDir,
|
|
343
396
|
sessionFile: options.sessionFile,
|
|
344
397
|
model: modelArg,
|
|
345
|
-
thinking: effectiveThinking,
|
|
346
398
|
systemPromptMode: agent.systemPromptMode,
|
|
347
399
|
inheritProjectContext: agent.inheritProjectContext,
|
|
400
|
+
inheritGlobalContext: agent.inheritGlobalContext,
|
|
348
401
|
inheritSkills: agent.inheritSkills,
|
|
349
402
|
requireReadTool: Boolean(shared.resolvedSkillNames?.length),
|
|
350
403
|
tools: agent.tools,
|
|
404
|
+
excludeTools: agent.excludeTools,
|
|
405
|
+
allowNestedSubagents: agent.allowNestedSubagents,
|
|
351
406
|
extensions: agent.extensions,
|
|
352
407
|
subagentOnlyExtensions: agent.subagentOnlyExtensions,
|
|
353
|
-
systemPrompt:
|
|
408
|
+
systemPrompt: shared.systemPrompt,
|
|
354
409
|
mcpDirectTools: agent.mcpDirectTools,
|
|
355
410
|
cwd: options.cwd ?? runtimeCwd,
|
|
356
|
-
promptFileStem: agent.name,
|
|
357
411
|
intercomSessionName: options.intercomSessionName,
|
|
412
|
+
sessionName: childSessionName,
|
|
358
413
|
orchestratorIntercomTarget: options.orchestratorIntercomTarget,
|
|
359
414
|
runId: options.runId,
|
|
360
415
|
childAgentName: agent.name,
|
|
361
416
|
childIndex: options.index ?? 0,
|
|
362
|
-
|
|
363
|
-
parentControlInbox: options.nestedRoute?.controlInbox,
|
|
364
|
-
parentRootRunId: options.nestedRoute?.rootRunId,
|
|
365
|
-
parentCapabilityToken: options.nestedRoute?.capabilityToken,
|
|
417
|
+
nestedRoute: options.nestedRoute,
|
|
366
418
|
runFanoutBudget: options.runFanoutBudget,
|
|
367
419
|
parentSessionId: options.parentSessionId,
|
|
368
|
-
|
|
369
|
-
steerCapabilityPath: options.steerCapabilityPath,
|
|
370
|
-
steerAckDir: options.steerAckDir,
|
|
420
|
+
forkCacheKey: options.context === "fork" ? deriveForkPromptCacheKey(options.parentSessionId) : undefined,
|
|
371
421
|
structuredOutput: options.structuredOutput,
|
|
372
422
|
fast: options.fast ?? agent.fast,
|
|
373
423
|
modelCandidates: shared.modelCandidates,
|
|
374
424
|
toolBudget: options.toolBudget,
|
|
375
|
-
allowZeroToolBudget: options.allowZeroToolBudget,
|
|
376
425
|
permissionRules,
|
|
377
426
|
permissionAuditPath,
|
|
378
427
|
childWatchdog,
|
|
428
|
+
watchdogStatus: (event) => onWatchdogStatus?.(event),
|
|
379
429
|
waitToolEnabled: options.waitToolEnabled,
|
|
430
|
+
waitToolDefaultTimeoutMs: options.waitToolDefaultTimeoutMs,
|
|
380
431
|
capabilityCeiling: options.capabilityCeiling,
|
|
381
432
|
thinkingCeiling: options.thinkingCeiling,
|
|
382
|
-
|
|
433
|
+
maxSubagentDepth: options.maxSubagentDepth,
|
|
434
|
+
runtimeSnapshotHost: options.runtimeSnapshotHost,
|
|
435
|
+
inherited: options.childRuntime,
|
|
436
|
+
host: "parent",
|
|
383
437
|
});
|
|
438
|
+
const { toolPlan, capabilityAudit, warnings, launchResolvedExtensions, capture } = launch;
|
|
384
439
|
if (!shared.launchWarnings.emitted && warnings.length > 0) {
|
|
385
440
|
for (const warning of warnings) console.warn(`[pi-subagents] ${warning}`);
|
|
386
441
|
shared.launchWarnings.emitted = true;
|
|
387
442
|
}
|
|
388
443
|
|
|
389
|
-
const effectiveSystemPrompt =
|
|
390
|
-
const toolPlan = resolvePiLaunchToolPlan({
|
|
391
|
-
tools: agent.tools,
|
|
392
|
-
extensions: agent.extensions,
|
|
393
|
-
subagentOnlyExtensions: agent.subagentOnlyExtensions,
|
|
394
|
-
mcpDirectTools: agent.mcpDirectTools,
|
|
395
|
-
cwd: options.cwd ?? runtimeCwd,
|
|
396
|
-
requireReadTool: Boolean(shared.resolvedSkillNames?.length),
|
|
397
|
-
structuredOutput: Boolean(options.structuredOutput),
|
|
398
|
-
fast: options.fast ?? agent.fast,
|
|
399
|
-
model: modelArg,
|
|
400
|
-
modelCandidates: shared.modelCandidates,
|
|
401
|
-
capabilityCeiling: options.capabilityCeiling,
|
|
402
|
-
inheritedCapabilityCeiling: decodeSubagentCapabilityCeiling(process.env[SUBAGENT_CAPABILITY_CEILING_ENV]),
|
|
403
|
-
agentName: agent.name,
|
|
404
|
-
permissionRules,
|
|
405
|
-
});
|
|
444
|
+
const effectiveSystemPrompt = shared.systemPrompt;
|
|
406
445
|
const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
|
|
407
446
|
const contractError = validateImplementationToolContract({
|
|
408
447
|
agent: agent.name,
|
|
@@ -415,11 +454,11 @@ async function runSingleAttempt(
|
|
|
415
454
|
completionGuard: agent.completionGuard,
|
|
416
455
|
});
|
|
417
456
|
if (contractError) {
|
|
418
|
-
cleanupTempDir(tempDir);
|
|
419
457
|
return {
|
|
420
458
|
index: options.index ?? 0,
|
|
421
459
|
agent: agent.name,
|
|
422
460
|
task,
|
|
461
|
+
...(childSessionName ? { sessionName: childSessionName } : {}),
|
|
423
462
|
messages: [],
|
|
424
463
|
finalOutput: "",
|
|
425
464
|
exitCode: 1,
|
|
@@ -433,7 +472,6 @@ async function runSingleAttempt(
|
|
|
433
472
|
...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
|
|
434
473
|
};
|
|
435
474
|
}
|
|
436
|
-
const launchResolvedExtensions = projectLaunchResolvedChildExtensions(toolPlan);
|
|
437
475
|
const launchContractDigest = launchBindingDigest({
|
|
438
476
|
definitionDigest: agentDefinitionDigest(agent),
|
|
439
477
|
task: shared.originalTask ?? task,
|
|
@@ -445,9 +483,11 @@ async function runSingleAttempt(
|
|
|
445
483
|
systemPrompt: effectiveSystemPrompt,
|
|
446
484
|
systemPromptMode: agent.systemPromptMode,
|
|
447
485
|
inheritProjectContext: agent.inheritProjectContext,
|
|
486
|
+
inheritGlobalContext: agent.inheritGlobalContext,
|
|
448
487
|
inheritSkills: agent.inheritSkills,
|
|
449
488
|
skills: shared.resolvedSkillNames ?? [],
|
|
450
489
|
tools: toolPlan.effectiveToolAllowlist,
|
|
490
|
+
...(toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
|
|
451
491
|
extensions: toolPlan.extensionArgs,
|
|
452
492
|
mcpDirectTools: toolPlan.effectiveMcpTools,
|
|
453
493
|
...(options.outputPath ? { outputPath: options.outputPath } : {}),
|
|
@@ -459,6 +499,7 @@ async function runSingleAttempt(
|
|
|
459
499
|
index: options.index ?? 0,
|
|
460
500
|
agent: agent.name,
|
|
461
501
|
task: shared.originalTask ?? task,
|
|
502
|
+
...(childSessionName ? { sessionName: childSessionName } : {}),
|
|
462
503
|
...(options.agentContract ? { agentContract: options.agentContract } : {}),
|
|
463
504
|
launchContractDigest,
|
|
464
505
|
launchResolvedExtensions,
|
|
@@ -472,19 +513,11 @@ async function runSingleAttempt(
|
|
|
472
513
|
transcriptPath: shared.transcriptWriter ? shared.artifactPaths?.transcriptPath : undefined,
|
|
473
514
|
skills: shared.resolvedSkillNames,
|
|
474
515
|
skillsWarning: shared.skillsWarning,
|
|
475
|
-
...(options.turnBudget ? { turnBudget: initialTurnBudgetState(options.turnBudget) } : {}),
|
|
476
516
|
...(options.toolBudget ? { toolBudget: initialToolBudgetState(options.toolBudget) } : {}),
|
|
477
517
|
...(options.capabilityCeiling ? { capabilityCeiling: options.capabilityCeiling } : {}),
|
|
478
518
|
...(capabilityAudit ? { capabilityAudit } : {}),
|
|
479
519
|
}, options.context);
|
|
480
520
|
const startTime = Date.now();
|
|
481
|
-
if (options.structuredOutput) {
|
|
482
|
-
try {
|
|
483
|
-
if (existsSync(options.structuredOutput.outputPath)) unlinkSync(options.structuredOutput.outputPath);
|
|
484
|
-
} catch {
|
|
485
|
-
// Missing/stale structured-output files are handled after the child exits.
|
|
486
|
-
}
|
|
487
|
-
}
|
|
488
521
|
const controlConfig = options.controlConfig ?? DEFAULT_CONTROL_CONFIG;
|
|
489
522
|
let interruptedByControl = false;
|
|
490
523
|
const allControlEvents: ControlEvent[] = [];
|
|
@@ -501,6 +534,7 @@ async function runSingleAttempt(
|
|
|
501
534
|
const progress: AgentProgress = {
|
|
502
535
|
index: options.index ?? 0,
|
|
503
536
|
agent: agent.name,
|
|
537
|
+
...(childSessionName ? { sessionName: childSessionName } : {}),
|
|
504
538
|
status: "running",
|
|
505
539
|
task,
|
|
506
540
|
skills: shared.resolvedSkillNames,
|
|
@@ -518,7 +552,6 @@ async function runSingleAttempt(
|
|
|
518
552
|
result.progress = progress;
|
|
519
553
|
const attemptTimeout = resolveAttemptTimeout(options);
|
|
520
554
|
if (attemptTimeout?.remainingMs === 0) {
|
|
521
|
-
cleanupTempDir(tempDir);
|
|
522
555
|
result.exitCode = 1;
|
|
523
556
|
result.timedOut = true;
|
|
524
557
|
result.error = attemptTimeout.message;
|
|
@@ -532,23 +565,38 @@ async function runSingleAttempt(
|
|
|
532
565
|
};
|
|
533
566
|
return result;
|
|
534
567
|
}
|
|
535
|
-
const spawnEnv = { ...process.env, ...sharedEnv, ...getSubagentDepthEnv(options.maxSubagentDepth) };
|
|
536
568
|
const mutationSnapshot = snapshotTrackedMutations(options.cwd ?? runtimeCwd);
|
|
537
569
|
let observedMutationAttempt = false;
|
|
538
570
|
let structuredOutputToolInvoked = false;
|
|
539
571
|
let structuredOutputMessageStartIndex: number | undefined;
|
|
540
572
|
let toolAvailabilityError: string | undefined;
|
|
573
|
+
let abortedBySignal = options.signal?.aborted === true;
|
|
541
574
|
|
|
542
|
-
|
|
543
|
-
const
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
575
|
+
if (options.workflowChildPermitLaunch) {
|
|
576
|
+
const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
|
|
577
|
+
workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
|
|
578
|
+
childKey: options.workflowChildPermitLaunch.childKey,
|
|
579
|
+
agent: agent.name,
|
|
580
|
+
launchContractDigest,
|
|
581
|
+
context: options.context ?? "fresh",
|
|
582
|
+
runner: "pi",
|
|
549
583
|
});
|
|
550
|
-
|
|
551
|
-
|
|
584
|
+
if (permitError) {
|
|
585
|
+
result.exitCode = 1;
|
|
586
|
+
result.error = permitError;
|
|
587
|
+
result.finalOutput = permitError;
|
|
588
|
+
progress.status = "failed";
|
|
589
|
+
progress.error = permitError;
|
|
590
|
+
return result;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
const childSessions = options.childSessionFactory ?? childSessionFactory();
|
|
594
|
+
let afterCompactionSettlement = false;
|
|
595
|
+
const exitCode = await new Promise<number>((resolve) => {
|
|
596
|
+
const jsonlWriter = createJsonlWriter(shared.jsonlPath, { pause() {}, resume() {} });
|
|
597
|
+
let session: ChildSession | undefined;
|
|
598
|
+
let unsubscribe: (() => void) | undefined;
|
|
599
|
+
let sessionSettled = false;
|
|
552
600
|
let lifecycleFinished = false;
|
|
553
601
|
let detached = false;
|
|
554
602
|
let intercomStarted = false;
|
|
@@ -557,39 +605,26 @@ async function runSingleAttempt(
|
|
|
557
605
|
let removeInterruptListener: (() => void) | undefined;
|
|
558
606
|
let activityTimer: NodeJS.Timeout | undefined;
|
|
559
607
|
let timeoutTimer: NodeJS.Timeout | undefined;
|
|
560
|
-
let
|
|
561
|
-
let timeoutHardKillTimer: NodeJS.Timeout | undefined;
|
|
562
|
-
let turnBudgetSoftReached = false;
|
|
563
|
-
let turnBudgetTerminationTimer: NodeJS.Timeout | undefined;
|
|
564
|
-
let turnBudgetHardKillTimer: NodeJS.Timeout | undefined;
|
|
565
|
-
let protocolHardKillTimer: NodeJS.Timeout | undefined;
|
|
566
|
-
const clearTurnBudgetTimers = () => {
|
|
567
|
-
if (turnBudgetTerminationTimer) {
|
|
568
|
-
clearTimeout(turnBudgetTerminationTimer);
|
|
569
|
-
turnBudgetTerminationTimer = undefined;
|
|
570
|
-
}
|
|
571
|
-
if (turnBudgetHardKillTimer) {
|
|
572
|
-
clearTimeout(turnBudgetHardKillTimer);
|
|
573
|
-
turnBudgetHardKillTimer = undefined;
|
|
574
|
-
}
|
|
575
|
-
};
|
|
608
|
+
let timeoutHardFinishTimer: NodeJS.Timeout | undefined;
|
|
576
609
|
const clearTimeoutTimers = () => {
|
|
577
610
|
if (timeoutTimer) {
|
|
578
611
|
clearTimeout(timeoutTimer);
|
|
579
612
|
timeoutTimer = undefined;
|
|
580
613
|
}
|
|
581
|
-
if (
|
|
582
|
-
clearTimeout(
|
|
583
|
-
|
|
584
|
-
}
|
|
585
|
-
if (timeoutHardKillTimer) {
|
|
586
|
-
clearTimeout(timeoutHardKillTimer);
|
|
587
|
-
timeoutHardKillTimer = undefined;
|
|
614
|
+
if (timeoutHardFinishTimer) {
|
|
615
|
+
clearTimeout(timeoutHardFinishTimer);
|
|
616
|
+
timeoutHardFinishTimer = undefined;
|
|
588
617
|
}
|
|
589
618
|
};
|
|
619
|
+
const abortChild = (): void => {
|
|
620
|
+
if (!session || sessionSettled || lifecycleFinished) return;
|
|
621
|
+
void session.abort().catch(() => {
|
|
622
|
+
// The session settles through its prompt promise; abort failures are not separately actionable.
|
|
623
|
+
});
|
|
624
|
+
};
|
|
590
625
|
|
|
591
626
|
const detachForeground = (reason: string): boolean => {
|
|
592
|
-
if (detached ||
|
|
627
|
+
if (detached || sessionSettled || lifecycleFinished || options.signal?.aborted) return false;
|
|
593
628
|
const receiptProgress = snapshotProgress(progress);
|
|
594
629
|
receiptProgress.status = "detached";
|
|
595
630
|
receiptProgress.durationMs = Date.now() - startTime;
|
|
@@ -624,19 +659,21 @@ async function runSingleAttempt(
|
|
|
624
659
|
}
|
|
625
660
|
if (!accepted) return false;
|
|
626
661
|
detached = true;
|
|
662
|
+
if (session) session.detached = true;
|
|
627
663
|
return true;
|
|
628
664
|
};
|
|
629
665
|
|
|
630
|
-
// If the child emits a terminal assistant stop but never
|
|
631
|
-
//
|
|
666
|
+
// If the child emits a terminal assistant stop but its run never settles
|
|
667
|
+
// (a hook is stuck), abort it after a short grace period and then finish
|
|
668
|
+
// without it.
|
|
632
669
|
const FINAL_STOP_GRACE_MS = 1000;
|
|
633
|
-
const
|
|
634
|
-
let
|
|
635
|
-
let forcedTerminationSignal = false;
|
|
670
|
+
const HARD_FINISH_MS = 3000;
|
|
671
|
+
let forcedTermination = false;
|
|
636
672
|
let cleanTerminalAssistantStopReceived = false;
|
|
637
673
|
let agentSettledReceived = false;
|
|
674
|
+
let compactionStartedReceived = false;
|
|
638
675
|
let finalDrainTimer: NodeJS.Timeout | undefined;
|
|
639
|
-
let
|
|
676
|
+
let finalHardFinishTimer: NodeJS.Timeout | undefined;
|
|
640
677
|
let watchdogTailTimer: NodeJS.Timeout | undefined;
|
|
641
678
|
let childWatchdogState: ChildWatchdogStateSnapshot | undefined;
|
|
642
679
|
const updateChildWatchdogState = (snapshot: ChildWatchdogStateSnapshot): void => {
|
|
@@ -655,9 +692,9 @@ async function runSingleAttempt(
|
|
|
655
692
|
clearTimeout(finalDrainTimer);
|
|
656
693
|
finalDrainTimer = undefined;
|
|
657
694
|
}
|
|
658
|
-
if (
|
|
659
|
-
clearTimeout(
|
|
660
|
-
|
|
695
|
+
if (finalHardFinishTimer) {
|
|
696
|
+
clearTimeout(finalHardFinishTimer);
|
|
697
|
+
finalHardFinishTimer = undefined;
|
|
661
698
|
}
|
|
662
699
|
};
|
|
663
700
|
const startFinalDrain = () => {
|
|
@@ -665,32 +702,30 @@ async function runSingleAttempt(
|
|
|
665
702
|
armWatchdogTail();
|
|
666
703
|
return;
|
|
667
704
|
}
|
|
668
|
-
if (
|
|
705
|
+
if (sessionSettled || finalDrainTimer || lifecycleFinished) return;
|
|
669
706
|
finalDrainTimer = setTimeout(() => {
|
|
670
|
-
if (lifecycleFinished ||
|
|
671
|
-
|
|
672
|
-
if (!termSent) return;
|
|
673
|
-
forcedTerminationSignal = true;
|
|
707
|
+
if (lifecycleFinished || sessionSettled) return;
|
|
708
|
+
forcedTermination = true;
|
|
674
709
|
if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !assistantError) {
|
|
675
|
-
result.error = result.error ?? `Subagent
|
|
710
|
+
result.error = result.error ?? `Subagent session did not settle within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Aborting it.`;
|
|
676
711
|
}
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
712
|
+
abortChild();
|
|
713
|
+
finalHardFinishTimer = setTimeout(() => {
|
|
714
|
+
if (lifecycleFinished || sessionSettled) return;
|
|
715
|
+
settle(undefined, true);
|
|
716
|
+
}, HARD_FINISH_MS);
|
|
717
|
+
finalHardFinishTimer.unref?.();
|
|
682
718
|
}, FINAL_STOP_GRACE_MS);
|
|
683
719
|
finalDrainTimer.unref?.();
|
|
684
720
|
};
|
|
685
721
|
function armWatchdogTail(): void {
|
|
686
|
-
if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || lifecycleFinished ||
|
|
722
|
+
if ((!cleanTerminalAssistantStopReceived && !agentSettledReceived) || watchdogTailTimer || lifecycleFinished || sessionSettled) return;
|
|
687
723
|
watchdogTailTimer = setTimeout(() => {
|
|
688
724
|
watchdogTailTimer = undefined;
|
|
689
725
|
updateChildWatchdogState({
|
|
690
726
|
phase: "stale",
|
|
691
727
|
seq: (childWatchdogState?.seq ?? 0) + 1,
|
|
692
728
|
lastUpdate: Date.now(),
|
|
693
|
-
followUpPending: false,
|
|
694
729
|
reason: "child watchdog tail timeout",
|
|
695
730
|
timedOut: true,
|
|
696
731
|
});
|
|
@@ -707,9 +742,10 @@ async function runSingleAttempt(
|
|
|
707
742
|
}
|
|
708
743
|
if (action === "start-drain") startFinalDrain();
|
|
709
744
|
};
|
|
745
|
+
const childLifecycleState: ChildLifecycleState = { compactionRetryActive: false };
|
|
710
746
|
|
|
711
747
|
const unsubscribeIntercomDetach = options.intercomEvents?.on?.(INTERCOM_DETACH_REQUEST_EVENT, (payload) => {
|
|
712
|
-
if (!options.allowIntercomDetach ||
|
|
748
|
+
if (!options.allowIntercomDetach || sessionSettled) return;
|
|
713
749
|
if (!payload || typeof payload !== "object") return;
|
|
714
750
|
const event = payload as { requestId?: unknown; runId?: unknown; agent?: unknown; childIndex?: unknown };
|
|
715
751
|
const requestId = event.requestId;
|
|
@@ -729,14 +765,8 @@ async function runSingleAttempt(
|
|
|
729
765
|
lifecycleFinished = true;
|
|
730
766
|
clearFinalDrainTimers();
|
|
731
767
|
clearWatchdogTailTimer();
|
|
732
|
-
clearStdioGuard();
|
|
733
768
|
clearTimeoutTimers();
|
|
734
769
|
clearAllToolTimeouts();
|
|
735
|
-
clearTurnBudgetTimers();
|
|
736
|
-
if (protocolHardKillTimer) {
|
|
737
|
-
clearTimeout(protocolHardKillTimer);
|
|
738
|
-
protocolHardKillTimer = undefined;
|
|
739
|
-
}
|
|
740
770
|
if (activityTimer) {
|
|
741
771
|
clearInterval(activityTimer);
|
|
742
772
|
activityTimer = undefined;
|
|
@@ -744,7 +774,13 @@ async function runSingleAttempt(
|
|
|
744
774
|
unsubscribeIntercomDetach?.();
|
|
745
775
|
removeAbortListener?.();
|
|
746
776
|
removeInterruptListener?.();
|
|
747
|
-
|
|
777
|
+
unsubscribe?.();
|
|
778
|
+
onWatchdogStatus = undefined;
|
|
779
|
+
void jsonlWriter.close().catch(() => {
|
|
780
|
+
// JSONL artifact flush is best effort.
|
|
781
|
+
});
|
|
782
|
+
// Report the run only after the child's extensions have shut down.
|
|
783
|
+
void Promise.resolve().then(() => session?.dispose()).catch(() => undefined).then(() => resolve(code));
|
|
748
784
|
};
|
|
749
785
|
|
|
750
786
|
const drainPendingControlEvents = (): ControlEvent[] | undefined => {
|
|
@@ -875,63 +911,13 @@ async function runSingleAttempt(
|
|
|
875
911
|
}));
|
|
876
912
|
return true;
|
|
877
913
|
};
|
|
878
|
-
const requestTurnBudgetAbort = (turnCount: number) => {
|
|
879
|
-
const budget = options.turnBudget;
|
|
880
|
-
if (!budget || result.timedOut || result.turnBudgetExceeded || interruptedByControl || processClosed || lifecycleFinished) return;
|
|
881
|
-
const message = turnBudgetExceededMessage(budget, turnCount);
|
|
882
|
-
result.turnBudgetExceeded = true;
|
|
883
|
-
result.wrapUpRequested = true;
|
|
884
|
-
result.turnBudget = turnBudgetState(budget, turnCount, true);
|
|
885
|
-
result.error = message;
|
|
886
|
-
result.finalOutput = message;
|
|
887
|
-
progress.status = "failed";
|
|
888
|
-
progress.error = message;
|
|
889
|
-
progress.durationMs = Date.now() - startTime;
|
|
890
|
-
fireUpdate();
|
|
891
|
-
trySignalChild(proc, "SIGINT");
|
|
892
|
-
turnBudgetTerminationTimer = setTimeout(() => {
|
|
893
|
-
if (processClosed || lifecycleFinished || result.timedOut) return;
|
|
894
|
-
trySignalChild(proc, "SIGTERM");
|
|
895
|
-
}, 1000);
|
|
896
|
-
turnBudgetTerminationTimer.unref?.();
|
|
897
|
-
turnBudgetHardKillTimer = setTimeout(() => {
|
|
898
|
-
if (processClosed || lifecycleFinished || result.timedOut) return;
|
|
899
|
-
trySignalChild(proc, "SIGKILL");
|
|
900
|
-
}, 4000);
|
|
901
|
-
turnBudgetHardKillTimer.unref?.();
|
|
902
|
-
};
|
|
903
|
-
|
|
904
|
-
const updateTurnBudget = (turnCount: number, terminalAssistantStop: boolean, toolWorkActiveOrStarting: boolean) => {
|
|
905
|
-
const budget = options.turnBudget;
|
|
906
|
-
if (!budget || result.timedOut || result.turnBudgetExceeded) return;
|
|
907
|
-
if (turnCount < budget.maxTurns) {
|
|
908
|
-
result.turnBudget = { ...budget, outcome: "within-budget", turnCount };
|
|
909
|
-
return;
|
|
910
|
-
}
|
|
911
|
-
if (!turnBudgetSoftReached) {
|
|
912
|
-
turnBudgetSoftReached = true;
|
|
913
|
-
result.wrapUpRequested = true;
|
|
914
|
-
appendRecentOutput(progress, [turnBudgetSoftNote(budget, turnCount)]);
|
|
915
|
-
}
|
|
916
|
-
const decision = turnBudgetDecision(budget, turnCount, terminalAssistantStop, toolWorkActiveOrStarting, options.enforceHardTurnLimit);
|
|
917
|
-
if (decision === "defer") {
|
|
918
|
-
result.turnBudget = turnBudgetDeferredState(
|
|
919
|
-
budget,
|
|
920
|
-
turnCount,
|
|
921
|
-
result.turnBudget?.terminationDeferredAtTurn,
|
|
922
|
-
);
|
|
923
|
-
return;
|
|
924
|
-
}
|
|
925
|
-
result.turnBudget = turnBudgetState(budget, turnCount, false);
|
|
926
|
-
if (decision === "abort") requestTurnBudgetAbort(turnCount);
|
|
927
|
-
};
|
|
928
|
-
|
|
929
914
|
const updateActivityState = (now: number): boolean => {
|
|
930
915
|
if (!controlConfig.enabled) return false;
|
|
931
916
|
const idleState = deriveActivityState({
|
|
932
917
|
config: controlConfig,
|
|
933
918
|
startedAt: startTime,
|
|
934
919
|
lastActivityAt: progress.lastActivityAt,
|
|
920
|
+
turnCount: progress.turnCount,
|
|
935
921
|
currentTool: progress.currentTool,
|
|
936
922
|
thinking: resolvedThinking,
|
|
937
923
|
now,
|
|
@@ -960,8 +946,9 @@ async function runSingleAttempt(
|
|
|
960
946
|
};
|
|
961
947
|
|
|
962
948
|
|
|
949
|
+
let lastStructuredDelegationProgressState: StructuredDelegationProgressState | undefined;
|
|
963
950
|
const emitUpdateSnapshot = (text: string) => {
|
|
964
|
-
if (!options.onUpdate ||
|
|
951
|
+
if (!options.onUpdate || sessionSettled) return;
|
|
965
952
|
const progressSnapshot = snapshotProgress(progress);
|
|
966
953
|
const resultSnapshot = snapshotStreamResult(result, progressSnapshot);
|
|
967
954
|
const controlEvents = drainPendingControlEvents();
|
|
@@ -977,19 +964,23 @@ async function runSingleAttempt(
|
|
|
977
964
|
};
|
|
978
965
|
|
|
979
966
|
const fireUpdate = () => {
|
|
980
|
-
if (!options.onUpdate ||
|
|
967
|
+
if (!options.onUpdate || sessionSettled) return;
|
|
981
968
|
progress.durationMs = Date.now() - startTime;
|
|
982
|
-
|
|
969
|
+
if (options.suppressUnchangedDelegationUpdates) {
|
|
970
|
+
if (lastStructuredDelegationProgressState && !structuredDelegationProgressChanged(lastStructuredDelegationProgressState, progress, result)) return;
|
|
971
|
+
lastStructuredDelegationProgressState = captureStructuredDelegationProgressState(progress, result);
|
|
972
|
+
}
|
|
973
|
+
const output = result.timedOut && result.finalOutput ? result.finalOutput : getFinalOutput(result.messages ?? []);
|
|
983
974
|
emitUpdateSnapshot(output || "(running...)");
|
|
984
975
|
};
|
|
985
976
|
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
const callId =
|
|
977
|
+
// Fork: shared, id-deduplicated tool-result completion. Pi hosts may
|
|
978
|
+
// deliver the same result either as a tool_result_end event or as a
|
|
979
|
+
// message_end whose message role is toolResult; both funnel through here
|
|
980
|
+
// so one result updates budget, output, and mutating-failure state once.
|
|
981
|
+
const handleToolResult = (message: Message, completion: { toolCallId?: unknown }, now: number): void => {
|
|
982
|
+
const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
|
|
983
|
+
const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
|
|
993
984
|
if (callId) {
|
|
994
985
|
if (handledToolResultIds.has(callId)) return;
|
|
995
986
|
if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
|
|
@@ -1030,24 +1021,26 @@ async function runSingleAttempt(
|
|
|
1030
1021
|
fireUpdate();
|
|
1031
1022
|
};
|
|
1032
1023
|
|
|
1033
|
-
const
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
jsonlWriter.writeLine(line);
|
|
1037
|
-
let evt: { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
|
|
1038
|
-
try {
|
|
1039
|
-
evt = JSON.parse(line) as { type?: string; message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown };
|
|
1040
|
-
} catch {
|
|
1041
|
-
rawStdoutTail.push(`${line}\n`);
|
|
1042
|
-
shared.transcriptWriter?.writeStdoutLine(line);
|
|
1043
|
-
shared.orcaProgressTab?.append(`${line}\n`);
|
|
1044
|
-
// Non-JSON stdout lines are expected; only structured events are parsed.
|
|
1045
|
-
return;
|
|
1046
|
-
}
|
|
1024
|
+
const processEvent = (evt: ChildSessionEvent & { message?: Message; toolName?: string; toolCallId?: string; args?: unknown; willRetry?: unknown }) => {
|
|
1025
|
+
if (lifecycleFinished) return;
|
|
1026
|
+
jsonlWriter.writeLine(JSON.stringify(projectChildSessionEventForJson(evt)));
|
|
1047
1027
|
shared.transcriptWriter?.writeChildEvent(evt);
|
|
1048
1028
|
shared.orcaProgressTab?.event(evt);
|
|
1049
|
-
if (evt.type === "
|
|
1050
|
-
|
|
1029
|
+
if (evt.type === "compaction_start") compactionStartedReceived = true;
|
|
1030
|
+
if (evt.type === "compaction_end" && evt.willRetry === true) {
|
|
1031
|
+
compactionStartedReceived = false;
|
|
1032
|
+
afterCompactionSettlement = false;
|
|
1033
|
+
}
|
|
1034
|
+
if (evt.type === "agent_start" || evt.type === "auto_retry_start") {
|
|
1035
|
+
compactionStartedReceived = false;
|
|
1036
|
+
afterCompactionSettlement = false;
|
|
1037
|
+
}
|
|
1038
|
+
const lifecycleAction = projectChildLifecycle(evt, false, childLifecycleState);
|
|
1039
|
+
if (evt.type === "agent_settled" && lifecycleAction === "start-drain") {
|
|
1040
|
+
agentSettledReceived = true;
|
|
1041
|
+
afterCompactionSettlement = compactionStartedReceived;
|
|
1042
|
+
}
|
|
1043
|
+
applyChildLifecycle(lifecycleAction);
|
|
1051
1044
|
|
|
1052
1045
|
if (isChildWatchdogStatusEvent(evt)) {
|
|
1053
1046
|
if (!childWatchdog) return;
|
|
@@ -1093,7 +1086,7 @@ async function runSingleAttempt(
|
|
|
1093
1086
|
if (options.toolBudget) {
|
|
1094
1087
|
result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount);
|
|
1095
1088
|
}
|
|
1096
|
-
const mutates = isMutatingTool(evt.toolName, toolArgs);
|
|
1089
|
+
const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
|
|
1097
1090
|
observedMutationAttempt = observedMutationAttempt || mutates;
|
|
1098
1091
|
pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
|
|
1099
1092
|
fireUpdate();
|
|
@@ -1115,24 +1108,26 @@ async function runSingleAttempt(
|
|
|
1115
1108
|
|
|
1116
1109
|
if (evt.type === "message_end" && evt.message) {
|
|
1117
1110
|
if (evt.message.role === "toolResult") {
|
|
1118
|
-
|
|
1111
|
+
// Fork: hosts that deliver tool results as message_end instead of
|
|
1112
|
+
// tool_result_end reach the same deduplicated completion path.
|
|
1113
|
+
handleToolResult(evt.message, evt, now);
|
|
1119
1114
|
} else {
|
|
1120
1115
|
result.messages!.push(evt.message);
|
|
1116
|
+
if (childWatchdog) {
|
|
1117
|
+
const next = applyChildWatchdogMessage(childWatchdogState, evt.message);
|
|
1118
|
+
if (next) updateChildWatchdogState(next);
|
|
1119
|
+
}
|
|
1121
1120
|
if (evt.message.role === "assistant") {
|
|
1122
1121
|
result.usage.turns++;
|
|
1123
1122
|
progress.turnCount = result.usage.turns;
|
|
1124
|
-
const stopReason = (evt.message as { stopReason?: string }).stopReason;
|
|
1125
1123
|
const toolCalls = Array.isArray(evt.message.content)
|
|
1126
1124
|
? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
|
|
1127
1125
|
: [];
|
|
1128
1126
|
const hasToolCall = toolCalls.length > 0;
|
|
1129
|
-
const terminalAssistantStop = stopReason === "stop" && !hasToolCall;
|
|
1130
|
-
const terminalStructuredOutputCall = Boolean(options.structuredOutput)
|
|
1131
|
-
&& toolCalls.length === 1
|
|
1132
|
-
&& (toolCalls[0] as { name?: string }).name === "structured_output";
|
|
1133
|
-
updateTurnBudget(result.usage.turns, terminalAssistantStop || terminalStructuredOutputCall, hasToolCall || Boolean(progress.currentTool));
|
|
1127
|
+
const terminalAssistantStop = (evt.message as { stopReason?: string }).stopReason === "stop" && !hasToolCall;
|
|
1134
1128
|
const u = evt.message.usage;
|
|
1135
1129
|
if (u) {
|
|
1130
|
+
const window = (u.input || 0) + (u.cacheRead || 0);
|
|
1136
1131
|
result.usage.input += u.input || 0;
|
|
1137
1132
|
result.usage.output += u.output || 0;
|
|
1138
1133
|
result.usage.cacheRead += u.cacheRead || 0;
|
|
@@ -1141,24 +1136,29 @@ async function runSingleAttempt(
|
|
|
1141
1136
|
progress.tokens = result.usage.input + result.usage.output;
|
|
1142
1137
|
progress.inputTokens = result.usage.input;
|
|
1143
1138
|
progress.outputTokens = result.usage.output;
|
|
1139
|
+
progress.window = window;
|
|
1140
|
+
progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
|
|
1144
1141
|
}
|
|
1145
1142
|
if (evt.message.model) {
|
|
1146
1143
|
progress.model = evt.message.model;
|
|
1147
1144
|
if (!result.model) result.model = evt.message.model;
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1145
|
+
if (expectedModelForVerification && !hasToolCall) {
|
|
1146
|
+
const modelVerificationError = formatSubagentModelVerificationError(expectedModelForVerification, evt.message.model, options.availableModels);
|
|
1147
|
+
if (modelVerificationError && !result.error) result.error = modelVerificationError;
|
|
1148
|
+
}
|
|
1152
1149
|
}
|
|
1153
|
-
|
|
1154
1150
|
if (evt.message.errorMessage) assistantError = evt.message.errorMessage;
|
|
1155
1151
|
const assistantText = extractTextFromContent(evt.message.content);
|
|
1156
1152
|
appendRecentOutput(progress, assistantText.split("\n").slice(-10));
|
|
1157
|
-
// Final assistant message: start the
|
|
1153
|
+
// Final assistant message: start the settle drain window.
|
|
1158
1154
|
if (terminalAssistantStop) {
|
|
1159
1155
|
if (!evt.message.errorMessage && assistantText.trim()) assistantError = undefined;
|
|
1160
1156
|
cleanTerminalAssistantStopReceived ||= !evt.message.errorMessage;
|
|
1161
|
-
|
|
1157
|
+
clearAllToolTimeouts();
|
|
1158
|
+
activeToolCalls.clear();
|
|
1159
|
+
activeToolKeysByName.clear();
|
|
1160
|
+
refreshCurrentTool();
|
|
1161
|
+
applyChildLifecycle(projectChildLifecycle(evt, true, childLifecycleState));
|
|
1162
1162
|
}
|
|
1163
1163
|
}
|
|
1164
1164
|
updateActivityState(now);
|
|
@@ -1181,17 +1181,18 @@ async function runSingleAttempt(
|
|
|
1181
1181
|
});
|
|
1182
1182
|
refreshCurrentTool();
|
|
1183
1183
|
}
|
|
1184
|
-
// Fork: the shared, id-deduplicated
|
|
1185
|
-
//
|
|
1186
|
-
//
|
|
1187
|
-
handleToolResult(evt.message, now);
|
|
1184
|
+
// Fork: the shared, id-deduplicated tail (message push, budget,
|
|
1185
|
+
// mutating-failure tracking, output) lives in handleToolResult; hosts
|
|
1186
|
+
// may deliver the same result via message_end(role=toolResult).
|
|
1187
|
+
handleToolResult(evt.message, evt, now);
|
|
1188
1188
|
}
|
|
1189
1189
|
};
|
|
1190
|
+
onWatchdogStatus = (event) => processEvent(event as unknown as Parameters<typeof processEvent>[0]);
|
|
1190
1191
|
|
|
1191
1192
|
fireUpdate();
|
|
1192
1193
|
if (controlConfig.enabled || options.onUpdate) {
|
|
1193
1194
|
activityTimer = setInterval(() => {
|
|
1194
|
-
if (
|
|
1195
|
+
if (sessionSettled || lifecycleFinished) {
|
|
1195
1196
|
return;
|
|
1196
1197
|
}
|
|
1197
1198
|
updateActivityState(Date.now());
|
|
@@ -1202,7 +1203,7 @@ async function runSingleAttempt(
|
|
|
1202
1203
|
|
|
1203
1204
|
if (attemptTimeout) {
|
|
1204
1205
|
timeoutTimer = setTimeout(() => {
|
|
1205
|
-
if (
|
|
1206
|
+
if (sessionSettled || lifecycleFinished || interruptedByControl) return;
|
|
1206
1207
|
result.timedOut = true;
|
|
1207
1208
|
clearAllToolTimeouts();
|
|
1208
1209
|
result.error = attemptTimeout.message;
|
|
@@ -1211,17 +1212,12 @@ async function runSingleAttempt(
|
|
|
1211
1212
|
progress.error = attemptTimeout.message;
|
|
1212
1213
|
progress.durationMs = Date.now() - startTime;
|
|
1213
1214
|
fireUpdate();
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
if (
|
|
1217
|
-
|
|
1218
|
-
}, 1000);
|
|
1219
|
-
timeoutTerminationTimer.unref?.();
|
|
1220
|
-
timeoutHardKillTimer = setTimeout(() => {
|
|
1221
|
-
if (processClosed || lifecycleFinished) return;
|
|
1222
|
-
trySignalChild(proc, "SIGKILL");
|
|
1215
|
+
abortChild();
|
|
1216
|
+
timeoutHardFinishTimer = setTimeout(() => {
|
|
1217
|
+
if (sessionSettled || lifecycleFinished) return;
|
|
1218
|
+
settle(undefined, true);
|
|
1223
1219
|
}, 4000);
|
|
1224
|
-
|
|
1220
|
+
timeoutHardFinishTimer.unref?.();
|
|
1225
1221
|
}, attemptTimeout.remainingMs);
|
|
1226
1222
|
timeoutTimer.unref?.();
|
|
1227
1223
|
}
|
|
@@ -1229,8 +1225,7 @@ async function runSingleAttempt(
|
|
|
1229
1225
|
let toolTimeoutSequence = 0;
|
|
1230
1226
|
const activeToolTimeouts = new Map<string, { toolName: string; timer: ReturnType<typeof setTimeout> }>();
|
|
1231
1227
|
const activeToolTimeoutKeysByName = new Map<string, string[]>();
|
|
1232
|
-
let
|
|
1233
|
-
let toolTimeoutHardKillTimer: ReturnType<typeof setTimeout> | undefined;
|
|
1228
|
+
let toolTimeoutHardFinishTimer: ReturnType<typeof setTimeout> | undefined;
|
|
1234
1229
|
const removeToolTimeoutKey = (key: string): void => {
|
|
1235
1230
|
const active = activeToolTimeouts.get(key);
|
|
1236
1231
|
if (!active) return;
|
|
@@ -1252,17 +1247,13 @@ async function runSingleAttempt(
|
|
|
1252
1247
|
};
|
|
1253
1248
|
const clearAllToolTimeouts = (): void => {
|
|
1254
1249
|
for (const key of [...activeToolTimeouts.keys()]) removeToolTimeoutKey(key);
|
|
1255
|
-
if (
|
|
1256
|
-
clearTimeout(
|
|
1257
|
-
|
|
1258
|
-
}
|
|
1259
|
-
if (toolTimeoutHardKillTimer) {
|
|
1260
|
-
clearTimeout(toolTimeoutHardKillTimer);
|
|
1261
|
-
toolTimeoutHardKillTimer = undefined;
|
|
1250
|
+
if (toolTimeoutHardFinishTimer) {
|
|
1251
|
+
clearTimeout(toolTimeoutHardFinishTimer);
|
|
1252
|
+
toolTimeoutHardFinishTimer = undefined;
|
|
1262
1253
|
}
|
|
1263
1254
|
};
|
|
1264
1255
|
const terminateForToolTimeout = (message: string): void => {
|
|
1265
|
-
if (
|
|
1256
|
+
if (sessionSettled || lifecycleFinished || interruptedByControl) return;
|
|
1266
1257
|
result.timedOut = true;
|
|
1267
1258
|
result.error = message;
|
|
1268
1259
|
result.finalOutput = message;
|
|
@@ -1270,17 +1261,12 @@ async function runSingleAttempt(
|
|
|
1270
1261
|
progress.error = message;
|
|
1271
1262
|
progress.durationMs = Date.now() - startTime;
|
|
1272
1263
|
fireUpdate();
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
if (
|
|
1276
|
-
|
|
1277
|
-
}, 1000);
|
|
1278
|
-
toolTimeoutTerminationTimer.unref?.();
|
|
1279
|
-
toolTimeoutHardKillTimer = setTimeout(() => {
|
|
1280
|
-
if (processClosed || lifecycleFinished) return;
|
|
1281
|
-
trySignalChild(proc, "SIGKILL");
|
|
1264
|
+
abortChild();
|
|
1265
|
+
toolTimeoutHardFinishTimer = setTimeout(() => {
|
|
1266
|
+
if (sessionSettled || lifecycleFinished) return;
|
|
1267
|
+
settle(undefined, true);
|
|
1282
1268
|
}, 4000);
|
|
1283
|
-
|
|
1269
|
+
toolTimeoutHardFinishTimer.unref?.();
|
|
1284
1270
|
};
|
|
1285
1271
|
const armToolTimeout = (event: { toolCallId?: unknown; toolName: string }): void => {
|
|
1286
1272
|
const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
|
|
@@ -1301,107 +1287,42 @@ async function runSingleAttempt(
|
|
|
1301
1287
|
activeToolTimeoutKeysByName.set(toolName, keys);
|
|
1302
1288
|
};
|
|
1303
1289
|
|
|
1304
|
-
|
|
1305
|
-
const
|
|
1306
|
-
if (
|
|
1307
|
-
|
|
1308
|
-
result.error = formatProtocolOutputLimit(limit);
|
|
1309
|
-
progress.status = "failed";
|
|
1310
|
-
progress.error = result.error;
|
|
1311
|
-
progress.durationMs = Date.now() - startTime;
|
|
1312
|
-
fireUpdate();
|
|
1313
|
-
if (!childExited) {
|
|
1314
|
-
trySignalChild(proc, "SIGTERM");
|
|
1315
|
-
protocolHardKillTimer = setTimeout(() => {
|
|
1316
|
-
if (!childExited) trySignalChild(proc, "SIGKILL");
|
|
1317
|
-
}, 3000);
|
|
1318
|
-
protocolHardKillTimer.unref?.();
|
|
1319
|
-
}
|
|
1320
|
-
};
|
|
1321
|
-
const stdoutReader = createBoundedLineReader({
|
|
1322
|
-
oversizedLineProjector: PI_AGGREGATE_EVENT_PROJECTOR,
|
|
1323
|
-
onLine: processLine,
|
|
1324
|
-
onLimit: failProtocol,
|
|
1325
|
-
});
|
|
1326
|
-
const stderrReader = createBoundedLineReader({
|
|
1327
|
-
stream: "stderr",
|
|
1328
|
-
maxPendingLineBytes: MAX_CHILD_STDERR_BYTES,
|
|
1329
|
-
onLine: (line) => shared.transcriptWriter?.writeStderrLine(line),
|
|
1330
|
-
onLimit: (limit) => shared.transcriptWriter?.writeStderrLine(formatProtocolOutputLimit(limit)),
|
|
1331
|
-
});
|
|
1332
|
-
|
|
1333
|
-
const clearStdioGuard = attachPostExitStdioGuard(proc, { idleMs: 2000, hardMs: 8000 });
|
|
1334
|
-
proc.stdout.on("data", (chunk: Buffer) => stdoutReader.push(chunk));
|
|
1335
|
-
proc.stderr.on("data", (chunk: Buffer) => {
|
|
1336
|
-
stderrTail.push(chunk);
|
|
1337
|
-
stderrReader.push(chunk);
|
|
1338
|
-
shared.orcaProgressTab?.append(chunk.toString("utf-8"));
|
|
1339
|
-
});
|
|
1340
|
-
proc.on("exit", () => {
|
|
1341
|
-
childExited = true;
|
|
1290
|
+
/** The child run ended (or was forced to end); fold in the captures and finish. */
|
|
1291
|
+
const settle = (promptError: unknown, forced = false): void => {
|
|
1292
|
+
if (lifecycleFinished || sessionSettled) return;
|
|
1293
|
+
sessionSettled = true;
|
|
1342
1294
|
clearFinalDrainTimers();
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
if (lifecycleFinished) return;
|
|
1346
|
-
processClosed = true;
|
|
1347
|
-
clearFinalDrainTimers();
|
|
1348
|
-
clearStdioGuard();
|
|
1349
|
-
void jsonlWriter.close().catch(() => {
|
|
1350
|
-
// JSONL artifact flush is best effort.
|
|
1351
|
-
});
|
|
1352
|
-
const toolDiagnosticError = readChildToolDiagnosticError(toolDiagnosticPath);
|
|
1295
|
+
const diagnostic = capture.toolDiagnostic();
|
|
1296
|
+
const toolDiagnosticError = diagnostic ? formatChildToolDiagnostic(diagnostic, { host: "parent" }) : undefined;
|
|
1353
1297
|
toolAvailabilityError = toolDiagnosticError;
|
|
1354
|
-
result.runtimeAcknowledgedExtensions =
|
|
1355
|
-
cleanupTempDir(tempDir);
|
|
1356
|
-
stdoutReader.end();
|
|
1357
|
-
stderrReader.end();
|
|
1358
|
-
const stderr = stderrTail.text();
|
|
1359
|
-
const rawStdout = rawStdoutTail.text();
|
|
1298
|
+
result.runtimeAcknowledgedExtensions = capture.runtimeAcknowledgedExtensions();
|
|
1360
1299
|
let closeError = result.error ?? toolDiagnosticError ?? assistantError;
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
if (!closeError && isUnexplainedProcessSignal({
|
|
1364
|
-
processSignal: signal,
|
|
1365
|
-
interrupted: result.interrupted,
|
|
1366
|
-
timedOut: result.timedOut,
|
|
1367
|
-
stopped: result.stopped,
|
|
1368
|
-
turnBudgetExceeded: result.turnBudgetExceeded,
|
|
1369
|
-
forcedDrainAfterFinalSuccess,
|
|
1370
|
-
})) {
|
|
1371
|
-
closeError = formatProcessSignalError(signal!);
|
|
1300
|
+
if (!closeError && promptError !== undefined) {
|
|
1301
|
+
closeError = promptError instanceof Error ? promptError.message : String(promptError);
|
|
1372
1302
|
}
|
|
1373
|
-
|
|
1374
|
-
|
|
1303
|
+
const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !closeError;
|
|
1304
|
+
const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(result.messages ?? []);
|
|
1305
|
+
if (!closeError && (abortedBySignal || session?.shutDown) && !result.interrupted && !result.timedOut) {
|
|
1306
|
+
closeError = session?.shutDown ? "Subagent stopped because the parent session shut down." : STOPPED_BEFORE_COMPLETION_ERROR;
|
|
1375
1307
|
}
|
|
1376
|
-
if (
|
|
1377
|
-
closeError =
|
|
1308
|
+
if (!closeError && forced && !forcedDrainAfterFinalSuccess) {
|
|
1309
|
+
closeError = "Subagent session did not settle after it was aborted.";
|
|
1378
1310
|
}
|
|
1379
|
-
const finalCode = forcedDrainAfterFinalSuccess ? 0 :
|
|
1311
|
+
const finalCode = forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal ? 0 : closeError || promptError !== undefined ? 1 : 0;
|
|
1380
1312
|
if (!result.error && closeError) result.error = closeError;
|
|
1381
1313
|
finish(finalCode);
|
|
1382
|
-
}
|
|
1383
|
-
proc.on("error", (error) => {
|
|
1384
|
-
if (lifecycleFinished) return;
|
|
1385
|
-
processClosed = true;
|
|
1386
|
-
clearFinalDrainTimers();
|
|
1387
|
-
clearStdioGuard();
|
|
1388
|
-
void jsonlWriter.close().catch(() => {
|
|
1389
|
-
// JSONL artifact flush is best effort.
|
|
1390
|
-
});
|
|
1391
|
-
cleanupTempDir(tempDir);
|
|
1392
|
-
stdoutReader.end();
|
|
1393
|
-
stderrReader.end();
|
|
1394
|
-
if (!result.error) {
|
|
1395
|
-
result.error = error instanceof Error ? error.message : String(error);
|
|
1396
|
-
}
|
|
1397
|
-
finish(1);
|
|
1398
|
-
});
|
|
1314
|
+
};
|
|
1399
1315
|
|
|
1400
1316
|
if (options.signal) {
|
|
1401
1317
|
const kill = () => {
|
|
1402
|
-
if (
|
|
1403
|
-
|
|
1404
|
-
|
|
1318
|
+
if (sessionSettled || lifecycleFinished) return;
|
|
1319
|
+
abortedBySignal = true;
|
|
1320
|
+
abortChild();
|
|
1321
|
+
const hardTimer = setTimeout(() => {
|
|
1322
|
+
if (sessionSettled || lifecycleFinished) return;
|
|
1323
|
+
settle(undefined, true);
|
|
1324
|
+
}, 3000);
|
|
1325
|
+
hardTimer.unref?.();
|
|
1405
1326
|
};
|
|
1406
1327
|
if (options.signal.aborted) kill();
|
|
1407
1328
|
else {
|
|
@@ -1412,7 +1333,7 @@ async function runSingleAttempt(
|
|
|
1412
1333
|
|
|
1413
1334
|
if (options.interruptSignal) {
|
|
1414
1335
|
const interrupt = () => {
|
|
1415
|
-
if (
|
|
1336
|
+
if (sessionSettled || lifecycleFinished) return;
|
|
1416
1337
|
if (result.timedOut) return;
|
|
1417
1338
|
interruptedByControl = true;
|
|
1418
1339
|
clearTimeoutTimers();
|
|
@@ -1423,11 +1344,12 @@ async function runSingleAttempt(
|
|
|
1423
1344
|
result.finalOutput = "Interrupted. Waiting for explicit next action.";
|
|
1424
1345
|
progress.activityState = undefined;
|
|
1425
1346
|
fireUpdate();
|
|
1426
|
-
|
|
1427
|
-
setTimeout(() => {
|
|
1428
|
-
if (
|
|
1429
|
-
|
|
1430
|
-
},
|
|
1347
|
+
abortChild();
|
|
1348
|
+
const hardTimer = setTimeout(() => {
|
|
1349
|
+
if (sessionSettled || lifecycleFinished) return;
|
|
1350
|
+
settle(undefined, true);
|
|
1351
|
+
}, 3000);
|
|
1352
|
+
hardTimer.unref?.();
|
|
1431
1353
|
};
|
|
1432
1354
|
if (options.interruptSignal.aborted) interrupt();
|
|
1433
1355
|
else {
|
|
@@ -1442,11 +1364,40 @@ async function runSingleAttempt(
|
|
|
1442
1364
|
options.onDetachReady?.((reason = "user request") => detachForeground(reason));
|
|
1443
1365
|
} catch (error) {
|
|
1444
1366
|
// A consumer callback is advisory. Keep the child attached and observable
|
|
1445
|
-
// rather than rejecting this attempt and orphaning its live
|
|
1367
|
+
// rather than rejecting this attempt and orphaning its live session.
|
|
1446
1368
|
appendRecentOutput(progress, [`Foreground detach callback failed: ${error instanceof Error ? error.message : String(error)}`]);
|
|
1447
1369
|
}
|
|
1370
|
+
|
|
1371
|
+
void (async () => {
|
|
1372
|
+
try {
|
|
1373
|
+
const created = await childSessions.create({
|
|
1374
|
+
...launch.session,
|
|
1375
|
+
onExtensionError: (error) => {
|
|
1376
|
+
shared.transcriptWriter?.writeStderrLine(`Extension error (${error.extensionPath}, ${error.event}): ${error.error instanceof Error ? error.error.message : String(error.error)}`);
|
|
1377
|
+
},
|
|
1378
|
+
});
|
|
1379
|
+
if (lifecycleFinished) {
|
|
1380
|
+
void created.dispose();
|
|
1381
|
+
return;
|
|
1382
|
+
}
|
|
1383
|
+
session = created;
|
|
1384
|
+
created.detached = detached;
|
|
1385
|
+
unsubscribe = created.subscribe((event) => processEvent(event as Parameters<typeof processEvent>[0]));
|
|
1386
|
+
if (abortedBySignal || interruptedByControl || result.timedOut) {
|
|
1387
|
+
abortChild();
|
|
1388
|
+
}
|
|
1389
|
+
options.onChildSession?.({ steer: (text) => created.steer(text), followUp: (text) => created.followUp(text) });
|
|
1390
|
+
await created.prompt(`Task: ${task}`);
|
|
1391
|
+
settle(undefined);
|
|
1392
|
+
} catch (error) {
|
|
1393
|
+
settle(error ?? new Error("Child session failed."));
|
|
1394
|
+
}
|
|
1395
|
+
})();
|
|
1448
1396
|
});
|
|
1449
1397
|
result.exitCode = exitCode;
|
|
1398
|
+
if (afterCompactionSettlement) {
|
|
1399
|
+
(result as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT] = true;
|
|
1400
|
+
}
|
|
1450
1401
|
if (interruptedByControl) {
|
|
1451
1402
|
result.exitCode = 0;
|
|
1452
1403
|
result.interrupted = true;
|
|
@@ -1462,10 +1413,15 @@ async function runSingleAttempt(
|
|
|
1462
1413
|
};
|
|
1463
1414
|
return result;
|
|
1464
1415
|
}
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1416
|
+
if (progress.currentTool
|
|
1417
|
+
&& isOrdinaryToolForMidToolExit(progress.currentTool)
|
|
1418
|
+
&& !abortedBySignal
|
|
1419
|
+
&& !result.timedOut
|
|
1420
|
+
&& !result.stopped
|
|
1421
|
+
&& !toolAvailabilityError) {
|
|
1422
|
+
result.exitCode = 1;
|
|
1423
|
+
result.error = formatMidToolExitError({ toolName: progress.currentTool });
|
|
1424
|
+
}
|
|
1469
1425
|
if (result.error && result.exitCode === 0) {
|
|
1470
1426
|
result.exitCode = 1;
|
|
1471
1427
|
}
|
|
@@ -1473,27 +1429,23 @@ async function runSingleAttempt(
|
|
|
1473
1429
|
if (options.structuredOutput && result.exitCode === 0 && !result.error) {
|
|
1474
1430
|
result.structuredOutputSchemaPath = options.structuredOutput.schemaPath;
|
|
1475
1431
|
result.structuredOutputPath = options.structuredOutput.outputPath;
|
|
1476
|
-
|
|
1432
|
+
const structured = capture.structuredOutput();
|
|
1433
|
+
if (!structuredOutputToolInvoked || !structured.called) {
|
|
1477
1434
|
result.exitCode = 1;
|
|
1478
1435
|
result.error = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
|
|
1479
1436
|
result.structuredOutputFailed = true;
|
|
1480
1437
|
} else {
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
const acceptanceReport = readStructuredOutputAcceptanceReport(options.structuredOutput);
|
|
1493
|
-
(result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReport = acceptanceReport.value;
|
|
1494
|
-
(result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReport.error;
|
|
1495
|
-
validatedStructuredOutput = true;
|
|
1496
|
-
}
|
|
1438
|
+
result.structuredOutput = structured.value;
|
|
1439
|
+
const acceptanceMode = options.structuredOutput.acceptanceReportPath
|
|
1440
|
+
? options.structuredOutput.acceptanceReportRequired ? "required" : "optional"
|
|
1441
|
+
: undefined;
|
|
1442
|
+
const acceptanceReportError = acceptanceMode === "required" && !structured.acceptanceReportProvided
|
|
1443
|
+
? MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR
|
|
1444
|
+
: undefined;
|
|
1445
|
+
(result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReport = acceptanceMode ? structured.acceptanceReport : undefined;
|
|
1446
|
+
(result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReportError;
|
|
1447
|
+
writeStructuredOutputArtifacts(options.structuredOutput, structured.value, acceptanceMode ? structured.acceptanceReport : undefined);
|
|
1448
|
+
validatedStructuredOutput = true;
|
|
1497
1449
|
}
|
|
1498
1450
|
}
|
|
1499
1451
|
if (result.exitCode === 0 && !result.error) {
|
|
@@ -1504,9 +1456,12 @@ async function runSingleAttempt(
|
|
|
1504
1456
|
: messages;
|
|
1505
1457
|
const errInfo = detectSubagentError(errorMessages);
|
|
1506
1458
|
const missingOutput = !finalText?.trim() && !validatedStructuredOutput;
|
|
1507
|
-
|
|
1459
|
+
const terminalEmptyAfterUsefulWork = !validatedStructuredOutput
|
|
1460
|
+
&& hasEmptyTerminalAssistantResponse(messages)
|
|
1461
|
+
&& (progress.toolCount > 0 || Boolean(finalText?.trim()));
|
|
1462
|
+
if ((missingOutput || terminalEmptyAfterUsefulWork) && (!errInfo.hasError || hasEmptyTerminalAssistantResponse(messages))) {
|
|
1508
1463
|
result.exitCode = 1;
|
|
1509
|
-
result.error =
|
|
1464
|
+
result.error = formatEmptyTerminalAssistantResponseError(messages);
|
|
1510
1465
|
} else if (errInfo.hasError) {
|
|
1511
1466
|
result.exitCode = errInfo.exitCode ?? 1;
|
|
1512
1467
|
result.error = errInfo.details
|
|
@@ -1525,6 +1480,7 @@ async function runSingleAttempt(
|
|
|
1525
1480
|
}
|
|
1526
1481
|
|
|
1527
1482
|
result.progressSummary = {
|
|
1483
|
+
...(childSessionName ? { sessionName: childSessionName } : {}),
|
|
1528
1484
|
toolCount: progress.toolCount,
|
|
1529
1485
|
tokens: progress.tokens,
|
|
1530
1486
|
durationMs: progress.durationMs,
|
|
@@ -1537,9 +1493,17 @@ async function runSingleAttempt(
|
|
|
1537
1493
|
result.outputState = fullOutput.trim() || result.structuredOutput !== undefined ? "present" : "absent";
|
|
1538
1494
|
if (result.timedOut) {
|
|
1539
1495
|
const timeoutMessage = formatTimeoutMessage(options.timeoutMs ?? 0);
|
|
1496
|
+
let requiredOutputMissing: boolean | undefined;
|
|
1497
|
+
if (options.outputMode === "file-only" && options.outputPath) {
|
|
1498
|
+
const outputChanged = hasSingleOutputChangedSinceSnapshot(options.outputPath, shared.outputSnapshot);
|
|
1499
|
+
requiredOutputMissing = outputChanged === undefined ? undefined : !outputChanged;
|
|
1500
|
+
} else if (options.structuredOutput) {
|
|
1501
|
+
requiredOutputMissing = !capture.structuredOutput().called;
|
|
1502
|
+
}
|
|
1540
1503
|
result.timeoutRecovery = buildTimeoutRecoverySummary({
|
|
1541
1504
|
termination: "timed-out",
|
|
1542
1505
|
evidence: mutationEvidence,
|
|
1506
|
+
requiredOutputMissing,
|
|
1543
1507
|
currentTool: progress.currentTool,
|
|
1544
1508
|
currentToolArgs: progress.currentToolArgs,
|
|
1545
1509
|
currentPath: progress.currentPath,
|
|
@@ -1550,14 +1514,6 @@ async function runSingleAttempt(
|
|
|
1550
1514
|
fullOutput = fullOutput.trim()
|
|
1551
1515
|
? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
|
|
1552
1516
|
: `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
|
|
1553
|
-
} else if (result.turnBudgetExceeded && result.turnBudget) {
|
|
1554
|
-
fullOutput = formatTurnBudgetOutput(turnBudgetExceededMessage(result.turnBudget, result.turnBudget.turnCount), fullOutput);
|
|
1555
|
-
} else if (result.turnBudget?.outcome === "termination-deferred") {
|
|
1556
|
-
const note = turnBudgetDeferredNote(result.turnBudget, result.turnBudget.terminationDeferredAtTurn ?? result.turnBudget.turnCount);
|
|
1557
|
-
fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
|
|
1558
|
-
} else if (result.wrapUpRequested && result.turnBudget?.outcome === "wrap-up-requested") {
|
|
1559
|
-
const note = turnBudgetSoftNote(result.turnBudget, result.turnBudget.wrapUpRequestedAtTurn ?? result.turnBudget.turnCount);
|
|
1560
|
-
fullOutput = fullOutput.trim() ? `${note}\n\n${fullOutput}` : note;
|
|
1561
1517
|
}
|
|
1562
1518
|
const completionGuardEnabled = isAgentContractV1(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
|
|
1563
1519
|
const completionGuard = ((result.exitCode === 0 && !result.error) || toolAvailabilityError) && completionGuardEnabled
|
|
@@ -1567,13 +1523,13 @@ async function runSingleAttempt(
|
|
|
1567
1523
|
messages: result.messages ?? [],
|
|
1568
1524
|
tools: contractTools,
|
|
1569
1525
|
mcpDirectTools: toolPlan.effectiveMcpTools,
|
|
1526
|
+
mutationTools: agent.mutationTools,
|
|
1570
1527
|
toolAvailabilityError,
|
|
1571
1528
|
mutationEvidence,
|
|
1572
1529
|
})
|
|
1573
1530
|
: undefined;
|
|
1574
1531
|
const mutationAttemptObserved = observedMutationAttempt || mutationEvidence.attemptedMutation;
|
|
1575
1532
|
let completionGuardTriggered = completionGuard?.triggered === true && !mutationAttemptObserved;
|
|
1576
|
-
const completionGuardBlocked = completionGuard?.blocked === true;
|
|
1577
1533
|
// The classifier is deliberately narrow, so a read-only review task can
|
|
1578
1534
|
// still be misread as implementation. Arbitrate BEFORE any failure side
|
|
1579
1535
|
// effect is published (effects, exit code, progress, notifications,
|
|
@@ -1590,31 +1546,26 @@ async function runSingleAttempt(
|
|
|
1590
1546
|
completionGuardTriggered = arbitration.triggered;
|
|
1591
1547
|
arbiterRescued = arbitration.rescued;
|
|
1592
1548
|
}
|
|
1593
|
-
|
|
1549
|
+
const completionEvidence = planCompletionEvidence({
|
|
1550
|
+
guard: completionGuard,
|
|
1551
|
+
guardTriggered: completionGuardTriggered,
|
|
1552
|
+
completionGuardEnabled,
|
|
1553
|
+
mutationCapable: hasMutationToolCapability(contractTools, toolPlan.effectiveMcpTools),
|
|
1554
|
+
implementationMutationExpected: expectsImplementationMutation(agent.name, shared.originalTask ?? task),
|
|
1555
|
+
mutationAttemptObserved,
|
|
1556
|
+
mutationEvidence,
|
|
1557
|
+
arbiterRescued,
|
|
1558
|
+
agentContractV1: isAgentContractV1(options.agentContract),
|
|
1559
|
+
});
|
|
1560
|
+
if (completionEvidence.fileMutation) {
|
|
1594
1561
|
result.effects = {
|
|
1595
1562
|
...(result.effects ?? {}),
|
|
1596
|
-
fileMutation:
|
|
1597
|
-
status: completionGuardBlocked
|
|
1598
|
-
? "blocked"
|
|
1599
|
-
: completionGuard.expectedMutation
|
|
1600
|
-
? completionGuardTriggered
|
|
1601
|
-
? "missing"
|
|
1602
|
-
: arbiterRescued
|
|
1603
|
-
? "not-applicable"
|
|
1604
|
-
: "observed"
|
|
1605
|
-
: "not-applicable",
|
|
1606
|
-
expected: completionGuard.expectedMutation,
|
|
1607
|
-
attempted: completionGuardBlocked ? false : completionGuard.attemptedMutation || mutationAttemptObserved,
|
|
1608
|
-
evidence: mutationEvidence,
|
|
1609
|
-
...(completionGuardBlocked && completionGuard.message ? { message: completionGuard.message } : {}),
|
|
1610
|
-
...(completionGuardTriggered ? { message: "Subagent completed without making edits for an implementation task." } : {}),
|
|
1611
|
-
...(arbiterRescued ? { resolvedBy: "llm-intent-arbiter" } : {}),
|
|
1612
|
-
},
|
|
1563
|
+
fileMutation: completionEvidence.fileMutation,
|
|
1613
1564
|
};
|
|
1614
1565
|
}
|
|
1615
|
-
if (
|
|
1566
|
+
if (completionEvidence.legacyFailureError) {
|
|
1616
1567
|
result.exitCode = 1;
|
|
1617
|
-
result.error =
|
|
1568
|
+
result.error = completionEvidence.legacyFailureError;
|
|
1618
1569
|
progress.status = "failed";
|
|
1619
1570
|
progress.error = result.error;
|
|
1620
1571
|
emitControlEvent(buildControlEvent({
|
|
@@ -1629,10 +1580,14 @@ async function runSingleAttempt(
|
|
|
1629
1580
|
}));
|
|
1630
1581
|
}
|
|
1631
1582
|
if (options.outputPath && result.exitCode === 0) {
|
|
1632
|
-
const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot);
|
|
1583
|
+
const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot, options.outputClaimPath);
|
|
1633
1584
|
fullOutput = stripAcceptanceReport(resolvedOutput.fullOutput);
|
|
1634
1585
|
result.savedOutputPath = resolvedOutput.savedPath;
|
|
1635
1586
|
result.outputSaveError = resolvedOutput.saveError;
|
|
1587
|
+
if (resolvedOutput.fatalError) {
|
|
1588
|
+
result.exitCode = 1;
|
|
1589
|
+
result.error = result.error ? `${result.error}\n${resolvedOutput.saveError}` : resolvedOutput.saveError;
|
|
1590
|
+
}
|
|
1636
1591
|
if (resolvedOutput.savedPath) {
|
|
1637
1592
|
result.outputReference = formatSavedOutputReference(resolvedOutput.savedPath, fullOutput);
|
|
1638
1593
|
if (result.outputState === "absent") result.outputState = "unknown";
|
|
@@ -1662,6 +1617,20 @@ async function runSingleAttempt(
|
|
|
1662
1617
|
return result;
|
|
1663
1618
|
}
|
|
1664
1619
|
|
|
1620
|
+
/** Keep the structured output artifact files other consumers read by path. */
|
|
1621
|
+
function writeStructuredOutputArtifacts(runtime: NonNullable<RunSyncOptions["structuredOutput"]>, value: unknown, acceptanceReport: unknown): void {
|
|
1622
|
+
try {
|
|
1623
|
+
mkdirSync(path.dirname(runtime.outputPath), { recursive: true });
|
|
1624
|
+
writeFileSync(runtime.outputPath, JSON.stringify(value), { mode: 0o600 });
|
|
1625
|
+
if (runtime.acceptanceReportPath) {
|
|
1626
|
+
if (acceptanceReport !== undefined) writeFileSync(runtime.acceptanceReportPath, JSON.stringify(acceptanceReport), { mode: 0o600 });
|
|
1627
|
+
else rmSync(runtime.acceptanceReportPath, { force: true });
|
|
1628
|
+
}
|
|
1629
|
+
} catch {
|
|
1630
|
+
// The captured value is already on the result; the file is observability only.
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
|
|
1665
1634
|
/**
|
|
1666
1635
|
* Run a subagent synchronously (blocking until complete)
|
|
1667
1636
|
*/
|
|
@@ -1672,12 +1641,28 @@ async function runSyncCompletionInner(
|
|
|
1672
1641
|
task: string,
|
|
1673
1642
|
options: RunSyncOptions,
|
|
1674
1643
|
): Promise<SingleResult> {
|
|
1644
|
+
const effectiveCwd = options.cwd ?? runtimeCwd;
|
|
1645
|
+
const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
|
|
1646
|
+
if (cwdError) {
|
|
1647
|
+
return redactResultPrompt(withRunContext({
|
|
1648
|
+
index: options.index ?? 0,
|
|
1649
|
+
agent: agentName,
|
|
1650
|
+
task,
|
|
1651
|
+
exitCode: 1,
|
|
1652
|
+
messages: [],
|
|
1653
|
+
usage: emptyUsage(),
|
|
1654
|
+
error: cwdError,
|
|
1655
|
+
}, options.context));
|
|
1656
|
+
}
|
|
1675
1657
|
options = {
|
|
1676
1658
|
...options,
|
|
1677
|
-
capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId),
|
|
1659
|
+
capabilityCeiling: intersectSubagentCapabilityCeilings(options.capabilityCeiling ?? resolveCurrentSubagentCapabilityCeiling(options.parentSessionId), options.childRuntime?.capabilityCeiling),
|
|
1678
1660
|
};
|
|
1661
|
+
const childSessionName = deriveChildSessionName({ agent: agentName, task });
|
|
1679
1662
|
const agent = agents.find((a) => a.name === agentName);
|
|
1680
1663
|
if (!agent) {
|
|
1664
|
+
const diagnosticContext = options.unknownAgentDiagnosticContext
|
|
1665
|
+
?? unknownAgentDiagnosticContext(discoverAgents(path.resolve(options.cwd ?? runtimeCwd), "both"));
|
|
1681
1666
|
return redactResultPrompt(withRunContext({
|
|
1682
1667
|
index: options.index ?? 0,
|
|
1683
1668
|
agent: agentName,
|
|
@@ -1685,7 +1670,7 @@ async function runSyncCompletionInner(
|
|
|
1685
1670
|
exitCode: 1,
|
|
1686
1671
|
messages: [],
|
|
1687
1672
|
usage: emptyUsage(),
|
|
1688
|
-
error:
|
|
1673
|
+
error: formatUnknownAgentError(agentName, diagnosticContext),
|
|
1689
1674
|
}, options.context));
|
|
1690
1675
|
}
|
|
1691
1676
|
options = {
|
|
@@ -1693,7 +1678,7 @@ async function runSyncCompletionInner(
|
|
|
1693
1678
|
thinkingCeiling: intersectThinkingCeilings(
|
|
1694
1679
|
options.thinkingCeiling,
|
|
1695
1680
|
agent.maxThinking,
|
|
1696
|
-
|
|
1681
|
+
options.childRuntime?.thinkingCeiling,
|
|
1697
1682
|
),
|
|
1698
1683
|
};
|
|
1699
1684
|
try {
|
|
@@ -1810,8 +1795,24 @@ async function runSyncCompletionInner(
|
|
|
1810
1795
|
agent.fallbackModels,
|
|
1811
1796
|
options.availableModels,
|
|
1812
1797
|
agent.modelProvider ?? options.preferredModelProvider,
|
|
1813
|
-
{
|
|
1798
|
+
{
|
|
1799
|
+
scope: options.modelScope,
|
|
1800
|
+
primaryModelFromParent: options.modelOverrideFromParent,
|
|
1801
|
+
origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
|
|
1802
|
+
},
|
|
1814
1803
|
);
|
|
1804
|
+
if (options.workflowChildPermitLaunch && candidates.length > 1) {
|
|
1805
|
+
const error = "Workflow child permit does not support model fallback.";
|
|
1806
|
+
return redactResultPrompt(withRunContext({
|
|
1807
|
+
index: options.index ?? 0,
|
|
1808
|
+
agent: agent.name,
|
|
1809
|
+
task,
|
|
1810
|
+
exitCode: 1,
|
|
1811
|
+
messages: [],
|
|
1812
|
+
usage: emptyUsage(),
|
|
1813
|
+
error,
|
|
1814
|
+
}, options.context));
|
|
1815
|
+
}
|
|
1815
1816
|
try {
|
|
1816
1817
|
for (const candidate of candidates) {
|
|
1817
1818
|
const model = applyThinkingSuffix(candidate, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
|
|
@@ -1901,15 +1902,17 @@ async function runSyncCompletionInner(
|
|
|
1901
1902
|
};
|
|
1902
1903
|
let lastResult: SingleResult | undefined;
|
|
1903
1904
|
const modelsToTry = candidates.length > 0 ? candidates : [undefined];
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
let taskDeliveryOverride: SubagentTaskDelivery | undefined;
|
|
1905
|
+
let abortRecoveryAttempted = false;
|
|
1906
|
+
let nextAttemptTask = taskWithAcceptance;
|
|
1907
1907
|
modelAttemptsLoop: for (let modelIndex = 0; modelIndex < modelsToTry.length; modelIndex++) {
|
|
1908
1908
|
const candidate = modelsToTry[modelIndex];
|
|
1909
|
-
|
|
1909
|
+
// The inner loop re-runs the same candidate at most once, for abort recovery.
|
|
1910
|
+
for (;;) {
|
|
1911
|
+
const recoveringAbort = abortRecoveryAttempted;
|
|
1912
|
+
const attemptTask = nextAttemptTask;
|
|
1910
1913
|
const verifyModel = Boolean(candidate) && !(options.modelOverrideFromParent && modelIndex === 0);
|
|
1911
1914
|
const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
|
|
1912
|
-
const result = await runSingleAttempt(runtimeCwd, agent,
|
|
1915
|
+
const result = await runSingleAttempt(runtimeCwd, agent, attemptTask, candidate, attemptOptions, {
|
|
1913
1916
|
sessionEnabled,
|
|
1914
1917
|
systemPrompt,
|
|
1915
1918
|
resolvedSkillNames: resolvedSkills.length > 0 ? resolvedSkills.map((skill) => skill.name) : undefined,
|
|
@@ -1923,13 +1926,12 @@ async function runSyncCompletionInner(
|
|
|
1923
1926
|
.filter((modelCandidate): modelCandidate is string => Boolean(modelCandidate)),
|
|
1924
1927
|
outputSnapshot,
|
|
1925
1928
|
originalTask: task,
|
|
1926
|
-
taskDelivery: taskDeliveryOverride,
|
|
1927
1929
|
orcaProgressTab,
|
|
1928
1930
|
launchWarnings,
|
|
1929
1931
|
verifyModel,
|
|
1930
1932
|
});
|
|
1931
1933
|
lastResult = result;
|
|
1932
|
-
if (
|
|
1934
|
+
if (!recoveringAbort) {
|
|
1933
1935
|
if (result.model) attemptedModels.push(result.model);
|
|
1934
1936
|
else if (candidate) attemptedModels.push(candidate);
|
|
1935
1937
|
}
|
|
@@ -1945,79 +1947,45 @@ async function runSyncCompletionInner(
|
|
|
1945
1947
|
usage: { ...result.usage },
|
|
1946
1948
|
};
|
|
1947
1949
|
modelAttempts.push(attempt);
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
interrupted: result.interrupted,
|
|
1966
|
-
timedOut: result.timedOut,
|
|
1967
|
-
stopped: result.stopped,
|
|
1968
|
-
turnBudgetExceeded: result.turnBudgetExceeded,
|
|
1969
|
-
});
|
|
1970
|
-
const retryDelayMs = SUBAGENT_STARTUP_RETRY_DELAYS_MS[startupAttemptIndex];
|
|
1971
|
-
if (startupFailure && retryDelayMs !== undefined) {
|
|
1972
|
-
const retryNote = formatSubagentStartupRetryNote({
|
|
1973
|
-
model: attempt.model,
|
|
1974
|
-
attempt: startupAttemptIndex + 1,
|
|
1975
|
-
maxAttempts: SUBAGENT_STARTUP_RETRY_DELAYS_MS.length + 1,
|
|
1976
|
-
delayMs: retryDelayMs,
|
|
1950
|
+
if (!attemptSucceeded) {
|
|
1951
|
+
const afterCompactionSettlement = (result as AbortRecoverySingleResult)[AFTER_COMPACTION_SETTLEMENT];
|
|
1952
|
+
const abortRecovery = planAbortRecovery({
|
|
1953
|
+
messages: result.messages ?? [],
|
|
1954
|
+
error: result.error,
|
|
1955
|
+
processSignal: result.processSignal,
|
|
1956
|
+
sessionAvailable: Boolean(options.sessionFile && existsSync(options.sessionFile)),
|
|
1957
|
+
alreadyResumed: abortRecoveryAttempted,
|
|
1958
|
+
stopped: result.stopped || result.detached || options.signal?.aborted,
|
|
1959
|
+
interrupted: result.interrupted || intercomDetached || options.interruptSignal?.aborted,
|
|
1960
|
+
timedOut: result.timedOut,
|
|
1961
|
+
toolBudgetExhausted: result.toolBudgetBlocked,
|
|
1962
|
+
usageBudgetExhausted: false,
|
|
1963
|
+
structuredOutputFailed: result.structuredOutputFailed,
|
|
1964
|
+
acceptanceFailed: false,
|
|
1965
|
+
currentTool: result.progress?.currentTool,
|
|
1966
|
+
afterCompactionSettlement,
|
|
1977
1967
|
});
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
result.error = undefined;
|
|
1984
|
-
result.finalOutput = "Interrupted. Waiting for explicit next action.";
|
|
1985
|
-
if (result.progress) {
|
|
1986
|
-
result.progress.status = "running";
|
|
1987
|
-
result.progress.error = undefined;
|
|
1988
|
-
}
|
|
1989
|
-
} else {
|
|
1990
|
-
const cancellationError = "Subagent startup retry cancelled before relaunch.";
|
|
1991
|
-
result.error = cancellationError;
|
|
1992
|
-
result.finalOutput = cancellationError;
|
|
1993
|
-
attempt.error = cancellationError;
|
|
1994
|
-
if (result.progress) result.progress.error = cancellationError;
|
|
1995
|
-
}
|
|
1996
|
-
break modelAttemptsLoop;
|
|
1997
|
-
}
|
|
1998
|
-
if (!taskDeliveryOverride && result.processSignal === "SIGKILL") {
|
|
1999
|
-
taskDeliveryOverride = "file";
|
|
2000
|
-
attemptNotes.push("[startup-retry] retrying with file task delivery to keep the task text out of the child process argv.");
|
|
1968
|
+
if (abortRecovery.action === "resume") {
|
|
1969
|
+
abortRecoveryAttempted = true;
|
|
1970
|
+
nextAttemptTask = abortRecovery.prompt;
|
|
1971
|
+
attemptNotes.push("[abort-recovery] provider/transport abort after useful progress; resuming the retained child session once.");
|
|
1972
|
+
continue;
|
|
2001
1973
|
}
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
if (startupFailure) {
|
|
2007
|
-
const startupError = formatSubagentStartupRetryExhaustedError({
|
|
2008
|
-
model: attempt.model,
|
|
2009
|
-
attempts: startupAttemptIndex + 1,
|
|
2010
|
-
});
|
|
2011
|
-
result.error = startupError;
|
|
2012
|
-
result.finalOutput = startupError;
|
|
2013
|
-
if (result.progress) {
|
|
2014
|
-
result.progress.error = startupError;
|
|
2015
|
-
result.progress.status = "failed";
|
|
1974
|
+
if (abortRecovery.diagnostic) {
|
|
1975
|
+
result.error = result.error ? `${result.error}\n${abortRecovery.diagnostic}` : abortRecovery.diagnostic;
|
|
1976
|
+
attempt.error = result.error;
|
|
1977
|
+
break modelAttemptsLoop;
|
|
2016
1978
|
}
|
|
2017
|
-
attempt.error = startupError;
|
|
2018
|
-
break modelAttemptsLoop;
|
|
2019
1979
|
}
|
|
2020
|
-
|
|
1980
|
+
if (recoveringAbort && !attemptSucceeded) break modelAttemptsLoop;
|
|
1981
|
+
if (options.workflowChildPermitLaunch && !attemptSucceeded) break modelAttemptsLoop;
|
|
1982
|
+
// Preserve the legacy intercom handoff contract: once this logical run has
|
|
1983
|
+
// been handed to a supervisor, terminating that attempt must not launch a
|
|
1984
|
+
// model fallback. Explicit user detach retains fallback.
|
|
1985
|
+
if (intercomDetached || result.timedOut) break modelAttemptsLoop;
|
|
1986
|
+
if (attemptSucceeded) break modelAttemptsLoop;
|
|
1987
|
+
|
|
1988
|
+
const retryableModelFailure = isRetryableModelFailureAttempt({ error: result.error, messages: result.messages, toolCount: result.progressSummary?.toolCount });
|
|
2021
1989
|
if (retryableModelFailure) recordRetryableModelFailure(result.model ?? candidate, result.error);
|
|
2022
1990
|
if (isContextOverflow(result.error)) {
|
|
2023
1991
|
result.contextOverflow = true;
|
|
@@ -2039,11 +2007,13 @@ async function runSyncCompletionInner(
|
|
|
2039
2007
|
usage: emptyUsage(),
|
|
2040
2008
|
error: "Subagent did not produce a result.",
|
|
2041
2009
|
} satisfies SingleResult, options.context);
|
|
2010
|
+
result.task = task;
|
|
2042
2011
|
|
|
2043
2012
|
result.usage = aggregateUsage;
|
|
2044
2013
|
result.attemptedModels = attemptedModels.length > 0 ? attemptedModels : undefined;
|
|
2045
2014
|
result.modelAttempts = modelAttempts.length > 0 ? modelAttempts : undefined;
|
|
2046
2015
|
result.progressSummary = {
|
|
2016
|
+
...(childSessionName ? { sessionName: childSessionName } : {}),
|
|
2047
2017
|
toolCount: totalToolCount,
|
|
2048
2018
|
tokens: aggregateUsage.input + aggregateUsage.output,
|
|
2049
2019
|
durationMs: totalDurationMs,
|
|
@@ -2097,8 +2067,6 @@ async function runSyncCompletionInner(
|
|
|
2097
2067
|
result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "stopped", message: "Acceptance was not evaluated because the subagent was stopped." });
|
|
2098
2068
|
} else if (result.timedOut) {
|
|
2099
2069
|
result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "timeout", message: "Acceptance was not evaluated because the subagent timed out." });
|
|
2100
|
-
} else if (result.turnBudgetExceeded) {
|
|
2101
|
-
result.acceptance = buildSkippedAcceptanceLedger(effectiveAcceptance, { id: "turn-budget", message: "Acceptance was not evaluated because the subagent exceeded its turn budget." });
|
|
2102
2070
|
} else {
|
|
2103
2071
|
result.acceptance = await evaluateAcceptance({
|
|
2104
2072
|
acceptance: effectiveAcceptance,
|
|
@@ -2106,12 +2074,13 @@ async function runSyncCompletionInner(
|
|
|
2106
2074
|
report: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReport,
|
|
2107
2075
|
reportError: (result as SingleResult & { structuredAcceptanceReport?: import("../../shared/types.ts").AcceptanceReport; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError,
|
|
2108
2076
|
fileOutput: childWrittenOutput !== undefined && options.outputPath
|
|
2109
|
-
? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only" }
|
|
2077
|
+
? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only", durable: result.savedOutputPath !== undefined }
|
|
2110
2078
|
: undefined,
|
|
2111
2079
|
cwd: options.cwd ?? runtimeCwd,
|
|
2112
2080
|
reportOptional: isAgentContractV1(options.agentContract),
|
|
2113
2081
|
artifactsDir: options.artifactsDir,
|
|
2114
2082
|
runId: options.runId,
|
|
2083
|
+
watchdog: result.watchdog,
|
|
2115
2084
|
});
|
|
2116
2085
|
}
|
|
2117
2086
|
} catch (error) {
|