@andorra-labs/code 0.1.12 → 0.1.14
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/dist/src/account-presentation.d.ts +1 -37
- package/dist/src/account-presentation.js +6 -43
- package/dist/src/activity.d.ts +0 -25
- package/dist/src/activity.js +1 -23
- package/dist/src/agent-definitions.d.ts +0 -26
- package/dist/src/agent-definitions.js +0 -43
- package/dist/src/agent-execution.d.ts +0 -2
- package/dist/src/agent-execution.js +347 -554
- package/dist/src/agent-mcp-catalog.d.ts +0 -8
- package/dist/src/agent-mcp-catalog.js +0 -2
- package/dist/src/agent-mcp.d.ts +0 -56
- package/dist/src/agent-mcp.js +11 -155
- package/dist/src/agent-modifiers.d.ts +0 -1
- package/dist/src/agent-modifiers.js +25 -68
- package/dist/src/analytics.d.ts +0 -66
- package/dist/src/analytics.js +0 -45
- package/dist/src/andorra/endpoint.d.ts +7 -0
- package/dist/src/andorra/endpoint.js +46 -0
- package/dist/src/andorra/entry.d.ts +21 -0
- package/dist/src/andorra/entry.js +100 -0
- package/dist/src/andorra/errors.d.ts +2 -0
- package/dist/src/andorra/errors.js +39 -0
- package/dist/src/andorra/hosted.d.ts +52 -0
- package/dist/src/andorra/hosted.js +126 -0
- package/dist/src/andorra/monitor.d.ts +151 -0
- package/dist/src/andorra/monitor.js +393 -0
- package/dist/src/andorra/notices.d.ts +7 -0
- package/dist/src/andorra/notices.js +15 -0
- package/dist/src/andorra/opt-in.d.ts +58 -0
- package/dist/src/andorra/opt-in.js +112 -0
- package/dist/src/andorra/request-watch.d.ts +6 -0
- package/dist/src/andorra/request-watch.js +10 -0
- package/dist/src/andorra/state.d.ts +86 -0
- package/dist/src/andorra/state.js +238 -0
- package/dist/src/andorra/terminal.d.ts +68 -0
- package/dist/src/andorra/terminal.js +125 -0
- package/dist/src/andorra/usage-format.d.ts +9 -0
- package/dist/src/andorra/usage-format.js +19 -0
- package/dist/src/anthropic-console-auth.d.ts +0 -24
- package/dist/src/anthropic-console-auth.js +0 -37
- package/dist/src/anthropic-credentials.d.ts +0 -25
- package/dist/src/anthropic-credentials.js +9 -29
- package/dist/src/app-server/protocol.d.ts +18 -246
- package/dist/src/app-server/protocol.js +1 -132
- package/dist/src/app-server/reasoning.d.ts +0 -31
- package/dist/src/app-server/reasoning.js +0 -54
- package/dist/src/app-server/terminal.d.ts +0 -36
- package/dist/src/app-server/terminal.js +3 -39
- package/dist/src/app-server/workspace.d.ts +0 -167
- package/dist/src/app-server/workspace.js +4 -406
- package/dist/src/app-server.d.ts +52 -925
- package/dist/src/app-server.js +828 -3076
- package/dist/src/artifacts.d.ts +0 -10
- package/dist/src/artifacts.js +1 -11
- package/dist/src/attachments.d.ts +4 -98
- package/dist/src/attachments.js +10 -130
- package/dist/src/auth/AuthManager.d.ts +9 -93
- package/dist/src/auth/AuthManager.js +164 -186
- package/dist/src/auth/callback-page.d.ts +0 -1
- package/dist/src/auth/callback-page.js +0 -4
- package/dist/src/auth/callback.d.ts +0 -25
- package/dist/src/auth/callback.js +1 -29
- package/dist/src/auth/deployment.d.ts +1 -16
- package/dist/src/auth/deployment.js +1 -16
- package/dist/src/auth/index.d.ts +1 -12
- package/dist/src/auth/index.js +1 -12
- package/dist/src/auth/lock.d.ts +0 -1
- package/dist/src/auth/lock.js +0 -1
- package/dist/src/auth/store.d.ts +33 -108
- package/dist/src/auth/store.js +55 -130
- package/dist/src/auth/types.d.ts +0 -8
- package/dist/src/auth-commands.d.ts +0 -5
- package/dist/src/auth-commands.js +0 -1
- package/dist/src/automation-runner.d.ts +0 -9
- package/dist/src/automation-runner.js +0 -11
- package/dist/src/automation-service.d.ts +0 -10
- package/dist/src/automation-service.js +3 -17
- package/dist/src/automation-tool.js +0 -5
- package/dist/src/automation-worker-shutdown.d.ts +0 -1
- package/dist/src/automation-worker-shutdown.js +0 -3
- package/dist/src/automations.d.ts +23 -2
- package/dist/src/automations.js +91 -12
- package/dist/src/background-tasks.d.ts +0 -23
- package/dist/src/background-tasks.js +0 -11
- package/dist/src/boot-trace.d.ts +0 -13
- package/dist/src/boot-trace.js +1 -14
- package/dist/src/browser-activity.js +0 -2
- package/dist/src/browser-bridge.d.ts +0 -2
- package/dist/src/browser-bridge.js +0 -27
- package/dist/src/browser-captcha-tool.d.ts +0 -13
- package/dist/src/browser-captcha-tool.js +3 -35
- package/dist/src/browser-extensions-tool.d.ts +24 -0
- package/dist/src/browser-extensions-tool.js +137 -0
- package/dist/src/browser-extensions.d.ts +127 -0
- package/dist/src/browser-extensions.js +729 -0
- package/dist/src/browser-observation.d.ts +0 -15
- package/dist/src/browser-observation.js +1 -22
- package/dist/src/browser-panel-tool.d.ts +1 -37
- package/dist/src/browser-panel-tool.js +3 -73
- package/dist/src/browser-runner.d.ts +0 -1
- package/dist/src/browser-runner.js +5 -46
- package/dist/src/browser-server.d.ts +0 -6
- package/dist/src/browser-server.js +6 -229
- package/dist/src/browser-session.d.ts +0 -25
- package/dist/src/browser-session.js +1 -71
- package/dist/src/browser-stealth.d.ts +19 -13
- package/dist/src/browser-stealth.js +22 -38
- package/dist/src/browser-ui/app.js +7 -174
- package/dist/src/browser-ui/style.css +0 -68
- package/dist/src/browser-ui/tokens.css +15 -97
- package/dist/src/browser-view.d.ts +106 -295
- package/dist/src/browser-view.js +551 -587
- package/dist/src/capabilities.d.ts +0 -8
- package/dist/src/capabilities.js +0 -29
- package/dist/src/capsolver.d.ts +0 -13
- package/dist/src/capsolver.js +0 -15
- package/dist/src/clarification-ui.d.ts +0 -7
- package/dist/src/clarification-ui.js +0 -8
- package/dist/src/claude-executable.d.ts +0 -1
- package/dist/src/claude-executable.js +1 -2
- package/dist/src/claude-provider.d.ts +6 -19
- package/dist/src/claude-provider.js +155 -63
- package/dist/src/cli-executable.d.ts +0 -16
- package/dist/src/cli-executable.js +0 -7
- package/dist/src/cli-process.d.ts +0 -26
- package/dist/src/cli-process.js +0 -18
- package/dist/src/cli-sign-in.d.ts +0 -20
- package/dist/src/cli-sign-in.js +1 -17
- package/dist/src/cli.d.ts +1 -55
- package/dist/src/cli.js +118 -742
- package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +4 -59
- package/dist/src/code-intelligence/CodeIntelligenceManager.js +26 -99
- package/dist/src/code-intelligence/ContextLedger.d.ts +0 -4
- package/dist/src/code-intelligence/ContextLedger.js +0 -10
- package/dist/src/code-intelligence/ContextRouter.d.ts +0 -6
- package/dist/src/code-intelligence/ContextRouter.js +0 -8
- package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.d.ts +0 -2
- package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.js +5 -12
- package/dist/src/code-intelligence/codegraph/CodeGraphProvider.d.ts +0 -6
- package/dist/src/code-intelligence/codegraph/CodeGraphProvider.js +0 -6
- package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.d.ts +0 -5
- package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.js +1 -17
- package/dist/src/code-intelligence/codegraph/repoExploreTool.d.ts +0 -5
- package/dist/src/code-intelligence/codegraph/repoExploreTool.js +0 -5
- package/dist/src/code-intelligence/repository.d.ts +0 -9
- package/dist/src/code-intelligence/repository.js +1 -11
- package/dist/src/code-intelligence/types.d.ts +0 -8
- package/dist/src/codex-auth.d.ts +0 -44
- package/dist/src/codex-auth.js +0 -45
- package/dist/src/codex-browser-auth.d.ts +0 -13
- package/dist/src/codex-browser-auth.js +3 -20
- package/dist/src/codex-errors.js +0 -2
- package/dist/src/codex-executable.d.ts +0 -2
- package/dist/src/codex-executable.js +1 -7
- package/dist/src/codex-provider.d.ts +0 -13
- package/dist/src/codex-provider.js +0 -28
- package/dist/src/codex-rpc.d.ts +0 -10
- package/dist/src/codex-rpc.js +0 -12
- package/dist/src/coding-tools.d.ts +4 -26
- package/dist/src/coding-tools.js +161 -181
- package/dist/src/command-metrics.d.ts +0 -4
- package/dist/src/command-output-tap.d.ts +0 -11
- package/dist/src/command-output-tap.js +0 -3
- package/dist/src/command-screens.d.ts +41 -1
- package/dist/src/command-screens.js +316 -113
- package/dist/src/commands.d.ts +12 -63
- package/dist/src/commands.js +98 -127
- package/dist/src/completion-gates.d.ts +0 -47
- package/dist/src/completion-gates.js +0 -14
- package/dist/src/completion.d.ts +0 -98
- package/dist/src/completion.js +2 -239
- package/dist/src/config.d.ts +15 -115
- package/dist/src/config.js +123 -172
- package/dist/src/context-budget.d.ts +0 -22
- package/dist/src/context-budget.js +0 -44
- package/dist/src/context-compaction.d.ts +29 -6
- package/dist/src/context-compaction.js +94 -25
- package/dist/src/context-selection.d.ts +0 -24
- package/dist/src/context-selection.js +0 -34
- package/dist/src/dashboard-view.d.ts +2 -2
- package/dist/src/dashboard-view.js +11 -37
- package/dist/src/dashboard.d.ts +0 -2
- package/dist/src/dashboard.js +0 -9
- package/dist/src/deadline.d.ts +0 -45
- package/dist/src/deadline.js +0 -54
- package/dist/src/decision/ContinuationAdapter.d.ts +0 -5
- package/dist/src/decision/ContinuationAdapter.js +0 -5
- package/dist/src/decision/DecisionEngine.d.ts +0 -4
- package/dist/src/decision/DecisionManager.d.ts +0 -1
- package/dist/src/decision/DecisionManager.js +2 -7
- package/dist/src/decision/DecisionPolicy.d.ts +0 -1
- package/dist/src/decision/DecisionPolicy.js +0 -1
- package/dist/src/decision/FactContinuations.d.ts +11 -43
- package/dist/src/decision/FactContinuations.js +126 -95
- package/dist/src/decision/FactServiceGate.d.ts +0 -1
- package/dist/src/decision/FactServiceGate.js +0 -4
- package/dist/src/decision/PreparedSteps.d.ts +0 -15
- package/dist/src/decision/PreparedSteps.js +1 -11
- package/dist/src/decision/applyToolMenu.d.ts +0 -1
- package/dist/src/decision/applyToolMenu.js +2 -6
- package/dist/src/decision/checks.d.ts +15 -28
- package/dist/src/decision/checks.js +118 -49
- package/dist/src/decision/facts.d.ts +0 -16
- package/dist/src/decision/facts.js +0 -30
- package/dist/src/decision/guidancePolicy.js +0 -1
- package/dist/src/decision/hostedPolicy.d.ts +0 -6
- package/dist/src/decision/hostedPolicy.js +0 -7
- package/dist/src/decision/hostedSkills.d.ts +0 -19
- package/dist/src/decision/hostedSkills.js +0 -19
- package/dist/src/decision/optimizationPolicy.d.ts +0 -3
- package/dist/src/decision/optimizationPolicy.js +1 -4
- package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +0 -7
- package/dist/src/decision/providers/AndorraDecisionProvider.js +4 -27
- package/dist/src/decision/providers/HttpDecisionProvider.d.ts +0 -2
- package/dist/src/decision/providers/HttpDecisionProvider.js +0 -6
- package/dist/src/decision/routeTools.d.ts +0 -8
- package/dist/src/decision/routeTools.js +1 -8
- package/dist/src/decision/toolFamilies.d.ts +0 -1
- package/dist/src/decision/toolFamilies.js +1 -2
- package/dist/src/decision/toolMenu.d.ts +0 -3
- package/dist/src/decision/toolMenu.js +0 -4
- package/dist/src/decision/types.d.ts +1 -6
- package/dist/src/default-graph.d.ts +0 -9
- package/dist/src/default-graph.js +0 -9
- package/dist/src/delegation-changes.d.ts +0 -56
- package/dist/src/delegation-changes.js +4 -130
- package/dist/src/diff-preview.d.ts +0 -1
- package/dist/src/diff-preview.js +0 -17
- package/dist/src/duration.d.ts +0 -50
- package/dist/src/duration.js +0 -50
- package/dist/src/efficiency.d.ts +0 -39
- package/dist/src/efficiency.js +0 -16
- package/dist/src/engine/protocol.d.ts +0 -2
- package/dist/src/engine/protocol.js +0 -2
- package/dist/src/engine-streams.d.ts +0 -9
- package/dist/src/extensions.d.ts +3 -2
- package/dist/src/extensions.js +63 -35
- package/dist/src/favicons.d.ts +0 -26
- package/dist/src/favicons.js +0 -34
- package/dist/src/file-diff.d.ts +2 -58
- package/dist/src/file-diff.js +0 -32
- package/dist/src/file-read-key.d.ts +0 -7
- package/dist/src/file-read-key.js +0 -7
- package/dist/src/file-read-state.d.ts +0 -1
- package/dist/src/file-read-state.js +0 -4
- package/dist/src/firefox-cookies.d.ts +0 -34
- package/dist/src/firefox-cookies.js +1 -55
- package/dist/src/git-identity-audit.d.ts +27 -0
- package/dist/src/git-identity-audit.js +286 -0
- package/dist/src/git-identity-guard.d.ts +4 -0
- package/dist/src/git-identity-guard.js +998 -0
- package/dist/src/git-identity-hold.d.ts +12 -0
- package/dist/src/git-identity-hold.js +81 -0
- package/dist/src/git-summary.d.ts +0 -58
- package/dist/src/git-summary.js +2 -212
- package/dist/src/goal-completion-verification.d.ts +2 -2
- package/dist/src/goal-completion-verification.js +3 -6
- package/dist/src/graph-account.d.ts +0 -21
- package/dist/src/graph-account.js +0 -17
- package/dist/src/graph-editor-session.d.ts +0 -1
- package/dist/src/graph-editor-session.js +0 -3
- package/dist/src/graph-health.d.ts +9 -61
- package/dist/src/graph-health.js +34 -59
- package/dist/src/graph-manager-chat.d.ts +36 -153
- package/dist/src/graph-manager-chat.js +161 -182
- package/dist/src/graph-provider-portability.d.ts +1 -21
- package/dist/src/graph-provider-portability.js +6 -45
- package/dist/src/graph-quota.d.ts +0 -33
- package/dist/src/graph-quota.js +1 -44
- package/dist/src/graph-runner.d.ts +0 -1
- package/dist/src/graph-runner.js +58 -391
- package/dist/src/graph-selection.d.ts +0 -14
- package/dist/src/graph-selection.js +2 -15
- package/dist/src/graph-server.d.ts +2 -10
- package/dist/src/graph-server.js +39 -101
- package/dist/src/graph-studio-features.d.ts +0 -5
- package/dist/src/graph-studio-features.js +2 -42
- package/dist/src/graph-sync.d.ts +0 -78
- package/dist/src/graph-sync.js +5 -201
- package/dist/src/graph-tool.d.ts +0 -18
- package/dist/src/graph-tool.js +0 -27
- package/dist/src/graph-ui/app.js +176 -492
- package/dist/src/graph-ui/compat.js +0 -7
- package/dist/src/graph-ui/controls.css +0 -48
- package/dist/src/graph-ui/controls.js +0 -88
- package/dist/src/graph-ui/drafts.js +0 -12
- package/dist/src/graph-ui/edge-router.js +0 -62
- package/dist/src/graph-ui/embed.js +0 -59
- package/dist/src/graph-ui/icons.js +0 -8
- package/dist/src/graph-ui/library.css +0 -5
- package/dist/src/graph-ui/manager-markdown.js +0 -11
- package/dist/src/graph-ui/manager-state.js +1 -78
- package/dist/src/graph-ui/manager.css +0 -18
- package/dist/src/graph-ui/manager.js +43 -185
- package/dist/src/graph-ui/model-picker.js +0 -29
- package/dist/src/graph-ui/sidebar.js +2 -3
- package/dist/src/graph-ui/skill-picker.js +373 -39
- package/dist/src/graph-ui/studio-canvas.js +3 -38
- package/dist/src/graph-ui/studio.css +0 -18
- package/dist/src/graph-ui/studio.js +3 -71
- package/dist/src/graph-ui/style.css +16 -136
- package/dist/src/graph-ui/theme.js +1 -26
- package/dist/src/graph-ui/tokens.css +19 -118
- package/dist/src/graphs.d.ts +6 -157
- package/dist/src/graphs.js +66 -269
- package/dist/src/grep-regex-worker.js +0 -2
- package/dist/src/grep-regex.d.ts +1 -5
- package/dist/src/grep-regex.js +6 -8
- package/dist/src/grok-provider.d.ts +0 -17
- package/dist/src/grok-provider.js +1 -26
- package/dist/src/handoffs.d.ts +0 -11
- package/dist/src/handoffs.js +0 -13
- package/dist/src/hardened-runtime.d.ts +0 -10
- package/dist/src/hardened-runtime.js +9 -47
- package/dist/src/harness-home.d.ts +21 -0
- package/dist/src/harness-home.js +87 -0
- package/dist/src/host-process-guard.d.ts +0 -50
- package/dist/src/host-process-guard.js +0 -641
- package/dist/src/limits.d.ts +0 -64
- package/dist/src/limits.js +0 -62
- package/dist/src/managed-sign-in.d.ts +0 -12
- package/dist/src/managed-sign-in.js +0 -16
- package/dist/src/markdown.d.ts +0 -28
- package/dist/src/markdown.js +1 -175
- package/dist/src/mcp.d.ts +0 -99
- package/dist/src/mcp.js +4 -170
- package/dist/src/membership-errors.d.ts +0 -14
- package/dist/src/membership-errors.js +1 -14
- package/dist/src/membership.d.ts +9 -59
- package/dist/src/membership.js +20 -91
- package/dist/src/memory/LocalToolMemory.d.ts +0 -1
- package/dist/src/memory/LocalToolMemory.js +2 -7
- package/dist/src/memory/MemoryDistiller.js +0 -15
- package/dist/src/memory/MemoryManager.d.ts +0 -3
- package/dist/src/memory/MemoryManager.js +6 -18
- package/dist/src/memory/MemoryPolicy.d.ts +0 -2
- package/dist/src/memory/MemoryPolicy.js +0 -2
- package/dist/src/memory/MemoryProvider.d.ts +0 -6
- package/dist/src/memory/MemoryRetriever.js +0 -7
- package/dist/src/memory/PermissionMemoryProvider.d.ts +0 -1
- package/dist/src/memory/PermissionMemoryProvider.js +0 -1
- package/dist/src/memory/ProjectMemory.d.ts +5 -40
- package/dist/src/memory/ProjectMemory.js +22 -47
- package/dist/src/memory/ToolFailureLessons.d.ts +0 -3
- package/dist/src/memory/ToolFailureLessons.js +0 -6
- package/dist/src/memory/providers/NoOpMemoryProvider.d.ts +0 -1
- package/dist/src/memory/providers/NoOpMemoryProvider.js +0 -1
- package/dist/src/memory/redaction.d.ts +0 -5
- package/dist/src/memory/redaction.js +0 -11
- package/dist/src/memory/repository.d.ts +0 -6
- package/dist/src/memory/repository.js +2 -12
- package/dist/src/memory/types.d.ts +0 -1
- package/dist/src/model-context-windows.d.ts +2 -0
- package/dist/src/model-context-windows.js +24 -0
- package/dist/src/model-health-cache.d.ts +0 -38
- package/dist/src/model-health-cache.js +2 -50
- package/dist/src/model-metadata.d.ts +1 -18
- package/dist/src/model-metadata.js +42 -45
- package/dist/src/model-override.d.ts +0 -36
- package/dist/src/model-override.js +0 -43
- package/dist/src/model-tiers.d.ts +0 -13
- package/dist/src/model-tiers.js +0 -23
- package/dist/src/opencode-catalog.d.ts +0 -2
- package/dist/src/opencode-catalog.js +0 -11
- package/dist/src/opencode-cli-provider.d.ts +0 -35
- package/dist/src/opencode-cli-provider.js +1 -44
- package/dist/src/opencode-provider.d.ts +0 -2
- package/dist/src/opencode-provider.js +1 -16
- package/dist/src/package-name.d.ts +0 -2
- package/dist/src/package-name.js +0 -2
- package/dist/src/paged-transcript.d.ts +0 -11
- package/dist/src/paged-transcript.js +2 -20
- package/dist/src/palette.d.ts +1 -63
- package/dist/src/palette.js +1 -64
- package/dist/src/permissions.d.ts +0 -15
- package/dist/src/permissions.js +17 -21
- package/dist/src/powershell-pool.d.ts +0 -9
- package/dist/src/powershell-pool.js +3 -26
- package/dist/src/process-warnings.d.ts +4 -0
- package/dist/src/process-warnings.js +103 -0
- package/dist/src/profile.d.ts +0 -43
- package/dist/src/profile.js +0 -43
- package/dist/src/project-reservation.d.ts +11 -0
- package/dist/src/project-reservation.js +143 -0
- package/dist/src/provider-connection.d.ts +0 -18
- package/dist/src/provider-connection.js +15 -39
- package/dist/src/provider-engine.d.ts +0 -21
- package/dist/src/provider-engine.js +1 -96
- package/dist/src/provider-import.d.ts +0 -49
- package/dist/src/provider-import.js +0 -60
- package/dist/src/provider-keys.d.ts +1 -36
- package/dist/src/provider-keys.js +5 -48
- package/dist/src/provider-settings.d.ts +16 -3
- package/dist/src/provider-settings.js +36 -52
- package/dist/src/providers.d.ts +14 -219
- package/dist/src/providers.js +69 -326
- package/dist/src/pull-requests.d.ts +0 -173
- package/dist/src/pull-requests.js +5 -195
- package/dist/src/qa/browser/PlaywrightRunner.d.ts +0 -7
- package/dist/src/qa/browser/PlaywrightRunner.js +2 -16
- package/dist/src/qa/command-policy.d.ts +0 -23
- package/dist/src/qa/command-policy.js +0 -30
- package/dist/src/qa/guidance.d.ts +0 -21
- package/dist/src/qa/guidance.js +0 -20
- package/dist/src/qa/profile/ProjectInspector.d.ts +0 -4
- package/dist/src/qa/profile/ProjectInspector.js +0 -6
- package/dist/src/qa/profile/QaConfigLoader.d.ts +0 -7
- package/dist/src/qa/profile/QaConfigLoader.js +0 -6
- package/dist/src/qa/profile/QaProfile.d.ts +0 -7
- package/dist/src/qa/profile/QaProfile.js +0 -7
- package/dist/src/qa/profile/yaml.d.ts +0 -9
- package/dist/src/qa/profile/yaml.js +0 -13
- package/dist/src/qa/qa-authorize.d.ts +0 -19
- package/dist/src/qa/qa-authorize.js +4 -11
- package/dist/src/qa/runtime/ProcessManager.d.ts +0 -31
- package/dist/src/qa/runtime/ProcessManager.js +4 -41
- package/dist/src/qa/runtime/PtyManager.d.ts +0 -4
- package/dist/src/qa/runtime/PtyManager.js +1 -7
- package/dist/src/qa/runtime/changes.d.ts +0 -11
- package/dist/src/qa/runtime/changes.js +1 -3
- package/dist/src/qa/tools.d.ts +0 -10
- package/dist/src/qa/tools.js +0 -12
- package/dist/src/qa/types.d.ts +0 -13
- package/dist/src/react-runtime.d.ts +2 -21
- package/dist/src/react-runtime.js +107 -422
- package/dist/src/read-document-doc.d.ts +0 -6
- package/dist/src/read-document-doc.js +0 -55
- package/dist/src/read-document-docx.d.ts +0 -16
- package/dist/src/read-document-docx.js +2 -69
- package/dist/src/read-document-text.d.ts +0 -17
- package/dist/src/read-document-text.js +0 -22
- package/dist/src/read-document-tool.d.ts +0 -31
- package/dist/src/read-document-tool.js +0 -30
- package/dist/src/read-document.d.ts +0 -49
- package/dist/src/read-document.js +1 -67
- package/dist/src/read-image.d.ts +0 -32
- package/dist/src/read-image.js +0 -33
- package/dist/src/remote/cert.d.ts +0 -18
- package/dist/src/remote/cert.js +0 -44
- package/dist/src/remote/client.d.ts +0 -70
- package/dist/src/remote/client.js +1 -116
- package/dist/src/remote/command.js +0 -17
- package/dist/src/remote/engine-pool.d.ts +0 -152
- package/dist/src/remote/engine-pool.js +22 -339
- package/dist/src/remote/errors.d.ts +0 -15
- package/dist/src/remote/errors.js +0 -7
- package/dist/src/remote/network.d.ts +0 -26
- package/dist/src/remote/network.js +1 -34
- package/dist/src/remote/pairing.d.ts +16 -51
- package/dist/src/remote/pairing.js +50 -57
- package/dist/src/remote/pem.d.ts +0 -4
- package/dist/src/remote/pem.js +0 -4
- package/dist/src/remote/roots.d.ts +0 -20
- package/dist/src/remote/roots.js +0 -8
- package/dist/src/remote/serve.d.ts +0 -47
- package/dist/src/remote/serve.js +0 -30
- package/dist/src/remote/server.d.ts +0 -14
- package/dist/src/remote/server.js +1 -79
- package/dist/src/remote/types.d.ts +1 -32
- package/dist/src/remote/types.js +0 -10
- package/dist/src/run-control.d.ts +2 -9
- package/dist/src/run-control.js +9 -13
- package/dist/src/run-progress.d.ts +0 -170
- package/dist/src/run-progress.js +0 -285
- package/dist/src/run-records.d.ts +0 -443
- package/dist/src/run-records.js +14 -687
- package/dist/src/run-temp.d.ts +12 -0
- package/dist/src/run-temp.js +50 -0
- package/dist/src/runtime.d.ts +12 -228
- package/dist/src/runtime.js +2 -128
- package/dist/src/sandbox-child.js +0 -1
- package/dist/src/save-lock.d.ts +0 -12
- package/dist/src/save-lock.js +0 -28
- package/dist/src/screen-selection.d.ts +0 -23
- package/dist/src/screen-selection.js +0 -22
- package/dist/src/secret-redaction.d.ts +0 -12
- package/dist/src/secret-redaction.js +0 -45
- package/dist/src/session-changes.d.ts +4 -80
- package/dist/src/session-changes.js +25 -130
- package/dist/src/session-goal.d.ts +129 -0
- package/dist/src/session-goal.js +230 -0
- package/dist/src/session-monitor.d.ts +1 -10
- package/dist/src/session-monitor.js +2 -39
- package/dist/src/session-reaper.d.ts +0 -15
- package/dist/src/session-reaper.js +0 -14
- package/dist/src/session-skills.d.ts +15 -44
- package/dist/src/session-skills.js +75 -60
- package/dist/src/session-summary.d.ts +0 -26
- package/dist/src/session-summary.js +0 -32
- package/dist/src/session-title.d.ts +0 -1
- package/dist/src/session-title.js +0 -2
- package/dist/src/sessions.d.ts +3 -122
- package/dist/src/sessions.js +9 -178
- package/dist/src/shell.d.ts +3 -20
- package/dist/src/shell.js +8 -72
- package/dist/src/side-panel.d.ts +5 -99
- package/dist/src/side-panel.js +76 -133
- package/dist/src/sign-in-detection.d.ts +0 -39
- package/dist/src/sign-in-detection.js +0 -43
- package/dist/src/sign-in-offer.d.ts +1 -19
- package/dist/src/sign-in-offer.js +0 -13
- package/dist/src/skill-commands.d.ts +0 -1
- package/dist/src/skill-commands.js +1 -4
- package/dist/src/skills/bundled/control-browser/SKILL.md +1 -1
- package/dist/src/skills/bundled/graph-manager/errors.md +1 -1
- package/dist/src/skills/bundled/provenance.json +738 -738
- package/dist/src/skills/invocable-skills.d.ts +0 -18
- package/dist/src/skills/invocable-skills.js +0 -17
- package/dist/src/skills/project-skills.d.ts +0 -1
- package/dist/src/skills/project-skills.js +0 -3
- package/dist/src/skills/prompt-skills.js +0 -14
- package/dist/src/skills/runtime-skills.d.ts +0 -13
- package/dist/src/skills/runtime-skills.js +0 -37
- package/dist/src/stall-recovery.d.ts +0 -25
- package/dist/src/stall-recovery.js +0 -38
- package/dist/src/stray-files.d.ts +0 -9
- package/dist/src/stray-files.js +0 -16
- package/dist/src/structured-step.d.ts +0 -22
- package/dist/src/structured-step.js +0 -22
- package/dist/src/subagent-run.d.ts +2 -163
- package/dist/src/subagent-run.js +18 -376
- package/dist/src/subagent-tree.d.ts +32 -0
- package/dist/src/subagent-tree.js +128 -0
- package/dist/src/telemetry/aggregate.d.ts +0 -37
- package/dist/src/telemetry/aggregate.js +0 -40
- package/dist/src/telemetry/capture-core.d.ts +0 -87
- package/dist/src/telemetry/capture-core.js +0 -67
- package/dist/src/telemetry/capture.d.ts +0 -1
- package/dist/src/telemetry/capture.js +0 -3
- package/dist/src/telemetry/classify.d.ts +0 -58
- package/dist/src/telemetry/classify.js +0 -60
- package/dist/src/telemetry/decision-capture.d.ts +0 -1
- package/dist/src/telemetry/emitter.d.ts +0 -30
- package/dist/src/telemetry/emitter.js +1 -62
- package/dist/src/telemetry/gate.d.ts +0 -29
- package/dist/src/telemetry/gate.js +0 -22
- package/dist/src/telemetry/identity.d.ts +0 -13
- package/dist/src/telemetry/identity.js +0 -29
- package/dist/src/telemetry/outbox.d.ts +0 -64
- package/dist/src/telemetry/outbox.js +1 -108
- package/dist/src/telemetry/schema.d.ts +1 -49
- package/dist/src/telemetry/schema.js +3 -84
- package/dist/src/telemetry/state.d.ts +0 -53
- package/dist/src/telemetry/state.js +0 -64
- package/dist/src/telemetry/surface.d.ts +0 -31
- package/dist/src/telemetry/surface.js +1 -39
- package/dist/src/telemetry/uploader.d.ts +0 -11
- package/dist/src/telemetry/uploader.js +0 -46
- package/dist/src/telemetry/uploads.d.ts +0 -11
- package/dist/src/telemetry/uploads.js +0 -11
- package/dist/src/telemetry/version.d.ts +0 -4
- package/dist/src/telemetry/version.js +0 -14
- package/dist/src/telemetry/workspace.d.ts +0 -7
- package/dist/src/telemetry/workspace.js +1 -22
- package/dist/src/terminal-ui.d.ts +33 -521
- package/dist/src/terminal-ui.js +145 -884
- package/dist/src/test-edit-guard.d.ts +74 -0
- package/dist/src/test-edit-guard.js +269 -0
- package/dist/src/text.d.ts +0 -1
- package/dist/src/text.js +0 -1
- package/dist/src/time-limit.d.ts +0 -36
- package/dist/src/time-limit.js +0 -37
- package/dist/src/timers.d.ts +0 -161
- package/dist/src/timers.js +0 -126
- package/dist/src/todos.d.ts +0 -1
- package/dist/src/todos.js +0 -3
- package/dist/src/token-rate.d.ts +0 -94
- package/dist/src/token-rate.js +0 -154
- package/dist/src/tool-activity.d.ts +0 -6
- package/dist/src/tool-activity.js +0 -7
- package/dist/src/tool-availability.d.ts +0 -13
- package/dist/src/tool-availability.js +1 -14
- package/dist/src/tool-call-clock.d.ts +1 -4
- package/dist/src/tool-call-clock.js +0 -13
- package/dist/src/tool-catalog.d.ts +0 -11
- package/dist/src/tool-catalog.js +0 -23
- package/dist/src/tool-dependencies.d.ts +0 -5
- package/dist/src/tool-dependencies.js +0 -4
- package/dist/src/tool-diff-stats.d.ts +0 -23
- package/dist/src/tool-diff-stats.js +0 -49
- package/dist/src/tool-errors.d.ts +9 -7
- package/dist/src/tool-errors.js +13 -6
- package/dist/src/tool-failure-tracker.d.ts +3 -11
- package/dist/src/tool-failure-tracker.js +19 -27
- package/dist/src/tool-names.d.ts +0 -16
- package/dist/src/tool-names.js +0 -12
- package/dist/src/tool-profile.d.ts +6 -0
- package/dist/src/tool-profile.js +23 -0
- package/dist/src/tool-result-filter.d.ts +0 -19
- package/dist/src/tool-result-filter.js +1 -66
- package/dist/src/tool-schema-compatibility.d.ts +0 -6
- package/dist/src/tool-schema-compatibility.js +0 -9
- package/dist/src/tools.d.ts +0 -4
- package/dist/src/tools.js +11 -114
- package/dist/src/trajectory.d.ts +0 -13
- package/dist/src/trajectory.js +23 -79
- package/dist/src/transcript.d.ts +0 -41
- package/dist/src/transcript.js +5 -60
- package/dist/src/types.d.ts +4 -168
- package/dist/src/untracked-file-removal.js +0 -20
- package/dist/src/update-check.d.ts +0 -14
- package/dist/src/update-check.js +1 -15
- package/dist/src/update.d.ts +0 -35
- package/dist/src/update.js +0 -100
- package/dist/src/usage-analytics.d.ts +17 -17
- package/dist/src/usage-analytics.js +168 -209
- package/dist/src/web-search.d.ts +0 -23
- package/dist/src/web-search.js +1 -27
- package/dist/src/widgets.d.ts +0 -25
- package/dist/src/widgets.js +0 -24
- package/dist/src/workspace-facts.d.ts +0 -12
- package/dist/src/workspace-facts.js +1 -18
- package/dist/src/workspace-git-metadata.d.ts +0 -16
- package/dist/src/workspace-git-metadata.js +0 -21
- package/dist/src/workspace-instructions.d.ts +3 -15
- package/dist/src/workspace-instructions.js +6 -19
- package/package.json +13 -2
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { goalRoute, routedOutcomes, runEndingOutcomes as goalRunEndingOutcomes } from './session-goal.js';
|
|
1
2
|
import { DecisionPolicy } from './decision/DecisionPolicy.js';
|
|
2
3
|
import { answerOnlyTask, hasAdaptiveAlternative } from './decision/optimizationPolicy.js';
|
|
3
4
|
import { resolveEfficiency } from './efficiency.js';
|
|
4
5
|
import { collectWorkspaceFacts } from './workspace-facts.js';
|
|
5
6
|
import { conversationContains, omittedContextNote, selectContext } from './context-selection.js';
|
|
7
|
+
import { MAPPED_INPUTS_HEADING } from './context-compaction.js';
|
|
6
8
|
import { orderSkillCatalog, selectToolCatalog } from './tool-catalog.js';
|
|
7
9
|
import { decideModelTier } from './model-tiers.js';
|
|
8
10
|
import { structuredText } from './code-intelligence/CodeIntelligenceManager.js';
|
|
@@ -23,6 +25,7 @@ import { createRunTelemetry, mergeRunTelemetry, recordAttempt, recordDecisionEve
|
|
|
23
25
|
import { bindUserWaits, createRuntimeBudget } from './deadline.js';
|
|
24
26
|
import { createAgentEngine } from './hardened-runtime.js';
|
|
25
27
|
import { completionTool } from './completion.js';
|
|
28
|
+
import { applyToolProfile } from './tool-profile.js';
|
|
26
29
|
import { DELIVERED_OUTCOME, GRAPH_MANAGER_GRAPH_ID, capabilitySubset, delegatesWriting, effectiveCapabilities, intakeCapabilities, isTestingNode, isWritingRole, laterAgentNodes, permitsBuiltInTool, testerOnEveryRoute } from './graphs.js';
|
|
27
30
|
import { DELEGATION_DIFF_LIMIT, LandingRestoreError, addChangeWorktree, assertDelegationGit, applyLanding, collectChange, prepareLanding, removeChangeWorktree, repositoryRoot, snapshotWorkspace } from './delegation-changes.js';
|
|
28
31
|
import { stopQaProcessesUnder } from './qa/runtime/ProcessManager.js';
|
|
@@ -35,12 +38,9 @@ import { removeUntrackedFileTool } from './untracked-file-removal.js';
|
|
|
35
38
|
import { permissionMode, serializeApprovals, assertPlanMutationAllowed } from './permissions.js';
|
|
36
39
|
import { adaptLegacyCodingToolArguments, canonicalToolName, canonicalizeToolList } from './tool-names.js';
|
|
37
40
|
const exec = promisify(execFile);
|
|
38
|
-
/** How many times one accept_change prepares a landing when the working folder keeps changing under it. */
|
|
39
41
|
const LANDING_ATTEMPTS = 3;
|
|
40
|
-
/** Serialized size of the `restore_tools` schema the engine adds when a catalog omits anything. */
|
|
41
42
|
const RESTORE_TOOL_SCHEMA_CHARS = 420;
|
|
42
43
|
const MISSING_CONFIRMATION = 'Use ask_user and obtain a real answer confirming design considerations before completing.';
|
|
43
|
-
/** Joins the plan body and the decision prompt the way `ask_user` joins its notes; the desktop splits on the same marker. */
|
|
44
44
|
export const PLAN_DECISION_MARKER = '\n\nPlan awaiting your decision:\n';
|
|
45
45
|
const PLAN_APPROVE_CHOICE = 'Approve plan';
|
|
46
46
|
const PLAN_REJECT_CHOICE = 'Reject plan';
|
|
@@ -52,48 +52,24 @@ Use ask_user to clarify requirements and explicitly confirm or revise proposed d
|
|
|
52
52
|
Write user-facing questions, choices and progress in plain everyday language. Ask one concrete decision at a time. Explain what changes for the user, not file names, code symbols, terminal escape sequences, git jargon or internal terms. Keep detailed research, repository workflow rules and test plans in codebaseFindings and taskInstruction, not the question or answer choices. Use 1-3 short proposedDesign notes only for consequences the user needs to decide. Prefer 2-3 short choices (about 2-6 words each), put your recommendation first and label it (Recommended). Never repeat tool-result JSON in public messages. For example: "Should this update include both scrolling and the Enter-key change?" with "Fix scrolling only (Recommended)" and "Include both changes".
|
|
53
53
|
After inspection and user confirmation, return a compact structured handoff containing the originalTask, requirements, acceptanceCriteria, designConsiderations, codebaseFindings and taskInstruction. Include agreed decisions and unresolved facts, not conversation transcripts. Do not implement code during intake. Spawning is optional and bounded by policy.
|
|
54
54
|
When multiple completion outcomes are declared, use this node's prompt and the confirmed task to choose exactly one declared outcome string. The graph follows every connection for that outcome, which may start several downstream branches. Never return an array of outcomes or invent an undeclared outcome. Selecting a route does not replace the required plan, research, user confirmation or structured handoff.`;
|
|
55
|
-
/** Appended to the Orchestrator instructions only while delegation is active (a writing role and a routed `delivered` outcome). */
|
|
56
55
|
const DELEGATION_INSTRUCTIONS = `This Orchestrator can also deliver the work through writing subagents. Two paths end this node: complete with the outcome "completed" to hand the task instruction to the next node as usual, or complete with the outcome "delivered" once subagents implemented the work and you reviewed and accepted their changes. Choose from the task: hand off when the next node should implement, deliver when the work fits bounded subagent tasks you can review.
|
|
57
56
|
Clarify first on either path: publish the plan with update_todos, research, and obtain the user's confirmation with ask_user before any writing subagent starts; writing spawns are refused until then.
|
|
58
57
|
Delegate implementation to the writing roles with spawn_subagent, several in parallel when their tasks are independent. Each runs in its own Git worktree started from the working folder as it stands and may run commands and tests there. Give each one a bounded task carrying the confirmed requirements and acceptance criteria, and ask it to report the commands and tests it ran.
|
|
59
58
|
Each writing spawn returns a change record: an id (use it exactly as returned), the changed files, the diff (the full diff is behind read_artifact when truncated), the worktree path, and the tests report the subagent gave. Review every change: read the diff, read files inside the worktree with your read tools when the diff is not enough, and weigh the tests report; a failure report is grounds for a fix.
|
|
60
59
|
Decide every change: accept_change with its id lands it in the working folder as uncommitted edits; discard_change drops it. A new subagent starts from the working folder, so it sees landed work only, never a change still waiting for your decision. To build on a change, accept it first and then spawn the follow-up. When work is wrong or incomplete, discard it and spawn a redo whose task carries your review findings, then review the redo. A conflict lands nothing and names the files: the change no longer fits the working folder and accepting it again conflicts again, so discard it, spawn a redo (it starts from the folder as it now stands) and accept the redo.
|
|
61
60
|
Complete with "delivered" only when no subagent is still running, at least one change landed, and every change is accepted or discarded. Never write code or run commands yourself: you have no write or shell tools, and the change tools take only an id. The one exception is remove_untracked_file, for a stray untracked file left by mistake (such as one named nul or after a sentence); remove it yourself instead of asking the user to.`;
|
|
62
|
-
/**
|
|
63
|
-
* Appended to a delegating Orchestrator's instructions when it continues a resumed conversation:
|
|
64
|
-
* the change registry is per visit and is not restored.
|
|
65
|
-
*/
|
|
66
61
|
const RESUMED_DELEGATION_INSTRUCTIONS = `This run was resumed. Changes from before the resume are no longer tracked: their ids are unknown to accept_change and discard_change, and their worktrees are gone. Work that was already landed stays in the working folder. Spawn again for anything that was still undecided. Completing as "delivered" needs at least one change accepted after the resume; otherwise complete as "completed".`;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
* obtained, by this node, and is carried into the retry's task text, so the requirement is already
|
|
73
|
-
* satisfied; appending this keeps a compliant model from re-asking and turning a promised
|
|
74
|
-
* single-question retry into a second interview.
|
|
75
|
-
*/
|
|
62
|
+
// An Orchestrator that declares its own outcomes routes every completion through one of them, delivered or not.
|
|
63
|
+
const ROUTED_DELEGATION_INSTRUCTIONS = DELEGATION_INSTRUCTIONS
|
|
64
|
+
.replace(/^This Orchestrator can also deliver[^\n]*/, 'This Orchestrator can also implement the work through writing subagents before it completes. Whether or not subagents implemented anything, complete with exactly one of the declared outcomes, chosen from this node\'s prompt and the state of the work: for example a route that releases work your subagents delivered, or one that sends work on for testing or for the next node to implement. There is no separate delivered outcome.')
|
|
65
|
+
.replace('Complete with "delivered" only when no subagent is still running, at least one change landed, and every change is accepted or discarded.', 'Complete only when no subagent is still running and every change is accepted or discarded.');
|
|
66
|
+
const ROUTED_RESUMED_DELEGATION_INSTRUCTIONS = RESUMED_DELEGATION_INSTRUCTIONS.replace(/ Completing as "delivered".*$/, '');
|
|
76
67
|
const RETAINED_CLARIFICATION_INSTRUCTION = 'This attempt retains a previous clarification: the user already answered this intake and their confirmed decisions are included in the task text. That answer satisfies the clarification requirement, so do not ask those questions again. Ask only if a genuinely new decision is required to hand off.';
|
|
77
|
-
/**
|
|
78
|
-
* Narrow the supplied limits by whatever this node configures.
|
|
79
|
-
*
|
|
80
|
-
* A node bound only ever tightens the run's own bound: `Math.min` against an absent supplied
|
|
81
|
-
* value would yield NaN, which reaches the executor as "Invalid limit", so an unlimited
|
|
82
|
-
* supplied bound leaves the node's explicit value in force. The key set comes from
|
|
83
|
-
* {@link LIMIT_KEYS} rather than the defaults, because the unlimited-by-default keys are
|
|
84
|
-
* absent from the defaults and testing those would silently drop a configured node bound.
|
|
85
|
-
* @param node - the graph node whose limits narrow the run.
|
|
86
|
-
* @param supplied - limits already in force for this run.
|
|
87
|
-
* @returns the effective limits for the node attempt.
|
|
88
|
-
*/
|
|
89
68
|
function mergeLimits(node, supplied = {}) {
|
|
90
69
|
const limits = resolveLimits(supplied);
|
|
91
70
|
const configured = { ...node.limits, ...(node.maxIterations !== undefined ? { maxIterations: Math.min(node.maxIterations, node.limits?.maxIterations ?? node.maxIterations) } : {}) };
|
|
92
71
|
for (const key of LIMIT_KEYS) {
|
|
93
72
|
const value = configured[key];
|
|
94
|
-
// A node's `0` alias means it adds no bound of its own. Min-ing it in would compute zero,
|
|
95
|
-
// which the budget reads as unlimited, so this node would silently discard an enclosing
|
|
96
|
-
// bound instead of leaving it in force.
|
|
97
73
|
if (isUnlimitedAlias(key, value))
|
|
98
74
|
continue;
|
|
99
75
|
if (value === undefined)
|
|
@@ -126,7 +102,6 @@ async function resolveBeforeAbort(resolve, signal) {
|
|
|
126
102
|
signal.removeEventListener('abort', abort);
|
|
127
103
|
}
|
|
128
104
|
}
|
|
129
|
-
/** Retry only read-only setup; a paused run must not wait for a stuck service. */
|
|
130
105
|
async function retryReadOnly(context, operation) {
|
|
131
106
|
for (;;) {
|
|
132
107
|
await context.runControl?.wait(context.signal);
|
|
@@ -141,13 +116,10 @@ async function retryReadOnly(context, operation) {
|
|
|
141
116
|
catch (error) {
|
|
142
117
|
if (context.signal.aborted || !pauseSignal?.aborted)
|
|
143
118
|
throw error;
|
|
144
|
-
// A fast resume may have replaced the controller already; inspect the
|
|
145
|
-
// captured signal rather than isPaused so that this attempt still retries.
|
|
146
119
|
await context.runControl.wait(context.signal);
|
|
147
120
|
}
|
|
148
121
|
}
|
|
149
122
|
}
|
|
150
|
-
/** Configures one shared executor; internal delegation never receives the scheduler or edges. */
|
|
151
123
|
export async function executeAgentNode(node, options) {
|
|
152
124
|
if (node.maxSubagents !== undefined && (!Number.isSafeInteger(node.maxSubagents) || node.maxSubagents < 0 || node.maxSubagents > 100))
|
|
153
125
|
throw new Error('maxSubagents must be an integer from 0 to 100');
|
|
@@ -160,11 +132,6 @@ export async function executeAgentNode(node, options) {
|
|
|
160
132
|
let checkpoint;
|
|
161
133
|
if (publishCheckpoint)
|
|
162
134
|
options = { ...options, onConversationCheckpoint: async (messages, state, conversation) => {
|
|
163
|
-
// The conversation is captured for the publication that follows the node — that one carries
|
|
164
|
-
// the outer invocation's allowance — and forwarded to the durable sink at every boundary.
|
|
165
|
-
// Forwarding is what makes the boundary durable: a node that continues after a mutating tool
|
|
166
|
-
// call must have that conversation on disk before the next model turn, or a process killed in
|
|
167
|
-
// that window resumes the node from a conversation that predates the call and runs it again.
|
|
168
135
|
checkpoint = { messages, state, conversation };
|
|
169
136
|
await publishCheckpoint(messages, state, conversation);
|
|
170
137
|
} };
|
|
@@ -174,24 +141,18 @@ export async function executeAgentNode(node, options) {
|
|
|
174
141
|
return () => { resume(); resumeParent?.(); };
|
|
175
142
|
};
|
|
176
143
|
const signal = AbortSignal.any([nodeBudget.signal, controller.signal]);
|
|
177
|
-
// Bind both prompts this node drives to its own clock. Wrapping only `approve` left the
|
|
178
|
-
// clearer case — an Orchestrator's `ask_user` — free to expire this node budget while the
|
|
179
|
-
// user was still answering, so their thinking time was charged to the run after all.
|
|
180
144
|
const bounded = bindUserWaits(options.context, nodeBudget, signal);
|
|
181
|
-
// Direct embedders may omit runId; observations and the returned run still
|
|
182
|
-
// need the same identity. Leave the off-mode path untouched.
|
|
183
145
|
if (options.decisionManager?.enabled && !options.runId)
|
|
184
146
|
options = { ...options, runId: randomUUID() };
|
|
185
147
|
const store = options.artifactStore ?? new ArtifactStore(options.runId ?? randomUUID());
|
|
186
148
|
const orchestrator = node.agentRole === 'orchestrator';
|
|
187
|
-
//
|
|
188
|
-
|
|
189
|
-
const delegationActive = orchestrator && delegatesWriting(node) && !!options.graph?.edges.some(edge => edge.source === node.id && edge.outcome === DELIVERED_OUTCOME);
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
if (delegationActive && options.resumeMessages?.[0]?.role === 'system' && !options.resumeMessages[0].content.includes(RESUMED_DELEGATION_INSTRUCTIONS)) {
|
|
149
|
+
// With declared outcomes the Orchestrator picks its route itself; with a single outcome, delegation needs a routed delivered port.
|
|
150
|
+
const routedDelegation = orchestrator && delegatesWriting(node) && node.completion?.mode === 'outcomes';
|
|
151
|
+
const delegationActive = routedDelegation || (orchestrator && delegatesWriting(node) && !!options.graph?.edges.some(edge => edge.source === node.id && edge.outcome === DELIVERED_OUTCOME));
|
|
152
|
+
const resumedDelegationInstructions = routedDelegation ? ROUTED_RESUMED_DELEGATION_INSTRUCTIONS : RESUMED_DELEGATION_INSTRUCTIONS;
|
|
153
|
+
if (delegationActive && options.resumeMessages?.[0]?.role === 'system' && !options.resumeMessages[0].content.includes(resumedDelegationInstructions)) {
|
|
193
154
|
const [system, ...rest] = options.resumeMessages;
|
|
194
|
-
options = { ...options, resumeMessages: [{ ...system, content: `${system.content}\n\n${
|
|
155
|
+
options = { ...options, resumeMessages: [{ ...system, content: `${system.content}\n\n${resumedDelegationInstructions}` }, ...rest] };
|
|
195
156
|
}
|
|
196
157
|
const retainedIntake = orchestrator && options.resumeMessages && options.resumeState?.orchestratorIntake?.nodeId === node.id
|
|
197
158
|
? options.resumeState.orchestratorIntake : undefined;
|
|
@@ -203,30 +164,65 @@ export async function executeAgentNode(node, options) {
|
|
|
203
164
|
const maxTotal = Math.min(policy.maxTotal ?? 8, node.maxSubagents ?? Infinity);
|
|
204
165
|
const approve = serializeApprovals((name, args, approvalSignal) => bounded.approve(name, args, approvalSignal), () => permissionMode(bounded));
|
|
205
166
|
let active = 0, total = 0;
|
|
206
|
-
|
|
167
|
+
// A subagent the parent stopped waiting on because the user sent the parent a message. It keeps
|
|
168
|
+
// working; the parent collects it with wait_subagent, writes to it with message_subagent, or stops it
|
|
169
|
+
// with cancel_subagent.
|
|
170
|
+
const background = new Map();
|
|
171
|
+
const subagentInboxes = new Map();
|
|
172
|
+
const backgroundNotices = [];
|
|
173
|
+
const backgroundGuard = () => background.size === 0 ? undefined
|
|
174
|
+
: `Subagent ${[...background.keys()].join(', ')} is still running in the background. Collect it with wait_subagent or stop it with cancel_subagent before finishing.`;
|
|
175
|
+
const holdSubagent = (id, role, work, cancel, inbox, steer) => {
|
|
176
|
+
if (!steer)
|
|
177
|
+
return work;
|
|
178
|
+
return new Promise((resolveCall, rejectCall) => {
|
|
179
|
+
let settled = false;
|
|
180
|
+
const handBack = () => {
|
|
181
|
+
if (settled)
|
|
182
|
+
return;
|
|
183
|
+
settled = true;
|
|
184
|
+
const entry = { role, work, cancel, inbox, done: false };
|
|
185
|
+
background.set(id, entry);
|
|
186
|
+
void work.catch(() => { }).finally(() => {
|
|
187
|
+
entry.done = true;
|
|
188
|
+
if (background.get(id) === entry)
|
|
189
|
+
backgroundNotices.push({ role: 'user', content: `Engine notice, not written by the user: subagent ${role} (${id}) has finished in the background. Call wait_subagent with its id to collect its result.` });
|
|
190
|
+
});
|
|
191
|
+
resolveCall(JSON.stringify({ status: 'running', subagentId: id, role,
|
|
192
|
+
message: 'The user sent you a message, so this call returned early. The subagent is still working in the background and nothing it did is lost. Read the user\'s message first. Then pass an instruction on with message_subagent, stop the subagent with cancel_subagent, or collect its result with wait_subagent. You cannot finish while it is running.' }));
|
|
193
|
+
};
|
|
194
|
+
work.then(value => { if (!settled) {
|
|
195
|
+
settled = true;
|
|
196
|
+
steer.removeEventListener('abort', handBack);
|
|
197
|
+
resolveCall(value);
|
|
198
|
+
} }, error => { if (!settled) {
|
|
199
|
+
settled = true;
|
|
200
|
+
steer.removeEventListener('abort', handBack);
|
|
201
|
+
rejectCall(error);
|
|
202
|
+
} });
|
|
203
|
+
if (steer.aborted)
|
|
204
|
+
handBack();
|
|
205
|
+
else
|
|
206
|
+
steer.addEventListener('abort', handBack, { once: true });
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
const reapBackground = async () => {
|
|
210
|
+
for (const [id, entry] of [...background]) {
|
|
211
|
+
background.delete(id);
|
|
212
|
+
entry.cancel.abort(new Error('The agent that started this subagent finished.'));
|
|
213
|
+
await entry.work.catch(() => { });
|
|
214
|
+
}
|
|
215
|
+
};
|
|
207
216
|
const changes = new Map();
|
|
208
|
-
/** Worktrees holding a pending change: the Orchestrator reads inside them without an outside-workspace prompt. */
|
|
209
217
|
const delegationRoots = [];
|
|
210
|
-
/** Every delegated worktree still on disk, whether or not a change holds it; all are removed when the node ends. */
|
|
211
218
|
const liveWorktrees = new Set();
|
|
212
|
-
/**
|
|
213
|
-
* Stops the processes a writing child left running inside its delegated worktree. There are two
|
|
214
|
-
* kinds, each kept by its own registry: a background job started with AsyncProcess, which
|
|
215
|
-
* outlives the tool call and the child, and the interpreter PowerShellFast reuses, which stays
|
|
216
|
-
* alive for its idle time after a command. Nothing can stop either afterwards (the Orchestrator
|
|
217
|
-
* has no shell), so they end with their child, and again before the worktree is removed: a
|
|
218
|
-
* job's listeners would outlive the folder, and on Windows a process whose current directory is
|
|
219
|
-
* a folder keeps the folder from being deleted. Both stops wait until the processes are gone.
|
|
220
|
-
*/
|
|
221
219
|
const stopWorktreeJobs = async (worktree) => {
|
|
222
|
-
// The tools key a process by the real path of the child's workspace, which can be spelled differently.
|
|
223
220
|
const root = await realpath(worktree).catch(() => undefined);
|
|
224
221
|
for (const folder of root !== undefined && root !== worktree ? [worktree, root] : [worktree]) {
|
|
225
222
|
await stopQaProcessesUnder(folder);
|
|
226
223
|
await disposePooledPowerShellUnder(folder);
|
|
227
224
|
}
|
|
228
225
|
};
|
|
229
|
-
/** Removes a delegated worktree and forgets it as a trusted read root. Best effort, like the removal itself. */
|
|
230
226
|
const dropWorktree = async (worktree) => {
|
|
231
227
|
liveWorktrees.delete(worktree);
|
|
232
228
|
await stopWorktreeJobs(worktree);
|
|
@@ -236,12 +232,6 @@ export async function executeAgentNode(node, options) {
|
|
|
236
232
|
delegationRoots.splice(index, 1);
|
|
237
233
|
await removeChangeWorktree(options.context.workspace, worktree);
|
|
238
234
|
};
|
|
239
|
-
/**
|
|
240
|
-
* Node-end cleanup, on every exit: an undecided change is discarded and announced, and every
|
|
241
|
-
* delegated worktree goes, including one a cancelled child was still working in. Accepted changes
|
|
242
|
-
* are already in the working folder and stay there. Also runs before a retry attempt, which
|
|
243
|
-
* starts a conversation that never saw the undecided changes. Returns the changes it discarded.
|
|
244
|
-
*/
|
|
245
235
|
const releaseChanges = async () => {
|
|
246
236
|
const discarded = [];
|
|
247
237
|
for (const change of changes.values()) {
|
|
@@ -256,9 +246,6 @@ export async function executeAgentNode(node, options) {
|
|
|
256
246
|
await emit('subagent.change', { subagentId: change.subagentId, changeId: change.id, state: 'discarded', files: change.files.map(file => file.path) });
|
|
257
247
|
return discarded;
|
|
258
248
|
};
|
|
259
|
-
// Delegated worktree setup is approved once per node visit: the first writing spawn's grant covers
|
|
260
|
-
// the visit's worktrees, with the same live-mode recheck the per-spawn path keeps. Concurrent
|
|
261
|
-
// writing spawns share one prompt rather than each raising their own.
|
|
262
249
|
let worktreeAudited = false, worktreeGranted = false;
|
|
263
250
|
let worktreeApproval;
|
|
264
251
|
const authorizeDelegatedWorktree = async (parentContext, approvalArgs) => {
|
|
@@ -278,16 +265,7 @@ export async function executeAgentNode(node, options) {
|
|
|
278
265
|
};
|
|
279
266
|
const waiters = [];
|
|
280
267
|
const emit = async (type, data) => options.onEvent?.({ type, time: new Date().toISOString(), data: { runId: options.runId, nodeId: node.id, ...data } });
|
|
281
|
-
/** Release this node's budget and abort its controller. Both operations are idempotent. */
|
|
282
268
|
const finish = () => { controller.abort(); nodeBudget.dispose(); };
|
|
283
|
-
/**
|
|
284
|
-
* Orchestrator intake that can end this node before the attempt starts.
|
|
285
|
-
*
|
|
286
|
-
* It runs in its own cleanup scope: the headless case returns here and either branch awaits
|
|
287
|
-
* an event sink that may reject, and the attempt's own `finally` is not in scope yet. Both
|
|
288
|
-
* exits would otherwise leave this node's timer retained until the original deadline.
|
|
289
|
-
* @returns an early result when intake cannot proceed, otherwise undefined.
|
|
290
|
-
*/
|
|
291
269
|
const runIntake = async () => {
|
|
292
270
|
if (!orchestrator)
|
|
293
271
|
return undefined;
|
|
@@ -307,7 +285,6 @@ export async function executeAgentNode(node, options) {
|
|
|
307
285
|
{ id: 'clarify', text: 'Confirm requirements and design considerations', status: 'pending' },
|
|
308
286
|
{ id: 'deliver', text: 'Complete the requested work and verify the result', status: 'pending' },
|
|
309
287
|
]);
|
|
310
|
-
// Intake continues into the attempt on success, so only a rejection leaves the function.
|
|
311
288
|
try {
|
|
312
289
|
await emit('graph.todos.updated', { todos });
|
|
313
290
|
}
|
|
@@ -326,16 +303,10 @@ export async function executeAgentNode(node, options) {
|
|
|
326
303
|
const nodeBudget = createRuntimeBudget(context.signal, nodeLimits.wallTimeMs, context.runControl);
|
|
327
304
|
const observationController = options.decisionManager?.enabled ? new AbortController() : undefined;
|
|
328
305
|
const nodeSignal = observationController ? AbortSignal.any([nodeBudget.signal, observationController.signal]) : nodeBudget.signal;
|
|
329
|
-
// The whole attempt is wrapped so this node's timer is released on every exit, including a
|
|
330
|
-
// rethrow: a long-lived session would otherwise keep one timer per finished attempt alive
|
|
331
|
-
// until its original deadline, retaining the budget closure for no reason.
|
|
332
306
|
try {
|
|
333
307
|
let result;
|
|
334
308
|
try {
|
|
335
309
|
nodeSignal.throwIfAborted();
|
|
336
|
-
// This node has its own clock in addition to the enclosing one, so the tool context must
|
|
337
|
-
// be bound to it as well: otherwise a wait on the user would pause the outer budget
|
|
338
|
-
// while this node's own deadline quietly expired underneath the open prompt.
|
|
339
310
|
result = await runWithinDeadline(configured, bindUserWaits({ ...context, signal: nodeSignal }, nodeBudget, nodeSignal), depth, inputs, task, subagentId, parentFallback, () => {
|
|
340
311
|
const resumeInvocation = suspendInvocationMemoryBudget();
|
|
341
312
|
const resume = nodeBudget.suspend();
|
|
@@ -348,10 +319,6 @@ export async function executeAgentNode(node, options) {
|
|
|
348
319
|
result = { id: options.runId ?? randomUUID(), graph: options.graph ?? DEFAULT_GRAPH, provider: configured.provider ?? options.provider, model: configured.model ?? options.model,
|
|
349
320
|
status: 'cancelled', usage: { inputTokens: 0, outputTokens: 0, requests: 0 }, toolCalls: 0, todos: todoStore.snapshot() };
|
|
350
321
|
}
|
|
351
|
-
// A node signal can end for two different reasons, and only one of them is a deadline.
|
|
352
|
-
// `context.signal` may itself be budget-derived from an enclosing node, so the cancellation
|
|
353
|
-
// test uses the session signal: testing the fused one would report an enclosing deadline
|
|
354
|
-
// to the user as "cancelled".
|
|
355
322
|
if (nodeSignal.aborted) {
|
|
356
323
|
const cancelled = (context.userSignal ?? context.signal).aborted;
|
|
357
324
|
result.status = cancelled ? 'cancelled' : 'exhausted';
|
|
@@ -366,28 +333,22 @@ export async function executeAgentNode(node, options) {
|
|
|
366
333
|
}
|
|
367
334
|
};
|
|
368
335
|
const runWithinDeadline = async (configured, context, depth, inputs, task, subagentId, parentFallback = false, suspendMemoryBudget, commandScope = depth > 0) => {
|
|
369
|
-
// The Orchestrator and its ordinary children run at the intake ceiling. A delegated writing child
|
|
370
|
-
// was admitted against the node's configured ceiling and keeps the capabilities it was given.
|
|
371
336
|
const delegatedChild = commandScope === 'delegated-worktree';
|
|
372
337
|
if (orchestrator && !delegatedChild)
|
|
373
338
|
configured = { ...configured, capabilities: intakeCapabilities(configured) };
|
|
374
|
-
// A delegating Orchestrator ends with `completed` (the handoff) or `delivered`; every other node
|
|
375
|
-
// keeps its configured policy, so an inactive Orchestrator is unchanged.
|
|
376
339
|
const completionPolicy = delegationActive && depth === 0 && configured.completion?.mode !== 'outcomes'
|
|
377
340
|
? { mode: 'outcomes', outcomes: [configured.completion?.outcome ?? 'completed', DELIVERED_OUTCOME] }
|
|
378
341
|
: configured.completion ?? { mode: 'single', outcome: 'completed' };
|
|
379
|
-
// Outcomes this node routes straight to an End node: its completion is then the run's result and
|
|
380
|
-
// its summary the answer the user reads, so the handoff passes the final-answer gates first. A
|
|
381
|
-
// delegated child and a node that hands off to another node are left alone: the plan belongs to
|
|
382
|
-
// the whole run, and a successor reads the output, not the summary. So is one iteration or copy
|
|
383
|
-
// of a loop or parallel modifier: the modifier aggregates those results, and it cannot be known
|
|
384
|
-
// inside an iteration whether it is the last. An Orchestrator is left alone too: the host seeds its
|
|
385
|
-
// plan with every stage of the run, and its `delivered` outcome has its own guard below (every
|
|
386
|
-
// change decided, at least one landed).
|
|
387
342
|
const declaredOutcomes = completionPolicy.mode === 'single' ? [completionPolicy.outcome] : completionPolicy.outcomes;
|
|
388
|
-
const
|
|
343
|
+
const endOutcomes = depth === 0 && !subagentId && !orchestrator && options.graph
|
|
389
344
|
? declaredOutcomes.filter(outcome => options.graph.edges.some(edge => edge.source === node.id && (edge.outcome ?? 'completed') === outcome && options.graph.nodes[edge.target]?.type === 'end'))
|
|
390
345
|
: [];
|
|
346
|
+
const finalAnswerOutcomes = options.modifierIteration === undefined ? endOutcomes : [];
|
|
347
|
+
// The session goal is checked on the last agent before the run ends, which may sit behind an
|
|
348
|
+
// action, join or other non-agent node rather than on a direct edge to End. An Orchestrator is
|
|
349
|
+
// included: its intake handoff routes to an agent, but its delivered outcome ends the run.
|
|
350
|
+
const goalGraph = depth === 0 && !subagentId ? options.graph : undefined;
|
|
351
|
+
const goalCanEndRun = goalGraph !== undefined && goalRunEndingOutcomes(goalGraph, node.id, routedOutcomes(node, declaredOutcomes)).length > 0;
|
|
391
352
|
context.toolState ??= { fileReads: new Map() };
|
|
392
353
|
if (configured.executor && configured.executor !== 'react-basic')
|
|
393
354
|
throw new Error('Only react-basic is available');
|
|
@@ -399,11 +360,6 @@ export async function executeAgentNode(node, options) {
|
|
|
399
360
|
if (inputText.length > contextChars)
|
|
400
361
|
throw new Error('Mapped inputs exceed context limit; pass artifact references instead');
|
|
401
362
|
const configuredProvider = configured.provider ?? options.provider;
|
|
402
|
-
// The model this node runs: its own, or — for a node that names neither a provider nor a model —
|
|
403
|
-
// the run's own model. A node that names a provider but no model runs that provider's
|
|
404
|
-
// configured model, which is the rule the checkpoint identity and the model preflight both
|
|
405
|
-
// use: they read the same node the same way, and a run that resolved such a node to the run's
|
|
406
|
-
// model would write a checkpoint no later run could recognize.
|
|
407
363
|
const configuredModel = configured.model ?? (configured.provider === undefined ? options.model : undefined);
|
|
408
364
|
const resolve = async (provider, model) => retryReadOnly(context, signal => options.resolveModel
|
|
409
365
|
? options.resolveModel(provider, model, signal)
|
|
@@ -412,10 +368,6 @@ export async function executeAgentNode(node, options) {
|
|
|
412
368
|
if (!resolved)
|
|
413
369
|
throw new Error(`Unknown provider ${provider}. Run andorra and open /providers first.`);
|
|
414
370
|
let model = configured.model ?? resolved.model;
|
|
415
|
-
// A delegated child inherits its parent's effective pair, so a parent continuing on a retry's
|
|
416
|
-
// fallback hands the fallback down too. The flag travels with the invocation because the
|
|
417
|
-
// child's own attempt counter starts at 1 and its node carries no retry policy: without it the
|
|
418
|
-
// selection resolver would read the child as running the primary pair and move it there.
|
|
419
371
|
let fallbackAttempt = parentFallback;
|
|
420
372
|
const orchestratorCompletionGuard = () => {
|
|
421
373
|
if (!clarified)
|
|
@@ -430,11 +382,8 @@ export async function executeAgentNode(node, options) {
|
|
|
430
382
|
const codeLedger = codeManager?.createLedger();
|
|
431
383
|
const codeIntel = codeManager?.active && permitsBuiltInTool(configured, 'repo_explore') ? codeManager : undefined;
|
|
432
384
|
const researchTool = (name) => ['Read', 'Glob', 'Grep', 'git_read', 'repo_explore'].includes(canonicalToolName(name));
|
|
433
|
-
// The panel browser tool is bound to the primary agent's session panel: a child
|
|
434
|
-
// driving the same visible tabs the parent is using cannot be authorized apart,
|
|
435
|
-
// so children never inherit it (and a role naming it fails selection below).
|
|
436
385
|
const catalog = [...options.tools, ...(options.tools.some(tool => tool.name === 'git_read') ? [] : [gitReadTool()])];
|
|
437
|
-
let tools = capabilityTools(configured, catalog, commandScope).filter(tool => !['ask_user', 'spawn_subagent', 'present_plan'].includes(tool.name) && (depth === 0 || !['browser.panel', 'browser.incognito'].includes(tool.name)) && (!orchestrator || delegatedChild || researchTool(tool.name) || ['read_skill_resource', 'qa.browser_session', 'browser.panel', 'browser.incognito'].includes(tool.name)));
|
|
386
|
+
let tools = capabilityTools(configured, catalog, commandScope).filter(tool => !['ask_user', 'spawn_subagent', 'present_plan'].includes(tool.name) && (depth === 0 || !['browser.panel', 'browser.incognito', 'browser.extensions'].includes(tool.name)) && (!orchestrator || delegatedChild || researchTool(tool.name) || ['read_skill_resource', 'qa.browser_session', 'browser.panel', 'browser.incognito', 'browser.extensions'].includes(tool.name)));
|
|
438
387
|
const compatibilityRecoverTools = options.tools.filter(tool => tool.providerVisible === false
|
|
439
388
|
&& permitsBuiltInTool(configured, tool.name, commandScope)
|
|
440
389
|
&& (!orchestrator || delegatedChild || researchTool(tool.name))).flatMap(legacy => {
|
|
@@ -443,15 +392,10 @@ export async function executeAgentNode(node, options) {
|
|
|
443
392
|
if (!canonical)
|
|
444
393
|
return [];
|
|
445
394
|
return [{ ...legacy, execute: (args, ctx) => {
|
|
446
|
-
// Resolve at call time: the node list is wrapped in place for research observation,
|
|
447
|
-
// so a legacy research call must run the wrapper or intake never sees evidence.
|
|
448
395
|
const current = tools.find(tool => tool.name === canonical.name) ?? canonical;
|
|
449
396
|
return current.execute(adaptLegacyCodingToolArguments(legacy.name, args), ctx);
|
|
450
397
|
} }];
|
|
451
398
|
});
|
|
452
|
-
// repo_explore is optional. When CodeGraph is unavailable, canonical
|
|
453
|
-
// Read/Glob/Grep remain the only filesystem research surface; legacy
|
|
454
|
-
// compatibility aliases stay hidden from the provider.
|
|
455
399
|
if (orchestrator && !codeIntel && configured.tools?.some(name => canonicalToolName(name) === 'repo_explore') && effectiveCapabilities(configured).filesystem !== 'none') {
|
|
456
400
|
const existing = new Set(tools.map(tool => tool.name));
|
|
457
401
|
for (const fallback of options.tools.filter(tool => ['Read', 'Glob', 'Grep'].includes(canonicalToolName(tool.name)) && tool.providerVisible !== false)) {
|
|
@@ -463,9 +407,6 @@ export async function executeAgentNode(node, options) {
|
|
|
463
407
|
}
|
|
464
408
|
if (codeLedger && codeIntel)
|
|
465
409
|
tools.push(codeIntel.exploreTool(codeLedger));
|
|
466
|
-
// Project memory is a session facility like update_todos: node allowlists and capability
|
|
467
|
-
// policies do not govern it (it never touches the workspace); contextPolicy.projectMemory
|
|
468
|
-
// false turns it off for a node. Delegated children work from their parent's brief.
|
|
469
410
|
if (options.projectMemory && depth === 0 && configured.contextPolicy?.projectMemory !== false) {
|
|
470
411
|
const present = new Set(tools.map(tool => tool.name));
|
|
471
412
|
tools.push(...options.projectMemory.tools().filter(tool => !present.has(tool.name)));
|
|
@@ -482,8 +423,9 @@ export async function executeAgentNode(node, options) {
|
|
|
482
423
|
return observation;
|
|
483
424
|
} };
|
|
484
425
|
}
|
|
426
|
+
const headlessRun = options.context.approvalMode === 'headless';
|
|
485
427
|
if (codeLedger && codeManager)
|
|
486
|
-
tools = codeManager.wrapTools(tools, codeLedger);
|
|
428
|
+
tools = codeManager.wrapTools(tools, codeLedger, { grepPolicy: headlessRun ? 'advisory' : 'graph-first' });
|
|
487
429
|
if (orchestrator && depth === 0)
|
|
488
430
|
tools.push({ name: 'ask_user', executionMode: 'sequential', description: 'Ask the user to clarify requirements and confirm or revise proposed design considerations. Ask one short question in plain language. Include only 1-3 brief user-facing consequences in proposedDesign; keep code details in the handoff. Prefer 2-3 short answer choices, with the recommended choice first and labelled (Recommended). Required before Orchestrator completion. A refusal stops intake.',
|
|
489
431
|
parameters: { type: 'object', properties: { question: { type: 'string', minLength: 1, maxLength: 500, description: 'One plain-language question about what the user wants.' }, proposedDesign: { type: 'array', items: { type: 'string', minLength: 1, maxLength: 240 }, minItems: 1, maxItems: 3, description: 'Short consequences that help the user decide. No source listings or implementation notes.' }, choices: { type: 'array', items: { type: 'string', minLength: 1, maxLength: 200 }, minItems: 2, maxItems: 8 } }, required: ['question', 'proposedDesign'], additionalProperties: false },
|
|
@@ -511,14 +453,6 @@ export async function executeAgentNode(node, options) {
|
|
|
511
453
|
await emit('agent.clarification.answered', { answered: true });
|
|
512
454
|
return JSON.stringify({ answer, proposedDesign: args.proposedDesign });
|
|
513
455
|
} });
|
|
514
|
-
// A top-level execution agent asks through the same prompt the Orchestrator's intake uses.
|
|
515
|
-
// Without the tool its only way to ask is prose: a question written beside a tool call pauses
|
|
516
|
-
// nothing, and a reply that is only a question is a stalled turn the runtime sends back, so
|
|
517
|
-
// the user watches the question scroll past while the run keeps working. It is offered only
|
|
518
|
-
// where a person can answer; a headless run keeps the complete_agent handoff, and a delegated
|
|
519
|
-
// child reports to its parent rather than to the user.
|
|
520
|
-
// The one write an Orchestrator makes itself: clearing a stray untracked file, which can be what
|
|
521
|
-
// stops a subagent from starting. It takes a path and nothing else, so it cannot write code.
|
|
522
456
|
if (orchestrator && depth === 0 && effectiveCapabilities(configured).filesystem !== 'none')
|
|
523
457
|
tools.push(removeUntrackedFileTool());
|
|
524
458
|
if (!orchestrator && depth === 0 && options.context.approvalMode !== 'headless' && options.context.askUser)
|
|
@@ -539,10 +473,6 @@ export async function executeAgentNode(node, options) {
|
|
|
539
473
|
ctx.signal.throwIfAborted();
|
|
540
474
|
const answered = typeof answer === 'string' && !!answer.trim() && answer.trim().toLowerCase() !== '/cancel';
|
|
541
475
|
await emit('agent.clarification.answered', { answered });
|
|
542
|
-
// The surfaces report two different refusals. No answer at all, or /cancel, is the user
|
|
543
|
-
// cancelling: the terminal's choice is labelled "Cancel this task", so the run stops as it
|
|
544
|
-
// does for an Orchestrator question. An empty answer is the desktop's Skip, which declines
|
|
545
|
-
// this one question and lets the work go on.
|
|
546
476
|
if (typeof answer !== 'string' || answer.trim().toLowerCase() === '/cancel')
|
|
547
477
|
throw new ClarificationRequiredError('Needs clarification: the user cancelled the task at a question. Nothing further was done.');
|
|
548
478
|
if (!answered)
|
|
@@ -551,11 +481,6 @@ export async function executeAgentNode(node, options) {
|
|
|
551
481
|
throw new Error('The answer exceeds 16000 characters; ask for a shorter decision.');
|
|
552
482
|
return JSON.stringify({ answered: true, answer });
|
|
553
483
|
} });
|
|
554
|
-
// Plan mode is offered at the run's top level regardless of the mode this attempt composed
|
|
555
|
-
// under: the mode is the user's pick and can change while the task runs (the live picker or
|
|
556
|
-
// /permissions plan), and a catalog keyed to the starting mode would leave a switched-in run
|
|
557
|
-
// told to present a plan it has no tool for. The execution-time check below decides what a
|
|
558
|
-
// call means under the mode in force when it lands.
|
|
559
484
|
if (depth === 0)
|
|
560
485
|
tools.push({ name: 'present_plan', executionMode: 'sequential', description: 'Present the implementation plan for the user to approve, reject, or send feedback on. Only meaningful while the run is in plan mode: file mutations and escalations stay refused until a plan is approved. Present one complete plan in markdown after researching; a later call may present a revised plan after feedback.',
|
|
561
486
|
parameters: { type: 'object', properties: { plan: { type: 'string', minLength: 1, maxLength: 16000, description: 'The implementation plan in markdown: what will change, the files or areas touched, the approach, and how it will be verified.' } }, required: ['plan'], additionalProperties: false },
|
|
@@ -563,8 +488,6 @@ export async function executeAgentNode(node, options) {
|
|
|
563
488
|
ctx.signal.throwIfAborted();
|
|
564
489
|
if (Object.keys(args).some(key => key !== 'plan') || typeof args.plan !== 'string' || !args.plan.trim() || args.plan.length > 16000)
|
|
565
490
|
throw new Error('Provide the plan as one markdown string of 1-16000 characters.');
|
|
566
|
-
// The mode is read live: a plan already approved, or the user switching modes by hand,
|
|
567
|
-
// leaves nothing to present for, and the error steers the model back to the task.
|
|
568
491
|
if (permissionMode(ctx) !== 'plan')
|
|
569
492
|
throw new Error('Plan mode is not active for this run; no plan presentation is needed. Proceed with the task under the current permissions.');
|
|
570
493
|
if (ctx.approvalMode === 'headless' || !ctx.askUser)
|
|
@@ -601,16 +524,11 @@ export async function executeAgentNode(node, options) {
|
|
|
601
524
|
tools.push(artifactTools[0]);
|
|
602
525
|
if (configured.tools === undefined || configured.tools.includes('write_artifact'))
|
|
603
526
|
tools.push({ ...write, execute: async (args, ctx) => { const result = await write.execute(args, ctx); scopedRefs.add(JSON.parse(result).ref); return result; } });
|
|
604
|
-
// Skill wrappers replace the visible resource reader later in this invocation.
|
|
605
|
-
// Delegation still needs its original, capability-filtered name to load inherited skills.
|
|
606
527
|
const canDelegateSkillReader = tools.some(tool => tool.name === 'read_skill_resource');
|
|
607
|
-
// Under a delegating Orchestrator no child spawns further, whatever the depth limit: a writing
|
|
608
|
-
// role spawned from a child would take the ordinary path, with a worktree made from HEAD that is
|
|
609
|
-
// kept and registered in the user's repository, outside the review this node promises.
|
|
610
528
|
if (policy.enabled && maxTotal > 0 && depth < (policy.maxDepth ?? 1) && !(delegationActive && depth > 0)) {
|
|
611
529
|
tools.push({ name: 'spawn_subagent', description: 'Run one configured role on a bounded task. Its typed result returns as an observation. Batch spawn calls can run concurrently within configured limits. Role contracts: ' + JSON.stringify((policy.roles ?? []).map(role => ({ id: role.id, name: role.name, instruction: role.instruction, inputSchema: role.inputSchema, outputSchema: role.outputSchema }))),
|
|
612
530
|
parameters: { type: 'object', properties: { role: { type: 'string', enum: (policy.roles ?? []).map(role => role.id) }, task: { type: 'string' }, input: { type: 'object' } }, required: ['role', 'task'], additionalProperties: false },
|
|
613
|
-
execute: async (args,
|
|
531
|
+
execute: async (args, callContext) => {
|
|
614
532
|
if (Object.keys(args).some(key => !['role', 'task', 'input'].includes(key)) || typeof args.role !== 'string' || typeof args.task !== 'string' || !args.task.trim() || args.task.length > 16000)
|
|
615
533
|
throw new Error('Choose a configured role and provide a task of 1–16000 characters');
|
|
616
534
|
const role = policy.roles?.find(item => item.id === args.role);
|
|
@@ -623,9 +541,6 @@ export async function executeAgentNode(node, options) {
|
|
|
623
541
|
throw new Error('Subagent input must be an object');
|
|
624
542
|
if (role.inputSchema)
|
|
625
543
|
validateValue(role.inputSchema, childInputs, `Subagent ${role.name} input`);
|
|
626
|
-
// A writing role of a delegating Orchestrator is admitted against the node's configured
|
|
627
|
-
// ceiling, not the intake ceiling the Orchestrator itself runs under; it starts only once
|
|
628
|
-
// the user has confirmed the design.
|
|
629
544
|
const delegated = delegationActive && depth === 0 && isWritingRole(role);
|
|
630
545
|
if (delegated && !clarified)
|
|
631
546
|
throw new Error('Ask the user to confirm the design before starting writing subagents: a real ask_user answer is required first.');
|
|
@@ -640,15 +555,10 @@ export async function executeAgentNode(node, options) {
|
|
|
640
555
|
throw new Error('Concurrent writing subagents require separate worktrees');
|
|
641
556
|
if ((policy.workspace ?? 'shared-read-only') === 'shared-read-only' && writingChild)
|
|
642
557
|
throw new Error('Shared read-only subagents cannot write');
|
|
643
|
-
// `browser.panel` and `browser.incognito` stay with the primary agent (see the tools filter above);
|
|
644
|
-
// excluded here rather than at selection so a role naming it explicitly is
|
|
645
|
-
// refused as exceeding the parent instead of silently losing its browser.
|
|
646
|
-
// A delegated writing role's tools come from the node's capabilities, not from the
|
|
647
|
-
// Orchestrator's own read-only intake kit: a worktree child may write and run commands.
|
|
648
558
|
const available = new Set(delegated
|
|
649
|
-
? [...capabilityTools({ ...node, capabilities: parentCapabilities, tools: undefined }, catalog, 'delegated-worktree').map(tool => tool.name).filter(name => name !== 'browser.panel' && name !== 'browser.incognito'),
|
|
559
|
+
? [...capabilityTools({ ...node, capabilities: parentCapabilities, tools: undefined }, catalog, 'delegated-worktree').map(tool => tool.name).filter(name => name !== 'browser.panel' && name !== 'browser.incognito' && name !== 'browser.extensions'),
|
|
650
560
|
...tools.map(tool => tool.name).filter(name => name === 'read_artifact' || name === 'write_artifact'), ...(canDelegateSkillReader ? ['read_skill_resource'] : [])]
|
|
651
|
-
: [...tools.map(tool => tool.name).filter(name => name !== 'browser.panel' && name !== 'browser.incognito'), ...(canDelegateSkillReader ? ['read_skill_resource'] : [])]);
|
|
561
|
+
: [...tools.map(tool => tool.name).filter(name => name !== 'browser.panel' && name !== 'browser.incognito' && name !== 'browser.extensions'), ...(canDelegateSkillReader ? ['read_skill_resource'] : [])]);
|
|
652
562
|
const childToolNames = delegated ? canonicalizeToolList(role.tools) ?? [...available]
|
|
653
563
|
: policy.toolInheritance === 'inherit' ? [...available] : canonicalizeToolList(role.tools) ?? [...available].filter(name => ['Read', 'Glob', 'Grep', 'git_read', 'qa.browser_session', 'read_skill_resource'].includes(canonicalToolName(name)));
|
|
654
564
|
if (childToolNames.some(name => !available.has(name)))
|
|
@@ -661,19 +571,30 @@ export async function executeAgentNode(node, options) {
|
|
|
661
571
|
contextPolicy: { history: false, maxChars: Math.min(contextChars, 16000) } };
|
|
662
572
|
if (depth > 0 && active >= (policy.maxConcurrent ?? 3))
|
|
663
573
|
throw new Error('Nested spawn would exceed concurrent subagent limit; finish current work first');
|
|
574
|
+
// A message for the parent ends the wait for a free slot too: the subagents holding the slots keep
|
|
575
|
+
// running in the background, so a queued call would otherwise keep the parent from reading it.
|
|
576
|
+
const steer = depth === 0 ? callContext.steerSignal : undefined;
|
|
664
577
|
while (active >= (policy.maxConcurrent ?? 3)) {
|
|
665
|
-
await new Promise((resolveWait, reject) => {
|
|
666
|
-
const cleanup = () =>
|
|
667
|
-
const ready = () => { cleanup(); resolveWait(); };
|
|
668
|
-
const
|
|
669
|
-
waiters.splice(i, 1); cleanup();
|
|
578
|
+
const free = await new Promise((resolveWait, reject) => {
|
|
579
|
+
const cleanup = () => { callContext.signal.removeEventListener('abort', abort); steer?.removeEventListener('abort', steered); };
|
|
580
|
+
const ready = () => { cleanup(); resolveWait(true); };
|
|
581
|
+
const leave = () => { const i = waiters.indexOf(ready); if (i >= 0)
|
|
582
|
+
waiters.splice(i, 1); cleanup(); };
|
|
583
|
+
const abort = () => { leave(); reject(callContext.signal.reason); };
|
|
584
|
+
const steered = () => { leave(); resolveWait(false); };
|
|
670
585
|
waiters.push(ready);
|
|
671
|
-
|
|
672
|
-
|
|
586
|
+
callContext.signal.addEventListener('abort', abort, { once: true });
|
|
587
|
+
steer?.addEventListener('abort', steered, { once: true });
|
|
588
|
+
if (callContext.signal.aborted)
|
|
673
589
|
abort();
|
|
590
|
+
else if (steer?.aborted)
|
|
591
|
+
steered();
|
|
674
592
|
});
|
|
593
|
+
if (!free)
|
|
594
|
+
return JSON.stringify({ status: 'not_started', role: role.id,
|
|
595
|
+
message: 'Not started: the user sent you a message while this subagent was waiting for a free slot. Read the message, then call spawn_subagent again if this task is still needed.' });
|
|
675
596
|
}
|
|
676
|
-
|
|
597
|
+
callContext.signal.throwIfAborted();
|
|
677
598
|
if (total >= maxTotal) {
|
|
678
599
|
waiters.shift()?.();
|
|
679
600
|
throw new Error('Maximum total subagents reached');
|
|
@@ -681,166 +602,207 @@ export async function executeAgentNode(node, options) {
|
|
|
681
602
|
active++;
|
|
682
603
|
total++;
|
|
683
604
|
const id = randomUUID();
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
await assertDelegationGit(parentWorkspace, parentContext.signal);
|
|
698
|
-
// A workspace that is a subfolder of its repository puts the child in the same
|
|
699
|
-
// subfolder of the worktree; the snapshot and the worktree cover the whole repository.
|
|
700
|
-
const inside = relative(await repositoryRoot(parentWorkspace, parentContext.signal), await realpath(parentWorkspace));
|
|
701
|
-
const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
|
|
702
|
-
const approvalArgs = { role: role.id, workspace: parentWorkspace, temporaryDirectoryPrefix,
|
|
703
|
-
operations: ['git snapshot of the working folder through a temporary index (no ref, stash or index change)', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree <snapshot>'],
|
|
704
|
-
warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. One grant covers every writing subagent of this Orchestrator visit; a change reaches the working folder only when the Orchestrator accepts it.' };
|
|
705
|
-
await authorizeDelegatedWorktree(parentContext, approvalArgs);
|
|
706
|
-
const base = await snapshotWorkspace(parentWorkspace, parentContext.signal);
|
|
707
|
-
await authorizeDelegatedWorktree(parentContext, approvalArgs);
|
|
708
|
-
const worktree = await addChangeWorktree(parentWorkspace, base, parentContext.signal);
|
|
709
|
-
liveWorktrees.add(worktree);
|
|
710
|
-
delegatedWorktree = { worktree, base };
|
|
711
|
-
workspace = inside ? join(worktree, inside) : worktree;
|
|
712
|
-
task += `\n\nThis task runs in a separate Git worktree started from the working folder as it stands: ${workspace}. Files ignored by Git (for example node_modules) are not in this worktree. Install what you need inside this worktree if a build or test requires it. Report the commands and tests you ran and their results in the tests list of your completion. This worktree shares the Git repository of the user's working folder: do not create or change stashes, branches, tags or Git configuration. Commit only if the task needs it; commits stay in this worktree, and your result is taken from the files as you leave them.`;
|
|
605
|
+
const cancel = new AbortController();
|
|
606
|
+
const childSignal = AbortSignal.any([callContext.signal, cancel.signal]);
|
|
607
|
+
const inbox = [];
|
|
608
|
+
subagentInboxes.set(id, inbox);
|
|
609
|
+
// Everything the subagent's start waits on (Git, the worktree approval) ends when the subagent is
|
|
610
|
+
// cancelled, not only its model run.
|
|
611
|
+
const parentContext = { ...callContext, signal: childSignal, steerSignal: undefined,
|
|
612
|
+
...(callContext.userSignal ? { userSignal: AbortSignal.any([callContext.userSignal, cancel.signal]) } : {}) };
|
|
613
|
+
const untilCancelled = (pending) => new Promise((resolvePending, rejectPending) => {
|
|
614
|
+
const abort = () => rejectPending(childSignal.reason);
|
|
615
|
+
if (childSignal.aborted) {
|
|
616
|
+
abort();
|
|
617
|
+
return;
|
|
713
618
|
}
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
let
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
619
|
+
childSignal.addEventListener('abort', abort, { once: true });
|
|
620
|
+
pending.then(value => { childSignal.removeEventListener('abort', abort); resolvePending(value); }, error => { childSignal.removeEventListener('abort', abort); rejectPending(error); });
|
|
621
|
+
});
|
|
622
|
+
const work = (async () => {
|
|
623
|
+
let workspaceArtifact;
|
|
624
|
+
let delegatedWorktree;
|
|
625
|
+
let keepWorktree = false;
|
|
626
|
+
try {
|
|
627
|
+
const parentWorkspace = parentContext.workspace;
|
|
628
|
+
let workspace = parentWorkspace;
|
|
629
|
+
let task = args.task;
|
|
630
|
+
if (delegated) {
|
|
631
|
+
if (parentCapabilities.git !== 'write')
|
|
632
|
+
throw new Error('Creating child worktrees requires parent Git write capability');
|
|
633
|
+
await assertDelegationGit(parentWorkspace, parentContext.signal);
|
|
634
|
+
const inside = relative(await repositoryRoot(parentWorkspace, parentContext.signal), await realpath(parentWorkspace));
|
|
635
|
+
const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
|
|
636
|
+
const approvalArgs = { role: role.id, workspace: parentWorkspace, temporaryDirectoryPrefix,
|
|
637
|
+
operations: ['git snapshot of the working folder through a temporary index (no ref, stash or index change)', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree <snapshot>'],
|
|
638
|
+
warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. One grant covers every writing subagent of this Orchestrator visit; a change reaches the working folder only when the Orchestrator accepts it.' };
|
|
639
|
+
await untilCancelled(authorizeDelegatedWorktree(callContext, approvalArgs));
|
|
640
|
+
const base = await snapshotWorkspace(parentWorkspace, parentContext.signal);
|
|
641
|
+
await untilCancelled(authorizeDelegatedWorktree(callContext, approvalArgs));
|
|
642
|
+
const worktree = await addChangeWorktree(parentWorkspace, base, parentContext.signal);
|
|
643
|
+
liveWorktrees.add(worktree);
|
|
644
|
+
delegatedWorktree = { worktree, base };
|
|
645
|
+
workspace = inside ? join(worktree, inside) : worktree;
|
|
646
|
+
task += `\n\nThis task runs in a separate Git worktree started from the working folder as it stands: ${workspace}. Files ignored by Git (for example node_modules) are not in this worktree. Install what you need inside this worktree if a build or test requires it. Report the commands and tests you ran and their results in the tests list of your completion. This worktree shares the Git repository of the user's working folder: do not create or change stashes, branches, tags or Git configuration. Commit only if the task needs it; commits stay in this worktree, and your result is taken from the files as you leave them.`;
|
|
647
|
+
}
|
|
648
|
+
else if (policy.workspace === 'worktree' && writingChild) {
|
|
649
|
+
if (parentCapabilities.git !== 'write')
|
|
650
|
+
throw new Error('Creating child worktrees requires parent Git write capability');
|
|
651
|
+
const temporaryDirectoryPrefix = join(tmpdir(), 'andorra-subagent-');
|
|
652
|
+
const approvalArgs = { role: role.id, workspace, temporaryDirectoryPrefix,
|
|
653
|
+
operations: ['git status --porcelain', 'create temporary directory', 'git worktree add --detach <temporary-directory>/worktree HEAD'],
|
|
654
|
+
warning: 'UNSANDBOXED: Git and PATH executables can access the entire host filesystem and network. This operation creates a temporary worktree outside the workspace and writes protected Git metadata, including an external common Git directory. Changes are retained for inspection.' };
|
|
655
|
+
let audited = false, explicitlyApproved = false;
|
|
656
|
+
const authorizeWorktree = async () => {
|
|
657
|
+
parentContext.signal.throwIfAborted();
|
|
739
658
|
assertPlanMutationAllowed(parentContext);
|
|
740
|
-
|
|
741
|
-
|
|
659
|
+
while (!audited || (!explicitlyApproved && permissionMode(parentContext) !== 'full-access')) {
|
|
660
|
+
await approveOperation({ ...parentContext, approve: async (...approval) => {
|
|
661
|
+
const allowed = await parentContext.approve(...approval);
|
|
662
|
+
assertPlanMutationAllowed(parentContext);
|
|
663
|
+
if (allowed === true)
|
|
664
|
+
explicitlyApproved = true;
|
|
665
|
+
return allowed;
|
|
666
|
+
} }, 'spawn_subagent.worktree', approvalArgs);
|
|
667
|
+
audited = true;
|
|
668
|
+
assertPlanMutationAllowed(parentContext);
|
|
669
|
+
}
|
|
670
|
+
assertPlanMutationAllowed(parentContext);
|
|
671
|
+
};
|
|
672
|
+
await authorizeWorktree();
|
|
673
|
+
const gitOptions = { cwd: workspace, signal: parentContext.signal, windowsHide: true, timeout: 15000, maxBuffer: 65536 };
|
|
674
|
+
const args = ['-c', 'core.hooksPath=', '-c', 'core.fsmonitor=false'];
|
|
675
|
+
const { stdout } = await exec('git', [...args, 'status', '--porcelain'], gitOptions);
|
|
676
|
+
if (stdout.trim())
|
|
677
|
+
throw new Error('Separate worktrees require a clean parent working tree. Commit or stash changes before delegation.');
|
|
678
|
+
await authorizeWorktree();
|
|
679
|
+
const directory = await mkdtemp(temporaryDirectoryPrefix);
|
|
680
|
+
workspace = join(directory, 'worktree');
|
|
681
|
+
await authorizeWorktree();
|
|
682
|
+
await exec('git', [...args, 'worktree', 'add', '--detach', workspace, 'HEAD'], gitOptions);
|
|
683
|
+
workspaceArtifact = await store.put('git-worktree', JSON.stringify({ workspace, role: role.id, note: 'Changes retained for explicit inspection and integration; not merged automatically.' }));
|
|
684
|
+
}
|
|
685
|
+
child.limits = {
|
|
686
|
+
...(policy.maxWallTimeMs === undefined ? {} : { wallTimeMs: policy.maxWallTimeMs }),
|
|
687
|
+
...(limits.maxIterations === undefined ? {} : { maxIterations: Math.min(limits.maxIterations, 40) }),
|
|
742
688
|
};
|
|
743
|
-
await
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
689
|
+
await emit('subagent.started', { subagentId: id, role: role.id, depth: depth + 1,
|
|
690
|
+
...(callContext.toolCallId ? { toolCallId: callContext.toolCallId } : {}),
|
|
691
|
+
...(callContext.toolInvocationId ? { toolInvocationId: callContext.toolInvocationId } : {}),
|
|
692
|
+
...(childProvider ? { provider: childProvider } : {}), ...(childModel ? { model: childModel } : {}),
|
|
693
|
+
task, ...(Object.keys(childInputs).length > 0 ? { input: childInputs } : {}) });
|
|
694
|
+
let result;
|
|
695
|
+
try {
|
|
696
|
+
result = await run(child, { ...parentContext, signal: childSignal, steerSignal: undefined, workspace, ...(parentContext.delegationRoots ? { delegationRoots: undefined } : {}) }, depth + 1, childInputs, task, id, fallbackAttempt, delegated ? 'delegated-worktree' : undefined);
|
|
697
|
+
}
|
|
698
|
+
catch (error) {
|
|
699
|
+
await emit('subagent.completed', { subagentId: id, role: role.id, status: childSignal.aborted ? 'cancelled' : 'failed' });
|
|
700
|
+
throw error;
|
|
701
|
+
}
|
|
702
|
+
finally {
|
|
703
|
+
if (delegatedWorktree)
|
|
704
|
+
await stopWorktreeJobs(delegatedWorktree.worktree);
|
|
705
|
+
}
|
|
706
|
+
if (result.telemetry)
|
|
707
|
+
mergeRunTelemetry(telemetry, result.telemetry);
|
|
708
|
+
if (result.status === 'succeeded' && researchResults.get(result))
|
|
709
|
+
observedResearch = true;
|
|
710
|
+
await emit('subagent.completed', { subagentId: id, role: role.id, status: result.status });
|
|
711
|
+
const returnedArtifacts = [...(result.completion?.artifacts ?? []), ...(workspaceArtifact ? [workspaceArtifact] : [])];
|
|
712
|
+
for (const artifact of returnedArtifacts)
|
|
713
|
+
scopedRefs.add(artifact.ref);
|
|
714
|
+
references(result.completion?.output, scopedRefs);
|
|
715
|
+
const observation = { status: result.status, reason: result.reason, outcome: result.completion?.outcome, output: result.completion?.output, artifacts: returnedArtifacts };
|
|
716
|
+
if (delegatedWorktree) {
|
|
717
|
+
observation.tests = result.completion?.tests ?? [];
|
|
718
|
+
const collected = result.status === 'succeeded' ? await collectChange(delegatedWorktree.worktree, delegatedWorktree.base, parentContext.signal) : undefined;
|
|
719
|
+
if (collected?.files.length) {
|
|
720
|
+
const { worktree, base } = delegatedWorktree;
|
|
721
|
+
let changeId = `change-${randomUUID().slice(0, 8)}`;
|
|
722
|
+
while (changes.has(changeId))
|
|
723
|
+
changeId = `change-${randomUUID().slice(0, 8)}`;
|
|
724
|
+
const truncated = collected.diff.length > DELEGATION_DIFF_LIMIT;
|
|
725
|
+
let diffArtifact, diffNote;
|
|
726
|
+
try {
|
|
727
|
+
diffArtifact = await store.put('delegation-diff', collected.diff);
|
|
728
|
+
scopedRefs.add(diffArtifact.ref);
|
|
729
|
+
}
|
|
730
|
+
catch (error) {
|
|
731
|
+
diffNote = `The full diff could not be stored as an artifact (${error instanceof Error ? error.message : String(error)}); read the changed files inside the worktree.`;
|
|
732
|
+
}
|
|
733
|
+
const root = await realpath(worktree);
|
|
734
|
+
changes.set(changeId, { id: changeId, subagentId: id, role: role.id, worktree, base, tree: collected.tree, files: collected.files, state: 'pending',
|
|
735
|
+
provider: result.provider ?? childProvider, model: result.model ?? childModel, conflicts: [], ...(diffArtifact ? { diffArtifact } : {}) });
|
|
736
|
+
delegationRoots.push(root);
|
|
737
|
+
keepWorktree = true;
|
|
738
|
+
await emit('subagent.change', { subagentId: id, changeId, state: 'pending', files: collected.files.map(file => file.path) });
|
|
739
|
+
observation.change = { id: changeId, worktree, files: collected.files, diff: truncated ? collected.diff.slice(0, DELEGATION_DIFF_LIMIT) : collected.diff, truncated,
|
|
740
|
+
...(diffArtifact ? { diffArtifact } : {}), ...(diffNote ? { diffNote } : {}) };
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
return JSON.stringify(observation);
|
|
744
|
+
}
|
|
745
|
+
finally {
|
|
746
|
+
subagentInboxes.delete(id);
|
|
747
|
+
if (delegatedWorktree && !keepWorktree)
|
|
748
|
+
await dropWorktree(delegatedWorktree.worktree);
|
|
749
|
+
active--;
|
|
750
|
+
waiters.shift()?.();
|
|
755
751
|
}
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
752
|
+
})();
|
|
753
|
+
return holdSubagent(id, role.id, work, cancel, inbox, steer);
|
|
754
|
+
} });
|
|
755
|
+
if (depth === 0) {
|
|
756
|
+
const backgrounded = (args, name, extra = []) => {
|
|
757
|
+
if (Object.keys(args).some(key => key !== 'id' && !extra.includes(key)) || typeof args.id !== 'string')
|
|
758
|
+
throw new Error(`${name} takes the subagentId of a subagent that is running in the background`);
|
|
759
|
+
const entry = background.get(args.id);
|
|
760
|
+
if (!entry)
|
|
761
|
+
throw new Error('No subagent with that id is running in the background. A spawn_subagent call that returned a result has already finished.');
|
|
762
|
+
return { id: args.id, entry };
|
|
763
|
+
};
|
|
764
|
+
const idParameter = { type: 'string', minLength: 1, description: 'The subagentId from a spawn_subagent or wait_subagent result whose status is running.' };
|
|
765
|
+
tools.push({ name: 'wait_subagent', description: 'Wait for a subagent that is running in the background and return its result, exactly as spawn_subagent would have. If the user sends you another message while you wait, this returns early again with status running.',
|
|
766
|
+
parameters: { type: 'object', properties: { id: idParameter }, required: ['id'], additionalProperties: false },
|
|
767
|
+
execute: async (args, ctx) => {
|
|
768
|
+
ctx.signal.throwIfAborted();
|
|
769
|
+
const { id, entry } = backgrounded(args, 'wait_subagent');
|
|
770
|
+
background.delete(id);
|
|
771
|
+
return holdSubagent(id, entry.role, entry.work, entry.cancel, entry.inbox, ctx.steerSignal);
|
|
772
|
+
} });
|
|
773
|
+
tools.push({ name: 'message_subagent', description: 'Send an instruction to a subagent that is running in the background. It stops what it is doing to read it, then carries on. Use this to pass on what the user asked for; the subagent never sees the user\'s messages to you.',
|
|
774
|
+
parameters: { type: 'object', properties: { id: idParameter, message: { type: 'string', minLength: 1, maxLength: 16000 } }, required: ['id', 'message'], additionalProperties: false },
|
|
775
|
+
execute: async (args, ctx) => {
|
|
776
|
+
ctx.signal.throwIfAborted();
|
|
777
|
+
const { id, entry } = backgrounded(args, 'message_subagent', ['message']);
|
|
778
|
+
if (typeof args.message !== 'string' || !args.message.trim() || args.message.length > 16000)
|
|
779
|
+
throw new Error('Provide the message as a string of 1-16000 characters');
|
|
780
|
+
if (entry.done)
|
|
781
|
+
throw new Error('That subagent has already finished. Collect its result with wait_subagent.');
|
|
782
|
+
entry.inbox.push({ role: 'user', content: `Message from ${node.name ?? 'the agent that started you'}, sent while you work. Follow it:\n${args.message.trim()}` });
|
|
783
|
+
ctx.runControl?.notifySteer(id);
|
|
784
|
+
await emit('subagent.messaged', { subagentId: id, role: entry.role, text: args.message.trim() });
|
|
785
|
+
return JSON.stringify({ delivered: true, subagentId: id, message: 'The subagent reads this before its next step and keeps working. Collect its result with wait_subagent.' });
|
|
786
|
+
} });
|
|
787
|
+
tools.push({ name: 'cancel_subagent', description: 'Stop a subagent that is running in the background. Work it has not reported is discarded.',
|
|
788
|
+
parameters: { type: 'object', properties: { id: idParameter }, required: ['id'], additionalProperties: false },
|
|
789
|
+
execute: async (args, ctx) => {
|
|
790
|
+
ctx.signal.throwIfAborted();
|
|
791
|
+
const { id, entry } = backgrounded(args, 'cancel_subagent');
|
|
792
|
+
background.delete(id);
|
|
793
|
+
entry.cancel.abort(new Error('Cancelled by the agent that started this subagent.'));
|
|
794
|
+
const output = await entry.work.catch(() => undefined);
|
|
765
795
|
let result;
|
|
766
796
|
try {
|
|
767
|
-
|
|
768
|
-
// them, whether it is a delegated writer or an ordinary research role.
|
|
769
|
-
result = await run(child, { ...parentContext, workspace, ...(parentContext.delegationRoots ? { delegationRoots: undefined } : {}) }, depth + 1, childInputs, task, id, fallbackAttempt, delegated ? 'delegated-worktree' : undefined);
|
|
770
|
-
}
|
|
771
|
-
catch (error) {
|
|
772
|
-
// A child that throws once started (oversized mapped inputs, a cancelled parent) still
|
|
773
|
-
// ends here: without a settling event, a listener counting this child keeps it running
|
|
774
|
-
// until the whole run ends. The spawn call itself still fails with the error.
|
|
775
|
-
await emit('subagent.completed', { subagentId: id, role: role.id, status: parentContext.signal.aborted ? 'cancelled' : 'failed' });
|
|
776
|
-
throw error;
|
|
797
|
+
result = output === undefined ? undefined : JSON.parse(output);
|
|
777
798
|
}
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
// collected: a worktree kept for review must not have a process still writing in it.
|
|
781
|
-
if (delegatedWorktree)
|
|
782
|
-
await stopWorktreeJobs(delegatedWorktree.worktree);
|
|
783
|
-
}
|
|
784
|
-
// The child's requests, tools and decisions were billed to the run, so its capture is
|
|
785
|
-
// folded into the parent's; the result object itself is consumed as a tool observation
|
|
786
|
-
// and would otherwise take those totals with it.
|
|
787
|
-
if (result.telemetry)
|
|
788
|
-
mergeRunTelemetry(telemetry, result.telemetry);
|
|
789
|
-
if (result.status === 'succeeded' && researchResults.get(result))
|
|
790
|
-
observedResearch = true;
|
|
791
|
-
await emit('subagent.completed', { subagentId: id, role: role.id, status: result.status });
|
|
792
|
-
const returnedArtifacts = [...(result.completion?.artifacts ?? []), ...(workspaceArtifact ? [workspaceArtifact] : [])];
|
|
793
|
-
for (const artifact of returnedArtifacts)
|
|
794
|
-
scopedRefs.add(artifact.ref);
|
|
795
|
-
references(result.completion?.output, scopedRefs);
|
|
796
|
-
const observation = { status: result.status, reason: result.reason, outcome: result.completion?.outcome, output: result.completion?.output, artifacts: returnedArtifacts };
|
|
797
|
-
if (delegatedWorktree) {
|
|
798
|
-
observation.tests = result.completion?.tests ?? [];
|
|
799
|
-
// A child that failed, was cancelled or changed nothing yields no change: its worktree
|
|
800
|
-
// goes in the cleanup below. Otherwise the change waits for the Orchestrator's review.
|
|
801
|
-
const collected = result.status === 'succeeded' ? await collectChange(delegatedWorktree.worktree, delegatedWorktree.base, parentContext.signal) : undefined;
|
|
802
|
-
if (collected?.files.length) {
|
|
803
|
-
const { worktree, base } = delegatedWorktree;
|
|
804
|
-
// Random rather than counted: a resumed visit starts a new registry, and a counter
|
|
805
|
-
// would hand out ids the resumed conversation already uses for other changes.
|
|
806
|
-
let changeId = `change-${randomUUID().slice(0, 8)}`;
|
|
807
|
-
while (changes.has(changeId))
|
|
808
|
-
changeId = `change-${randomUUID().slice(0, 8)}`;
|
|
809
|
-
const truncated = collected.diff.length > DELEGATION_DIFF_LIMIT;
|
|
810
|
-
// The full diff is an artifact the Orchestrator can page through; one too large even
|
|
811
|
-
// for an artifact stays readable in the worktree, and the observation says so.
|
|
812
|
-
let diffArtifact, diffNote;
|
|
813
|
-
try {
|
|
814
|
-
diffArtifact = await store.put('delegation-diff', collected.diff);
|
|
815
|
-
scopedRefs.add(diffArtifact.ref);
|
|
816
|
-
}
|
|
817
|
-
catch (error) {
|
|
818
|
-
diffNote = `The full diff could not be stored as an artifact (${error instanceof Error ? error.message : String(error)}); read the changed files inside the worktree.`;
|
|
819
|
-
}
|
|
820
|
-
// The record is registered only after every step that can throw: a pending record must
|
|
821
|
-
// never point at a worktree the cleanup below already removed.
|
|
822
|
-
const root = await realpath(worktree);
|
|
823
|
-
changes.set(changeId, { id: changeId, subagentId: id, role: role.id, worktree, base, tree: collected.tree, files: collected.files, state: 'pending',
|
|
824
|
-
provider: result.provider ?? childProvider, model: result.model ?? childModel, conflicts: [], ...(diffArtifact ? { diffArtifact } : {}) });
|
|
825
|
-
delegationRoots.push(root);
|
|
826
|
-
keepWorktree = true;
|
|
827
|
-
await emit('subagent.change', { subagentId: id, changeId, state: 'pending', files: collected.files.map(file => file.path) });
|
|
828
|
-
observation.change = { id: changeId, worktree, files: collected.files, diff: truncated ? collected.diff.slice(0, DELEGATION_DIFF_LIMIT) : collected.diff, truncated,
|
|
829
|
-
...(diffArtifact ? { diffArtifact } : {}), ...(diffNote ? { diffNote } : {}) };
|
|
830
|
-
}
|
|
799
|
+
catch {
|
|
800
|
+
result = undefined;
|
|
831
801
|
}
|
|
832
|
-
return JSON.stringify(
|
|
833
|
-
}
|
|
834
|
-
|
|
835
|
-
if (delegatedWorktree && !keepWorktree)
|
|
836
|
-
await dropWorktree(delegatedWorktree.worktree);
|
|
837
|
-
active--;
|
|
838
|
-
waiters.shift()?.();
|
|
839
|
-
}
|
|
840
|
-
} });
|
|
802
|
+
return JSON.stringify({ status: 'cancelled', subagentId: id, role: entry.role, ...(result === undefined ? {} : { result }) });
|
|
803
|
+
} });
|
|
804
|
+
}
|
|
841
805
|
}
|
|
842
|
-
// The landing tools act on a change record by id and nothing else: the Orchestrator cannot
|
|
843
|
-
// supply content, a patch or a command through them, so it still cannot write code itself.
|
|
844
806
|
if (delegationActive && depth === 0) {
|
|
845
807
|
const idOnly = () => ({ type: 'object', properties: { id: { type: 'string', minLength: 1, description: 'The change id from a spawn_subagent result.' } }, required: ['id'], additionalProperties: false });
|
|
846
808
|
const undecided = (args, name) => {
|
|
@@ -866,36 +828,24 @@ export async function executeAgentNode(node, options) {
|
|
|
866
828
|
const { base, tree } = change;
|
|
867
829
|
assertPlanMutationAllowed(ctx);
|
|
868
830
|
const conflict = async (conflicts, detail) => {
|
|
869
|
-
// The paths stay on the record after a later clean landing: the delivery record says
|
|
870
|
-
// the change conflicted before it landed.
|
|
871
831
|
change.state = 'conflict';
|
|
872
832
|
change.conflicts = conflicts;
|
|
873
833
|
await announce(change);
|
|
874
834
|
return JSON.stringify({ state: 'conflict', conflicts, detail });
|
|
875
835
|
};
|
|
876
836
|
const failed = async (error) => {
|
|
877
|
-
// A landing that wrote part of the change and could not put the folder back is not a
|
|
878
|
-
// conflict the Orchestrator can review its way out of: the node stops, and its reason
|
|
879
|
-
// carries the snapshot commit and the files the user needs to recover.
|
|
880
837
|
if (error instanceof LandingRestoreError) {
|
|
881
838
|
change.state = 'conflict';
|
|
882
839
|
change.conflicts = error.paths;
|
|
883
840
|
await announce(change);
|
|
884
841
|
throw new ClarificationRequiredError(error.message);
|
|
885
842
|
}
|
|
886
|
-
// A cancelled run propagates as cancellation. Any other failure happened before
|
|
887
|
-
// anything was written (the snapshot, the merge or the copy made before applying), so
|
|
888
|
-
// it is a conflict in effect.
|
|
889
843
|
if (ctx.signal.aborted || (error instanceof Error && error.name === 'AbortError'))
|
|
890
844
|
throw error;
|
|
891
845
|
return conflict([], error instanceof Error ? error.message : String(error));
|
|
892
846
|
};
|
|
893
|
-
/** Paths an approval prompt of this call already covered. */
|
|
894
847
|
const granted = new Set();
|
|
895
848
|
let asked = false;
|
|
896
|
-
// A landing is prepared, authorized for the paths it writes, then applied. The folder can
|
|
897
|
-
// change while a prompt is open; the apply then refuses the prepared patch as a whole and
|
|
898
|
-
// the landing is prepared again from the folder as it now stands.
|
|
899
849
|
for (let attempt = 1;; attempt++) {
|
|
900
850
|
ctx.signal.throwIfAborted();
|
|
901
851
|
let prepared;
|
|
@@ -907,13 +857,6 @@ export async function executeAgentNode(node, options) {
|
|
|
907
857
|
}
|
|
908
858
|
if (!prepared.ready)
|
|
909
859
|
return conflict(prepared.conflicts, prepared.detail);
|
|
910
|
-
// Landing follows the rule for an Edit of the same files, and the files are the ones
|
|
911
|
-
// the merged patch writes or removes, not the ones the subagent changed: a file the
|
|
912
|
-
// user moved meanwhile takes the edit at its new place. A change lands at the
|
|
913
|
-
// repository root, so it can reach files above a subfolder workspace or protected
|
|
914
|
-
// metadata inside it; those prompt exactly where an Edit of them would. Inside the
|
|
915
|
-
// workspace, the modes that auto-approve workspace writes land without a prompt and
|
|
916
|
-
// audit the grant.
|
|
917
860
|
const files = prepared.landing.files;
|
|
918
861
|
const { classifyWorkspaceWrites } = await import('./tools.js');
|
|
919
862
|
const { outside, protected: protectedPaths } = await classifyWorkspaceWrites(ctx.workspace, prepared.landing.root, files);
|
|
@@ -930,21 +873,14 @@ export async function executeAgentNode(node, options) {
|
|
|
930
873
|
}
|
|
931
874
|
await ctx.onApprovalEvent?.('node.tool.approval.requested', { name: 'accept_change', arguments: { id: change.id, files }, mode: 'workspace-policy' });
|
|
932
875
|
await ctx.onApprovalEvent?.('node.tool.approval.decided', { name: 'accept_change', mode: 'workspace-policy', approved: true, actor: 'workspace-policy' });
|
|
933
|
-
// The audit hooks can yield to a live permission change; a policy grant holds only
|
|
934
|
-
// while the policy that gave it is still the live one.
|
|
935
876
|
assertPlanMutationAllowed(ctx);
|
|
936
877
|
if (automatic())
|
|
937
878
|
break;
|
|
938
879
|
}
|
|
939
880
|
ctx.signal.throwIfAborted();
|
|
940
881
|
assertPlanMutationAllowed(ctx);
|
|
941
|
-
// The review record (Keep / Undo) keeps what each landed path holds before the patch writes or
|
|
942
|
-
// removes it, the same way an Edit's write is recorded, and holds its lock while the patch is applied
|
|
943
|
-
// so an Undo cannot interleave with the landing. A landing that does not land records nothing.
|
|
944
882
|
const recording = ctx.fileChanges ? await ctx.fileChanges.beforeWrite(files.map(file => join(prepared.landing.root, ...file.split('/')))).catch(() => undefined) : undefined;
|
|
945
883
|
const locked = recording ? await recording.begin().then(() => true, () => false) : false;
|
|
946
|
-
// The lock can wait behind an Undo; a stop or a switch to Plan mode in that wait still decides, and
|
|
947
|
-
// is refused exactly as it is just above, with the lock given back.
|
|
948
884
|
try {
|
|
949
885
|
ctx.signal.throwIfAborted();
|
|
950
886
|
assertPlanMutationAllowed(ctx);
|
|
@@ -996,44 +932,32 @@ export async function executeAgentNode(node, options) {
|
|
|
996
932
|
},
|
|
997
933
|
};
|
|
998
934
|
tools = tools.map(requirePublishedPlan);
|
|
999
|
-
// The manager applies provider-specific bounds to its decision snapshot.
|
|
1000
935
|
const decisionRoles = tools.some(tool => tool.name === 'spawn_subagent')
|
|
1001
936
|
? (policy.roles ?? []).map(role => role.id) : [];
|
|
1002
|
-
const systemPrompt = [orchestrator && depth === 0 ? ORCHESTRATOR_INSTRUCTIONS : '', orchestrator && depth === 0 && delegationActive ? DELEGATION_INSTRUCTIONS : '', configured.systemPrompt ?? configured.prompt ?? ''].filter(Boolean).join('\n\n');
|
|
1003
|
-
// The nodes that can run after this one, and the QA guidance this node can act on. A node whose
|
|
1004
|
-
// work is sure to reach a testing node is told so and leaves the running-app testing to it: told
|
|
1005
|
-
// only to verify, an implementation node scripted clicks into the user's own window. The check
|
|
1006
|
-
// is on the graph node's routes, so a delegated child answers to its parent's: a writer whose
|
|
1007
|
-
// work can be delivered straight to Done keeps its own running-app checks.
|
|
937
|
+
const systemPrompt = [orchestrator && depth === 0 ? ORCHESTRATOR_INSTRUCTIONS : '', orchestrator && depth === 0 && delegationActive ? (routedDelegation ? ROUTED_DELEGATION_INSTRUCTIONS : DELEGATION_INSTRUCTIONS) : '', configured.systemPrompt ?? configured.prompt ?? ''].filter(Boolean).join('\n\n');
|
|
1008
938
|
const graphNodeId = options.nodeId ?? node.id;
|
|
1009
939
|
const laterNodes = options.graph ? laterAgentNodes(options.graph, graphNodeId) : [];
|
|
1010
940
|
const routeTester = options.graph ? testerOnEveryRoute(options.graph, graphNodeId) : undefined;
|
|
1011
941
|
const reachableTester = laterNodes.find(isTestingNode)?.name;
|
|
1012
942
|
const nodeInstructions = [options.instructions, qaGuidance({ tools: tools.map(tool => tool.name), laterTester: routeTester })].filter(Boolean).join('\n\n');
|
|
1013
|
-
const
|
|
1014
|
-
// Skills the node's own prompts name as `/name`. A delegated child runs a dispatched task, not
|
|
1015
|
-
// these prompts, so only the node itself reads them.
|
|
943
|
+
const requestedInheritedSkills = [...new Set(options.inheritedSkills ?? [])];
|
|
1016
944
|
const promptSkillNames = depth === 0 ? promptSkillReferences(configured.instruction, configured.systemPrompt ?? configured.prompt) : [];
|
|
1017
945
|
const canReadProjectSkills = ['Read', 'Glob', 'Grep', 'repo_explore'].some(name => permitsBuiltInTool(configured, name, commandScope));
|
|
1018
|
-
|
|
1019
|
-
// Inherited and prompt-named references still load even if ambient discovery is disabled.
|
|
1020
|
-
const discoverProjectSkills = canReadProjectSkills && (inheritedSkills.length > 0 || promptSkillNames.length > 0
|
|
946
|
+
const discoverProjectSkills = canReadProjectSkills && (requestedInheritedSkills.length > 0 || promptSkillNames.length > 0
|
|
1021
947
|
|| options.efficiency?.projectSkillDiscovery === true
|
|
1022
948
|
|| (options.efficiency?.projectSkillDiscovery !== false && options.decisionManager?.skillRoutingEnabled === true));
|
|
1023
949
|
const resourceReader = tools.find(tool => tool.name === 'read_skill_resource');
|
|
1024
|
-
const skills = discoverProjectSkills ||
|
|
950
|
+
const skills = discoverProjectSkills || requestedInheritedSkills.length > 0 || promptSkillNames.length > 0 || resourceReader || tools.some(tool => tool.name === 'qa.browser_session')
|
|
1025
951
|
? await discoverRuntimeSkills(context.workspace, context.signal, tools.map(tool => tool.name), discoverProjectSkills) : [];
|
|
1026
|
-
// A
|
|
1027
|
-
//
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
// reports it.
|
|
952
|
+
// A skill inherited from earlier nodes that this node cannot load (broken locally, or no skill
|
|
953
|
+
// reader among its tools) is left out for this node only; the run continues without it.
|
|
954
|
+
const inheritedSkills = requestedInheritedSkills.filter(id => {
|
|
955
|
+
const local = skills.find(skill => skill.id === id);
|
|
956
|
+
return local ? !local.unavailable : !!resourceReader;
|
|
957
|
+
});
|
|
1033
958
|
const promptSkills = [];
|
|
1034
959
|
const missingPromptSkills = [];
|
|
1035
960
|
for (const reference of promptSkillNames) {
|
|
1036
|
-
// `/skill::name` is the command of an installed skill whose name is a built-in command.
|
|
1037
961
|
const name = reference.startsWith('skill::') ? reference.slice('skill::'.length) : reference;
|
|
1038
962
|
let id;
|
|
1039
963
|
if (!skills.some(skill => skill.id === name)) {
|
|
@@ -1041,7 +965,7 @@ export async function executeAgentNode(node, options) {
|
|
|
1041
965
|
try {
|
|
1042
966
|
id = resourceReader.resolveSkillEntryId(name, 'SKILL.md');
|
|
1043
967
|
}
|
|
1044
|
-
catch {
|
|
968
|
+
catch { }
|
|
1045
969
|
}
|
|
1046
970
|
if (!id && options.installedSkillClaims?.(name)) {
|
|
1047
971
|
missingPromptSkills.push(reference);
|
|
@@ -1058,13 +982,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1058
982
|
const list = missingPromptSkills.map(name => '/' + name).join(', ');
|
|
1059
983
|
await emit('graph.skill.missing', { skills: missingPromptSkills, text: `${configured.name ?? configured.id} names ${list}, which ${missingPromptSkills.length === 1 ? 'is' : 'are'} not available on this machine. The node runs without ${missingPromptSkills.length === 1 ? 'it' : 'them'}.` });
|
|
1060
984
|
}
|
|
1061
|
-
for (const id of inheritedSkills) {
|
|
1062
|
-
const local = skills.find(skill => skill.id === id);
|
|
1063
|
-
if (local?.unavailable)
|
|
1064
|
-
throw new Error(`Node ${configured.id}: inherited skill "${id}" is unavailable: ${local.unavailable}`);
|
|
1065
|
-
if (!local && !resourceReader)
|
|
1066
|
-
throw new Error(`Node ${configured.id}: inherited skill "${id}" cannot be loaded. Enable the skill reader or disable skill inheritance on this node.`);
|
|
1067
|
-
}
|
|
1068
985
|
const loadedSkills = new Set();
|
|
1069
986
|
const missingSkillError = () => {
|
|
1070
987
|
const missing = inheritedSkills.filter(id => !loadedSkills.has(id));
|
|
@@ -1078,88 +995,54 @@ export async function executeAgentNode(node, options) {
|
|
|
1078
995
|
loadedSkills.add(id);
|
|
1079
996
|
await options.onSkillActivated?.(id);
|
|
1080
997
|
}).map(requirePublishedPlan) : [];
|
|
1081
|
-
// Merge registered external resources into the same tool, without duplicate schemas.
|
|
1082
998
|
if (skillTools.length)
|
|
1083
999
|
tools = tools.filter(tool => tool.name !== 'read_skill_resource');
|
|
1084
1000
|
const effectiveTask = typeof inputs.taskInstruction === 'string' && inputs.taskInstruction.trim() ? inputs.taskInstruction.trim() : task;
|
|
1085
1001
|
const graphFirstSearch = depth === 0 && !!codeIntel?.active && codeGraphRoute(effectiveTask) === 'graph';
|
|
1086
1002
|
const decisionTask = depth > 0 ? task : options.decisionPreflight?.task ?? effectiveTask;
|
|
1087
1003
|
let result;
|
|
1088
|
-
// Every attempt's capture is folded here: a failed attempt whose result is discarded still
|
|
1089
|
-
// spent tokens and executed tools, and the run's totals must include them.
|
|
1090
1004
|
const telemetry = createRunTelemetry();
|
|
1091
1005
|
let attempts = depth === 0 ? configured.retry?.maxAttempts ?? 1 : 1;
|
|
1092
1006
|
const efficiency = resolveEfficiency(options.efficiency);
|
|
1093
|
-
// Bounded facts about the workspace, collected once per node when a feature that reads them is
|
|
1094
|
-
// on; the runner may have collected them for the run already.
|
|
1095
1007
|
const facts = depth === 0 && (efficiency.contextSelection || efficiency.catalogSelection)
|
|
1096
1008
|
? options.workspaceFacts ?? await collectWorkspaceFacts(context.workspace, { signal: context.signal }) : undefined;
|
|
1097
|
-
// Adaptive routing state across attempts: the tier the attempt ran on, how often it escalated,
|
|
1098
|
-
// and what the failed attempt left behind, so a re-attempt inspects rather than repeats it.
|
|
1099
1009
|
const nodeBaseline = { provider, model };
|
|
1100
1010
|
let routedTier;
|
|
1101
1011
|
let escalations = 0;
|
|
1102
1012
|
let previousAttemptReason;
|
|
1103
|
-
// An escalation that was granted an attempt but could not move up (no higher tier configured, an
|
|
1104
|
-
// unresolvable target, the limit reached) closes the path: the loop never extends again on a tier
|
|
1105
|
-
// that already exhausted itself, so the node budget stays the bound it was before routing.
|
|
1106
1013
|
let escalationPending = false;
|
|
1107
1014
|
let escalationFailed = false;
|
|
1108
1015
|
let previousMutations;
|
|
1109
|
-
// The plan the user approved in this invocation, if any. A retry starts a fresh conversation
|
|
1110
|
-
// that would otherwise inherit only the files: without carrying the approval forward, a
|
|
1111
|
-
// replacement model could implement the original request without the constraints the user
|
|
1112
|
-
// approved. Set by present_plan when its answer is the approval.
|
|
1113
1016
|
let approvedPlan;
|
|
1114
|
-
// A retry rebuilds the conversation from the node task, so a message the user steered into the
|
|
1115
|
-
// failed attempt is not in it — and the engine's queue has already spliced it out. What each
|
|
1116
|
-
// attempt read is retained here and offered again to the next one; without that, the run would
|
|
1117
|
-
// finish under the instructions the message corrected while its transcript says it was read.
|
|
1118
1017
|
const consumedSteers = [];
|
|
1119
|
-
// Ids of the changes that were still undecided when an attempt failed. A retry starts a fresh
|
|
1120
|
-
// conversation that has none of the failed attempt's spawn results, so it could not review
|
|
1121
|
-
// them, and completing as delivered requires every change decided: they are discarded before
|
|
1122
|
-
// the retry starts, and the retry is told so. Landed changes stay and still count.
|
|
1123
1018
|
const discardedAtRetry = [];
|
|
1124
1019
|
for (let attempt = 1; attempt <= attempts; attempt++) {
|
|
1125
1020
|
context.signal.throwIfAborted();
|
|
1021
|
+
// A retry starts over: a subagent the last attempt left in the background is stopped first, before its
|
|
1022
|
+
// worktree is removed underneath it and before the new attempt could start it again.
|
|
1023
|
+
if (depth === 0 && attempt > 1)
|
|
1024
|
+
await reapBackground();
|
|
1126
1025
|
if (delegationActive && depth === 0 && attempt > 1)
|
|
1127
1026
|
for (const change of await releaseChanges())
|
|
1128
1027
|
discardedAtRetry.push(change.id);
|
|
1129
1028
|
if (attempt > 1 && configured.retry?.fallback)
|
|
1130
1029
|
fallbackAttempt = true;
|
|
1131
|
-
// This invocation's identity for the caller's live-selection resolver: a delegated child is
|
|
1132
|
-
// `<node>/<role>`, and `#fallback` marks a pair continuing a retry's fallback.
|
|
1133
1030
|
const liveNodeId = `${node.id}${subagentId ? '/' + configured.id : ''}${fallbackAttempt ? '#fallback' : ''}`;
|
|
1134
|
-
// Resolve the live pair before this attempt's window, transcript and request are built. The
|
|
1135
|
-
// runner froze the graph the run started on, so a node reached after a live model change
|
|
1136
|
-
// would otherwise judge the predecessor's transcript against the superseded pair, discard
|
|
1137
|
-
// it, and only then move to the model that produced it.
|
|
1138
1031
|
const liveModel = await options.getLiveModel?.(liveNodeId, provider, model, context.signal);
|
|
1139
|
-
// A live selection is the user's explicit choice for this attempt, whatever it names.
|
|
1140
1032
|
const liveSelected = liveModel !== undefined;
|
|
1141
1033
|
if (liveModel && (liveModel.provider !== provider || liveModel.model !== model)) {
|
|
1142
1034
|
provider = liveModel.provider;
|
|
1143
1035
|
model = liveModel.model;
|
|
1144
1036
|
resolved = liveModel;
|
|
1145
|
-
// The node's start line named the pair the frozen graph resolves: publish the pair that
|
|
1146
|
-
// actually answers so the rows and the live chip follow, as they do for a mid-node switch.
|
|
1147
1037
|
await emit('agent.model.changed', { provider, model, ...(liveModel.contextWindow === undefined ? {} : { contextWindow: liveModel.contextWindow }), ...(subagentId ? { subagentId } : {}) });
|
|
1148
1038
|
}
|
|
1149
1039
|
else if (!subagentId) {
|
|
1150
|
-
// The window of the pair this attempt runs, published even though nothing changed. `run.context`
|
|
1151
|
-
// describes the session's pair, and for a graph whose every node pins its own provider that
|
|
1152
|
-
// snapshot is built without discovery — so a window only the endpoint reports (no saved
|
|
1153
|
-
// per-model entry) was known here, where the node resolved its model, and nowhere a client
|
|
1154
|
-
// could read it. An unknown window is published as unknown: the reading must not stay sized
|
|
1155
|
-
// against the pair another node ran.
|
|
1156
1040
|
await emit('agent.model.resolved', { provider, model, ...(resolved.contextWindow === undefined ? {} : { contextWindow: resolved.contextWindow }) });
|
|
1157
1041
|
}
|
|
1158
1042
|
loadedSkills.clear();
|
|
1159
1043
|
const retainedClarification = Boolean(orchestrator && depth === 0 && confirmedClarifications.length);
|
|
1160
|
-
let taskBase = `${task}${retainedClarification ? `\n\nConfirmed user clarification observations (retain these decisions across retries):\n${JSON.stringify(confirmedClarifications)}` : ''}\n\nNode instruction: ${configured.instruction ?? 'Complete the assigned task.'}
|
|
1044
|
+
let taskBase = `${task}${retainedClarification ? `\n\nConfirmed user clarification observations (retain these decisions across retries):\n${JSON.stringify(confirmedClarifications)}` : ''}\n\nNode instruction: ${configured.instruction ?? 'Complete the assigned task.'}${MAPPED_INPUTS_HEADING}${inputText}${typeof inputs.taskInstruction === 'string' ? `\n\nTask instruction from handoff:\n${inputs.taskInstruction}` : ''}`;
|
|
1161
1045
|
if (previousMutations?.length) {
|
|
1162
|
-
// The escalated attempt starts a fresh conversation; the files are the only state it inherits.
|
|
1163
1046
|
taskBase += `\n\nA previous attempt on another model already changed these workspace files: ${JSON.stringify(previousMutations)}. Inspect them before changing them again and do not repeat work that is already done.`;
|
|
1164
1047
|
}
|
|
1165
1048
|
if (delegationActive && depth === 0 && attempt > 1) {
|
|
@@ -1171,9 +1054,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1171
1054
|
}
|
|
1172
1055
|
}
|
|
1173
1056
|
if (approvedPlan !== undefined && permissionMode(context) !== 'plan') {
|
|
1174
|
-
// The approval granted editing permissions to this invocation, so the fresh attempt
|
|
1175
|
-
// implements the plan the user approved rather than reinterpreting the raw task. Still in
|
|
1176
|
-
// plan mode, the attempt must present again instead — the approval did not happen.
|
|
1177
1057
|
taskBase += `\n\nThe user approved this plan in a previous attempt of this task; implement it as approved:\n${approvedPlan}`;
|
|
1178
1058
|
}
|
|
1179
1059
|
if (inheritedSkills.length) {
|
|
@@ -1194,28 +1074,17 @@ export async function executeAgentNode(node, options) {
|
|
|
1194
1074
|
}
|
|
1195
1075
|
let attemptPrompt = retainedClarification ? `${systemPrompt}\n\n${RETAINED_CLARIFICATION_INSTRUCTION}` : systemPrompt;
|
|
1196
1076
|
const executionLimits = mergeLimits(configured, depth ? { ...limits, wallTimeMs: configured.limits?.wallTimeMs } : limits);
|
|
1197
|
-
// The initial model's smaller window must not become the permanent character ceiling:
|
|
1198
|
-
// a later live selection can increase it again, up to this configured node limit.
|
|
1199
1077
|
const contextCharCeiling = executionLimits.maxContextChars;
|
|
1200
1078
|
const window = resolved.contextWindow;
|
|
1201
1079
|
if (window !== undefined && Number.isSafeInteger(window) && window > 0)
|
|
1202
1080
|
executionLimits.maxContextChars = Math.min(executionLimits.maxContextChars, window * 3);
|
|
1203
1081
|
let attemptRepoBlock = '';
|
|
1204
|
-
// Room left for repository context, under two ceilings (the same pair the skill catalog uses,
|
|
1205
|
-
// see `skillContextBudget`). `repoBudget` is what the whole request can still hold: it counts
|
|
1206
|
-
// the tool schemas, and gets them back when routing trims the catalog. `repoPolicyRoom` is what
|
|
1207
|
-
// the node's context policy still allows the node to be handed to read, which the tool schemas
|
|
1208
|
-
// are not part of. Charging the schemas to the policy left a node with the full tool set a
|
|
1209
|
-
// negative budget before its task was read, so it never received repository context.
|
|
1210
1082
|
let repoBudget = 0;
|
|
1211
1083
|
let repoPolicyRoom = 0;
|
|
1212
1084
|
const repoRoom = () => Math.min(repoBudget, repoPolicyRoom);
|
|
1213
1085
|
const spendRepoRoom = (chars) => { repoBudget -= chars; repoPolicyRoom -= chars; };
|
|
1214
1086
|
let committedChars = 0;
|
|
1215
1087
|
if (depth === 0 && codeLedger && codeIntel) {
|
|
1216
|
-
// Budget the rendered turn, not its stored `task`: the seed the request actually carries expands
|
|
1217
|
-
// a continued turn's direction into the message (`turnModelTask`), and budgeting less than the
|
|
1218
|
-
// request sends would let the repository block be sized into an over-window prompt.
|
|
1219
1088
|
const historyChars = configured.contextPolicy?.history ? (options.history ?? []).reduce((sum, item) => sum + turnModelTask(item).length + JSON.stringify(item.completion).length, 0) : 0;
|
|
1220
1089
|
const toolSchemaChars = JSON.stringify(tools.map(tool => ({ name: tool.name, description: tool.description, parameters: tool.parameters }))).length;
|
|
1221
1090
|
const contractChars = JSON.stringify({ outputSchema: configured.outputSchema, completion: configured.completion }).length;
|
|
@@ -1228,8 +1097,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1228
1097
|
let attemptTools = tools;
|
|
1229
1098
|
const initialPromptChars = attemptPrompt.length;
|
|
1230
1099
|
let recoverTools;
|
|
1231
|
-
// These values are pinned in the executor request. Count their serialized
|
|
1232
|
-
// representation (including nested JSON escaping), not only task text.
|
|
1233
1100
|
const skillContextBudget = () => {
|
|
1234
1101
|
const pinned = [taskBase, attemptPrompt, nodeInstructions,
|
|
1235
1102
|
JSON.stringify(configured.outputSchema ?? { type: 'object' }),
|
|
@@ -1242,16 +1109,7 @@ export async function executeAgentNode(node, options) {
|
|
|
1242
1109
|
const schemaChars = JSON.stringify([...attemptTools, completionTool({ ...options, completionPolicy, outputSchema: configured.outputSchema })]
|
|
1243
1110
|
.map(({ name, description, parameters }) => ({ name, description, parameters }))).length
|
|
1244
1111
|
+ JSON.stringify((recoverTools ?? []).filter(tool => !attemptTools.includes(tool)).map(tool => tool.name)).length;
|
|
1245
|
-
// Reserve executor instructions, message wrappers and the skill reference wrapper before
|
|
1246
|
-
// allocating optional content.
|
|
1247
1112
|
const fixedChars = JSON.stringify(pinned).length + historyChars + 8300;
|
|
1248
|
-
// Two different ceilings, and the tool schemas count against only one of them. The node's
|
|
1249
|
-
// context policy bounds what the node is handed to read (its task, mapped inputs, history and
|
|
1250
|
-
// optional references such as this catalog); the tool schemas are sent whatever that policy
|
|
1251
|
-
// says and, for a node with the full tool set, are about as large as the default policy on
|
|
1252
|
-
// their own. Charging them to the policy left the catalog no room on exactly those nodes, so
|
|
1253
|
-
// an agent with every tool was never told which skills exist. The execution limit is the
|
|
1254
|
-
// real bound on the whole request (it follows the model's window), so the schemas count there.
|
|
1255
1113
|
const policyRoom = contextChars - fixedChars;
|
|
1256
1114
|
const requestRoom = executionLimits.maxContextChars - fixedChars - schemaChars;
|
|
1257
1115
|
return Math.max(0, Math.min(8000, policyRoom, requestRoom));
|
|
@@ -1259,10 +1117,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1259
1117
|
let memoryBlockAdded = false;
|
|
1260
1118
|
let pendingMemoryApplication;
|
|
1261
1119
|
let pendingGraphApplication;
|
|
1262
|
-
// The single layer that counts decision events into this invocation's capture. Both stages
|
|
1263
|
-
// publish through it: the preflight manager through the sink below, the post-tool check
|
|
1264
|
-
// through the executor's event path. Counting at a stage callback as well would double the
|
|
1265
|
-
// counters once the runtime's capture is merged in.
|
|
1266
1120
|
const recordDecision = (event) => {
|
|
1267
1121
|
if (event.type.startsWith('decision.'))
|
|
1268
1122
|
recordDecisionEvent(telemetry, event.type, event.data);
|
|
@@ -1278,17 +1132,12 @@ export async function executeAgentNode(node, options) {
|
|
|
1278
1132
|
repository: { codeGraphAvailable: depth === 0 && !!codeIntel?.active && repoRoom() >= 512 && allowsGraphRouting(effectiveTask), memoryAvailable: decisionManager.active ? depth === 0 && configured.agentRole !== 'orchestrator' && !!options.memory?.activeFor(options.runId) && options.memory.automaticRetrieval : (depth === 0 ? options.decisionPreflight?.memoryAvailable : undefined) ?? options.memory?.activeFor(options.runId) ?? false },
|
|
1279
1133
|
capabilities: { toolFamilies: toolFamilies(tools), subagentRoles: decisionRoles, ...(skills.length ? { skills: skills.filter(skill => !skill.unavailable).map(({ id, description }) => ({ id, description })) } : {}) },
|
|
1280
1134
|
run: depth === 0 && options.modifierIteration !== undefined ? { iteration: options.modifierIteration } : {},
|
|
1281
|
-
// Host-only consumer eligibility; the manager removes this before egress.
|
|
1282
1135
|
consumers: { answerOnly: answerOnlyTask(decisionTask),
|
|
1283
1136
|
adaptiveRouting: attempt === 1 && depth === 0 && !subagentId && !fallbackAttempt
|
|
1284
1137
|
&& configured.provider === undefined && configured.model === undefined && !options.modelPinned && !liveSelected
|
|
1285
1138
|
&& hasAdaptiveAlternative(efficiency.adaptiveRouting, nodeBaseline, options.configuredModels ?? []),
|
|
1286
1139
|
},
|
|
1287
|
-
}, { runId: options.runId, nodeId: configured.id, invocationId: randomUUID() }, { codeGraph: depth === 0 && !!codeIntel?.active && repoRoom() >= 512 && codeGraphRoute(effectiveTask) === 'graph', memory: depth === 0 && (options.decisionPreflight?.memory ?? (configured.agentRole !== 'orchestrator' && !!options.memory?.activeFor(options.runId) && options.memory.automaticRetrieval)) }, signal, event => {
|
|
1288
|
-
// The decision manager publishes through this sink, not through the runtime's own event
|
|
1289
|
-
// helper. The sink forwards to the caller's `onEvent`, which is the unwrapped one: the
|
|
1290
|
-
// runtime wraps only the options object it is given, so these events would otherwise
|
|
1291
|
-
// never reach the capture this invocation returns.
|
|
1140
|
+
}, { runId: options.runId, nodeId: configured.id, invocationId: randomUUID(), ...(subagentId ? { subagentId } : {}) }, { codeGraph: depth === 0 && !!codeIntel?.active && repoRoom() >= 512 && codeGraphRoute(effectiveTask) === 'graph', memory: depth === 0 && (options.decisionPreflight?.memory ?? (configured.agentRole !== 'orchestrator' && !!options.memory?.activeFor(options.runId) && options.memory.automaticRetrieval)) }, signal, event => {
|
|
1292
1141
|
if (signal.aborted)
|
|
1293
1142
|
return;
|
|
1294
1143
|
return recordDecision(event);
|
|
@@ -1312,16 +1161,12 @@ export async function executeAgentNode(node, options) {
|
|
|
1312
1161
|
return preflight(signal);
|
|
1313
1162
|
});
|
|
1314
1163
|
else {
|
|
1315
|
-
// A shadow answer may arrive after the node returns; the finish waits for it so the
|
|
1316
|
-
// request and its terminal events are counted together.
|
|
1317
1164
|
const shadow = preflight(context.runControl ? AbortSignal.any([context.signal, context.runControl.signal]) : context.signal);
|
|
1318
1165
|
(telemetry.pendingDecisions ??= []).push(shadow.catch(() => undefined));
|
|
1319
1166
|
void shadow.catch(() => undefined);
|
|
1320
1167
|
}
|
|
1321
1168
|
}
|
|
1322
1169
|
context.signal.throwIfAborted();
|
|
1323
|
-
// Facts settle what no decision needs to: an empty workspace has no source to explore and no
|
|
1324
|
-
// repository history to recall, so neither retrieval is attempted.
|
|
1325
1170
|
let retrievalSkipped = false;
|
|
1326
1171
|
if (efficiency.contextSelection && depth === 0 && facts?.empty && (codeIntel || options.memory?.activeFor(options.runId))) {
|
|
1327
1172
|
retrievalSkipped = true;
|
|
@@ -1329,11 +1174,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1329
1174
|
activeRouting = { ...activeRouting, codeGraph: false, memory: false };
|
|
1330
1175
|
await emitEfficiency('efficiency.context.retrieval_skipped', { reason: 'empty_workspace' });
|
|
1331
1176
|
}
|
|
1332
|
-
// Adaptive model-tier routing, decided once per attempt before this attempt's conversation
|
|
1333
|
-
// is built. Explicit choices (a node pin, a run pin, a live selection) are never overridden;
|
|
1334
|
-
// uncertainty keeps the baseline; a target the configuration cannot resolve keeps it too.
|
|
1335
|
-
// A retry that the node's own `retry.fallback` serves is an explicit choice, so routing does not
|
|
1336
|
-
// move it back to the tier that just failed; an escalation retry is routing's own move.
|
|
1337
1177
|
const explicitFallbackRetry = attempt > 1 && configured.retry?.fallback !== undefined && !escalationPending;
|
|
1338
1178
|
if (efficiency.adaptiveRouting.enabled && depth === 0 && !subagentId && explicitFallbackRetry) {
|
|
1339
1179
|
await emitEfficiency('efficiency.routing.decided', { tier: undefined, reason: 'pinned', evidence: 'pinned', applied: false, attempt });
|
|
@@ -1347,10 +1187,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1347
1187
|
});
|
|
1348
1188
|
let applied = false;
|
|
1349
1189
|
let unresolved = false;
|
|
1350
|
-
// `served` is what routing needs: the attempt ran on the decision's resolved target — either
|
|
1351
|
-
// because routing moved the model onto it or because that target already was the model in
|
|
1352
|
-
// use. `applied` stays "the model changed"; a tier naming the baseline model is not a
|
|
1353
|
-
// change, but it is still the tier that served, and the escalation climbs from it.
|
|
1354
1190
|
let served = false;
|
|
1355
1191
|
if (decision.target) {
|
|
1356
1192
|
const target = decision.target;
|
|
@@ -1370,8 +1206,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1370
1206
|
served = true;
|
|
1371
1207
|
const routedWindow = routed.contextWindow;
|
|
1372
1208
|
executionLimits.maxContextChars = routedWindow !== undefined && Number.isSafeInteger(routedWindow) && routedWindow > 0 ? Math.min(contextCharCeiling, routedWindow * 3) : contextCharCeiling;
|
|
1373
|
-
// The repository budget was sized against the baseline window; the routed window is what
|
|
1374
|
-
// this attempt actually has, and retrieval must not fill what no longer fits.
|
|
1375
1209
|
if (depth === 0 && codeLedger && codeIntel)
|
|
1376
1210
|
repoBudget = executionLimits.maxContextChars - committedChars;
|
|
1377
1211
|
await emit('agent.model.changed', { provider, model, ...(routedWindow === undefined ? {} : { contextWindow: routedWindow }), tier: decision.tier });
|
|
@@ -1384,9 +1218,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1384
1218
|
}
|
|
1385
1219
|
}
|
|
1386
1220
|
}
|
|
1387
|
-
// Only a tier whose resolved target served this attempt counts as routed: a decision without
|
|
1388
|
-
// a target (the tier is not configured) or one that could not resolve leaves the attempt on
|
|
1389
|
-
// what it had, and an escalation can only climb from a tier that actually ran.
|
|
1390
1221
|
if (served)
|
|
1391
1222
|
routedTier = decision.tier;
|
|
1392
1223
|
if (decision.reason === 'escalated' && applied)
|
|
@@ -1398,15 +1229,11 @@ export async function executeAgentNode(node, options) {
|
|
|
1398
1229
|
}
|
|
1399
1230
|
await emitEfficiency('efficiency.routing.decided', { tier: decision.tier, reason: unresolved ? 'unconfigured' : decision.reason, evidence: decision.evidence, applied, served, attempt });
|
|
1400
1231
|
}
|
|
1401
|
-
// The transcript this attempt will inherit, if any: the engine reuses a predecessor's
|
|
1402
|
-
// conversation only on the same provider and model (see its `previousConversation` guard).
|
|
1403
1232
|
const inheritedConversation = depth === 0 && configured.contextPolicy?.conversation !== 'isolate' && configured.contextPolicy?.skillInheritance !== 'none'
|
|
1404
1233
|
&& options.previousConversation?.provider === provider && options.previousConversation.model === model ? options.previousConversation : undefined;
|
|
1405
1234
|
const historicalToolNames = [...new Set((inheritedConversation?.messages ?? []).flatMap(message => (message.toolCalls ?? []).map(call => call.name)))];
|
|
1406
|
-
/** The skill catalog entry list, ordered and bounded under catalog selection, whole or absent otherwise. */
|
|
1407
1235
|
const skillCatalogText = (budget) => {
|
|
1408
1236
|
if (!efficiency.catalogSelection) {
|
|
1409
|
-
// The shipped all-or-nothing catalog; the callers' own budget checks decide as before.
|
|
1410
1237
|
const all = JSON.stringify(skills.map(({ id, description, unavailable }) => ({ id, description, ...(unavailable ? { unavailable } : {}) })));
|
|
1411
1238
|
return JSON.stringify(all).length <= budget ? all : undefined;
|
|
1412
1239
|
}
|
|
@@ -1417,8 +1244,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1417
1244
|
if (activeRouting?.decisions) {
|
|
1418
1245
|
const decisions = activeRouting.decisions;
|
|
1419
1246
|
recoverTools = [...tools, ...skillTools];
|
|
1420
|
-
// Facts style keeps every permitted schema: a wrongly omitted tool costs a restore_tools turn,
|
|
1421
|
-
// more than the schemas it would save over a whole run.
|
|
1422
1247
|
attemptTools = options.decisionManager?.toolTrimmingEnabled === false ? [...recoverTools] : routeToolFamilies(recoverTools, decisions);
|
|
1423
1248
|
if (inheritedSkills.length) {
|
|
1424
1249
|
const loader = skillTools.find(tool => tool.name === 'Skill');
|
|
@@ -1426,8 +1251,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1426
1251
|
attemptTools.push(loader);
|
|
1427
1252
|
}
|
|
1428
1253
|
if (efficiency.catalogSelection) {
|
|
1429
|
-
// A tool the inherited transcript already called keeps its schema: providers that validate
|
|
1430
|
-
// historical tool calls against the catalog would otherwise reject the request.
|
|
1431
1254
|
for (const name of historicalToolNames) {
|
|
1432
1255
|
const historical = recoverTools.find(tool => tool.name === name);
|
|
1433
1256
|
if (historical && !attemptTools.some(tool => tool.name === name))
|
|
@@ -1454,8 +1277,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1454
1277
|
attemptPrompt += `\n\nSome already-permitted tool schemas were omitted to reduce context: ${JSON.stringify(omitted.map(tool => tool.name))}. If task evidence requires one, call restore_tools with its name in the names array, then call the restored tool normally. Restoration never grants new permissions or bypasses approvals.`;
|
|
1455
1278
|
const skillBudget = skillContextBudget();
|
|
1456
1279
|
let skillBlock = '';
|
|
1457
|
-
// Keep the routed identifier ahead of the optional catalog: a large
|
|
1458
|
-
// catalog must not erase a confident selection. Bodies stay tool-loaded.
|
|
1459
1280
|
const selectedSkill = options.decisionManager?.skillRoutingEnabled
|
|
1460
1281
|
? skills.find(skill => !skill.unavailable && skill.id === DecisionPolicy.choice(decisions, 'skill_role')) : undefined;
|
|
1461
1282
|
if (selectedSkill && attemptTools.some(tool => tool.name === 'Skill')) {
|
|
@@ -1485,7 +1306,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1485
1306
|
}
|
|
1486
1307
|
}
|
|
1487
1308
|
else if (skillTools.length) {
|
|
1488
|
-
// Decision failure or uncertainty must leave the bounded catalog accessible.
|
|
1489
1309
|
attemptTools = [...tools, ...skillTools];
|
|
1490
1310
|
const catalog = skillCatalogText(skillContextBudget());
|
|
1491
1311
|
if (catalog !== undefined) {
|
|
@@ -1501,18 +1321,11 @@ export async function executeAgentNode(node, options) {
|
|
|
1501
1321
|
}
|
|
1502
1322
|
}
|
|
1503
1323
|
}
|
|
1504
|
-
// Plan-mode guidance is mandatory even without Jev decisions (disabled, signed out,
|
|
1505
|
-
// or no routing result). The tool is always available, but does not announce the mode.
|
|
1506
1324
|
if (depth === 0 && permissionMode(bounded) === 'plan')
|
|
1507
1325
|
attemptPrompt += `\n\n${PLAN_MODE_INSTRUCTIONS}`;
|
|
1508
1326
|
if (efficiency.catalogSelection && depth === 0) {
|
|
1509
|
-
// Deterministic, task-appropriate catalog from the permitted tools. Everything omitted stays
|
|
1510
|
-
// restorable through restore_tools under the same permission checks; nothing is added.
|
|
1511
1327
|
const selection = selectToolCatalog({ tools: attemptTools, task: effectiveTask, facts, explicitTools: configured.tools, historicalToolNames,
|
|
1512
1328
|
codeGraphAvailable: !!codeIntel?.active, memoryAvailable: !!options.memory?.activeFor(options.runId) });
|
|
1513
|
-
// Omission is applied only when it saves more than it costs: the omitted names are listed
|
|
1514
|
-
// in the prompt and `restore_tools` joins the catalog (about 420 serialized characters), so
|
|
1515
|
-
// dropping one small schema would make the request larger, not smaller.
|
|
1516
1329
|
const note = `\n\nSome already-permitted tool schemas were omitted for this task: ${JSON.stringify(selection.omitted.map(tool => tool.name))}. If task evidence requires one, call restore_tools with its name in the names array, then call the restored tool normally. Restoration never grants new permissions or bypasses approvals.`;
|
|
1517
1330
|
const saved = selection.schemaCharsBefore - selection.schemaCharsAfter;
|
|
1518
1331
|
const applied = selection.omitted.length > 0 && saved > note.length + RESTORE_TOOL_SCHEMA_CHARS;
|
|
@@ -1526,7 +1339,14 @@ export async function executeAgentNode(node, options) {
|
|
|
1526
1339
|
}
|
|
1527
1340
|
await emitEfficiency('efficiency.catalog.selected', { omitted: applied ? selection.omitted.length : 0, candidates: selection.omitted.length, schemaCharsBefore: selection.schemaCharsBefore, schemaCharsAfter: applied ? selection.schemaCharsAfter : selection.schemaCharsBefore, reasons: applied ? Object.values(selection.reasons).sort() : [], ...(selection.omitted.length && !applied ? { skipped: 'no_benefit' } : {}) });
|
|
1528
1341
|
}
|
|
1529
|
-
if (graphFirstSearch) {
|
|
1342
|
+
if (graphFirstSearch && headlessRun) {
|
|
1343
|
+
const repoExplore = tools.find(tool => tool.name === 'repo_explore');
|
|
1344
|
+
if (repoExplore && !attemptTools.some(tool => tool.name === 'repo_explore'))
|
|
1345
|
+
attemptTools.push(repoExplore);
|
|
1346
|
+
if (attemptTools.some(tool => tool.name === 'repo_explore'))
|
|
1347
|
+
attemptPrompt += '\n\nRepository search: repo_explore (CodeGraph) answers questions about structure, callers and data flow and returns source. Grep finds exact text. Both are available; use whichever fits the question.';
|
|
1348
|
+
}
|
|
1349
|
+
else if (graphFirstSearch) {
|
|
1530
1350
|
const fallbackSearch = attemptTools.filter(tool => canonicalToolName(tool.name) === 'Grep');
|
|
1531
1351
|
if (fallbackSearch.length) {
|
|
1532
1352
|
const beforeGraphFirst = [...attemptTools];
|
|
@@ -1543,29 +1363,21 @@ export async function executeAgentNode(node, options) {
|
|
|
1543
1363
|
}
|
|
1544
1364
|
if (codeLedger && codeIntel) {
|
|
1545
1365
|
const schemaSize = (catalog) => JSON.stringify(catalog.map(({ name, description, parameters }) => ({ name, description, parameters }))).length;
|
|
1546
|
-
// Trimmed schemas give room back to the request only; prompt growth is charged to both.
|
|
1547
1366
|
repoBudget += schemaSize(tools) - schemaSize(attemptTools);
|
|
1548
1367
|
spendRepoRoom(attemptPrompt.length - initialPromptChars);
|
|
1549
1368
|
}
|
|
1550
1369
|
if (activeRouting?.memory && depth === 0 && configured.agentRole !== 'orchestrator' && options.memory?.activeFor(options.runId) && options.memory.automaticRetrieval) {
|
|
1551
|
-
// Baseline retrieval used to precede node clocks. Keep fallback retrieval
|
|
1552
|
-
// exempt from those clocks, while retaining run deadlines and cancellation.
|
|
1553
1370
|
const resume = !pendingMemoryApplication ? suspendMemoryBudget?.() : undefined;
|
|
1554
1371
|
try {
|
|
1555
1372
|
context.signal.throwIfAborted();
|
|
1556
1373
|
const memory = await retryReadOnly(context, signal => options.memory.retrieve({ task: options.decisionPreflight?.task ?? effectiveTask, nodeId: configured.id, runId: options.runId, signal }));
|
|
1557
1374
|
let memoryBlock = memory.block;
|
|
1558
1375
|
if (efficiency.contextSelection && memoryBlock) {
|
|
1559
|
-
// Memory entries are untrusted evidence ranked by what they share with the task; the
|
|
1560
|
-
// omitted ones are named so memory_search can fetch them. Nothing is reworded.
|
|
1561
1376
|
const items = [...memory.context.current, ...(memory.context.historical ?? [])];
|
|
1562
1377
|
const selection = selectContext(items.map(item => ({ id: item.id, kind: 'memory', content: `${item.title}\n${item.content}`, item })), { task: effectiveTask, maxChars: Number.MAX_SAFE_INTEGER });
|
|
1563
|
-
// Selection decides relevance only; the character budget stays with the block builder, which
|
|
1564
|
-
// clips an oversized entry into a bounded excerpt the way the unselected block already does.
|
|
1565
1378
|
if (selection.omitted.length) {
|
|
1566
1379
|
const selected = new Set(selection.selected.map(candidate => candidate.item));
|
|
1567
1380
|
const rebuilt = buildMemoryBlock({ current: memory.context.current.filter(item => selected.has(item)), historical: (memory.context.historical ?? []).filter(item => selected.has(item)) }, memoryBlock.length);
|
|
1568
|
-
// The note survives even when nothing was kept: what was retrieved and set aside stays recoverable.
|
|
1569
1381
|
memoryBlock = rebuilt ? `${rebuilt}\n${omittedContextNote(selection.omitted, 'memory_search')}` : omittedContextNote(selection.omitted, 'memory_search');
|
|
1570
1382
|
}
|
|
1571
1383
|
await emitEfficiency('efficiency.context.selected', { source: 'memory', candidates: items.length, selected: selection.selected.length, omitted: selection.omitted.length,
|
|
@@ -1594,9 +1406,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1594
1406
|
}
|
|
1595
1407
|
if (depth === 0 && codeIntel && codeLedger) {
|
|
1596
1408
|
let repoSelection;
|
|
1597
|
-
// Content-level selection among the files the graph returned: identifier overlap with the
|
|
1598
|
-
// task, with every kept file's dependencies kept too. Only structured results (per-file
|
|
1599
|
-
// content) are selected; unstructured provider text is injected as before.
|
|
1600
1409
|
const selectRepository = efficiency.contextSelection ? (found) => {
|
|
1601
1410
|
if (found.files.length < 2 || found.files.some(file => file.content === undefined))
|
|
1602
1411
|
return found;
|
|
@@ -1619,18 +1428,18 @@ export async function executeAgentNode(node, options) {
|
|
|
1619
1428
|
}
|
|
1620
1429
|
}
|
|
1621
1430
|
if (graphFirstSearch && !attemptRepoBlock) {
|
|
1622
|
-
// Automatic graph lookup either could not fit or did not provide
|
|
1623
|
-
// usable context. Enable textual fallback in this same coding-model
|
|
1624
|
-
// turn instead of spending another turn discovering that fact.
|
|
1625
1431
|
codeLedger.markExhausted();
|
|
1626
1432
|
const catalog = recoverTools ?? tools;
|
|
1627
1433
|
for (const fallback of catalog.filter(tool => canonicalToolName(tool.name) === 'Grep')) {
|
|
1628
1434
|
if (!attemptTools.some(tool => tool.name === fallback.name))
|
|
1629
1435
|
attemptTools.push(fallback);
|
|
1630
1436
|
}
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1437
|
+
const stillIndexing = repoRoom() >= 512 && (await codeIntel.getStatus().catch(() => undefined))?.state === 'indexing';
|
|
1438
|
+
attemptPrompt += stillIndexing
|
|
1439
|
+
? '\n\nCodeGraph is still indexing this repository, so no repository context was preloaded. Grep is available now. repo_explore usually becomes ready within seconds; use it once it answers.'
|
|
1440
|
+
: repoRoom() >= 512
|
|
1441
|
+
? '\n\nCodeGraph did not return usable context for this task, so canonical Grep fallback is enabled for this invocation.'
|
|
1442
|
+
: '\n\nThe node context budget has no room for CodeGraph source injection, so canonical Grep fallback is enabled for this invocation.';
|
|
1634
1443
|
}
|
|
1635
1444
|
}
|
|
1636
1445
|
if (pendingGraphApplication) {
|
|
@@ -1640,17 +1449,21 @@ export async function executeAgentNode(node, options) {
|
|
|
1640
1449
|
} };
|
|
1641
1450
|
void publish(event);
|
|
1642
1451
|
}
|
|
1643
|
-
// Finalization resumes the same conversation; a provider retry still starts
|
|
1644
|
-
// fresh and must gather its own research evidence.
|
|
1645
1452
|
observedResearch = Boolean(attemptRepoBlock) || (depth === 0 && attempt === 1 && !!retainedIntake?.observedResearch);
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
// the same attempt see only what the engine newly queued. Replaying keeps the list intact, so
|
|
1649
|
-
// a third attempt still sees what the first one read and the second one replayed.
|
|
1453
|
+
attemptTools = applyToolProfile(attemptTools, options.toolProfile);
|
|
1454
|
+
const engineRecoverTools = applyToolProfile([...(recoverTools ?? []), ...compatibilityRecoverTools.filter(tool => !(recoverTools ?? []).some(current => current.name === tool.name))], options.toolProfile);
|
|
1650
1455
|
let replaying = attempt > 1 && consumedSteers.length > 0;
|
|
1456
|
+
// A subagent reads only what is addressed to it: what its parent sent with message_subagent, and
|
|
1457
|
+
// what the user sent to it by name. Messages to the parent never reach it.
|
|
1458
|
+
const subagentSteering = (id) => {
|
|
1459
|
+
const inbox = subagentInboxes.get(id);
|
|
1460
|
+
if (inbox === undefined)
|
|
1461
|
+
return undefined;
|
|
1462
|
+
return async (signal) => [...inbox.splice(0), ...(await options.getSubagentSteeringMessages?.(id, signal) ?? [])];
|
|
1463
|
+
};
|
|
1651
1464
|
const steeringSource = options.getSteeringMessages;
|
|
1652
1465
|
const steeringForAttempt = steeringSource === undefined ? undefined : async (signal) => {
|
|
1653
|
-
const fresh = await steeringSource(signal);
|
|
1466
|
+
const fresh = [...await steeringSource(signal), ...backgroundNotices.splice(0)];
|
|
1654
1467
|
const replay = replaying ? [...consumedSteers] : [];
|
|
1655
1468
|
replaying = false;
|
|
1656
1469
|
for (const message of fresh)
|
|
@@ -1658,7 +1471,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1658
1471
|
return [...replay, ...fresh];
|
|
1659
1472
|
};
|
|
1660
1473
|
result = await createAgentEngine().execute({ ...options, instructions: nodeInstructions || undefined, todoStore, context, provider, model,
|
|
1661
|
-
// Graph Manager's chat edits graphs on the user's behalf; a task plan is noise in its conversation.
|
|
1662
1474
|
todoList: options.todoList !== false && options.graph?.id !== GRAPH_MANAGER_GRAPH_ID,
|
|
1663
1475
|
efficiency: configured.tools && options.efficiency?.toolMenuRouting
|
|
1664
1476
|
? { ...options.efficiency, toolMenuRouting: { ...options.efficiency.toolMenuRouting, pinnedTools: [...new Set([...(options.efficiency.toolMenuRouting.pinnedTools ?? []), ...configured.tools.map(canonicalToolName)])] } }
|
|
@@ -1667,25 +1479,25 @@ export async function executeAgentNode(node, options) {
|
|
|
1667
1479
|
adapter: resolved.adapter, contextWindow: resolved.contextWindow, tools: attemptTools, recoverTools: engineRecoverTools, decisionTask,
|
|
1668
1480
|
telemetryIdentity: { providerType: resolved.providerType, baseUrl: resolved.baseUrl, role: subagentId ? 'subagent' : orchestrator ? 'orchestrator' : 'agent' }, decisionHints: activeRouting?.decisions, budget, artifactStore: store,
|
|
1669
1481
|
previousConversation: depth === 0 && configured.contextPolicy?.conversation !== 'isolate' && configured.contextPolicy?.skillInheritance !== 'none' && options.previousConversation?.provider === provider && options.previousConversation.model === model ? options.previousConversation : undefined,
|
|
1670
|
-
// The inner callback is returned rather than called and dropped: the durable write it
|
|
1671
|
-
// performs is awaited by the runtime, so the promise has to travel back up through here.
|
|
1672
1482
|
onConversationCheckpoint: depth === 0 && options.onConversationCheckpoint ? (messages, state, conversation) => options.onConversationCheckpoint(messages, { ...state, ...(orchestrator ? { orchestratorIntake: {
|
|
1673
1483
|
nodeId: node.id, clarified, publishedPlan, observedResearch,
|
|
1674
1484
|
confirmedClarifications: structuredClone(confirmedClarifications),
|
|
1675
1485
|
} } : {}) }, conversation) : undefined,
|
|
1676
1486
|
onTodosUpdated: orchestrator && depth === 0 ? () => { publishedPlan = true; options.onTodosUpdated?.(); } : options.onTodosUpdated,
|
|
1677
1487
|
subagentId, limits: executionLimits, contextCharCeiling, systemPrompt: attemptPrompt, nodeInstruction: configured.instruction,
|
|
1678
|
-
|
|
1679
|
-
// subagent owns a dispatched task, so letting it consume the steer would apply the
|
|
1680
|
-
// instruction to the wrong agent and lose it from the root conversation.
|
|
1681
|
-
getSteeringMessages: subagentId ? undefined : steeringForAttempt,
|
|
1682
|
-
// Attachments belong to the conversation the user submitted into: a dispatched
|
|
1683
|
-
// subagent's task is its own opening message, and the root's files and images would
|
|
1684
|
-
// silently answer questions the child never received.
|
|
1488
|
+
getSteeringMessages: subagentId ? subagentSteering(subagentId) : steeringForAttempt,
|
|
1685
1489
|
attachments: subagentId ? undefined : options.attachments,
|
|
1686
1490
|
canonicalTask: orchestrator && depth === 0 ? options.task : undefined,
|
|
1687
1491
|
...(finalAnswerOutcomes.length ? { finalAnswerOutcomes } : {}),
|
|
1492
|
+
goalCompletionVerification: options.graph && !goalCanEndRun ? undefined : options.goalCompletionVerification,
|
|
1493
|
+
sessionGoal: depth === 0 && !subagentId ? options.goalCompletionVerification?.goal : undefined,
|
|
1494
|
+
...(goalGraph && goalCanEndRun ? { goalRoute: (completion) => goalRoute(goalGraph, node, completion, {
|
|
1495
|
+
looping: options.modifierIteration !== undefined, copies: node.modifiers?.parallel?.mode === 'copies', ...(completionPolicy.mode === 'single' ? { defaultOutcome: completionPolicy.outcome } : {})
|
|
1496
|
+
}) } : {}),
|
|
1688
1497
|
completionGuard: orchestrator && depth === 0 ? completion => {
|
|
1498
|
+
const waiting = backgroundGuard();
|
|
1499
|
+
if (waiting)
|
|
1500
|
+
return waiting;
|
|
1689
1501
|
const missing = missingSkillError();
|
|
1690
1502
|
if (missing)
|
|
1691
1503
|
return missing;
|
|
@@ -1695,25 +1507,23 @@ export async function executeAgentNode(node, options) {
|
|
|
1695
1507
|
const output = completion.output;
|
|
1696
1508
|
if (!output || typeof output.taskInstruction !== 'string' || !output.taskInstruction.trim() || ['requirements', 'acceptanceCriteria', 'designConsiderations', 'codebaseFindings'].some(key => !Array.isArray(output[key]) || output[key].some(value => typeof value !== 'string')))
|
|
1697
1509
|
return 'Return requirements, acceptanceCriteria, designConsiderations and codebaseFindings as string arrays and a nonempty taskInstruction in the structured handoff.';
|
|
1698
|
-
|
|
1699
|
-
|
|
1700
|
-
if (completion.outcome === DELIVERED_OUTCOME) {
|
|
1510
|
+
if (routedDelegation || completion.outcome === DELIVERED_OUTCOME) {
|
|
1511
|
+
const finishing = routedDelegation ? 'completing' : 'completing as delivered';
|
|
1701
1512
|
if (active > 0)
|
|
1702
|
-
return
|
|
1513
|
+
return `Wait for every running subagent to finish before ${finishing}.`;
|
|
1703
1514
|
const records = [...changes.values()];
|
|
1704
1515
|
if (records.some(change => change.state === 'pending' || change.state === 'conflict'))
|
|
1705
|
-
return
|
|
1706
|
-
if (!records.some(change => change.state === 'landed'))
|
|
1516
|
+
return `Accept or discard every change before ${finishing}.`;
|
|
1517
|
+
if (!routedDelegation && !records.some(change => change.state === 'landed'))
|
|
1707
1518
|
return 'Land at least one accepted change before completing as delivered.';
|
|
1708
1519
|
}
|
|
1709
|
-
} : inheritedSkills.length || promptSkills.length ?
|
|
1520
|
+
} : depth === 0 && policy.enabled ? () => backgroundGuard() ?? (inheritedSkills.length || promptSkills.length ? missingSkillError() : undefined)
|
|
1521
|
+
: inheritedSkills.length || promptSkills.length ? () => missingSkillError() : undefined, completionPolicy, outputSchema: configured.outputSchema,
|
|
1710
1522
|
history: configured.contextPolicy?.history ? options.history : [],
|
|
1711
1523
|
task: attemptRepoBlock ? `${taskBase}\n\n${attemptRepoBlock}` : taskBase,
|
|
1712
1524
|
onUsage: (usage, origin) => {
|
|
1713
1525
|
options.onUsage?.(usage, origin);
|
|
1714
1526
|
},
|
|
1715
|
-
// Decision events from the runtime's own path (the post-tool check) reach the capture
|
|
1716
|
-
// here, once, instead of being counted by the runtime and again by this invocation.
|
|
1717
1527
|
onEvent: recordDecision });
|
|
1718
1528
|
if (result.telemetry) {
|
|
1719
1529
|
recordAttempt(result.telemetry, attempt > 1);
|
|
@@ -1722,16 +1532,12 @@ export async function executeAgentNode(node, options) {
|
|
|
1722
1532
|
}
|
|
1723
1533
|
previousAttemptReason = result.reason;
|
|
1724
1534
|
previousMutations = result.mutations;
|
|
1725
|
-
// Bounded upward escalation: a routed attempt that exhausted itself on a defined failure gets
|
|
1726
|
-
// one more attempt on the next tier, within the same node budget and never after a cancel.
|
|
1727
1535
|
const tiers = efficiency.adaptiveRouting.tiers ?? {};
|
|
1728
1536
|
const higherTier = routedTier === 'economy' ? tiers.balanced ?? tiers.premium : routedTier === 'balanced' ? tiers.premium : undefined;
|
|
1729
1537
|
const escalate = efficiency.adaptiveRouting.enabled && depth === 0 && !subagentId && routedTier !== undefined && higherTier !== undefined && !escalationFailed
|
|
1730
1538
|
&& escalations < efficiency.adaptiveRouting.maxEscalations && result.status === 'exhausted'
|
|
1731
1539
|
&& ['repeatedToolFailure', 'maxIterations'].includes(result.reason ?? '') && !context.signal.aborted
|
|
1732
1540
|
&& (options.budget === undefined || options.budget.maxToolCalls === undefined || options.budget.toolCalls < options.budget.maxToolCalls);
|
|
1733
|
-
// Every admitted escalation is pending, whether or not the loop had to grow for it: the next
|
|
1734
|
-
// attempt is routing's move, so a configured fallback does not take it instead.
|
|
1735
1541
|
if (escalate) {
|
|
1736
1542
|
escalationPending = true;
|
|
1737
1543
|
if (attempt === attempts)
|
|
@@ -1752,11 +1558,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1752
1558
|
return result;
|
|
1753
1559
|
};
|
|
1754
1560
|
try {
|
|
1755
|
-
// `userSignal` is pinned to the session signal here, before any budget-derived signal
|
|
1756
|
-
// replaces `signal`, so prompts driven by nested executors can never inherit a deadline.
|
|
1757
|
-
// `bounded` supplies both prompts already exempt from this node's clock.
|
|
1758
|
-
// A wake this node arms is its own reminder about its own work, so the wake names the node and the
|
|
1759
|
-
// attempt: delivery returns it to this node rather than to the graph's entry.
|
|
1760
1561
|
const wakeOrigin = options.runId === undefined ? undefined : { runId: options.runId, nodeId: node.id };
|
|
1761
1562
|
const result = await run(node, { ...bounded, approve, ...(wakeOrigin === undefined ? {} : { wakeOrigin }), ...(delegationActive ? { delegationRoots } : {}) }, 0, orchestrator ? { ...options.mappedInputs, originalTask: options.task } : options.mappedInputs ?? {}, options.task);
|
|
1762
1563
|
if (orchestrator && !clarified && result.status === 'exhausted' && result.reason === MISSING_CONFIRMATION) {
|
|
@@ -1764,12 +1565,7 @@ export async function executeAgentNode(node, options) {
|
|
|
1764
1565
|
result.reason = 'Needs clarification: use ask_user to confirm the user design considerations before implementation.';
|
|
1765
1566
|
delete result.completion;
|
|
1766
1567
|
}
|
|
1767
|
-
|
|
1768
|
-
// the conflicts it last hit. The guard already proved each one was decided, so the record is
|
|
1769
|
-
// written once, after acceptance. The accepted edits are already in the working folder, so a
|
|
1770
|
-
// store that cannot take the record (ENOSPC, EACCES) must not turn the delivered run into a
|
|
1771
|
-
// failure: the completion is kept and its summary says the record is missing.
|
|
1772
|
-
if (delegationActive && result.status === 'succeeded' && result.completion?.outcome === DELIVERED_OUTCOME) {
|
|
1568
|
+
if (delegationActive && result.status === 'succeeded' && result.completion && (routedDelegation ? [...changes.values()].some(change => change.state === 'landed') : result.completion.outcome === DELIVERED_OUTCOME)) {
|
|
1773
1569
|
const content = JSON.stringify({ changes: [...changes.values()].map(change => ({
|
|
1774
1570
|
id: change.id, subagentId: change.subagentId, role: change.role, provider: change.provider, model: change.model, state: change.state,
|
|
1775
1571
|
files: change.files, conflicts: change.conflicts ?? [], ...(change.diffArtifact ? { diffArtifact: change.diffArtifact } : {}),
|
|
@@ -1791,8 +1587,6 @@ export async function executeAgentNode(node, options) {
|
|
|
1791
1587
|
delete result.completion;
|
|
1792
1588
|
}
|
|
1793
1589
|
if ((result.status === 'succeeded' || result.status === 'needs_clarification' || options.context.signal.aborted) && checkpoint) {
|
|
1794
|
-
// Capture the outer invocation allowance, including setup and delegated work,
|
|
1795
|
-
// not just the inner executor's clock and direct tool calls.
|
|
1796
1590
|
const narrow = (inner, outer) => inner === undefined ? outer : outer === undefined ? inner : Math.min(inner, outer);
|
|
1797
1591
|
await publishCheckpoint?.(checkpoint.messages, { ...checkpoint.state,
|
|
1798
1592
|
remainingWallTimeMs: narrow(checkpoint.state.remainingWallTimeMs, nodeBudget.remainingMs()),
|
|
@@ -1802,9 +1596,8 @@ export async function executeAgentNode(node, options) {
|
|
|
1802
1596
|
return result;
|
|
1803
1597
|
}
|
|
1804
1598
|
finally {
|
|
1805
|
-
// Delegated worktrees never outlive the node, whatever ended it; the release runs before the
|
|
1806
|
-
// node's controller is aborted so its announcements still reach the event sink.
|
|
1807
1599
|
try {
|
|
1600
|
+
await reapBackground();
|
|
1808
1601
|
if (delegationActive)
|
|
1809
1602
|
await releaseChanges();
|
|
1810
1603
|
}
|