@andorra-labs/code 0.1.11 → 0.1.13
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/README.md +8 -2
- package/THIRD_PARTY_NOTICES.md +15 -0
- package/dist/src/account-presentation.d.ts +1 -37
- package/dist/src/account-presentation.js +2 -42
- 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 +59 -414
- 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 +14 -153
- 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/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 +0 -28
- package/dist/src/app-server/protocol.d.ts +19 -244
- 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 +33 -918
- package/dist/src/app-server.js +608 -2984
- 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 +0 -93
- package/dist/src/auth/AuthManager.js +3 -165
- 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 +0 -16
- package/dist/src/auth/deployment.js +0 -16
- package/dist/src/auth/index.d.ts +0 -11
- package/dist/src/auth/index.js +0 -11
- package/dist/src/auth/lock.d.ts +0 -1
- package/dist/src/auth/lock.js +0 -1
- package/dist/src/auth/store.d.ts +7 -108
- package/dist/src/auth/store.js +21 -129
- 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 +10 -25
- package/dist/src/browser-panel-tool.js +64 -60
- package/dist/src/browser-runner.d.ts +0 -1
- package/dist/src/browser-runner.js +7 -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 +0 -12
- package/dist/src/browser-stealth.js +0 -36
- 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 +11 -93
- package/dist/src/browser-view.d.ts +52 -290
- package/dist/src/browser-view.js +354 -567
- 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 +166 -61
- 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 +3 -56
- package/dist/src/cli.js +193 -702
- package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +4 -59
- package/dist/src/code-intelligence/CodeIntelligenceManager.js +27 -100
- 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 +1 -26
- package/dist/src/codex-rpc.d.ts +0 -10
- package/dist/src/codex-rpc.js +0 -12
- package/dist/src/coding-tools.d.ts +6 -27
- package/dist/src/coding-tools.js +193 -205
- 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 +24 -0
- package/dist/src/command-screens.js +132 -100
- package/dist/src/commands.d.ts +6 -63
- package/dist/src/commands.js +20 -100
- package/dist/src/completion-gates.d.ts +0 -47
- package/dist/src/completion-gates.js +0 -14
- package/dist/src/completion.d.ts +2 -58
- package/dist/src/completion.js +90 -186
- package/dist/src/config.d.ts +12 -116
- package/dist/src/config.js +41 -171
- 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 +0 -2
- package/dist/src/dashboard-view.js +0 -35
- 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 +1 -5
- 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 +0 -1
- package/dist/src/decision/toolMenu.d.ts +0 -3
- package/dist/src/decision/toolMenu.js +0 -4
- package/dist/src/decision/types.d.ts +0 -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 +15 -124
- package/dist/src/diff-preview.d.ts +1 -1
- package/dist/src/diff-preview.js +4 -12
- 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 +13 -0
- package/dist/src/engine-streams.js +16 -0
- package/dist/src/extensions.d.ts +3 -2
- package/dist/src/extensions.js +76 -37
- 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 +1 -0
- package/dist/src/file-read-key.js +5 -0
- 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 +1 -3
- package/dist/src/graph-health.d.ts +7 -49
- package/dist/src/graph-health.js +35 -46
- package/dist/src/graph-manager-chat.d.ts +27 -128
- package/dist/src/graph-manager-chat.js +36 -166
- 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 +47 -387
- package/dist/src/graph-selection.d.ts +0 -14
- package/dist/src/graph-selection.js +0 -14
- package/dist/src/graph-server.d.ts +3 -11
- package/dist/src/graph-server.js +70 -111
- 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 +229 -498
- package/dist/src/graph-ui/compat.js +0 -7
- package/dist/src/graph-ui/controls.css +47 -43
- 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 +2 -7
- package/dist/src/graph-ui/index.html +2 -2
- 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 +110 -49
- package/dist/src/graph-ui/manager.css +2 -20
- package/dist/src/graph-ui/manager.js +251 -166
- package/dist/src/graph-ui/model-picker.js +250 -0
- package/dist/src/graph-ui/provider-glyphs/alibaba-cloud.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/anthropic.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/aws-bedrock.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/claude.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/deepseek.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/fireworks.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/kimi.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/minimax.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/openai.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/opencode.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/openrouter.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/xai.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/xiaomi-mimo.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/zai.png +0 -0
- 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 +11 -134
- package/dist/src/graph-ui/theme.js +1 -26
- package/dist/src/graph-ui/tokens.css +15 -114
- package/dist/src/graphs.d.ts +7 -156
- package/dist/src/graphs.js +72 -273
- 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 +8 -46
- 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 +21 -82
- package/dist/src/mcp.js +228 -237
- package/dist/src/membership-errors.d.ts +0 -14
- package/dist/src/membership-errors.js +0 -13
- package/dist/src/membership.d.ts +2 -60
- package/dist/src/membership.js +0 -85
- 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 +42 -0
- package/dist/src/memory/ProjectMemory.js +285 -0
- package/dist/src/memory/ToolFailureLessons.d.ts +0 -3
- package/dist/src/memory/ToolFailureLessons.js +0 -6
- package/dist/src/memory/index.d.ts +1 -0
- package/dist/src/memory/index.js +1 -0
- 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-health-cache.d.ts +0 -38
- package/dist/src/model-health-cache.js +1 -49
- package/dist/src/model-metadata.d.ts +0 -18
- package/dist/src/model-metadata.js +2 -42
- 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 +6 -22
- package/dist/src/package-name.d.ts +1 -0
- package/dist/src/package-name.js +1 -0
- package/dist/src/paged-transcript.d.ts +0 -11
- package/dist/src/paged-transcript.js +2 -20
- package/dist/src/palette.d.ts +0 -63
- package/dist/src/palette.js +0 -63
- package/dist/src/permissions.d.ts +0 -15
- package/dist/src/permissions.js +0 -17
- 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 +0 -39
- package/dist/src/provider-engine.d.ts +0 -21
- package/dist/src/provider-engine.js +3 -98
- 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 +0 -2
- package/dist/src/provider-settings.js +0 -32
- package/dist/src/providers.d.ts +0 -217
- package/dist/src/providers.js +0 -315
- 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 +2 -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 +106 -418
- 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 +1 -19
- package/dist/src/remote/cert.js +2 -51
- package/dist/src/remote/client.d.ts +0 -70
- package/dist/src/remote/client.js +2 -117
- 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 +17 -335
- 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 +2 -0
- package/dist/src/remote/pem.js +7 -0
- 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 +0 -7
- package/dist/src/run-control.js +0 -7
- 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 +44 -678
- package/dist/src/run-temp.d.ts +12 -0
- package/dist/src/run-temp.js +50 -0
- package/dist/src/runtime.d.ts +11 -227
- package/dist/src/runtime.js +0 -127
- 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 +2 -120
- 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 +43 -0
- package/dist/src/sign-in-detection.js +154 -0
- package/dist/src/sign-in-offer.d.ts +17 -0
- package/dist/src/sign-in-offer.js +103 -0
- 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/SKILL.md +22 -4
- package/dist/src/skills/bundled/provenance.json +2 -2
- 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 +1 -8
- package/dist/src/skills/runtime-skills.js +8 -32
- package/dist/src/stall-recovery.d.ts +0 -25
- package/dist/src/stall-recovery.js +0 -38
- package/dist/src/stray-files.d.ts +5 -0
- package/dist/src/stray-files.js +65 -0
- package/dist/src/structured-step.d.ts +0 -22
- package/dist/src/structured-step.js +0 -22
- package/dist/src/subagent-run.d.ts +0 -163
- package/dist/src/subagent-run.js +10 -374
- 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 +1 -82
- 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 +15 -524
- package/dist/src/terminal-ui.js +80 -876
- 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 +1 -8
- 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 +1 -2
- package/dist/src/tool-schema-compatibility.js +2 -7
- 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 +1 -37
- package/dist/src/transcript.js +11 -61
- package/dist/src/types.d.ts +2 -167
- package/dist/src/untracked-file-removal.d.ts +3 -0
- package/dist/src/untracked-file-removal.js +105 -0
- package/dist/src/update-check.d.ts +0 -14
- package/dist/src/update-check.js +2 -16
- package/dist/src/update.d.ts +4 -29
- package/dist/src/update.js +20 -98
- 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 +4 -5
- package/dist/src/workspace-git-metadata.js +37 -9
- package/dist/src/workspace-instructions.d.ts +3 -15
- package/dist/src/workspace-instructions.js +7 -20
- package/package.json +2 -2
package/dist/src/cli.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import './process-warnings.js';
|
|
2
3
|
import { randomUUID } from 'node:crypto';
|
|
3
4
|
import { bootMark } from './boot-trace.js';
|
|
4
5
|
import { createSessionTrajectory } from './trajectory.js';
|
|
@@ -14,37 +15,33 @@ import { workspacePermissionKey, permissionLabel } from './permissions.js';
|
|
|
14
15
|
import { configDirectory, loadConfig, resolveCodeIntelConfig, resolveConfiguredLimits, saveConfig } from './config.js';
|
|
15
16
|
import { compactHistory, compactedContextEstimate, executeCommand, HELP } from './commands.js';
|
|
16
17
|
import { applyModelContextWindow, createAdapter, providerSecrets, recordProviderModel } from './providers.js';
|
|
17
|
-
import { createTools } from './tools.js';
|
|
18
18
|
import { disposeAllQaProcesses, disposeAllQaPtys, getQaPtyManager } from './qa/index.js';
|
|
19
19
|
import { disposePooledPowerShell } from './powershell-pool.js';
|
|
20
|
-
import { loadWorkspaceInstructions } from './workspace-instructions.js';
|
|
20
|
+
import { loadWorkspaceInstructions, systemPromptOverrideFor } from './workspace-instructions.js';
|
|
21
21
|
import { runGraph, stopReasonPhrase } from './runtime.js';
|
|
22
22
|
import { GraphDeletedError, validateGraph } from './graphs.js';
|
|
23
|
-
import { checkGraphModelHealth, formatGraphHealthFailure } from './graph-health.js';
|
|
23
|
+
import { checkGraphModelHealth, checkSessionModelHealth, formatGraphHealthFailure } from './graph-health.js';
|
|
24
|
+
import { ModelHealthCache } from './model-health-cache.js';
|
|
24
25
|
import { getMembership, loadAccessibleGraph, PaidMembershipRequiredError } from './membership.js';
|
|
25
26
|
import { configuredSurface, createRunHandle, drainTelemetry, graphShape, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
|
|
26
27
|
import { createRunTelemetry, recordModelUse } from './telemetry/capture.js';
|
|
27
28
|
import { pricingFor } from './model-tiers.js';
|
|
28
29
|
import { GraphProviderUnavailableError } from './graph-provider-portability.js';
|
|
29
30
|
import { MAX_SUBAGENT_TASK_CHARS, SubagentInvalidArgumentError, SubagentProviderNotSetError, SubagentRunInProgressError, SubagentRunner, SubagentSelectionError } from './subagent-run.js';
|
|
30
|
-
/** Shown when a saved per-account graph selection is denied account access at launch or refresh. */
|
|
31
31
|
const GRAPH_FALLBACK_NOTICE = 'The selected graph needs paid account access, which is currently unavailable. Starting with the local Default graph; once access is restored, switch back with /graph.';
|
|
32
32
|
const missingSavedGraph = (error) => error?.code === 'ENOENT';
|
|
33
|
-
/** A stale saved choice should not abort startup after a crash between graph removal and config reset. */
|
|
34
33
|
const graphFallbackReason = (error) => error instanceof FreeTierLimitError || error instanceof GraphDeletedError
|
|
35
34
|
? `${error.message} Starting with the local Default graph.`
|
|
36
35
|
: missingSavedGraph(error) ? 'The selected graph is no longer stored locally. Starting with the Default graph; use /graph to choose another.' : GRAPH_FALLBACK_NOTICE;
|
|
37
36
|
import { configuredGraphSelection, currentGraphSubject } from './graph-selection.js';
|
|
38
|
-
import { launchGraphEditor } from './graph-server.js';
|
|
39
37
|
import { createGraphEditorSession } from './graph-editor-session.js';
|
|
40
38
|
import { FreeTierLimitError } from './graph-quota.js';
|
|
41
|
-
import { updateInstallation } from './update.js';
|
|
42
39
|
import { availableUpdate, parseUpdateAnswer, recordUpdateChoice, updateCheckDisabled } from './update-check.js';
|
|
40
|
+
import { offerSignInImport } from './sign-in-offer.js';
|
|
43
41
|
import { RunControl } from './run-control.js';
|
|
44
42
|
import { TimerRegistry } from './timers.js';
|
|
45
43
|
import { TerminalUI } from './terminal-ui.js';
|
|
46
44
|
import { listInvocableSkills } from './skills/invocable-skills.js';
|
|
47
|
-
/** Give the `/` popup the skills a person can type. Best effort: a failed read leaves the popup on the built-in commands. */
|
|
48
45
|
function offerSkillCommands(terminal, config, directory) {
|
|
49
46
|
if (!terminal)
|
|
50
47
|
return;
|
|
@@ -55,13 +52,15 @@ import { attachmentLabel, attachmentReadRoots, attachmentReferenceBlock, pruneAt
|
|
|
55
52
|
import { describeTool, formatAnswer, formatEvent, formatRunResult } from './transcript.js';
|
|
56
53
|
import { staticToolTimestamp } from './tool-call-clock.js';
|
|
57
54
|
import { LocalToolMemory } from './memory/LocalToolMemory.js';
|
|
55
|
+
import { ProjectMemory } from './memory/ProjectMemory.js';
|
|
58
56
|
import { askClarification } from './clarification-ui.js';
|
|
59
57
|
import { refreshModelContext, resolveModelContext, withEvaluationReasoningEffort } from './model-metadata.js';
|
|
60
|
-
import { isScreenCommand, runCommandScreen } from './command-screens.js';
|
|
58
|
+
import { isScreenCommand, pickPermissionMode, runCommandScreen } from './command-screens.js';
|
|
61
59
|
import { CodeIntelligenceManager } from './code-intelligence/CodeIntelligenceManager.js';
|
|
62
60
|
import { ToolActivity, activityForRuntimeEvent } from './tool-activity.js';
|
|
63
|
-
import { extensionSnapshot,
|
|
61
|
+
import { effectiveExtensionConfig, extensionSnapshot, resolveSkillInvocations } from './extensions.js';
|
|
64
62
|
import { isBuiltinSlashCommand } from './skill-commands.js';
|
|
63
|
+
import { metSessionGoal, newSessionGoal, parseGoalCommand } from './session-goal.js';
|
|
65
64
|
import { copySessionSkill, removeSessionSkill, sessionSkillCommand, skillForRun } from './session-skills.js';
|
|
66
65
|
import { executeAuthCommand } from './auth-commands.js';
|
|
67
66
|
import { setAuthSignOutReporter } from './auth/index.js';
|
|
@@ -73,16 +72,27 @@ import { TodoStore } from './todos.js';
|
|
|
73
72
|
import { canExtendLineage, carryRailOwnedFields, displayHistory, lineagePoints, lineageThrough, SessionStore, sessionName, projectIdentity } from './sessions.js';
|
|
74
73
|
import { SessionTitle } from './session-title.js';
|
|
75
74
|
import { createBrowserBridge } from './browser-bridge.js';
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
75
|
+
const loadTools = () => import('./tools.js');
|
|
76
|
+
import { enablePrivateRunTemp, removePrivateRunTemp } from './run-temp.js';
|
|
77
|
+
import { TOOL_PROFILES, isToolProfile } from './tool-profile.js';
|
|
78
|
+
const WARM_IDLE_MS = 400;
|
|
79
|
+
async function warmRunModules(lastInputAt, stop) {
|
|
80
|
+
for (const load of [loadTools, () => import('./engine-streams.js').then(module => module.loadEngineStreams()), () => import('typebox/compile')]) {
|
|
81
|
+
for (;;) {
|
|
82
|
+
if (stop())
|
|
83
|
+
return;
|
|
84
|
+
const quiet = Date.now() - lastInputAt();
|
|
85
|
+
if (quiet >= WARM_IDLE_MS)
|
|
86
|
+
break;
|
|
87
|
+
await new Promise(resolve => setTimeout(resolve, WARM_IDLE_MS - quiet).unref());
|
|
88
|
+
}
|
|
89
|
+
await load().catch(() => { });
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const updateInstallation = async (...args) => (await import('./update.js')).updateInstallation(...args);
|
|
93
|
+
const launchGraphEditor = async (noOpen) => (await import('./graph-server.js')).launchGraphEditor(noOpen);
|
|
94
|
+
const startBrowserServer = async () => (await import('./browser-server.js')).startBrowserServer();
|
|
95
|
+
const openBrowserUrl = (url) => { void import('./browser-server.js').then(module => module.openBrowserUrl(url)); };
|
|
86
96
|
export async function cliVersion() {
|
|
87
97
|
try {
|
|
88
98
|
const manifest = JSON.parse(await readFile(fileURLToPath(new URL('../../package.json', import.meta.url)), 'utf8'));
|
|
@@ -92,12 +102,6 @@ export async function cliVersion() {
|
|
|
92
102
|
return 'unknown';
|
|
93
103
|
}
|
|
94
104
|
}
|
|
95
|
-
/**
|
|
96
|
-
* Asks once at interactive startup whether to install a newer npm release: Yes installs it and
|
|
97
|
-
* ends this launch (the running process is still the old version), No asks again next launch,
|
|
98
|
-
* Skip stays quiet until a newer release than this one appears. Never fails startup.
|
|
99
|
-
* Returns true when the update was installed and the caller should exit.
|
|
100
|
-
*/
|
|
101
105
|
async function offerStartupUpdate() {
|
|
102
106
|
try {
|
|
103
107
|
if (await updateCheckDisabled())
|
|
@@ -137,7 +141,19 @@ async function offerStartupUpdate() {
|
|
|
137
141
|
return false;
|
|
138
142
|
}
|
|
139
143
|
}
|
|
140
|
-
|
|
144
|
+
async function offerStartupSignIns() {
|
|
145
|
+
let lines;
|
|
146
|
+
try {
|
|
147
|
+
await offerSignInImport({
|
|
148
|
+
write: text => { process.stdout.write(text); },
|
|
149
|
+
ask: question => (lines ??= createInterface({ input: process.stdin, output: process.stdout, terminal: true })).question(question),
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
catch { }
|
|
153
|
+
finally {
|
|
154
|
+
lines?.close();
|
|
155
|
+
}
|
|
156
|
+
}
|
|
141
157
|
export async function gitBranch(workspace) {
|
|
142
158
|
try {
|
|
143
159
|
const root = await realpath(workspace);
|
|
@@ -146,7 +162,6 @@ export async function gitBranch(workspace) {
|
|
|
146
162
|
return suffix === '' || (!isAbsolute(suffix) && suffix !== '..' && !suffix.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`));
|
|
147
163
|
};
|
|
148
164
|
const metadataPath = async (target) => {
|
|
149
|
-
// Check lexical paths before resolution, then reject symlink/junction escapes.
|
|
150
165
|
if (!contained(resolve(target)))
|
|
151
166
|
throw new Error('Git metadata is outside the workspace');
|
|
152
167
|
const canonical = await realpath(target);
|
|
@@ -193,55 +208,22 @@ export async function gitBranch(workspace) {
|
|
|
193
208
|
export function safeTerminal(text) {
|
|
194
209
|
return stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '');
|
|
195
210
|
}
|
|
196
|
-
/** Short follow-up directions that mean "continue the unfinished work" rather than start a new task. */
|
|
197
211
|
export function isContinuationPrompt(text) {
|
|
198
212
|
const normalized = text.trim().replace(/[.!?]+$/, '').trim();
|
|
199
213
|
return normalized.length <= 160 && /^(?:continue|resume|retry|try again|keep going|keep working)(?:\b.*)?$/i.test(normalized);
|
|
200
214
|
}
|
|
201
|
-
/** Retain an unfinished run's plan only when the next prompt explicitly continues that work. */
|
|
202
215
|
export function continuedTodos(task, lastRun) {
|
|
203
216
|
return lastRun && lastRun.status !== 'succeeded' && isContinuationPrompt(task)
|
|
204
217
|
? (lastRun.todos ?? []).map(todo => ({ ...todo }))
|
|
205
218
|
: [];
|
|
206
219
|
}
|
|
207
|
-
// Re-exported for the callers that already imported it from the CLI; the definition moved beside
|
|
208
|
-
// the provider configuration it reads so the app-server can register secrets without the CLI.
|
|
209
220
|
export { providerSecrets };
|
|
210
|
-
/**
|
|
211
|
-
* Append one runtime event to the record of the run it belongs to.
|
|
212
|
-
*
|
|
213
|
-
* Not every event belongs to a run. The memory health check emitted while the memory manager is
|
|
214
|
-
* constructed, and code-intelligence state before the first run starts, carry no run identity at
|
|
215
|
-
* all: they describe the session. They are skipped, because a per-run file cannot name them --
|
|
216
|
-
* writing one anyway is what used to leave a `runs/undefined.jsonl` behind in the installation.
|
|
217
|
-
* An identity that is present but not well formed is a bug in whatever produced it rather than an
|
|
218
|
-
* absent one, so `runRecordPath` still throws for it.
|
|
219
|
-
* @param directory - the installation directory holding `runs/`.
|
|
220
|
-
* @param event - the runtime event to persist.
|
|
221
|
-
*/
|
|
222
221
|
export async function appendRunEvent(directory, event) {
|
|
223
222
|
const runId = event.data.runId;
|
|
224
223
|
if (runId === undefined || runId === null)
|
|
225
224
|
return;
|
|
226
225
|
await appendFile(runRecordPath(directory, runId, 'jsonl'), JSON.stringify(event) + '\n', { mode: 0o600 });
|
|
227
226
|
}
|
|
228
|
-
/**
|
|
229
|
-
* Add the reasoning effort and context window of a root node's own resolution to its
|
|
230
|
-
* `agent.session.started` data, so the footer can describe the model that is answering.
|
|
231
|
-
*
|
|
232
|
-
* The executor reports the provider and model a node resolved but not the effort or window that
|
|
233
|
-
* came with them, and those differ per node: a node that overrides the model loses the provider's
|
|
234
|
-
* saved effort and window (`resolveModelContext`), so reusing the session's numbers would put
|
|
235
|
-
* values on the footer that belong to a model that is not running. Only a root node session is
|
|
236
|
-
* decorated -- a delegated child repeats its parent's node id, and a plain prompt run has no
|
|
237
|
-
* graph node at all -- and the caller's event object is never mutated, so the events the run
|
|
238
|
-
* record holds stay exactly as the runtime emitted them. Both keys are always written together,
|
|
239
|
-
* even when unknown: the terminal reads their presence as proof that this node's resolution is
|
|
240
|
-
* authoritative, so an unknown window cannot silently inherit the session's.
|
|
241
|
-
* @param event - the runtime event on its way to the terminal.
|
|
242
|
-
* @param lookup - the memoized resolution of a provider/model pair, as the node's executor asked for it.
|
|
243
|
-
* @returns the event to hand to the terminal; the original event when there is nothing to add.
|
|
244
|
-
*/
|
|
245
227
|
export async function withNodeModelResolution(event, lookup) {
|
|
246
228
|
if (event.type !== 'agent.session.started' || typeof event.data.subagentId === 'string')
|
|
247
229
|
return event;
|
|
@@ -260,14 +242,6 @@ export async function withNodeModelResolution(event, lookup) {
|
|
|
260
242
|
return { ...event, data: { ...event.data, reasoningEffort: resolved.reasoningEffort, contextWindow: resolved.contextWindow } };
|
|
261
243
|
}
|
|
262
244
|
const SIGN_OUT_NOTICE = 'Your Andorra session was revoked or expired, so the stored login was removed. Run /login to sign in again.';
|
|
263
|
-
/**
|
|
264
|
-
* Report an automatic sign-out where the current surface can see it, and record it.
|
|
265
|
-
*
|
|
266
|
-
* `--json` paths reserve stdout for the machine-readable result, the interactive path must print
|
|
267
|
-
* through the terminal (its alternate screen owns stdout), and the early command paths have
|
|
268
|
-
* neither, so the destination is chosen per call. The journal callback is optional because a
|
|
269
|
-
* sign-out can be discovered before the session journal exists (`auth status`, `--configure`).
|
|
270
|
-
*/
|
|
271
245
|
function reportSignOut(json, terminal, reason, journal) {
|
|
272
246
|
if (json)
|
|
273
247
|
process.stderr.write(safeTerminal(SIGN_OUT_NOTICE) + '\n');
|
|
@@ -282,20 +256,14 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
282
256
|
const persistConfig = dependencies.saveConfig ?? saveConfig;
|
|
283
257
|
const loadGraph = dependencies.loadGraph ?? loadAccessibleGraph;
|
|
284
258
|
const checkGraphHealth = dependencies.checkGraphHealth ?? checkGraphModelHealth;
|
|
285
|
-
|
|
286
|
-
|
|
259
|
+
const checkSessionModel = dependencies.checkSessionModel ?? (dependencies.checkGraphHealth === undefined ? checkSessionModelHealth : undefined);
|
|
260
|
+
const modelHealth = new ModelHealthCache(configDirectory());
|
|
287
261
|
if (argv[0] === 'mcp-server') {
|
|
288
262
|
if (argv.length !== 2 || argv[1] !== '--stdio')
|
|
289
263
|
throw new Error('Usage: andorra mcp-server --stdio');
|
|
290
264
|
const { runAgentMcpServer } = await import('./agent-mcp.js');
|
|
291
265
|
return await runAgentMcpServer();
|
|
292
266
|
}
|
|
293
|
-
// Registered before the early authenticated commands (`login`, `logout`, `auth status`,
|
|
294
|
-
// `graph`, `--configure`): each can refresh a stale token and discover a revoked session, and
|
|
295
|
-
// that sign-out must not be silent. The registration after the journal exists replaces this one
|
|
296
|
-
// so the notice also reaches the terminal and the `--debug` journal.
|
|
297
|
-
// The subagent command prints one JSON line on stdout and --json is optional there, so its
|
|
298
|
-
// sign-out notice belongs on stderr like the other machine-output paths.
|
|
299
267
|
const machineOutput = argv.includes('--json') || argv[0] === 'subagent' || argv[0] === 'automations';
|
|
300
268
|
setAuthSignOutReporter(error => reportSignOut(machineOutput, undefined, error.message));
|
|
301
269
|
if (argv[0] === 'login' || argv[0] === 'logout' || argv[0] === 'auth') {
|
|
@@ -310,10 +278,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
310
278
|
process.once('SIGTERM', cancel);
|
|
311
279
|
try {
|
|
312
280
|
const print = (message) => process.stdout.write(safeTerminal(message) + '\n');
|
|
313
|
-
// Where no browser can open here, the address that finishes the sign-in is pasted back on
|
|
314
|
-
// stdin. Only an interactive terminal is asked: piped input is not someone at a keyboard.
|
|
315
281
|
const lines = argv[0] === 'login' && process.stdin.isTTY ? createInterface({ input: process.stdin, output: process.stdout, terminal: true }) : undefined;
|
|
316
|
-
// readline swallows Ctrl+C while it reads; route it to the same cancellation.
|
|
317
282
|
lines?.on('SIGINT', cancel);
|
|
318
283
|
const readCallback = lines ? (prompt, signal) => lines.question(`${prompt} `, { signal }) : undefined;
|
|
319
284
|
try {
|
|
@@ -338,11 +303,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
338
303
|
if (argv[0] === 'app-server') {
|
|
339
304
|
if (argv.length !== 2 || argv[1] !== '--stdio')
|
|
340
305
|
throw new Error('Usage: andorra app-server --stdio');
|
|
341
|
-
// Loaded on demand: the machine-client surface pulls in the PTY, QA, and graph-server modules,
|
|
342
|
-
// and an ordinary TUI or headless invocation must not pay for them.
|
|
343
306
|
const { runAppServer } = await import('./app-server.js');
|
|
344
307
|
bootMark('app-server.imported');
|
|
345
|
-
// The desktop client owns this process and its stdio; in this mode nothing may print to stdout.
|
|
346
308
|
return await runAppServer();
|
|
347
309
|
}
|
|
348
310
|
if (argv[0] === 'automations') {
|
|
@@ -350,8 +312,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
350
312
|
return runAutomationCommand(argv.slice(1), line => process.stdout.write(line + '\n'));
|
|
351
313
|
}
|
|
352
314
|
if (argv[0] === 'remote') {
|
|
353
|
-
// Loaded on demand like `app-server`: the remote modules pull in TLS, x509, and the peer
|
|
354
|
-
// client, and no other command path needs them.
|
|
355
315
|
const { REMOTE_USAGE, runRemoteCommand } = await import('./remote/command.js');
|
|
356
316
|
if (argv.includes('--help') || argv.includes('-h')) {
|
|
357
317
|
process.stdout.write(`${REMOTE_USAGE}\n`);
|
|
@@ -380,7 +340,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
380
340
|
help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
|
|
381
341
|
prompt: { type: 'string', short: 'p' }, 'no-tui': { type: 'boolean' },
|
|
382
342
|
provider: { type: 'string' }, model: { type: 'string' }, graph: { type: 'string' },
|
|
383
|
-
cwd: { type: 'string' }, yolo: { type: 'boolean' }, jev: { type: 'string' }, json: { type: 'boolean' }, debug: { type: 'boolean' },
|
|
343
|
+
cwd: { type: 'string' }, yolo: { type: 'boolean' }, jev: { type: 'string' }, json: { type: 'boolean' }, debug: { type: 'boolean' }, tools: { type: 'string' }, goal: { type: 'string' },
|
|
384
344
|
configure: { type: 'boolean' }, 'run-input': { type: 'string' }, 'run-state': { type: 'string' },
|
|
385
345
|
} });
|
|
386
346
|
const readValues = async (path, flag) => {
|
|
@@ -396,7 +356,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
396
356
|
let terminal;
|
|
397
357
|
const print = (text) => terminal ? terminal.print(text) : process.stdout.write(safeTerminal(text) + '\n');
|
|
398
358
|
if (values.help) {
|
|
399
|
-
print(`Andorra Code\nUsage: andorra [--cwd path] [--provider id] [--model id] [--graph id] [--run-input file.json] [--run-state file.json] [--yolo] [--jev on|off] [--debug]\n andorra --prompt "task" [--json] [--yolo] [--jev on|off] [--debug]\n andorra subagent --prompt "task" [--provider id] [--model id] [--read-only]\n andorra graph [--no-open]\n andorra automations list|run|service|serve\n andorra app-server --stdio\n andorra mcp-server --stdio\n andorra remote serve|status|code|devices|revoke|share|unshare|pair|workspaces|unpair|rotate-cert\n andorra update\n andorra login [--no-browser]\n andorra logout [--all]\n andorra auth status\n\n${HELP}`);
|
|
359
|
+
print(`Andorra Code\nUsage: andorra [--cwd path] [--provider id] [--model id] [--graph id] [--run-input file.json] [--run-state file.json] [--goal "text"] [--yolo] [--jev on|off] [--debug]\n andorra --prompt "task" [--json] [--yolo] [--jev on|off] [--tools default|coding] [--debug]\n andorra subagent --prompt "task" [--provider id] [--model id] [--read-only]\n andorra graph [--no-open]\n andorra automations list|run|service|serve\n andorra app-server --stdio\n andorra mcp-server --stdio\n andorra remote serve|status|code|devices|revoke|share|unshare|pair|workspaces|unpair|rotate-cert\n andorra update\n andorra login [--no-browser]\n andorra logout [--all]\n andorra auth status\n\n${HELP}`);
|
|
400
360
|
return 0;
|
|
401
361
|
}
|
|
402
362
|
if (values.version) {
|
|
@@ -409,15 +369,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
409
369
|
}
|
|
410
370
|
const interactive = values.prompt === undefined;
|
|
411
371
|
const sessionStartedAt = Date.now();
|
|
412
|
-
// Declared early because the startup guard's closing record reads it before the signal
|
|
413
|
-
// handlers below exist; nothing sets it true until terminate() runs.
|
|
414
372
|
let terminated = false;
|
|
415
|
-
// The journal starts before the first fallible startup step (graph flag, config load,
|
|
416
|
-
// workspace resolution), so a failed `--debug` invocation still explains itself. Provider
|
|
417
|
-
// credentials are not known until the config loads; they register once it does.
|
|
418
373
|
let trajectory = await createSessionTrajectory({
|
|
419
|
-
// The log lives beside the sessions this terminal writes, so the window can find a session's
|
|
420
|
-
// conversation: it reads the log of the session it is showing.
|
|
421
374
|
directory: dependencies.trajectoryDirectory ?? join(configDirectory(), 'trajectories'),
|
|
422
375
|
onError: message => { if (values.json)
|
|
423
376
|
process.stderr.write(safeTerminal(message) + '\n');
|
|
@@ -428,23 +381,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
428
381
|
version: await cliVersion(), interactive,
|
|
429
382
|
} } : {}),
|
|
430
383
|
});
|
|
431
|
-
// The trajectory just recorded `session.started`; the conversation began here. It is emitted once
|
|
432
|
-
// per creation, never for a reopen. The promise is retained so the drain at exit runs after the
|
|
433
|
-
// enqueue: a drain that starts first exits with the event still pending in a tearing-down home.
|
|
434
|
-
// The conversation does not exist yet: an interactive session opened and closed without a task
|
|
435
|
-
// creates no saved conversation, so the start is emitted where the first one is created.
|
|
436
384
|
let sessionStarted = Promise.resolve();
|
|
437
385
|
const noteSessionStarted = (extra = {}) => {
|
|
438
386
|
sessionStarted = sessionStarted.then(() => currentGraphSubject().catch(() => undefined)).then(subject => reportSessionStarted({ home: configDirectory(), surface: configuredSurface('cli'), ...(subject === undefined ? {} : { subject }), ...extra })).catch(() => { });
|
|
439
387
|
};
|
|
440
|
-
/**
|
|
441
|
-
* The log a session's conversation is written to.
|
|
442
|
-
*
|
|
443
|
-
* A session has one log. The process opens one before the configuration is read, so a failed
|
|
444
|
-
* start still explains itself, and a session the user picks or forks takes a log of its own: the
|
|
445
|
-
* records of two conversations must never share a file, or the window would show them mixed. The
|
|
446
|
-
* log is named after the session, so the window finds it by the session's own id.
|
|
447
|
-
*/
|
|
448
388
|
const openSessionTrajectory = async (sessionId) => {
|
|
449
389
|
const directory = dependencies.trajectoryDirectory ?? join(configDirectory(), 'trajectories');
|
|
450
390
|
const path = join(directory, `${sessionId}.jsonl`);
|
|
@@ -461,25 +401,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
461
401
|
noteSessionStarted({ workspace });
|
|
462
402
|
trajectory.addSecrets(providerSecrets(config.providers));
|
|
463
403
|
};
|
|
464
|
-
/**
|
|
465
|
-
* `--debug` session accounting: every user command with its wall-clock cost, CLI-level
|
|
466
|
-
* errors that never reach a runtime event, and a closing summary. Model requests, tool
|
|
467
|
-
* calls and their timings are recorded unconditionally through the adapter wrapper and
|
|
468
|
-
* runtime events; these records add the conversation layer around them.
|
|
469
|
-
*/
|
|
470
404
|
const debugRecord = (type, data) => values.debug ? trajectory.record(type, data) : undefined;
|
|
471
405
|
const sessionEndedRecord = (extra = {}) => debugRecord('session.ended', { durationMs: Date.now() - sessionStartedAt, usage: sessionUsage(), interactive, terminated, ...extra });
|
|
472
|
-
// An automatic sign-out must be visible and recorded: the wipe removes the credential itself,
|
|
473
|
-
// so without this the user only sees authenticated features stop working. Explicit /logout is
|
|
474
|
-
// reported by its own command and never reaches this reporter. This registration replaces the
|
|
475
|
-
// early one, so the notice also reaches the terminal and the `--debug` journal.
|
|
476
406
|
setAuthSignOutReporter(error => reportSignOut(values.json === true, terminal, error.message, message => { void debugRecord('auth.signed-out', { message }); }));
|
|
477
|
-
/**
|
|
478
|
-
* Startup failures after the journal exists must still close it: a `--debug` invocation
|
|
479
|
-
* that dies during validation or initialization would otherwise leave the log open at
|
|
480
|
-
* `session.started` with no explanation. No provider call can have happened yet, so the
|
|
481
|
-
* closing summary reports zero usage; whatever manager was created is released.
|
|
482
|
-
*/
|
|
483
407
|
let releaseCodeIntel;
|
|
484
408
|
const startupGuard = async (operation) => {
|
|
485
409
|
try {
|
|
@@ -494,16 +418,22 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
494
418
|
try {
|
|
495
419
|
await releaseCodeIntel?.();
|
|
496
420
|
}
|
|
497
|
-
catch {
|
|
421
|
+
catch { }
|
|
498
422
|
throw error;
|
|
499
423
|
}
|
|
500
424
|
};
|
|
501
|
-
/** Fails startup under the journal-closing guard; the guard rethrows the wrapped error. */
|
|
502
425
|
const startupReject = (message) => startupGuard(async () => { throw new Error(message); });
|
|
503
426
|
if (values.graph && values.graph !== 'default')
|
|
504
427
|
await startupGuard(() => loadGraph(values.graph));
|
|
505
428
|
if (values.json && !values.prompt)
|
|
506
429
|
await startupReject('--json requires --prompt');
|
|
430
|
+
if (values.tools !== undefined && !values.prompt)
|
|
431
|
+
await startupReject('--tools requires --prompt');
|
|
432
|
+
const startupGoal = values.goal === undefined ? undefined : parseGoalCommand(`/goal ${values.goal}`);
|
|
433
|
+
if (startupGoal && startupGoal.action !== 'set')
|
|
434
|
+
await startupReject(startupGoal.action === 'invalid' ? `--goal: ${startupGoal.reason}` : '--goal takes the goal text, for example --goal "All tests pass"');
|
|
435
|
+
if (values.tools !== undefined && !isToolProfile(values.tools))
|
|
436
|
+
await startupReject(`--tools takes one of: ${TOOL_PROFILES.join(', ')}`);
|
|
507
437
|
if (values['no-tui'] && !values.prompt)
|
|
508
438
|
await startupReject('--no-tui requires --prompt');
|
|
509
439
|
if (values.jev !== undefined && !['on', 'off'].includes(values.jev))
|
|
@@ -517,6 +447,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
517
447
|
await trajectory.flush();
|
|
518
448
|
return 0;
|
|
519
449
|
}
|
|
450
|
+
bootMark('cli.update-check');
|
|
451
|
+
if (interactive)
|
|
452
|
+
await offerStartupSignIns();
|
|
453
|
+
bootMark('cli.sign-ins');
|
|
520
454
|
const config = await startupGuard(() => loadConfig());
|
|
521
455
|
const workspace = await startupGuard(async () => {
|
|
522
456
|
const resolved = await realpath(values.cwd ?? process.cwd());
|
|
@@ -544,9 +478,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
544
478
|
selected.model = values.model;
|
|
545
479
|
}
|
|
546
480
|
});
|
|
481
|
+
bootMark('cli.config');
|
|
547
482
|
const permissions = values.yolo ? 'full-access' : config.workspacePermissions?.[workspacePermissionKey(workspace)] ?? 'ask-for-approval';
|
|
548
|
-
// `--jev on|off` is this session's decision policy the way `--yolo` is its permission mode: it is
|
|
549
|
-
// never written to the configuration, and an explicit `/jev on|off` during the session replaces it.
|
|
550
483
|
let jevOverride = values.jev === undefined ? undefined : values.jev === 'on';
|
|
551
484
|
const jevOn = () => jevOverride ?? config.jevEnabled !== false;
|
|
552
485
|
const afterJevCommand = (input, result) => {
|
|
@@ -558,21 +491,17 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
558
491
|
else
|
|
559
492
|
result.text += `\nThis session started with --jev ${jevOverride ? 'on' : 'off'}, which overrides the saved preference until /jev on|off.`;
|
|
560
493
|
};
|
|
561
|
-
const state = await startupGuard(async () => ({ config, workspace, graph: values.graph ?? configuredGraphSelection(config, await currentGraphSubject()), permissions, yolo: permissions === 'full-access', usage: { inputTokens: 0, outputTokens: 0, requests: 0 }, notify: print, history: [],
|
|
562
|
-
// `/login` on a machine without a browser takes the sign-in address pasted back from another device.
|
|
494
|
+
const state = await startupGuard(async () => ({ config, workspace, graph: values.graph ?? configuredGraphSelection(config, await currentGraphSubject()), permissions, yolo: permissions === 'full-access', usage: { inputTokens: 0, outputTokens: 0, requests: 0 }, notify: print, history: [], ...(startupGoal?.action === 'set' ? { goal: newSessionGoal(startupGoal.text) } : {}),
|
|
563
495
|
readLine: async (prompt, signal) => {
|
|
564
496
|
if (!terminal)
|
|
565
497
|
throw new Error('No interactive terminal to read from.');
|
|
566
498
|
return terminal.question(prompt, { signal, title: 'Sign in', history: false });
|
|
567
499
|
},
|
|
568
|
-
// Over SSH only the terminal's own clipboard (OSC 52) reaches the machine the user sits at.
|
|
569
500
|
copyText: (text) => {
|
|
570
501
|
if (!terminal)
|
|
571
502
|
throw new Error('No interactive terminal.');
|
|
572
503
|
terminal.copyText(text, { terminalOnly: Boolean(process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY) });
|
|
573
504
|
},
|
|
574
|
-
// Direct /model shares the graph-override question with the /model screen; without a
|
|
575
|
-
// terminal the answer is always "keep", so nothing is ever overridden unobserved.
|
|
576
505
|
confirmModelOverride: async (question) => {
|
|
577
506
|
if (!terminal)
|
|
578
507
|
return false;
|
|
@@ -582,12 +511,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
582
511
|
], { description: question });
|
|
583
512
|
return choice === 'override';
|
|
584
513
|
} }));
|
|
585
|
-
// A saved per-account graph selection re-checks membership on every launch, so a transient
|
|
586
|
-
// account-service failure or a membership lapse must not deny the whole session: fall back
|
|
587
|
-
// to the local Andorra Agent graph and say so. A selection whose providers this machine
|
|
588
|
-
// cannot serve stays selected instead — the session refresh reports it and the header asks for
|
|
589
|
-
// the model override that runs it, so /model is one command away rather than a re-selection.
|
|
590
|
-
// An explicit --graph flag still fails fast because the caller asked for that exact graph.
|
|
591
514
|
let startupGraph;
|
|
592
515
|
let startupGraphSelection;
|
|
593
516
|
let startupGraphReused = false;
|
|
@@ -601,8 +524,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
601
524
|
startupGraphSelection = selection;
|
|
602
525
|
}
|
|
603
526
|
catch (error) {
|
|
604
|
-
// Nothing is printed here: the refresh right below the terminal's start reports the
|
|
605
|
-
// binding failure and sets the override hint, so the reason and the way out arrive together.
|
|
606
527
|
if (error instanceof GraphProviderUnavailableError && values.graph === undefined)
|
|
607
528
|
return;
|
|
608
529
|
if (values.graph !== undefined || (!(error instanceof PaidMembershipRequiredError || error instanceof GraphDeletedError) && !missingSavedGraph(error)))
|
|
@@ -613,9 +534,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
613
534
|
process.stderr.write(safeTerminal(graphFallbackNotice) + '\n');
|
|
614
535
|
}
|
|
615
536
|
});
|
|
537
|
+
bootMark('cli.startup-graph');
|
|
616
538
|
let activeUsage = { inputTokens: 0, outputTokens: 0, requests: 0, cacheRead: 0, cacheWrite: 0 };
|
|
617
|
-
// Cache totals stay sparse: a provider that reports no cache counts must not
|
|
618
|
-
// materialize explicit zeros in persisted session state or the /usage screen.
|
|
619
539
|
const foldCache = (target, cacheRead, cacheWrite) => {
|
|
620
540
|
const read = (target.cacheRead ?? 0) + (cacheRead ?? 0);
|
|
621
541
|
if (read > 0)
|
|
@@ -624,12 +544,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
624
544
|
if (write > 0)
|
|
625
545
|
target.cacheWrite = write;
|
|
626
546
|
};
|
|
627
|
-
// Input size of the most recent model request, i.e. how full the live conversation
|
|
628
|
-
// context currently is. Providers that report no usage leave it at its last value.
|
|
629
547
|
let contextUsedTokens = 0;
|
|
630
|
-
// The reading the record keeps for the desktop's context ring: only what the current run
|
|
631
|
-
// measured, never the footer's estimates. The window is left out — the footer sizes against
|
|
632
|
-
// the active provider, not the model that answered — so the desktop sizes it from configuration.
|
|
633
548
|
let runContext;
|
|
634
549
|
const sessionUsage = () => ({
|
|
635
550
|
requests: state.usage.requests + activeUsage.requests,
|
|
@@ -646,8 +561,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
646
561
|
const runtimeProvider = (provider) => ({
|
|
647
562
|
...provider, contextWindow: sessionContexts.get(contextKey(provider)) ?? provider.contextWindow,
|
|
648
563
|
});
|
|
649
|
-
// Config is known only now (the journal starts before config load), so provider credentials
|
|
650
|
-
// register here; mid-session /providers edits re-register through the same helper.
|
|
651
564
|
trajectory.addSecrets(providerSecrets(config.providers));
|
|
652
565
|
const selectedProvider = config.providers.find(p => p.id === config.provider);
|
|
653
566
|
await debugRecord('session.context', {
|
|
@@ -665,27 +578,21 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
665
578
|
if (!savedSession)
|
|
666
579
|
return;
|
|
667
580
|
const pendingHistory = pendingTask ? [{ task: pendingTask, completion: { summary: RUNNING_TURN_SUMMARY, tests: [], status: 'running' }, ...(pendingRunId === undefined ? {} : { runId: pendingRunId }), ...(pendingAttachments?.length ? { attachments: pendingAttachments } : {}) }] : [];
|
|
668
|
-
savedSession = { projectId: savedSession.projectId ?? projectIdentity(workspace), ...savedSession, contextHistory: [...state.history ?? [], ...pendingHistory].slice(-6), updatedAt: new Date().toISOString(), history: [...sessionArchive, ...pendingHistory], usage: { ...state.usage }, trajectoryId: trajectory.sessionId };
|
|
581
|
+
savedSession = { projectId: savedSession.projectId ?? projectIdentity(workspace), ...savedSession, goal: state.goal, contextHistory: [...state.history ?? [], ...pendingHistory].slice(-6), updatedAt: new Date().toISOString(), history: [...sessionArchive, ...pendingHistory], usage: { ...state.usage }, trajectoryId: trajectory.sessionId };
|
|
669
582
|
const record = savedSession;
|
|
670
583
|
try {
|
|
671
|
-
// This command's copy of the session was read when it started, while the desktop archives
|
|
672
|
-
// and renames through its own process. Take the same per-session mutation lock every rail
|
|
673
|
-
// mutation takes, read the stored record under it, and carry the fields that belong to the
|
|
674
|
-
// rail, or a save here silently returns an archived session to the working rail. A lock
|
|
675
|
-
// another process will not give up is not a reason to lose this turn: the save then goes
|
|
676
|
-
// through unmerged, which is exactly what it did before.
|
|
677
584
|
let releaseRailLock;
|
|
678
585
|
try {
|
|
679
586
|
releaseRailLock = await acquireSessionMutationLock(configDirectory(), record.id);
|
|
680
587
|
}
|
|
681
|
-
catch {
|
|
588
|
+
catch { }
|
|
682
589
|
try {
|
|
683
590
|
if (releaseRailLock) {
|
|
684
591
|
let stored;
|
|
685
592
|
try {
|
|
686
593
|
stored = JSON.parse(await readFile(join(configDirectory(), 'sessions', `${record.id}.json`), 'utf8'));
|
|
687
594
|
}
|
|
688
|
-
catch {
|
|
595
|
+
catch { }
|
|
689
596
|
carryRailOwnedFields(record, stored);
|
|
690
597
|
}
|
|
691
598
|
if (browserBridge)
|
|
@@ -706,7 +613,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
706
613
|
}
|
|
707
614
|
};
|
|
708
615
|
const directory = configDirectory();
|
|
709
|
-
// Spooled attachments are files, not records: retire the ones no conversation can still reference.
|
|
710
616
|
void pruneAttachments(directory).catch(() => { });
|
|
711
617
|
let browserApp;
|
|
712
618
|
let browserBridge;
|
|
@@ -714,21 +620,30 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
714
620
|
let browserPrompt;
|
|
715
621
|
let browserAcceptance = Promise.resolve();
|
|
716
622
|
let browserRollbackFailed = false;
|
|
717
|
-
// Finalization keeps the session non-idle so the browser cannot submit into
|
|
718
|
-
// a terminal whose next question is not armed yet. A cancellation recorded
|
|
719
|
-
// while a durably accepted prompt is still starting aborts it at run start.
|
|
720
623
|
let browserDraining = false;
|
|
721
624
|
let browserCancelPending = false;
|
|
722
625
|
const rollbackFailureMessage = 'Session storage rollback failed. Repair local storage and inspect session history before restarting this CLI.';
|
|
723
626
|
await startupGuard(() => mkdir(runRecordsDirectory(directory), { recursive: true }));
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
627
|
+
let runEventSink;
|
|
628
|
+
const codeIntelLabel = (state) => state === 'indexing' ? 'Indexing' : state === 'ready' ? 'Ready' : state === 'syncing' ? 'Updating'
|
|
629
|
+
: state === 'degraded' ? 'Degraded' : state === 'error' ? 'Error' : undefined;
|
|
630
|
+
const codeIntelNotice = (event) => {
|
|
631
|
+
if (event.type === 'codeintel.state') {
|
|
632
|
+
const label = codeIntelLabel(event.data.state);
|
|
633
|
+
terminal?.setStatus({ codeIntel: label });
|
|
634
|
+
if (event.data.state === 'error')
|
|
635
|
+
process.stderr.write(`CodeGraph: ${String(event.data.detail ?? 'unavailable')}\n`);
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
const homeWorkspace = workspace === await realpath(homedir()).catch(() => homedir());
|
|
639
|
+
const codeIntelOpening = CodeIntelligenceManager.create({
|
|
640
|
+
permissions: state.permissions,
|
|
641
|
+
config: homeWorkspace ? { ...resolveCodeIntelConfig(config), enabled: false, enabledRepos: [] } : resolveCodeIntelConfig(config), workspace,
|
|
642
|
+
onEvent: event => (runEventSink ?? codeIntelNotice)(event),
|
|
643
|
+
});
|
|
644
|
+
codeIntelOpening.catch(() => { });
|
|
728
645
|
try {
|
|
729
646
|
const recovered = await reconcileInterruptedRuns(directory, undefined, { skipOwnProcess: true, includePending: true });
|
|
730
|
-
// A recovered run still owes its `interrupted` finish, so the pair joins through the same
|
|
731
|
-
// telemetry id the open record carried.
|
|
732
647
|
await reportInterruptedRuns({ home: directory, surface: configuredSurface('cli') }, recovered.interrupted);
|
|
733
648
|
const parts = [];
|
|
734
649
|
if (recovered.runs.length > 0)
|
|
@@ -743,43 +658,12 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
743
658
|
print(notice);
|
|
744
659
|
}
|
|
745
660
|
}
|
|
746
|
-
catch {
|
|
747
|
-
|
|
748
|
-
const
|
|
749
|
-
|
|
750
|
-
const codeIntelNotice = (event) => {
|
|
751
|
-
if (event.type === 'codeintel.state') {
|
|
752
|
-
const label = codeIntelLabel(event.data.state);
|
|
753
|
-
terminal?.setStatus({ codeIntel: label });
|
|
754
|
-
if (event.data.state === 'error')
|
|
755
|
-
process.stderr.write(`CodeGraph: ${String(event.data.detail ?? 'unavailable')}\n`);
|
|
756
|
-
}
|
|
757
|
-
};
|
|
758
|
-
// A shell commonly starts in the user's home. Never recursively index that
|
|
759
|
-
// personal tree as an implicit side effect of opening the coding client.
|
|
760
|
-
// This override is session-only; /codegraph enable remains an explicit opt-in.
|
|
761
|
-
const homeWorkspace = workspace === await realpath(homedir()).catch(() => homedir());
|
|
762
|
-
const codeIntel = await startupGuard(() => CodeIntelligenceManager.create({
|
|
763
|
-
permissions: state.permissions,
|
|
764
|
-
config: homeWorkspace ? { ...resolveCodeIntelConfig(config), enabled: false, enabledRepos: [] } : resolveCodeIntelConfig(config), workspace,
|
|
765
|
-
onEvent: event => (runEventSink ?? codeIntelNotice)(event),
|
|
766
|
-
}));
|
|
661
|
+
catch { }
|
|
662
|
+
bootMark('cli.reconciled');
|
|
663
|
+
const codeIntel = await startupGuard(() => codeIntelOpening);
|
|
664
|
+
bootMark('cli.codeintel');
|
|
767
665
|
releaseCodeIntel = () => codeIntel.dispose();
|
|
768
666
|
state.codeIntel = codeIntel;
|
|
769
|
-
/**
|
|
770
|
-
* Feed the side panel's live sections: the working tree, the branch, and the terminals.
|
|
771
|
-
*
|
|
772
|
-
* The Git summary spawns `git`, so it runs at most once at a time and not more often than the
|
|
773
|
-
* panel could show a difference - a run that writes a file per second must not spawn a process
|
|
774
|
-
* per file, and a reader only needs the count to move. A call the throttle or an in-flight read
|
|
775
|
-
* turns away is not dropped: it is remembered as pending and re-run when the read settles, so
|
|
776
|
-
* the last event before a quiet stretch is still reflected. The branch is read here rather than
|
|
777
|
-
* only at run boundaries because a tool can switch branches mid-run, and reading it is two
|
|
778
|
-
* bounded file reads (`gitBranch` never executes anything). The terminal list needs no care at
|
|
779
|
-
* all: the QA PTY sessions live in this process, so listing them is a map walk.
|
|
780
|
-
* @param force - read the working tree now, ignoring the throttle. Run boundaries pass it;
|
|
781
|
-
* tool completions do not, so a tool-heavy run cannot spawn hundreds of git processes.
|
|
782
|
-
*/
|
|
783
667
|
let changesInFlight = false;
|
|
784
668
|
let changesReadAt = 0;
|
|
785
669
|
let changesPending;
|
|
@@ -790,20 +674,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
790
674
|
const CHANGE_REFRESH_MS = 2_000;
|
|
791
675
|
const TERMINAL_WATCH_MS = 1_000;
|
|
792
676
|
const listTerminals = () => getQaPtyManager(workspace).list().map(session => ({ id: session.id, command: session.command, running: session.running, startedAt: session.startedAt }));
|
|
793
|
-
/**
|
|
794
|
-
* Notice a background terminal that exits on its own.
|
|
795
|
-
*
|
|
796
|
-
* The manager records the exit in its own session, but nothing in the tool flow reports it:
|
|
797
|
-
* without this watch the panel would keep a finished session as running, keep counting its age
|
|
798
|
-
* up, and keep the frame's clock ticking until the run ended. The watch exists only while a
|
|
799
|
-
* displayed session is running, and the map walk it performs is free.
|
|
800
|
-
*/
|
|
801
677
|
const watchTerminals = (sessions) => {
|
|
802
678
|
const running = sessions.some(session => session.running);
|
|
803
679
|
if (running && !terminalsTimer) {
|
|
804
680
|
terminalsTimer = setInterval(() => {
|
|
805
|
-
// The ages it maintains are only drawn by the panel: hidden, the watch stops and the
|
|
806
|
-
// `panel` event re-arms it when the panel comes back.
|
|
807
681
|
if (!terminal || !terminal.panelVisible()) {
|
|
808
682
|
clearInterval(terminalsTimer);
|
|
809
683
|
terminalsTimer = undefined;
|
|
@@ -833,10 +707,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
833
707
|
void gitChangeSummary(workspace, { signal: panelReads.signal })
|
|
834
708
|
.then(changes => { changesReadAt = Date.now(); changesEverRead = true; terminal?.setStatus({ changes }); })
|
|
835
709
|
.catch(() => {
|
|
836
|
-
// A read that failed leaves the last good reading in place, and it counts as an attempt:
|
|
837
|
-
// a repository that rejects every read (an unreadable index, a filter it cannot vouch for)
|
|
838
|
-
// must not make each following tool event start another full scan. With nothing to keep,
|
|
839
|
-
// the section is told the reading is unavailable instead of claiming to still read.
|
|
840
710
|
changesReadAt = Date.now();
|
|
841
711
|
if (!changesEverRead) {
|
|
842
712
|
terminal?.setStatus({ changes: { isGit: true, files: 0, untracked: 0, insertions: 0, deletions: 0, unavailable: 'the working tree could not be read' } });
|
|
@@ -848,40 +718,21 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
848
718
|
changesPending = undefined;
|
|
849
719
|
if (panelReads.signal.aborted || pending === undefined)
|
|
850
720
|
return;
|
|
851
|
-
// A queued forced read (a run boundary) starts now; a queued tool boundary waits out the
|
|
852
|
-
// rest of the window it was turned away from, so draining the queue cannot run two scans
|
|
853
|
-
// milliseconds apart.
|
|
854
|
-
// Through the gate even here: the panel may have been hidden (a narrowed terminal, the
|
|
855
|
-
// dashboard, a modal) between the request and this drain.
|
|
856
721
|
if (pending === 'force')
|
|
857
722
|
refreshPanelStatus(true);
|
|
858
723
|
else
|
|
859
724
|
scheduleChanges(CHANGE_REFRESH_MS - (Date.now() - changesReadAt));
|
|
860
725
|
});
|
|
861
726
|
};
|
|
862
|
-
/**
|
|
863
|
-
* Read now, or at the end of the throttle window - never later, and never not at all.
|
|
864
|
-
*
|
|
865
|
-
* A request that arrives inside the window is queued rather than dropped, and because nothing
|
|
866
|
-
* else would come back for it, the queue is drained by a timer armed for the remainder of the
|
|
867
|
-
* window: the last tool completion of a quiet task must still reach the panel, and a run that
|
|
868
|
-
* ends while a read is in flight must not leave the counts behind an unsettled snapshot.
|
|
869
|
-
*/
|
|
870
727
|
const scheduleChanges = (delayMs) => {
|
|
871
728
|
if (changesTimer || panelReads.signal.aborted)
|
|
872
729
|
return;
|
|
873
|
-
// Through the gate, not around it: the panel may have been hidden (a narrowed terminal, the
|
|
874
|
-
// dashboard) between the request and its timer, and a hidden panel buys no git process.
|
|
875
730
|
changesTimer = setTimeout(() => { changesTimer = undefined; refreshPanelStatus(true); }, Math.max(0, delayMs));
|
|
876
731
|
changesTimer.unref?.();
|
|
877
732
|
};
|
|
878
733
|
const refreshPanelStatus = (force = false) => {
|
|
879
734
|
if (!terminal)
|
|
880
735
|
return;
|
|
881
|
-
// The panel is the only consumer of both reads, so a terminal that cannot show it - too
|
|
882
|
-
// narrow, too short, or on the dashboard or a modal screen - costs nothing: no terminal list,
|
|
883
|
-
// no branch read and, above all, no git process. `panel-visible` brings the summary back when
|
|
884
|
-
// a resize or a closed screen makes the panel reachable again.
|
|
885
736
|
if (!terminal.panelVisible()) {
|
|
886
737
|
changesPending = undefined;
|
|
887
738
|
return;
|
|
@@ -890,8 +741,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
890
741
|
terminal.setStatus({ terminals: sessions });
|
|
891
742
|
watchTerminals(sessions);
|
|
892
743
|
void gitBranch(workspace).then(branch => terminal?.setStatus({ branch }));
|
|
893
|
-
// The queue remembers which kind of request is waiting, because the two are drained
|
|
894
|
-
// differently and a forced request must not be softened into a throttled one.
|
|
895
744
|
if (changesInFlight) {
|
|
896
745
|
changesPending = force || changesPending === 'force' ? 'force' : 'throttled';
|
|
897
746
|
return;
|
|
@@ -908,18 +757,14 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
908
757
|
await startupGuard(async () => {
|
|
909
758
|
const selected = config.providers.find(p => p.id === config.provider);
|
|
910
759
|
const codeIntelState = codeIntelLabel((await codeIntel.getStatus()).state);
|
|
911
|
-
terminal = new TerminalUI({ account: { label: 'Checking account...', notice: 'Checking member access. Local Andorra Agent remains available.' }, workspace, provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, version: await cliVersion(), branch: await gitBranch(workspace), yolo: state.yolo, permissions: permissionLabel(state.permissions), graphSelection: state.graph ?? 'default',
|
|
760
|
+
terminal = new TerminalUI({ goal: state.goal, account: { label: 'Checking account...', notice: 'Checking member access. Local Andorra Agent remains available.' }, workspace, provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, version: await cliVersion(), branch: await gitBranch(workspace), yolo: state.yolo, permissions: permissionLabel(state.permissions), graphSelection: state.graph ?? 'default',
|
|
912
761
|
graph: startupGraph ?? await loadGraph(state.graph ?? 'default').catch(() => undefined), ...(codeIntelState ? { codeIntel: codeIntelState } : {}), clipboardImageProbe: readClipboardImage, clipboardTextWriter: writeClipboardText });
|
|
913
762
|
offerSkillCommands(terminal, state.config, directory);
|
|
914
763
|
terminal.setLocalCommandHandler((input, mode, durationMs) => {
|
|
915
|
-
// Local view commands never reach either CLI command loop.
|
|
916
764
|
void debugRecord('command.started', { input, mode });
|
|
917
765
|
void debugRecord('command.completed', { input, mode, durationMs });
|
|
918
766
|
});
|
|
919
767
|
terminal.setStatus({ codeIntel: codeIntelLabel((await codeIntel.getStatus()).state), jevEnabled });
|
|
920
|
-
// The first render after `start()` announces the panel when it is visible, and that event owns
|
|
921
|
-
// the first summary: asking here as well would run the whole multi-process read twice on every
|
|
922
|
-
// wide-terminal launch.
|
|
923
768
|
terminal.on('panel', () => refreshPanelStatus(true));
|
|
924
769
|
if (graphFallbackNotice)
|
|
925
770
|
terminal.print(graphFallbackNotice);
|
|
@@ -928,19 +773,17 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
928
773
|
jevEnabled = jevOn();
|
|
929
774
|
const configured = config.providers.find(p => p.id === config.provider);
|
|
930
775
|
const selected = configured ? runtimeProvider(configured) : undefined;
|
|
931
|
-
terminal?.setStatus({ provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, yolo: state.yolo, permissions: permissionLabel(state.permissions), jevEnabled, ...sessionUsage() });
|
|
776
|
+
terminal?.setStatus({ provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, yolo: state.yolo, permissions: permissionLabel(state.permissions), jevEnabled, goal: state.goal, ...sessionUsage() });
|
|
932
777
|
};
|
|
933
778
|
let graphModelsHealthy = false;
|
|
934
|
-
const refreshGraphStatus = async () => {
|
|
779
|
+
const refreshGraphStatus = async (background) => {
|
|
935
780
|
if (terminal) {
|
|
936
|
-
const controller = active ?? new AbortController();
|
|
937
|
-
const ownsController = !active;
|
|
781
|
+
const controller = background ?? active ?? new AbortController();
|
|
782
|
+
const ownsController = !background && !active;
|
|
938
783
|
if (ownsController)
|
|
939
784
|
active = controller;
|
|
940
785
|
terminal.setStatus({ activity: 'Checking graph models', backgroundActivity: true });
|
|
941
786
|
graphModelsHealthy = false;
|
|
942
|
-
// Run preflights reuse the startup graph until a refresh replaces it; dropping the
|
|
943
|
-
// cache first means a failed refresh falls back to loading again at run time.
|
|
944
787
|
startupGraph = undefined;
|
|
945
788
|
startupGraphSelection = undefined;
|
|
946
789
|
startupGraphReused = false;
|
|
@@ -950,24 +793,14 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
950
793
|
graph = await loadGraph(state.graph ?? 'default', controller.signal);
|
|
951
794
|
}
|
|
952
795
|
catch (error) {
|
|
953
|
-
// A graph that cannot bind keeps the selection: `/graph` has just accepted it (or the
|
|
954
|
-
// user is about to repair it with /model), the run is what refuses it, and replacing it
|
|
955
|
-
// with Default here would silently undo the choice — and point /model's repair at the
|
|
956
|
-
// wrong graph. Its definition is still read, unbound, so the status bar names it; the
|
|
957
|
-
// run preflight keeps loading the bound graph, so the refusal stays where it belongs.
|
|
958
796
|
if (error instanceof GraphProviderUnavailableError) {
|
|
959
797
|
const definition = await loadGraph(state.graph ?? 'default', controller.signal, undefined, { bindProviders: false }).catch(() => undefined);
|
|
960
798
|
if (!controller.signal.aborted) {
|
|
961
|
-
// The hint is what the session should do about the selection, so it is set from the
|
|
962
|
-
// binding failure itself; the unbound definition only names the graph beside it.
|
|
963
799
|
terminal.setStatus({ graphSelection: state.graph ?? 'default', ...(definition === undefined ? {} : { graph: definition }), graphNeedsOverride: true, jevEnabled: jevOn() });
|
|
964
800
|
print(error.message);
|
|
965
801
|
}
|
|
966
802
|
return;
|
|
967
803
|
}
|
|
968
|
-
// The refresh path applies the same membership fallback as startup: without it the
|
|
969
|
-
// denial would only print here while state.graph stays on the paid graph and the first
|
|
970
|
-
// task retries the denied selection.
|
|
971
804
|
if (values.graph !== undefined || (state.graph ?? 'default') === 'default' || (!(error instanceof PaidMembershipRequiredError || error instanceof GraphDeletedError) && !missingSavedGraph(error)))
|
|
972
805
|
throw error;
|
|
973
806
|
state.graph = 'default';
|
|
@@ -979,18 +812,33 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
979
812
|
startupGraphSelection = state.graph ?? 'default';
|
|
980
813
|
jevEnabled = jevOn();
|
|
981
814
|
terminal.setStatus({ graphSelection: state.graph ?? 'default', graph, graphNeedsOverride: false, jevEnabled });
|
|
982
|
-
|
|
815
|
+
await modelHealth.load();
|
|
816
|
+
const sessionOnly = (state.graph ?? 'default') === 'default' && checkSessionModel !== undefined;
|
|
817
|
+
const health = sessionOnly
|
|
818
|
+
? await checkSessionModel(config, controller.signal, { verified: modelHealth })
|
|
819
|
+
: await checkGraphHealth(graph, config, controller.signal, { verified: modelHealth });
|
|
983
820
|
graphModelsHealthy = health.healthy;
|
|
984
821
|
if (!health.healthy)
|
|
985
|
-
print(formatGraphHealthFailure(health
|
|
822
|
+
print(formatGraphHealthFailure(health, sessionOnly
|
|
823
|
+
? 'Choose another model with /model, or check the provider with /providers.'
|
|
824
|
+
: undefined));
|
|
986
825
|
}
|
|
987
826
|
finally {
|
|
988
827
|
if (ownsController)
|
|
989
828
|
active = undefined;
|
|
990
|
-
terminal.setStatus({ activity: graphModelsHealthy ? 'Ready' : 'Graph models unavailable' });
|
|
829
|
+
terminal.setStatus({ activity: background?.signal.aborted ? 'Ready' : graphModelsHealthy ? 'Ready' : 'Graph models unavailable' });
|
|
991
830
|
}
|
|
992
831
|
}
|
|
993
832
|
};
|
|
833
|
+
let startupGraphCheck;
|
|
834
|
+
const settleStartupGraphCheck = async () => {
|
|
835
|
+
const pending = startupGraphCheck;
|
|
836
|
+
if (!pending)
|
|
837
|
+
return;
|
|
838
|
+
startupGraphCheck = undefined;
|
|
839
|
+
pending.controller.abort(new Error('Superseded by a submitted task'));
|
|
840
|
+
await pending.done;
|
|
841
|
+
};
|
|
994
842
|
const graphEditor = createGraphEditorSession();
|
|
995
843
|
let accountRefresh;
|
|
996
844
|
let accountRefreshTimer;
|
|
@@ -1003,7 +851,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1003
851
|
if (!request.signal.aborted)
|
|
1004
852
|
terminal?.setStatus({ account });
|
|
1005
853
|
}
|
|
1006
|
-
catch {
|
|
854
|
+
catch { }
|
|
1007
855
|
};
|
|
1008
856
|
let active;
|
|
1009
857
|
let exiting = false;
|
|
@@ -1016,37 +864,20 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1016
864
|
};
|
|
1017
865
|
let runControl;
|
|
1018
866
|
let approvePending;
|
|
1019
|
-
// Self-wake prompts armed by the agent's set_timer tool. A due prompt goes to whichever
|
|
1020
|
-
// surface can take it right now: a live terminal-graph run consumes it as steering at its
|
|
1021
|
-
// next turn boundary, and an idle conversation composer receives it as a new task. Anywhere
|
|
1022
|
-
// else - a command screen, a browser task, the save/teardown window between runs - it waits
|
|
1023
|
-
// in `timerPending` until a composer or a turn boundary comes back to collect it, so a
|
|
1024
|
-
// prompt is never delivered to the wrong surface and never silently dropped.
|
|
1025
867
|
const sessionTimers = new TimerRegistry();
|
|
1026
868
|
const timerSteering = [];
|
|
1027
869
|
const timerPending = [];
|
|
1028
|
-
// Set when a timer's prompt resumed a paused run: prepareTurn injects steering *before*
|
|
1029
|
-
// the direction queue, so any later timer must hold in `timerPending` until the poll that
|
|
1030
|
-
// carried the resume direction has happened, and only then join the steering channel.
|
|
1031
|
-
// Without the hold, the later prompt would reach the model ahead of the earliest deadline.
|
|
1032
870
|
let timerResumePending = false;
|
|
1033
871
|
const deliverTimerPrompts = () => {
|
|
1034
|
-
// Canceled runs may not receive a prompt that no conversation will ever read, so past
|
|
1035
|
-
// teardown the due timers are reaped and discarded rather than queued.
|
|
1036
872
|
if (exiting) {
|
|
1037
873
|
sessionTimers.takeDue();
|
|
1038
874
|
return;
|
|
1039
875
|
}
|
|
1040
|
-
// `takeDue` returns prompts soonest-deadline first, so every channel below preserves order.
|
|
1041
876
|
for (const due of sessionTimers.takeDue())
|
|
1042
877
|
timerPending.push(`[Timer] ${due.prompt}`);
|
|
1043
878
|
while (timerPending.length) {
|
|
1044
879
|
const text = timerPending[0];
|
|
1045
880
|
if (runControl && active && !active.signal.aborted) {
|
|
1046
|
-
// A paused run is blocked in RunControl.wait() until resume(): only that call both
|
|
1047
|
-
// clears the pause and carries a direction in, which is why user steering from the
|
|
1048
|
-
// browser resumes with its text instead of queueing. A timer due mid-pause must wake
|
|
1049
|
-
// the run the same way, or the promised self-wake waits for the user to type.
|
|
1050
881
|
if (runControl.isPaused) {
|
|
1051
882
|
if (runControl.resume(text)) {
|
|
1052
883
|
timerResumePending = true;
|
|
@@ -1061,10 +892,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1061
892
|
timerSteering.push(timerPending.shift());
|
|
1062
893
|
continue;
|
|
1063
894
|
}
|
|
1064
|
-
// Runs this process executes through `run()` — terminal tasks and prompts accepted by
|
|
1065
|
-
// the authenticated browser bridge — drain `timerSteering` at their turn boundaries. A
|
|
1066
|
-
// task owned by the standalone browser server polls its own queue instead, so a timer
|
|
1067
|
-
// due then waits in `timerPending` and reaches the composer when the terminal is idle.
|
|
1068
895
|
if (terminal?.acceptConversationPrompt(text)) {
|
|
1069
896
|
timerPending.shift();
|
|
1070
897
|
continue;
|
|
@@ -1073,10 +900,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1073
900
|
}
|
|
1074
901
|
};
|
|
1075
902
|
sessionTimers.onDue = deliverTimerPrompts;
|
|
1076
|
-
// Ctrl+C escalates: the first press stops the live run — pausing interactive runs so a
|
|
1077
|
-
// message can resume them, aborting everything else — and the next press, or a press with
|
|
1078
|
-
// nothing left to stop, terminates the program. A run that keeps running past its abort
|
|
1079
|
-
// signal would otherwise leave Ctrl+C with no remaining effect.
|
|
1080
903
|
const interrupt = () => {
|
|
1081
904
|
if (runControl) {
|
|
1082
905
|
if (runControl.isPaused)
|
|
@@ -1093,14 +916,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1093
916
|
else
|
|
1094
917
|
kill();
|
|
1095
918
|
};
|
|
1096
|
-
const teardown = () => { terminated = true; exiting = true; active?.abort(); sessionTimers.clear(); terminal?.close(); };
|
|
1097
|
-
// The Ctrl+C escalation must not become a suggestion: after the terminal is restored, a
|
|
1098
|
-
// run wedged past its abort signal gets a short grace window and then a hard exit.
|
|
1099
|
-
// SIGTERM keeps the patient teardown instead — cleanup of a canceled shell tree is a
|
|
1100
|
-
// bounded wait that outlives this window, and its contract is tested to finish it.
|
|
1101
|
-
// The timer stays referenced on purpose: a wedge can leave main() awaiting a promise
|
|
1102
|
-
// with no other live handle, and an unreferenced timer would let the event loop drain
|
|
1103
|
-
// and the process exit with the implicit status 0 before the backstop ever fires.
|
|
919
|
+
const teardown = () => { terminated = true; exiting = true; active?.abort(); startupGraphCheck?.controller.abort(); sessionTimers.clear(); terminal?.close(); };
|
|
1104
920
|
let killBackstop;
|
|
1105
921
|
const kill = () => {
|
|
1106
922
|
teardown();
|
|
@@ -1110,23 +926,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1110
926
|
process.on('SIGINT', interrupt);
|
|
1111
927
|
process.on('SIGTERM', teardown);
|
|
1112
928
|
terminal?.on('SIGINT', interrupt);
|
|
1113
|
-
terminal?.on('close', () => { tabTitle.close(); exiting = true; active?.abort(); });
|
|
1114
|
-
/**
|
|
1115
|
-
* Carry one attempt into the next turn's context. The turns live on `state` so commands
|
|
1116
|
-
* such as /compact and /clear can replace them and the next run sees the result.
|
|
1117
|
-
*
|
|
1118
|
-
* A turn that failed, was cancelled, or crashed still happened: the user asked for this
|
|
1119
|
-
* work and the agent may already have read files or changed the workspace. Dropping it
|
|
1120
|
-
* would make the next message start from a blank history, so the task is retained with a
|
|
1121
|
-
* plain statement of how it ended instead of a fabricated success.
|
|
1122
|
-
* @param task - the task the user submitted.
|
|
1123
|
-
* @param completion - the validated completion, or a summary of the outcome.
|
|
1124
|
-
*/
|
|
929
|
+
terminal?.on('close', () => { tabTitle.close(); exiting = true; active?.abort(); startupGraphCheck?.controller.abort(); });
|
|
1125
930
|
const rememberTurn = (task, completion, runId, attachments) => {
|
|
1126
931
|
sessionArchive.push({ task, completion, runId, ...(attachments?.length ? { attachments } : {}) });
|
|
1127
932
|
state.history = [...state.history ?? [], { task, completion, runId, ...(attachments?.length ? { attachments } : {}) }].slice(-6);
|
|
1128
933
|
};
|
|
1129
|
-
/** Render how an attempt ended as history the next turn can read. */
|
|
1130
934
|
const outcomeCompletion = (status, reason, limits) => ({
|
|
1131
935
|
summary: status === 'cancelled'
|
|
1132
936
|
? 'This attempt was cancelled before it finished; its work may be incomplete.'
|
|
@@ -1134,24 +938,18 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1134
938
|
tests: [], ...(status === 'succeeded' ? {} : { status: status }),
|
|
1135
939
|
});
|
|
1136
940
|
const toolActivity = new ToolActivity();
|
|
1137
|
-
/** The task text an attachment-only submission runs with; both surfaces substitute the same words. */
|
|
1138
941
|
const ATTACHMENT_ONLY_TASK = 'See the attached file(s).';
|
|
1139
942
|
const run = async (task, pending = []) => {
|
|
943
|
+
await settleStartupGraphCheck();
|
|
1140
944
|
if (browserRollbackFailed)
|
|
1141
945
|
throw new Error(rollbackFailureMessage);
|
|
1142
946
|
if (!config.providers.length) {
|
|
1143
947
|
print('Add a provider in /providers before starting a task.');
|
|
1144
948
|
return 1;
|
|
1145
949
|
}
|
|
1146
|
-
// Attachments resolve to disk-backed refs once, before any record names them: a bad
|
|
1147
|
-
// reference refuses the whole turn rather than half-attaching.
|
|
1148
950
|
if (pending.length && terminal)
|
|
1149
951
|
terminal.print(`⌷ attached: ${pending.map(attachmentLabel).join(' · ')}`);
|
|
1150
952
|
let attachments;
|
|
1151
|
-
// Spool directories this run's attached content lives in: the tool layer reads them as
|
|
1152
|
-
// trusted paths, so a paste is readable in every permission mode, steers included. The
|
|
1153
|
-
// replayed history's spools count too — the model is told to read those files again — but
|
|
1154
|
-
// they are owned by the persisted turns, so only this run's steers are cleaned up below.
|
|
1155
953
|
const attachmentSpools = new Set();
|
|
1156
954
|
const steeredSpools = new Set();
|
|
1157
955
|
for (const root of await attachmentReadRoots(directory, (state.history ?? []).flatMap(turn => turn.attachments ?? [])))
|
|
@@ -1167,7 +965,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1167
965
|
for (const root of await attachmentReadRoots(directory, attachments.refs))
|
|
1168
966
|
attachmentSpools.add(root);
|
|
1169
967
|
}
|
|
1170
|
-
// Cancellation must already own this run while its first snapshot is pending.
|
|
1171
968
|
active = new AbortController();
|
|
1172
969
|
if (browserCancelPending) {
|
|
1173
970
|
browserCancelPending = false;
|
|
@@ -1177,7 +974,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1177
974
|
trajectory.addSecrets(providerSecrets(config.providers));
|
|
1178
975
|
if (!savedSession) {
|
|
1179
976
|
savedSession = { version: 1, id: trajectory.sessionId, name: sessionName(task), workspace, updatedAt: new Date().toISOString(), history: [], usage: { ...state.usage } };
|
|
1180
|
-
// This is the creation this event names: the first task that lands on the session.
|
|
1181
977
|
noteSessionStarted({ workspace });
|
|
1182
978
|
}
|
|
1183
979
|
const accepted = browserAcceptance;
|
|
@@ -1192,27 +988,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1192
988
|
}
|
|
1193
989
|
browserBridge?.startRun();
|
|
1194
990
|
const runId = randomUUID();
|
|
1195
|
-
// The telemetry id is random and unrelated to the persisted run id, which is derived from local
|
|
1196
|
-
// state. It is written into the open record so recovery can still join a crash's pair.
|
|
1197
991
|
const telemetryRunId = randomUUID();
|
|
1198
992
|
const startedAt = new Date().toISOString();
|
|
1199
|
-
// Which nodes' newest checkpoint could not be written. A checkpoint is the conversation a
|
|
1200
|
-
// resume re-enters the node with, so the node is marked until one of its later writes lands,
|
|
1201
|
-
// and the record carries the mark past a crash: a resume of the attempt warns that the node may
|
|
1202
|
-
// repeat work.
|
|
1203
993
|
const checkpointHealth = createCheckpointFailureTracker(directory, runId);
|
|
1204
|
-
// The selector this attempt runs on, captured at start. Every record the attempt writes
|
|
1205
|
-
// carries it: the result's own `graph` is the pinned graph object, whose id is the bundled
|
|
1206
|
-
// harness's id rather than the selection that loaded it ('default' loads `software-engineer`),
|
|
1207
|
-
// and a resume has to re-select through the same access rules — so it needs this, not the
|
|
1208
|
-
// pinned identity. Captured here rather than re-read at finalize, where a later /graph change
|
|
1209
|
-
// could mislabel the attempt.
|
|
1210
994
|
const runGraphSelection = state.graph ?? 'default';
|
|
1211
|
-
// Bind persisted run inspection to the signed-in account at run creation.
|
|
1212
995
|
const accountSubject = await currentGraphSubject();
|
|
1213
|
-
// The flushable telemetry handle, created before the first terminal path can reach it. The
|
|
1214
|
-
// graph's own size is filled in once it is pinned; until then the open record and a crash carry
|
|
1215
|
-
// zeros rather than a guess.
|
|
1216
996
|
const telemetrySurface = { home: directory, config, ...(accountSubject ? { subject: accountSubject } : {}), surface: configuredSurface('cli') };
|
|
1217
997
|
const telemetryHandle = createRunHandle(telemetryRunId, startedAt, {
|
|
1218
998
|
graphId: runGraphSelection, nodes: 0, subagents: false, permissionMode: state.permissions,
|
|
@@ -1221,32 +1001,22 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1221
1001
|
let telemetryFinished = false;
|
|
1222
1002
|
let telemetryStart;
|
|
1223
1003
|
let telemetrySettled = Promise.resolve();
|
|
1224
|
-
// One start per run, and the finish waits for it: a preflight failure reaches the finish before
|
|
1225
|
-
// the normal start site, and emitting the finish alone would leave a run with no start.
|
|
1226
1004
|
const startTelemetry = () => {
|
|
1227
1005
|
telemetryStart ??= reportRunStarted(telemetrySurface, telemetryHandle).catch(() => { });
|
|
1228
1006
|
return telemetryStart;
|
|
1229
1007
|
};
|
|
1230
|
-
// Preflight probes are billed requests this attempt made, so they get their own model tuples:
|
|
1231
|
-
// without one, `models[].requests` and the token totals omit every probe, and a run that failed
|
|
1232
|
-
// the health check alone would report no model at all.
|
|
1233
1008
|
const probeModels = new Map();
|
|
1234
|
-
// Set when the health check was rejected by the provider: the run never reached the graph, so
|
|
1235
|
-
// the finish has to classify it from this evidence rather than from a missing result.
|
|
1236
1009
|
let healthProviderFailed = false;
|
|
1237
1010
|
const finishTelemetry = (status, reason, result) => {
|
|
1238
1011
|
if (telemetryFinished)
|
|
1239
1012
|
return;
|
|
1240
1013
|
telemetryFinished = true;
|
|
1241
|
-
// The probes precede the graph, so their tuples are added to whatever capture the finish
|
|
1242
|
-
// reports; a run with no result still reports them, which is the probe-only failure.
|
|
1243
1014
|
const capture = result?.telemetry ?? createRunTelemetry();
|
|
1244
1015
|
for (const probe of probeModels.values()) {
|
|
1245
1016
|
const provider = config.providers.find(item => item.id === probe.provider);
|
|
1246
1017
|
recordModelUse(capture, {
|
|
1247
1018
|
...(provider === undefined ? {} : { providerType: provider.type, baseUrl: provider.baseUrl }),
|
|
1248
1019
|
model: probe.model, role: 'other', usage: probe.usage,
|
|
1249
|
-
// A probe is a billed request like any other: the user's routing prices cost it too.
|
|
1250
1020
|
...(provider === undefined ? {} : { pricing: pricingFor(config.efficiency?.adaptiveRouting, probe.provider, probe.model) }),
|
|
1251
1021
|
});
|
|
1252
1022
|
}
|
|
@@ -1258,19 +1028,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1258
1028
|
...(result ? { toolCalls: result.toolCalls } : {}),
|
|
1259
1029
|
})).catch(() => { });
|
|
1260
1030
|
};
|
|
1261
|
-
// Any terminal rewrite of this attempt's record keeps its identity fields and folds in the
|
|
1262
|
-
// partial usage accumulated before the failure, so the Runs view never reports a crashed
|
|
1263
|
-
// attempt's model calls as zero while the session totals already count them.
|
|
1264
1031
|
const finalizeRunRecord = async (status, reason) => {
|
|
1265
1032
|
const record = { id: runId, status, reason, graphSelection: runGraphSelection,
|
|
1266
1033
|
...(accountSubject ? { accountSubject } : {}), usage: { ...activeUsage },
|
|
1267
1034
|
...(savedSession ? { sessionId: savedSession.id } : {}), startedAt,
|
|
1268
|
-
// A record that stopped being a live run says when it did. A terminal status alone cannot tell a
|
|
1269
|
-
// closed attempt apart from the open claim of a run that reused this id, and that difference is
|
|
1270
|
-
// what lets a claim left by a failed cleanup be reclaimed instead of holding the session busy.
|
|
1271
1035
|
endedAt: new Date().toISOString(),
|
|
1272
|
-
// The flag a resume consults before it trusts this attempt's conversation: a checkpoint
|
|
1273
|
-
// that could not be written leaves the node to be re-entered from its opening task.
|
|
1274
1036
|
...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
|
|
1275
1037
|
...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }) };
|
|
1276
1038
|
try {
|
|
@@ -1282,44 +1044,15 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1282
1044
|
}
|
|
1283
1045
|
finishTelemetry(status, reason);
|
|
1284
1046
|
};
|
|
1285
|
-
// The attempt ends by landing this process's own session record and only then withdrawing the
|
|
1286
|
-
// open claim that names the run to every engine's mutation guard. Clearing the claim before the
|
|
1287
|
-
// save would let a rename, archive or delete be accepted into the window that save — written
|
|
1288
|
-
// from the record this process captured at start — then silently overwrites, or recreates for a
|
|
1289
|
-
// delete. Until this point the claim keeps the guard's answer true: the run may be finished, but
|
|
1290
|
-
// its record is still the one arriving. On a failed save the open record and the claim both
|
|
1291
|
-
// stay, and startup recovery owns that pair.
|
|
1292
1047
|
const settleRunRecord = async () => {
|
|
1293
1048
|
await persistSession();
|
|
1294
1049
|
await clearOpenRunClaim(directory, runId);
|
|
1295
1050
|
};
|
|
1296
|
-
// The open record names the session and the process that own this attempt, and it lands before
|
|
1297
|
-
// both the cancellation check below and the marker turn: a second engine's startup recovery
|
|
1298
|
-
// must never see the marker before the record that proves the attempt is live — otherwise it
|
|
1299
|
-
// classifies the live attempt as a crash and races its synthesized record against this one,
|
|
1300
|
-
// exactly as the app-server path's ordering prevents. A stop arriving while the first snapshot
|
|
1301
|
-
// is still saving must leave a record the Runs view can find, and the early return finalizes
|
|
1302
|
-
// that record in place. The normal finalizer replaces it too; a crash before then leaves it on
|
|
1303
|
-
// disk, where startup recovery turns it into an interrupted one instead of the run vanishing
|
|
1304
|
-
// with only a journal behind.
|
|
1305
|
-
// The run's own scope and effort ride in the open record too, not only in the result the
|
|
1306
|
-
// finalizer writes: a hard kill leaves this record as the only thing recovery preserves, and a
|
|
1307
|
-
// later resume of an attempt that never finalized rebuilds `$run.input.*`/`$run.state.*` from
|
|
1308
|
-
// it. Persisting them only at the end would make a crashed run resume under a different scope
|
|
1309
|
-
// than the one it was started with — silently dropping or changing mapped inputs.
|
|
1310
|
-
// Kept in a variable because the pinned graph's real shape is stamped into it after preflight:
|
|
1311
|
-
// a crash before finalization then emits an interrupted finish that matches the start instead
|
|
1312
|
-
// of the zeros written here.
|
|
1313
1051
|
const openRecord = {
|
|
1314
1052
|
id: runId, status: 'running', sessionId: savedSession.id, startedAt, pid: process.pid,
|
|
1315
1053
|
graphSelection: runGraphSelection, ...(accountSubject ? { accountSubject } : {}),
|
|
1316
1054
|
graph: { id: state.graph ?? 'default' }, provider: config.provider, model: config.providers.find(p => p.id === config.provider)?.model ?? '',
|
|
1317
|
-
// The producing surface travels with the record: recovery can run on another surface in the
|
|
1318
|
-
// same home, and an interrupted finish must still be labeled with the one that started.
|
|
1319
1055
|
surface: telemetrySurface.surface,
|
|
1320
|
-
// `startSent` stays false until the start is queued: this record is written before graph
|
|
1321
|
-
// loading and the model-health check, and recovery reads the flag to decide whether it owes
|
|
1322
|
-
// the missing start as well as the finish.
|
|
1323
1056
|
telemetry: { runId: telemetryRunId, nodes: 0, subagents: false, jevEnabled: jevOn(), decisionRouting: config.decisions?.mode ?? 'off', permissions: state.permissions, startSent: false },
|
|
1324
1057
|
...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }),
|
|
1325
1058
|
};
|
|
@@ -1327,20 +1060,12 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1327
1060
|
process.stderr.write(`Could not write the open run record: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1328
1061
|
return false;
|
|
1329
1062
|
});
|
|
1330
|
-
// The marker's in-flight claim is only provable through that record: without it recovery would
|
|
1331
|
-
// read the marker as an orphaned crash, so the marker stays unwritten and the run proceeds —
|
|
1332
|
-
// the same order and fallback the app-server start uses.
|
|
1333
|
-
// The saved reading belongs to the newest run: one this session inherited (a fork of a desktop
|
|
1334
|
-
// session) or an earlier run left must not describe the run starting now.
|
|
1335
1063
|
runContext = undefined;
|
|
1336
1064
|
if (savedSession?.context !== undefined)
|
|
1337
1065
|
savedSession = { ...savedSession, context: undefined };
|
|
1338
1066
|
if (openRecordWritten)
|
|
1339
1067
|
await persistSession(task, runId, attachments?.refs);
|
|
1340
1068
|
if (active.signal.aborted || exiting) {
|
|
1341
|
-
// Cancellation can arrive while the accepted prompt is still being saved,
|
|
1342
|
-
// before the graph's try/finally owns cleanup. Retain the cancelled turn and
|
|
1343
|
-
// clear its pending state before persisting the idle browser snapshot.
|
|
1344
1069
|
await finalizeRunRecord('cancelled', 'the user stopped this run');
|
|
1345
1070
|
rememberTurn(task, outcomeCompletion('cancelled', undefined, undefined), runId, attachments?.refs);
|
|
1346
1071
|
browserDraining = true;
|
|
@@ -1355,10 +1080,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1355
1080
|
}
|
|
1356
1081
|
updateTitle();
|
|
1357
1082
|
terminal?.setStatus({ session: savedSession.name });
|
|
1358
|
-
// The node's furthest conversation, persisted as it is reached so a stopped run leaves a
|
|
1359
|
-
// resumable checkpoint (`run.resume` in the app-server re-enters it). Writes serialize —
|
|
1360
|
-
// concurrent branches must not leave an older conversation as the file's final content — and
|
|
1361
|
-
// a failure only costs durability, never the run.
|
|
1362
1083
|
let checkpointWrites = Promise.resolve();
|
|
1363
1084
|
const persistCheckpoint = (nodeId, messages, state, meta) => {
|
|
1364
1085
|
checkpointWrites = checkpointWrites
|
|
@@ -1367,18 +1088,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1367
1088
|
await checkpointHealth.failed({ nodeId, generation: meta?.generation }, error);
|
|
1368
1089
|
process.stderr.write(`Could not write the run checkpoint: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1369
1090
|
});
|
|
1370
|
-
// The write is handed back so the runtime can await it: the checkpoint is the conversation a
|
|
1371
|
-
// resume re-enters the node with, and a run that advanced past a mutating tool call while its
|
|
1372
|
-
// checkpoint was still queued could be killed with that conversation unwritten.
|
|
1373
1091
|
return checkpointWrites;
|
|
1374
1092
|
};
|
|
1375
|
-
// Interactive runs stream the model's reasoning into the terminal's live preview
|
|
1376
|
-
// line. The wrap sits outside the trajectory so reasoning deltas never reach run
|
|
1377
|
-
// records. Subagent calls are excluded, and so are calls that arrive while another
|
|
1378
|
-
// previewing call is in flight: concurrent graph branches and parallel modifier
|
|
1379
|
-
// copies carry no subagentId, and several streams sharing one preview line would
|
|
1380
|
-
// interleave and flicker. The flag is claimed synchronously before the first await,
|
|
1381
|
-
// so exactly one concurrent call ever owns the preview.
|
|
1382
1093
|
let previewInFlight = false;
|
|
1383
1094
|
const tracedAdapter = (provider) => {
|
|
1384
1095
|
if (provider.apiKey)
|
|
@@ -1391,11 +1102,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1391
1102
|
return {
|
|
1392
1103
|
...(traced.listModels ? { listModels: (signal) => traced.listModels(signal) } : {}),
|
|
1393
1104
|
async generate(request) {
|
|
1394
|
-
// Every runtime call, previewing or not, feeds the footer's speed readout as it
|
|
1395
|
-
// streams, so a long thinking stream moves the number instead of holding it until
|
|
1396
|
-
// usage arrives. A new attempt or a failure drops the estimate; a success leaves it
|
|
1397
|
-
// for the usage delta to replace, so the reading does not flick back to the old
|
|
1398
|
-
// average in between. Calls without an invocation id (health probes) are not metered.
|
|
1399
1105
|
const invocationId = request.context?.invocationId;
|
|
1400
1106
|
const metered = meterStreamedRequest(request, terminal);
|
|
1401
1107
|
const generate = async (call) => {
|
|
@@ -1412,8 +1118,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1412
1118
|
return generate(metered);
|
|
1413
1119
|
previewInFlight = true;
|
|
1414
1120
|
terminal.clearThinking();
|
|
1415
|
-
// Each HTTP attempt retraces the preview, so a retried stream replaces the
|
|
1416
|
-
// failed attempt's text instead of concatenating with it.
|
|
1417
1121
|
try {
|
|
1418
1122
|
return await generate({
|
|
1419
1123
|
...metered,
|
|
@@ -1429,14 +1133,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1429
1133
|
};
|
|
1430
1134
|
};
|
|
1431
1135
|
await writeActivity(directory, 'running', { detail: task, runId });
|
|
1432
|
-
// Back to running after a prompt, unless the user paused the run while it waited; paused
|
|
1433
|
-
// runs are themselves waiting on the user's next message.
|
|
1434
1136
|
const runResumed = () => runControl?.isPaused
|
|
1435
1137
|
? writeActivity(directory, 'awaiting-input', { kind: 'steering', detail: 'Paused - send a message in the terminal to steer the run', runId })
|
|
1436
1138
|
: writeActivity(directory, 'running', { runId });
|
|
1437
1139
|
runControl = terminal ? new RunControl() : undefined;
|
|
1438
|
-
// A fresh control cannot hold a timer resume, so a latch left set by a run that ended
|
|
1439
|
-
// between the resume and its next poll must not hold this run's first due batch.
|
|
1440
1140
|
timerResumePending = false;
|
|
1441
1141
|
if (runControl) {
|
|
1442
1142
|
runControl.yolo = state.yolo;
|
|
@@ -1452,10 +1152,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1452
1152
|
void writeActivity(directory, 'running', { runId });
|
|
1453
1153
|
});
|
|
1454
1154
|
let liveCommands = Promise.resolve();
|
|
1155
|
+
const livePicker = new AbortController();
|
|
1455
1156
|
terminal?.setRunInputHandler(text => {
|
|
1456
|
-
// Composer input during a run bypasses the question loop, so it gets no outer
|
|
1457
|
-
// command pair: steering text gets a single marker (delivery is traced by
|
|
1458
|
-
// agent.messages.injected), while the live commands below keep full timing records.
|
|
1459
1157
|
if (!text.startsWith('/')) {
|
|
1460
1158
|
void debugRecord('command.steer', { input: text });
|
|
1461
1159
|
return runControl?.isPaused ? runControl.resume(text) : false;
|
|
@@ -1469,7 +1167,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1469
1167
|
return true;
|
|
1470
1168
|
}
|
|
1471
1169
|
if (command === '/attach') {
|
|
1472
|
-
// Mid-run, an attachment rides the next steer rather than a new task.
|
|
1473
1170
|
void debugRecord('command.steer', { input: text });
|
|
1474
1171
|
const argument = text.slice('/attach'.length).trim().replace(/^"(.*)"$/, '$1');
|
|
1475
1172
|
const target = argument ? resolve(workspace, argument) : '';
|
|
@@ -1486,13 +1183,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1486
1183
|
}
|
|
1487
1184
|
const commandStartedAt = Date.now();
|
|
1488
1185
|
void debugRecord('command.started', { input: text, mode: 'in-run' });
|
|
1489
|
-
// Create each command's draft only after prior saves and live updates finish.
|
|
1490
|
-
// Even status commands must queue: executeCommand commits their draft too.
|
|
1491
1186
|
liveCommands = liveCommands.then(async () => {
|
|
1492
1187
|
if (command === '/browser') {
|
|
1493
1188
|
browserApp ??= await startBrowserServer();
|
|
1494
|
-
// Teardown can pass the cleanup loop while this startup is pending;
|
|
1495
|
-
// a server that finishes after exiting must neither open nor linger.
|
|
1496
1189
|
if (exiting)
|
|
1497
1190
|
await browserApp.close().catch(() => { });
|
|
1498
1191
|
else {
|
|
@@ -1500,9 +1193,32 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1500
1193
|
openBrowserUrl(browserApp.url);
|
|
1501
1194
|
}
|
|
1502
1195
|
}
|
|
1196
|
+
else if (text.trim() === '/permissions' && terminal) {
|
|
1197
|
+
const before = state.permissions;
|
|
1198
|
+
let picked;
|
|
1199
|
+
try {
|
|
1200
|
+
picked = await pickPermissionMode(state, terminal, livePicker.signal, { yieldToQuestions: true });
|
|
1201
|
+
}
|
|
1202
|
+
catch (error) {
|
|
1203
|
+
if (!(error instanceof Error && error.name === 'AbortError'))
|
|
1204
|
+
throw error;
|
|
1205
|
+
if (!livePicker.signal.aborted)
|
|
1206
|
+
print('Permissions unchanged: the run asked a question, so the picker closed. Type /permissions again afterwards.');
|
|
1207
|
+
}
|
|
1208
|
+
if (picked !== undefined && !livePicker.signal.aborted)
|
|
1209
|
+
await executeCommand(`/permissions ${picked}`, state, persistConfig);
|
|
1210
|
+
if (state.permissions !== before) {
|
|
1211
|
+
if (runControl) {
|
|
1212
|
+
runControl.yolo = state.yolo;
|
|
1213
|
+
runControl.permissions = state.permissions;
|
|
1214
|
+
}
|
|
1215
|
+
if (state.yolo)
|
|
1216
|
+
approvePending?.();
|
|
1217
|
+
print(`Permissions: ${permissionLabel(state.permissions ?? 'ask-for-approval')} (remembered for this workspace).`);
|
|
1218
|
+
refreshStatus();
|
|
1219
|
+
}
|
|
1220
|
+
}
|
|
1503
1221
|
else {
|
|
1504
|
-
// `/jev` saves at once but the run keeps the decision policy it started with; the reply says so.
|
|
1505
|
-
// The spread shares `state.config`, so the saved value lands on the session's configuration.
|
|
1506
1222
|
const commandState = command === '/usage' ? { ...state, usage: sessionUsage() } : command === '/jev' ? { ...state, running: true } : state;
|
|
1507
1223
|
const result = await executeCommand(text, commandState, persistConfig);
|
|
1508
1224
|
afterJevCommand(text, result);
|
|
@@ -1527,22 +1243,17 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1527
1243
|
return true;
|
|
1528
1244
|
});
|
|
1529
1245
|
terminal?.startTask();
|
|
1530
|
-
// A run's own preflight and teardown both change what the working tree holds.
|
|
1531
1246
|
refreshPanelStatus(true);
|
|
1532
1247
|
const retainedTodos = continuedTodos(task, state.lastRun);
|
|
1533
1248
|
const todoStore = new TodoStore();
|
|
1534
1249
|
if (retainedTodos.length)
|
|
1535
1250
|
todoStore.update(retainedTodos);
|
|
1536
1251
|
toolActivity.clear();
|
|
1537
|
-
// A short "Continue"/"Resume" after an unfinished run is the same work. Keep the
|
|
1538
|
-
// previous plan visible and seed it into the new graph run until the agent updates it.
|
|
1539
1252
|
if (retainedTodos.length)
|
|
1540
1253
|
terminal?.setTodos(retainedTodos);
|
|
1541
1254
|
else
|
|
1542
1255
|
terminal?.setTodos([]);
|
|
1543
1256
|
terminal?.setStatus({ activity: 'Thinking' });
|
|
1544
|
-
// Interactive runs keep the composer live so the user can steer the run in place;
|
|
1545
|
-
// approved/clarification questions still take precedence over steering.
|
|
1546
1257
|
terminal?.setSteering(true);
|
|
1547
1258
|
const selected = config.providers.find(p => p.id === config.provider);
|
|
1548
1259
|
const preflight = async (operation) => {
|
|
@@ -1563,21 +1274,17 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1563
1274
|
};
|
|
1564
1275
|
let mcp;
|
|
1565
1276
|
try {
|
|
1566
|
-
// The startup preflight already loaded this selection through the membership gate, so the
|
|
1567
|
-
// initial run reuses it rather than spending a second account-service round trip whose
|
|
1568
|
-
// transient failure could still deny the run. Later runs load again so on-disk graph
|
|
1569
|
-
// edits stay observable mid-session; a graph refresh arms one more reuse.
|
|
1570
1277
|
const loadedGraph = startupGraph && !startupGraphReused && startupGraphSelection === (state.graph ?? 'default')
|
|
1571
1278
|
? (startupGraphReused = true, startupGraph)
|
|
1572
1279
|
: await preflight(signal => loadGraph(state.graph ?? 'default', signal));
|
|
1573
1280
|
terminal?.setStatus({ activity: 'Checking graph models', backgroundActivity: true });
|
|
1574
1281
|
graphModelsHealthy = false;
|
|
1282
|
+
await modelHealth.load();
|
|
1575
1283
|
const health = await preflight(signal => checkGraphHealth(loadedGraph, config, signal, {
|
|
1284
|
+
verified: modelHealth,
|
|
1576
1285
|
onUsage: (delta, reference) => {
|
|
1577
1286
|
const key = `${reference.provider}\0${reference.model}`;
|
|
1578
1287
|
const entry = probeModels.get(key) ?? { provider: reference.provider, model: reference.model, usage: {} };
|
|
1579
|
-
// Only the measurements the provider actually reported are carried, so the tuple keeps
|
|
1580
|
-
// its coverage instead of claiming a measured zero.
|
|
1581
1288
|
for (const field of ['requests', 'inputTokens', 'outputTokens', 'cacheRead', 'cacheWrite']) {
|
|
1582
1289
|
const value = delta[field];
|
|
1583
1290
|
if (typeof value === 'number')
|
|
@@ -1585,8 +1292,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1585
1292
|
}
|
|
1586
1293
|
probeModels.set(key, entry);
|
|
1587
1294
|
},
|
|
1588
|
-
// The probes are model calls this attempt pays for, so they belong in the trajectory
|
|
1589
|
-
// beside the run's own calls.
|
|
1590
1295
|
createAdapter: provider => tracedAdapter(provider),
|
|
1591
1296
|
}));
|
|
1592
1297
|
graphModelsHealthy = health.healthy;
|
|
@@ -1595,44 +1300,36 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1595
1300
|
throw new Error(formatGraphHealthFailure(health));
|
|
1596
1301
|
}
|
|
1597
1302
|
const graph = validateGraph(loadedGraph, { providers: config.providers, defaultProvider: config.provider, spawnAvailable: true });
|
|
1598
|
-
// The pinned graph is known now, so the start carries its real size and delegation shape.
|
|
1599
1303
|
Object.assign(telemetryHandle.dimensions, { graphId: runGraphSelection, ...graphShape(graph) });
|
|
1600
1304
|
const startQueued = startTelemetry();
|
|
1601
1305
|
if (!openRecordWritten)
|
|
1602
1306
|
void startQueued;
|
|
1603
|
-
// Stamp the same shape into the open record, because a crash before finalization is
|
|
1604
|
-
// recovered from that file: zeros there would produce a finish that disagrees with its start.
|
|
1605
|
-
// `startSent` is stamped only once the start is actually queued, so a crash in between is
|
|
1606
|
-
// recovered as a pair rather than as a finish with no start.
|
|
1607
1307
|
if (openRecordWritten) {
|
|
1608
1308
|
await startQueued.catch(() => { });
|
|
1609
1309
|
openRecord.telemetry = { ...openRecord.telemetry, ...graphShape(graph), startSent: telemetryHandle.started !== false };
|
|
1610
1310
|
await writeOpenRunRecord(directory, openRecord).catch(() => { });
|
|
1611
1311
|
}
|
|
1612
|
-
// The in-flight record is created before graph preflight. Once the pinned
|
|
1613
|
-
// revision is known, stamp its small sidecar so live runs can safely show
|
|
1614
|
-
// revision-matched node and edge overlays before finalization.
|
|
1615
1312
|
await writeStudioRunSummary(directory, {
|
|
1616
1313
|
id: runId, status: 'running', startedAt, graphSelection: runGraphSelection,
|
|
1617
1314
|
...(accountSubject ? { accountSubject } : {}),
|
|
1618
1315
|
graph: { id: graph.id, revision: graph.revision }
|
|
1619
1316
|
}).catch(() => { });
|
|
1620
1317
|
terminal?.setStatus({ activity: 'Thinking' });
|
|
1621
|
-
const workspaceGuidance = await preflight(signal => loadWorkspaceInstructions(workspace, signal, config.systemPromptOverride));
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
const invocation = isBuiltinSlashCommand(task) ? undefined : await preflight(signal => resolveSkillInvocation(task, config, signal, directory));
|
|
1625
|
-
// A slash invocation becomes the session's skill; a later message without one inherits it
|
|
1626
|
-
// until the user turns it off with /skill off (see `src/session-skills.ts`).
|
|
1627
|
-
const runSkill = await preflight(signal => skillForRun({ invocation, home: directory, sessionId: savedSession?.id, config, signal }));
|
|
1318
|
+
const workspaceGuidance = await preflight(signal => loadWorkspaceInstructions(workspace, signal, systemPromptOverrideFor(graph, config.systemPromptOverride)));
|
|
1319
|
+
const invocations = isBuiltinSlashCommand(task) ? [] : await preflight(signal => resolveSkillInvocations(task, effectiveExtensionConfig(config, workspace), signal, directory));
|
|
1320
|
+
const runSkill = await preflight(signal => skillForRun({ invocations, home: directory, sessionId: savedSession?.id, config: effectiveExtensionConfig(config, workspace), signal }));
|
|
1628
1321
|
if (runSkill.notice)
|
|
1629
1322
|
terminal ? terminal.print(runSkill.notice) : process.stderr.write(safeTerminal(runSkill.notice) + '\n');
|
|
1630
|
-
const snapshot = await preflight(signal => extensionSnapshot(config, signal, directory, runSkill.skill
|
|
1323
|
+
const snapshot = await preflight(signal => extensionSnapshot(effectiveExtensionConfig(config, workspace), signal, directory, runSkill.skills?.map(skill => skill.id)));
|
|
1631
1324
|
for (const notice of snapshot.notices)
|
|
1632
1325
|
terminal ? terminal.print(notice) : process.stderr.write(safeTerminal(notice) + '\n');
|
|
1633
1326
|
const instructions = `${workspaceGuidance}${snapshot.instructions}`;
|
|
1634
1327
|
const resolvedModels = new Map();
|
|
1328
|
+
const runGoal = state.goal?.status === 'active' ? state.goal : undefined;
|
|
1329
|
+
let goalVerified = false;
|
|
1635
1330
|
const onRunEvent = async (event) => {
|
|
1331
|
+
if (event.type === 'agent.completion.verified' && event.data.source === 'goal_verifier' && !event.data.subagentId)
|
|
1332
|
+
goalVerified = event.data.passed === true;
|
|
1636
1333
|
if (!/reasoning|thinking\.delta/.test(event.type))
|
|
1637
1334
|
browserBridge?.event(trajectory.sanitize(event));
|
|
1638
1335
|
event = { ...event, data: { ...event.data, conversationId: savedSession?.id ?? trajectory.sessionId } };
|
|
@@ -1643,13 +1340,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1643
1340
|
await appendRunEvent(directory, event);
|
|
1644
1341
|
await trajectory.recordEvent(event);
|
|
1645
1342
|
terminal?.setStatus({ session: savedSession?.name ?? trajectory.sessionId });
|
|
1646
|
-
// The executor's own resolution of this node's model is memoized here, so the footer can
|
|
1647
|
-
// follow the node instead of the session's selection.
|
|
1648
1343
|
terminal?.handleRuntimeEvent(await withNodeModelResolution(event, (provider, model) => resolvedModels.get(JSON.stringify([provider, model]))));
|
|
1649
|
-
// Tool boundaries are when the panel's live sections can have moved: a completion may
|
|
1650
|
-
// have written files or ended a background terminal, a start may have opened one. These
|
|
1651
|
-
// stay on the summary's own throttle - a tool-heavy run would otherwise spawn a git
|
|
1652
|
-
// process per tool - while the run boundaries above force the read.
|
|
1653
1344
|
if (event.type === 'node.tool.started' || event.type === 'node.tool.completed' || event.type === 'node.tool.failed')
|
|
1654
1345
|
refreshPanelStatus();
|
|
1655
1346
|
if (terminal && event.type === 'graph.todos.updated') {
|
|
@@ -1666,9 +1357,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1666
1357
|
const entry = formatEvent(event);
|
|
1667
1358
|
if (entry) {
|
|
1668
1359
|
if (terminal)
|
|
1669
|
-
terminal.print(entry.text, entry.detail, entry.toolCall, false, /failed|error|stopped/.test(event.type));
|
|
1670
|
-
// The plain path has no Ctrl+O, so an agent message whose code block collapsed into
|
|
1671
|
-
// `detail` must print the full rendering, not the truncated summary.
|
|
1360
|
+
terminal.print(entry.text, entry.detail, entry.toolCall, false, /failed|error|stopped/.test(event.type), false, entry.clipRows);
|
|
1672
1361
|
else if (event.type === 'agent.message' && entry.detail)
|
|
1673
1362
|
print(staticToolTimestamp(entry.detail, entry.toolCall));
|
|
1674
1363
|
else
|
|
@@ -1705,7 +1394,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1705
1394
|
}
|
|
1706
1395
|
} };
|
|
1707
1396
|
const mcpModule = await import('./mcp.js');
|
|
1708
|
-
// How each server answered is recorded, so the desktop's MCP page can show it without starting it.
|
|
1709
1397
|
return mcpModule.connectMcpServers(snapshot.servers, extensionContext, message => terminal ? terminal.print(message) : process.stderr.write(safeTerminal(message) + '\n'), active.signal, { status: mcpModule.mcpTaskStatusReporter(configDirectory()) });
|
|
1710
1398
|
}) : { tools: [], close: async () => { } };
|
|
1711
1399
|
if (terminal) {
|
|
@@ -1723,14 +1411,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1723
1411
|
}
|
|
1724
1412
|
refreshStatus();
|
|
1725
1413
|
}
|
|
1726
|
-
// A cancelled metadata lookup must not create a graph run after preflight.
|
|
1727
1414
|
active.signal.throwIfAborted();
|
|
1728
1415
|
let membership = !jevOn() ? { paid: false } : await preflight(signal => getMembership(signal));
|
|
1729
1416
|
if (jevOn() && !membership.subject && membership.unavailable) {
|
|
1730
|
-
// The lookup has a five-second budget and the account service cold-starts past it after a
|
|
1731
|
-
// quiet spell; the second lookup then answers in well under a second. Without the retry
|
|
1732
|
-
// Jev is off for the whole run and nothing says so (7 of 12 Jev runs in the 2026-11-01
|
|
1733
|
-
// A/B ran without a single decision round).
|
|
1734
1417
|
membership = await preflight(signal => getMembership(signal));
|
|
1735
1418
|
}
|
|
1736
1419
|
if (jevOn() && !membership.subject) {
|
|
@@ -1746,8 +1429,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1746
1429
|
jevEnabled = jevOn();
|
|
1747
1430
|
terminal?.setStatus({ graph, jevEnabled });
|
|
1748
1431
|
const commandMemory = config.commandMemory === false ? undefined : await LocalToolMemory.open({ workspace, directory });
|
|
1749
|
-
const
|
|
1750
|
-
|
|
1432
|
+
const projectMemory = config.projectMemory === false ? undefined : await ProjectMemory.open({ home: directory, workspace });
|
|
1433
|
+
const execute = (options) => runGraph(graph, { ...options, runInput, runState, commandMemory, projectMemory, todoStore,
|
|
1434
|
+
...(runSkill.skills?.length ? { inheritedSkills: runSkill.skills.map(skill => skill.id), skillInvocationInstruction: runSkill.instruction } : {}),
|
|
1751
1435
|
resolveModel: (id, model) => {
|
|
1752
1436
|
const provider = config.providers.find(item => item.id === id);
|
|
1753
1437
|
if (!provider)
|
|
@@ -1773,8 +1457,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1773
1457
|
},
|
|
1774
1458
|
});
|
|
1775
1459
|
const result = await execute({ task, runId, provider: selected.id, model: selected.model, ...(attachments ? { attachments } : {}),
|
|
1460
|
+
...(runGoal ? { goalCompletionVerification: { goal: runGoal.text } } : {}),
|
|
1776
1461
|
...(config.efficiency ? { efficiency: config.efficiency } : {}),
|
|
1777
|
-
|
|
1462
|
+
...(terminal ? {} : { toolProfile: isToolProfile(values.tools) ? values.tools : config.toolProfile }),
|
|
1778
1463
|
modelPinned: Boolean(values.model || values.provider),
|
|
1779
1464
|
configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
|
|
1780
1465
|
onNodeCheckpoint: persistCheckpoint,
|
|
@@ -1784,43 +1469,20 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1784
1469
|
activeUsage.outputTokens += usage.outputTokens;
|
|
1785
1470
|
activeUsage.cacheRead += usage.cacheRead ?? 0;
|
|
1786
1471
|
activeUsage.cacheWrite += usage.cacheWrite ?? 0;
|
|
1787
|
-
// The delta's input size is the live conversation: every request resends the
|
|
1788
|
-
// whole context, so the latest measured one shows how full the window currently
|
|
1789
|
-
// is. Deltas that carry no measurement - transport attempts, a completion whose
|
|
1790
|
-
// provider omitted usage, a failed request's close signal - report zeros by
|
|
1791
|
-
// design, and treating them as a context size would wipe the last real estimate
|
|
1792
|
-
// (model-backed distillation runs last, so its no-usage close would otherwise
|
|
1793
|
-
// leave the idle footer at `context: 0%`).
|
|
1794
1472
|
if (usage.inputTokens > 0) {
|
|
1795
1473
|
contextUsedTokens = usage.inputTokens;
|
|
1796
1474
|
runContext = { usedTokens: usage.inputTokens, ...(usage.cacheRead === undefined ? {} : { cacheRead: usage.cacheRead }) };
|
|
1797
1475
|
}
|
|
1798
|
-
// The same per-request delta feeds the footer speed readout. Providers report a
|
|
1799
|
-
// request's tokens only as it completes, so this is the number credited to the
|
|
1800
|
-
// window that produced it - the streamed decode window when the adapter measured
|
|
1801
|
-
// one, so prompt processing does not count as generating time; the origin's
|
|
1802
|
-
// invocation id names that request, so a completion pairs with its own window even
|
|
1803
|
-
// when concurrent requests finish out of order. Diffing the cumulative totals
|
|
1804
|
-
// instead would smear or drop it in a graph whose nodes each report their own totals.
|
|
1805
1476
|
terminal?.noteGeneratedTokens(usage.outputTokens, origin?.invocationId, origin?.final === true, usage.decodeMs);
|
|
1806
1477
|
terminal?.setStatus(sessionUsage());
|
|
1807
1478
|
},
|
|
1808
|
-
adapter: tracedAdapter(runtimeProvider(selected)), tools: [...createTools(), ...snapshot.tools, ...mcp.tools], installedSkillClaims: snapshot.claimsSkillName, history: state.history, instructions, codeIntel, ...decisionPolicy,
|
|
1809
|
-
// Installation-wide bounds. Nothing is set by default, which leaves the run with no
|
|
1810
|
-
// wall clock and no iteration ceiling; a graph or node bound still narrows these.
|
|
1479
|
+
adapter: tracedAdapter(runtimeProvider(selected)), tools: [...(await loadTools()).createTools(), ...snapshot.tools, ...mcp.tools], installedSkillClaims: snapshot.claimsSkillName, history: state.history, instructions, codeIntel, ...decisionPolicy,
|
|
1811
1480
|
limits: resolveConfiguredLimits(config),
|
|
1812
|
-
// Polled at turn boundaries: each queued steer becomes a user message in the live
|
|
1813
|
-
// conversation, so the run redirects without restarting or losing its context.
|
|
1814
1481
|
getSteeringMessages: terminal ? async () => {
|
|
1815
1482
|
if (exiting)
|
|
1816
1483
|
return [];
|
|
1817
1484
|
deliverTimerPrompts();
|
|
1818
|
-
// Release held timer prompts only after the poll that carried a timer's resume
|
|
1819
|
-
// direction: this poll runs immediately before prepareTurn injects those directions,
|
|
1820
|
-
// so prompts released from the next poll onward reach the model strictly later.
|
|
1821
1485
|
timerResumePending = false;
|
|
1822
|
-
// A steered turn carries its own attachments: each queued steer is one user message,
|
|
1823
|
-
// so its files and images are resolved against that steer alone, never pooled.
|
|
1824
1486
|
const steered = terminal.takeSteeringTurns();
|
|
1825
1487
|
const messages = [];
|
|
1826
1488
|
for (const turn of steered) {
|
|
@@ -1834,8 +1496,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1834
1496
|
attachmentSpools.add(root);
|
|
1835
1497
|
steeredSpools.add(root);
|
|
1836
1498
|
}
|
|
1837
|
-
// An attachment-only steer arrives with empty text; the stand-in names what the
|
|
1838
|
-
// chips carry, exactly as an attachment-only task does (ATTACHMENT_ONLY_TASK).
|
|
1839
1499
|
messages.push({ role: 'user', content: `${turn.text || ATTACHMENT_ONLY_TASK}\n\n${attachmentReferenceBlock(resolved.refs)}`, ...(resolved.images.length ? { images: resolved.images } : {}) });
|
|
1840
1500
|
}
|
|
1841
1501
|
catch (error) {
|
|
@@ -1846,9 +1506,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1846
1506
|
return messages;
|
|
1847
1507
|
} : undefined,
|
|
1848
1508
|
context: { workspace, signal: active.signal, runControl, timers: terminal ? sessionTimers : undefined,
|
|
1849
|
-
// Both terminal surfaces create future work through this context. Carry the run's
|
|
1850
|
-
// selections, including CLI overrides; the graph selector must retain 'default'
|
|
1851
|
-
// rather than the resolved harness id so replay follows the same access rules.
|
|
1852
1509
|
automationDirectory: directory,
|
|
1853
1510
|
wakeCarry: { provider: selected.id, model: selected.model, graph: runGraphSelection,
|
|
1854
1511
|
...(selected.reasoningEffort === undefined ? {} : { reasoningEffort: selected.reasoningEffort }) },
|
|
@@ -1870,11 +1527,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1870
1527
|
await runResumed();
|
|
1871
1528
|
}
|
|
1872
1529
|
} : undefined,
|
|
1873
|
-
// Approving a plan flips this session only, the way the engine's own flip does: the saved
|
|
1874
|
-
// workspace default keeps planning the next task, so the footer follows the live mode and
|
|
1875
|
-
// the configuration is never touched. The control is updated with the state, exactly as
|
|
1876
|
-
// `/permissions` does mid-run — `permissionMode()` reads the control first, so a flip of
|
|
1877
|
-
// the state alone would leave every tool still refused.
|
|
1878
1530
|
approvePlan: terminal ? async () => {
|
|
1879
1531
|
const saved = state.config.workspacePermissions?.[workspacePermissionKey(workspace)];
|
|
1880
1532
|
const next = saved === 'ask-for-approval' || saved === 'approve-for-me' || saved === 'full-access' ? saved : 'ask-for-approval';
|
|
@@ -1884,7 +1536,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1884
1536
|
runControl.yolo = state.yolo;
|
|
1885
1537
|
runControl.permissions = state.permissions;
|
|
1886
1538
|
}
|
|
1887
|
-
// An editing mode by construction, so the index resumes if plan mode had suspended it.
|
|
1888
1539
|
await state.codeIntel?.setPermissions(next);
|
|
1889
1540
|
terminal.setStatus({ permissions: permissionLabel(state.permissions), ...sessionUsage() });
|
|
1890
1541
|
return next;
|
|
@@ -1923,19 +1574,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1923
1574
|
state.usage.outputTokens += result.usage.outputTokens;
|
|
1924
1575
|
foldCache(state.usage, result.usage.cacheRead, result.usage.cacheWrite);
|
|
1925
1576
|
activeUsage = { inputTokens: 0, outputTokens: 0, requests: 0, cacheRead: 0, cacheWrite: 0 };
|
|
1926
|
-
// Let the last checkpoint land before the record and the cleanup below decide whether one
|
|
1927
|
-
// survives: deleting while a write was in flight would recreate the file a succeeded run is
|
|
1928
|
-
// meant to leave behind nothing to resume.
|
|
1929
1577
|
await checkpointWrites;
|
|
1930
|
-
// The final record keeps the open record's identity fields: recovery and the Runs view key a
|
|
1931
|
-
// run by its session and start time, and the finalizer replaces the open record in place.
|
|
1932
1578
|
const finishedRecord = { ...result, graphSelection: runGraphSelection,
|
|
1933
1579
|
...(accountSubject ? { accountSubject } : {}),
|
|
1934
1580
|
...(savedSession ? { sessionId: savedSession.id } : {}), startedAt,
|
|
1935
|
-
// The stamp the mutation guard needs to tell a closed attempt from a live claim of the same run id.
|
|
1936
1581
|
endedAt: new Date().toISOString(),
|
|
1937
|
-
// The flag a resume consults before it trusts this attempt's conversation: a checkpoint
|
|
1938
|
-
// that could not be written leaves the node to be re-entered from its opening task.
|
|
1939
1582
|
...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
|
|
1940
1583
|
...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }) };
|
|
1941
1584
|
await writeFile(runRecordPath(directory, result.id, 'json'), JSON.stringify(finishedRecord, null, 2) + '\n', { mode: 0o600 });
|
|
@@ -1946,20 +1589,16 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1946
1589
|
graph: { id: result.graph.id, revision: typeof result.graph.revision === 'number' ? result.graph.revision : undefined },
|
|
1947
1590
|
toolCalls: result.toolCalls
|
|
1948
1591
|
}).catch(() => { });
|
|
1949
|
-
// A multi-node graph can finish an early node and stop in a later one, keeping that node's
|
|
1950
|
-
// completion on a non-success result; the status is the attempt's last word, so stamp it.
|
|
1951
1592
|
rememberTurn(task, { ...(result.completion ?? outcomeCompletion(result.status, result.reason, result.limits)), ...(result.status === 'succeeded' ? {} : { status: result.status }) }, runId, attachments?.refs);
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1593
|
+
const goalMet = runGoal !== undefined && goalVerified && result.status === 'succeeded' && state.goal === runGoal;
|
|
1594
|
+
if (goalMet) {
|
|
1595
|
+
state.goal = metSessionGoal(runGoal);
|
|
1596
|
+
terminal?.setStatus({ goal: state.goal });
|
|
1597
|
+
}
|
|
1955
1598
|
if (savedSession)
|
|
1956
1599
|
savedSession = { ...savedSession, widgets: result.widgets, context: runContext };
|
|
1957
|
-
// A finished run has nothing to resume: only stopped attempts keep a durable checkpoint.
|
|
1958
1600
|
if (result.status === 'succeeded') {
|
|
1959
1601
|
await removeRunCheckpoint(directory, result.id);
|
|
1960
|
-
// Nothing resumes a finished run, and only the opening turn's refs are persisted — a
|
|
1961
|
-
// steer's spools have no reader left once its checkpoint is gone. Until then (stopped,
|
|
1962
|
-
// failed) they stay: the checkpoint's conversation still names those files.
|
|
1963
1602
|
await Promise.all([...steeredSpools].map(root => rm(root, { recursive: true, force: true }).catch(() => { })));
|
|
1964
1603
|
}
|
|
1965
1604
|
if (values.json)
|
|
@@ -1967,8 +1606,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1967
1606
|
else {
|
|
1968
1607
|
const summary = result.completion?.summary ?? (result.status === 'cancelled' ? 'Cancelled.' : `The run did not finish: ${stopReasonPhrase(result.reason, result.limits)}.`);
|
|
1969
1608
|
if (terminal) {
|
|
1970
|
-
// The summary is markdown like every agent message: render it, and keep a collapsed
|
|
1971
|
-
// code block's full text behind Ctrl+O instead of printing fences verbatim.
|
|
1972
1609
|
const entry = formatRunResult({ id: result.id, status: result.status, summary, tests: result.completion?.tests });
|
|
1973
1610
|
terminal.print(entry.text, entry.detail, undefined, true);
|
|
1974
1611
|
}
|
|
@@ -1979,38 +1616,28 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
1979
1616
|
print(` ${check}`);
|
|
1980
1617
|
if (!terminal)
|
|
1981
1618
|
print(`Run ${result.id} · ${result.status}`);
|
|
1619
|
+
if (goalMet)
|
|
1620
|
+
print(`Goal met: ${runGoal.text}`);
|
|
1982
1621
|
}
|
|
1983
1622
|
return terminated ? 143 : result.status === 'succeeded' ? 0 : result.status === 'cancelled' ? 130 : 1;
|
|
1984
1623
|
}
|
|
1985
1624
|
catch (error) {
|
|
1986
|
-
// An attempt that never reached `runGraph` still owns its open record: leaving it `running`
|
|
1987
|
-
// tells the Runs view a task is working until the process dies, and recovery then calls a
|
|
1988
|
-
// deliberate stop a crash. Replace it with the outcome this path actually knows — the shared
|
|
1989
|
-
// finalizer carries the identity fields and whatever usage the run had already spent.
|
|
1990
1625
|
if (active?.signal.aborted) {
|
|
1991
1626
|
await finalizeRunRecord('cancelled', 'the user stopped this run');
|
|
1992
1627
|
rememberTurn(task, outcomeCompletion('cancelled', undefined, undefined), runId, attachments?.refs);
|
|
1993
1628
|
return terminated ? 143 : 130;
|
|
1994
1629
|
}
|
|
1995
|
-
// A crash is an attempt too. Record it before rethrowing so the caller's error report
|
|
1996
|
-
// does not also cost the user the context of what they asked for.
|
|
1997
1630
|
await finalizeRunRecord('infrastructure_error', error instanceof Error ? error.message : 'the run failed unexpectedly');
|
|
1998
1631
|
rememberTurn(task, outcomeCompletion('infrastructure_error', error instanceof Error ? error.message : 'the run failed unexpectedly', undefined), runId, attachments?.refs);
|
|
1999
1632
|
throw error;
|
|
2000
1633
|
}
|
|
2001
1634
|
finally {
|
|
2002
1635
|
browserDraining = true;
|
|
2003
|
-
// Stop accepting live commands before draining; idle commands must not race
|
|
2004
|
-
// a permission save accepted just before the run completed.
|
|
2005
1636
|
terminal?.setRunInputHandler(undefined);
|
|
2006
|
-
|
|
2007
|
-
// pending write itself has to finish before the process moves on; the chain never rejects.
|
|
1637
|
+
livePicker.abort();
|
|
2008
1638
|
await checkpointWrites;
|
|
2009
1639
|
await liveCommands;
|
|
2010
|
-
// A crashed run's partial provider spend still happened: fold it into the session
|
|
2011
1640
|
await mcp?.close();
|
|
2012
|
-
// totals before the live counter resets, or a crashed command's usage vanishes from
|
|
2013
|
-
// /usage and the --debug summary even though the journal recorded the model calls.
|
|
2014
1641
|
state.usage.requests += activeUsage.requests;
|
|
2015
1642
|
state.usage.inputTokens += activeUsage.inputTokens;
|
|
2016
1643
|
state.usage.outputTokens += activeUsage.outputTokens;
|
|
@@ -2018,10 +1645,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2018
1645
|
activeUsage = { inputTokens: 0, outputTokens: 0, requests: 0, cacheRead: 0, cacheWrite: 0 };
|
|
2019
1646
|
terminal?.finishTask();
|
|
2020
1647
|
runEventSink = undefined;
|
|
2021
|
-
// The run is over: detach its live state before the awaited cleanup below, so a
|
|
2022
|
-
// Ctrl+C landing during slow cleanup I/O reads as idle and exits instead of pausing
|
|
2023
|
-
// a run that no longer exists (and the pause listener cannot re-attach to claim
|
|
2024
|
-
// input is needed when nothing is listening anymore).
|
|
2025
1648
|
removeControlListener?.();
|
|
2026
1649
|
runControl = undefined;
|
|
2027
1650
|
approvePending = undefined;
|
|
@@ -2030,7 +1653,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2030
1653
|
awaitingInput = 0;
|
|
2031
1654
|
updateTitle(false);
|
|
2032
1655
|
await settleRunRecord();
|
|
2033
|
-
// Deliver what this run queued before the process leaves; a no-op while no endpoint exists.
|
|
2034
1656
|
await telemetrySettled;
|
|
2035
1657
|
await sessionStarted;
|
|
2036
1658
|
await drainTelemetry(telemetrySurface);
|
|
@@ -2044,18 +1666,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2044
1666
|
}
|
|
2045
1667
|
await writeActivity(directory, 'idle');
|
|
2046
1668
|
refreshStatus();
|
|
2047
|
-
// Release the composer back to the normal question flow before the next prompt. A steer
|
|
2048
|
-
// submitted after the executor's final poll has nowhere to go; say so rather than
|
|
2049
|
-
// dropping text the user watched being accepted.
|
|
2050
1669
|
for (const undelivered of terminal?.setSteering(false) ?? []) {
|
|
2051
|
-
// An attachment-only steer returns empty text: its chips went back to the queue, where
|
|
2052
|
-
// they are visible, so a blank "Not delivered" line would report nothing at all.
|
|
2053
1670
|
if (undelivered)
|
|
2054
1671
|
terminal?.print(`Not delivered — the run had already finished: ${undelivered}`);
|
|
2055
1672
|
}
|
|
2056
|
-
// A timer prompt that queued as steering after the executor's final poll still owes its
|
|
2057
|
-
// delivery: it goes back to `timerPending` so the next composer hand-off runs it as a
|
|
2058
|
-
// fresh task rather than dropping a wake-up the agent asked for.
|
|
2059
1673
|
for (const queued of timerSteering.splice(0))
|
|
2060
1674
|
timerPending.push(queued);
|
|
2061
1675
|
if (terminal)
|
|
@@ -2068,9 +1682,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2068
1682
|
};
|
|
2069
1683
|
try {
|
|
2070
1684
|
if (values.prompt !== undefined) {
|
|
1685
|
+
enablePrivateRunTemp();
|
|
2071
1686
|
if (!values.json)
|
|
2072
1687
|
print(sessionDescription());
|
|
2073
|
-
// Machine consumers keep stdout pure JSON, so the debug log location goes to stderr.
|
|
2074
1688
|
else if (values.debug)
|
|
2075
1689
|
process.stderr.write(safeTerminal(sessionDescription()) + '\n');
|
|
2076
1690
|
const commandStartedAt = Date.now();
|
|
@@ -2083,17 +1697,17 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2083
1697
|
throw error;
|
|
2084
1698
|
}
|
|
2085
1699
|
finally {
|
|
1700
|
+
removePrivateRunTemp();
|
|
2086
1701
|
await debugRecord('command.completed', { input: values.prompt, mode: 'headless', durationMs: Date.now() - commandStartedAt });
|
|
2087
1702
|
}
|
|
2088
1703
|
}
|
|
2089
1704
|
terminal.start();
|
|
1705
|
+
bootMark('cli.started');
|
|
2090
1706
|
browserBridge = await createBrowserBridge(directory, () => {
|
|
2091
1707
|
const snapshot = {
|
|
2092
1708
|
...(savedSession ?? { version: 1, id: trajectory.sessionId, name: 'New CLI session', workspace, updatedAt: new Date(sessionStartedAt).toISOString(), history: [], usage: { ...state.usage } }),
|
|
2093
1709
|
projectId: projectIdentity(workspace), contextHistory: structuredClone(state.history ?? []), history: sessionArchive, status: browserDraining || (browserPrompt && browserCancelPending) ? 'cancelling' : browserPrompt || (runControl && active) ? active?.signal.aborted ? 'cancelling' : 'running' : 'idle', prompt: browserPrompt, events: [], pending: runControl && active && !active.signal.aborted ? terminal.browserQuestion() : undefined, permissions: state.permissions, provider: config.provider, model: config.providers.find(item => item.id === config.provider)?.model, graph: state.graph,
|
|
2094
1710
|
};
|
|
2095
|
-
// The authenticated bridge also persists this snapshot. Preserve canonical
|
|
2096
|
-
// routing/storage metadata; the server separately redacts public paths.
|
|
2097
1711
|
return { ...trajectory.sanitize(snapshot), id: snapshot.id, parentId: snapshot.parentId, workspace: snapshot.workspace, updatedAt: snapshot.updatedAt, status: snapshot.status };
|
|
2098
1712
|
}, {
|
|
2099
1713
|
prompt: async (text) => {
|
|
@@ -2102,7 +1716,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2102
1716
|
if (browserRollbackFailed)
|
|
2103
1717
|
throw new Error(rollbackFailureMessage);
|
|
2104
1718
|
text = text.trim();
|
|
2105
|
-
if (text.startsWith('/') && (isBuiltinSlashCommand(text) || !await
|
|
1719
|
+
if (text.startsWith('/') && (isBuiltinSlashCommand(text) || !(await resolveSkillInvocations(text, effectiveExtensionConfig(config, workspace), undefined, directory)).length))
|
|
2106
1720
|
throw new Error('Run built-in slash commands in the terminal, or invoke an enabled skill as /skillname.');
|
|
2107
1721
|
if (!config.providers.length)
|
|
2108
1722
|
throw new Error('Add a provider in /providers before starting a task.');
|
|
@@ -2112,19 +1726,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2112
1726
|
browserPrompt = text;
|
|
2113
1727
|
if (!savedSession)
|
|
2114
1728
|
savedSession = { version: 1, id: trajectory.sessionId, name: sessionName(text), workspace, updatedAt: new Date().toISOString(), history: [], usage: { ...state.usage } };
|
|
2115
|
-
// A fresh acceptance timestamp keeps the acknowledged interrupted task
|
|
2116
|
-
// inside the history age window even if the CLI exits before the run's
|
|
2117
|
-
// own persistence. Rejection restores the untouched previous record.
|
|
2118
1729
|
else
|
|
2119
1730
|
savedSession = { ...savedSession, updatedAt: new Date().toISOString() };
|
|
2120
|
-
// Register fresh sessions as well as their recoverable browser prompt.
|
|
2121
|
-
// The terminal run waits for these writes before updating either record.
|
|
2122
1731
|
const record = { projectId: projectIdentity(workspace), ...savedSession, history: sessionArchive, contextHistory: state.history ?? [] };
|
|
2123
1732
|
browserAcceptance = browserBridge.persist(() => sessions.save(record)).catch(async (error) => {
|
|
2124
|
-
// The archive may commit before the primary fails. Clear the rejected
|
|
2125
|
-
// prompt through the same queue before allowing another terminal task.
|
|
2126
|
-
// Steering queued during the pending start must not leak into the
|
|
2127
|
-
// next task either.
|
|
2128
1733
|
active = undefined;
|
|
2129
1734
|
browserPrompt = undefined;
|
|
2130
1735
|
browserSteering.length = 0;
|
|
@@ -2134,9 +1739,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2134
1739
|
if (previousSession)
|
|
2135
1740
|
await browserBridge.persist(() => sessions.save(previousSession));
|
|
2136
1741
|
else {
|
|
2137
|
-
// There was no durable session before this rejected first prompt.
|
|
2138
|
-
// Do not create an empty archive that would reappear after restart,
|
|
2139
|
-
// or retry the same unavailable archive write during rollback.
|
|
2140
1742
|
const cleanup = await Promise.allSettled([
|
|
2141
1743
|
rm(join(directory, 'browser-history', `${record.id}.json`), { force: true }),
|
|
2142
1744
|
rm(join(directory, 'sessions', `${record.id}.json`), { force: true }),
|
|
@@ -2147,14 +1749,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2147
1749
|
}
|
|
2148
1750
|
}
|
|
2149
1751
|
catch (rollbackError) {
|
|
2150
|
-
// An archive-first acceptance can leave a rejected prompt recoverable
|
|
2151
|
-
// against the old primary. Remove it even if rollback storage fails,
|
|
2152
|
-
// and fence both browser and terminal tasks until storage is repaired.
|
|
2153
1752
|
browserRollbackFailed = true;
|
|
2154
1753
|
const cleanup = await Promise.allSettled([
|
|
2155
1754
|
rm(join(directory, 'browser-history', `${record.id}.json`), { force: true }),
|
|
2156
|
-
// Fresh sessions have no previous primary to preserve. Retry its
|
|
2157
|
-
// removal independently even if the archive cleanup still fails.
|
|
2158
1755
|
...(!previousSession ? [rm(join(directory, 'sessions', `${record.id}.json`), { force: true })] : []),
|
|
2159
1756
|
]);
|
|
2160
1757
|
const failures = cleanup.filter(result => result.status === 'rejected');
|
|
@@ -2168,11 +1765,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2168
1765
|
return accepted;
|
|
2169
1766
|
},
|
|
2170
1767
|
steer: text => {
|
|
2171
|
-
// Command screens also own `active`, but cannot consume graph steering.
|
|
2172
|
-
// Reject here so their input cannot be queued into the next task. An
|
|
2173
|
-
// acknowledged or starting prompt owns browserPrompt before runControl
|
|
2174
|
-
// exists: queue its steering for the run's first poll instead of
|
|
2175
|
-
// rejecting text the UI already advertises as steerable.
|
|
2176
1768
|
if (browserDraining || active?.signal.aborted || (!browserPrompt && (!runControl || !active)))
|
|
2177
1769
|
throw new Error('No task is accepting steering; return to the terminal prompt first.');
|
|
2178
1770
|
if (runControl?.isPaused)
|
|
@@ -2181,10 +1773,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2181
1773
|
browserSteering.push(text);
|
|
2182
1774
|
},
|
|
2183
1775
|
cancel: () => {
|
|
2184
|
-
// Command screens own `active` too. A task prompt identifies the
|
|
2185
|
-
// accepted/preflight window before its graph RunControl is installed.
|
|
2186
|
-
// While that acknowledged prompt is still starting, record the
|
|
2187
|
-
// cancellation intent: run() honors it as soon as it owns a signal.
|
|
2188
1776
|
if (!active && browserPrompt) {
|
|
2189
1777
|
browserCancelPending = true;
|
|
2190
1778
|
return;
|
|
@@ -2194,35 +1782,37 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2194
1782
|
active.abort(new Error('Cancelled from browser'));
|
|
2195
1783
|
},
|
|
2196
1784
|
answer: answer => {
|
|
2197
|
-
// Configuration wizards also ask terminal questions, but only live
|
|
2198
|
-
// graph questions and approvals belong to the browser runtime controls.
|
|
2199
1785
|
if (!runControl || !active || active.signal.aborted)
|
|
2200
1786
|
throw new Error('No task is accepting answers; return to the terminal prompt first.');
|
|
2201
1787
|
terminal.resolveQuestion(answer);
|
|
2202
1788
|
},
|
|
2203
1789
|
});
|
|
2204
1790
|
terminal.setStatus({ session: trajectory.sessionId });
|
|
2205
|
-
// Keep the startup transcript focused on the task. Full identifiers and journal paths
|
|
2206
|
-
// remain available through /status, and --debug opts into their startup display.
|
|
2207
1791
|
if (values.debug)
|
|
2208
1792
|
print(sessionDescription());
|
|
2209
1793
|
void refreshAccountStatus();
|
|
2210
|
-
|
|
2211
|
-
|
|
2212
|
-
|
|
2213
|
-
|
|
2214
|
-
|
|
2215
|
-
|
|
2216
|
-
|
|
1794
|
+
const startupCheckController = new AbortController();
|
|
1795
|
+
startupGraphCheck = {
|
|
1796
|
+
controller: startupCheckController,
|
|
1797
|
+
done: refreshGraphStatus(startupCheckController).catch(error => {
|
|
1798
|
+
if (!exiting && !startupCheckController.signal.aborted)
|
|
1799
|
+
print(`Graph check failed: ${error instanceof Error ? error.message : 'Unknown failure'}`);
|
|
1800
|
+
}),
|
|
1801
|
+
};
|
|
1802
|
+
void startupGraphCheck.done.then(() => bootMark('cli.graph-checked'));
|
|
1803
|
+
let lastInputAt = Date.now();
|
|
1804
|
+
const noteInput = () => { lastInputAt = Date.now(); };
|
|
1805
|
+
process.stdin.on('data', noteInput);
|
|
1806
|
+
void warmRunModules(() => lastInputAt, () => exiting || active !== undefined)
|
|
1807
|
+
.finally(() => process.stdin.off('data', noteInput))
|
|
1808
|
+
.then(() => bootMark('cli.warm'));
|
|
2217
1809
|
accountPolling = setInterval(scheduleAccountRefresh, 60_000);
|
|
2218
1810
|
accountPolling.unref?.();
|
|
2219
1811
|
while (!exiting) {
|
|
2220
1812
|
let line;
|
|
2221
1813
|
try {
|
|
2222
1814
|
const asked = terminal.question('Describe a task, or type /help', { conversationPrompt: true });
|
|
2223
|
-
|
|
2224
|
-
// command screen or an approval owned the terminal; now the composer is armed again,
|
|
2225
|
-
// so hand it every self-wake prompt that had to wait.
|
|
1815
|
+
bootMark('cli.prompt');
|
|
2226
1816
|
deliverTimerPrompts();
|
|
2227
1817
|
line = (await asked).trim();
|
|
2228
1818
|
}
|
|
@@ -2230,18 +1820,16 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2230
1820
|
break;
|
|
2231
1821
|
}
|
|
2232
1822
|
if (!line) {
|
|
2233
|
-
// An empty submission is a real submission when attachments are queued — paste-then-Enter
|
|
2234
|
-
// is the primary flow — and the substitute text names the intent the paste carried.
|
|
2235
1823
|
if (!(terminal?.hasQueuedAttachments() ?? false))
|
|
2236
1824
|
continue;
|
|
2237
1825
|
line = ATTACHMENT_ONLY_TASK;
|
|
2238
1826
|
}
|
|
1827
|
+
await settleStartupGraphCheck();
|
|
2239
1828
|
const commandStartedAt = Date.now();
|
|
2240
1829
|
await debugRecord('command.started', { input: line, mode: 'interactive' });
|
|
2241
1830
|
try {
|
|
2242
1831
|
if (line === '/browser') {
|
|
2243
1832
|
browserApp ??= await startBrowserServer();
|
|
2244
|
-
// A pending startup can outlive teardown; close instead of opening.
|
|
2245
1833
|
if (exiting)
|
|
2246
1834
|
await browserApp.close().catch(() => { });
|
|
2247
1835
|
else {
|
|
@@ -2261,54 +1849,33 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2261
1849
|
const record = records.find(item => item.id === selected);
|
|
2262
1850
|
if (!record || record.id === savedSession?.id)
|
|
2263
1851
|
continue;
|
|
2264
|
-
// The lineage and the fork points that go with it are what make the totals exact, so
|
|
2265
|
-
// they are kept whole: a chain that was cut short would lose the older ancestors. The
|
|
2266
|
-
// refusal runs before the current conversation's timers are cleared, because a switch
|
|
2267
|
-
// that cannot happen must not leave the conversation it was leaving without them.
|
|
2268
1852
|
if (!canExtendLineage(record.ancestors)) {
|
|
2269
1853
|
throw new Error('This session has been resumed too many times to keep its lineage, so it cannot be resumed again.');
|
|
2270
1854
|
}
|
|
2271
|
-
// Armed timers and undelivered prompts belong to the conversation being replaced:
|
|
2272
|
-
// firing one into a different resumed conversation would wake that session with a
|
|
2273
|
-
// prompt nobody inside it asked for. Cancel them at the switch, visibly.
|
|
2274
1855
|
const abandonedTimers = sessionTimers.list().length + timerPending.length + timerSteering.length;
|
|
2275
1856
|
sessionTimers.clear();
|
|
2276
1857
|
timerPending.length = 0;
|
|
2277
1858
|
timerSteering.length = 0;
|
|
2278
|
-
// Fork the saved snapshot so concurrent terminals never overwrite one another.
|
|
2279
|
-
// Archive files the record the user picked, not the work: the resumed conversation is a
|
|
2280
|
-
// live task, so the fork starts unarchived even when its source is put away.
|
|
2281
1859
|
const { archived: _archived, autoArchived: _autoArchived, ...resumedRecord } = record;
|
|
2282
|
-
// The fork copies the parent's history and the parent's totals. The totals it inherited
|
|
2283
|
-
// are recorded as they are now, so the work this fork does itself can be told from the
|
|
2284
|
-
// work it was given, even if the parent keeps working afterwards. The lineage is written
|
|
2285
|
-
// down as well, so a session deleted later in the chain does not leave this fork looking
|
|
2286
|
-
// like the root of its own work.
|
|
2287
1860
|
savedSession = { ...resumedRecord, id: randomUUID(), parentId: record.id,
|
|
2288
1861
|
ancestors: lineageThrough(record.ancestors, record.id), inheritedUsage: { ...record.usage },
|
|
2289
1862
|
inheritedTurns: record.history.length, lineage: lineagePoints(record, record.usage, record.history.length) };
|
|
2290
|
-
// The conversation that is being replaced keeps the log it was written to, and this one
|
|
2291
|
-
// takes a log of its own, so neither session shows the other's records.
|
|
2292
1863
|
await openSessionTrajectory(savedSession.id);
|
|
2293
|
-
// The resumed conversation keeps following the skill its source was.
|
|
2294
1864
|
await copySessionSkill(directory, record.id, savedSession.id).catch(() => { });
|
|
2295
1865
|
await trajectory.record('session.resumed', { resumedSessionId: savedSession.id, sourceSessionId: record.id });
|
|
2296
1866
|
sessionArchive = structuredClone(record.history);
|
|
2297
1867
|
state.history = structuredClone(record.contextHistory ?? record.history).slice(-6);
|
|
2298
1868
|
state.usage = { ...record.usage };
|
|
1869
|
+
state.goal = record.goal ? { ...record.goal } : undefined;
|
|
1870
|
+
terminal.setStatus({ goal: state.goal });
|
|
2299
1871
|
terminal.resetDashboardSession(record.usage);
|
|
2300
1872
|
delete state.lastRun;
|
|
2301
1873
|
contextUsedTokens = compactedContextEstimate(state.history);
|
|
2302
1874
|
sessionContexts.clear();
|
|
2303
1875
|
terminal.clearConversation();
|
|
2304
1876
|
terminal.setTodos([]);
|
|
2305
|
-
// A continued turn leads with the direction the user sent after the stop — the same line the
|
|
2306
|
-
// desktop's timeline shows — because that message, not the stopped attempt's original task,
|
|
2307
|
-
// is what this turn's work answers to; the stopped turn above it still carries the original.
|
|
2308
1877
|
for (const turn of displayHistory(sessionArchive)) {
|
|
2309
1878
|
terminal.printPrompt(turn.direction ?? turn.task);
|
|
2310
|
-
// A saved answer is markdown like a live one, so it is rendered the same way: printed
|
|
2311
|
-
// verbatim, a restored conversation showed raw `**`, `##` and fences.
|
|
2312
1879
|
const answer = formatAnswer(turn.completion.summary);
|
|
2313
1880
|
terminal.print(answer.text, answer.detail, undefined, true);
|
|
2314
1881
|
}
|
|
@@ -2322,8 +1889,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2322
1889
|
continue;
|
|
2323
1890
|
}
|
|
2324
1891
|
if (/^\/attach(?:\s|$)/.test(line)) {
|
|
2325
|
-
// Composer-local, so it lives beside the loop rather than in the command table:
|
|
2326
|
-
// it queues an attachment for the next task instead of running to completion.
|
|
2327
1892
|
const argument = line.slice('/attach'.length).trim().replace(/^"(.*)"$/, '$1');
|
|
2328
1893
|
if (!argument) {
|
|
2329
1894
|
print('Usage: /attach <path> — queue a file or folder with your next task. Large pastes and dropped files attach automatically.');
|
|
@@ -2366,11 +1931,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2366
1931
|
terminal.printPrompt(line);
|
|
2367
1932
|
else
|
|
2368
1933
|
print(`You > ${line}`);
|
|
2369
|
-
const
|
|
2370
|
-
? await
|
|
2371
|
-
if (line.startsWith('/') && !
|
|
2372
|
-
// The session's active skill is the conversation's, so its controls answer here rather than
|
|
2373
|
-
// in `executeCommand`, which knows nothing of the session.
|
|
1934
|
+
const skillInvocations = line.startsWith('/') && !isBuiltinSlashCommand(line)
|
|
1935
|
+
? await resolveSkillInvocations(line, effectiveExtensionConfig(config, workspace), undefined, directory) : [];
|
|
1936
|
+
if (line.startsWith('/') && !skillInvocations.length) {
|
|
2374
1937
|
if (/^\/skill(?:\s|$)/.test(line.trim())) {
|
|
2375
1938
|
print(await sessionSkillCommand(directory, savedSession?.id, line));
|
|
2376
1939
|
continue;
|
|
@@ -2396,9 +1959,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2396
1959
|
if (/^\/graph(?:\s|$)|^\/(?:auth\s+)?logout\s*$/.test(line) || command.clear && /^\/(providers|model)(?:\s|$)/.test(line))
|
|
2397
1960
|
await refreshGraphStatus();
|
|
2398
1961
|
refreshStatus();
|
|
2399
|
-
// `/clear` drops the chat entries before its own notice is printed, so the notice lands on
|
|
2400
|
-
// the wiped screen and survives it. The headless paths have no terminal (and no screen
|
|
2401
|
-
// entries), so they keep their plain stdout stream.
|
|
2402
1962
|
if (command.resetScreen)
|
|
2403
1963
|
terminal?.clearConversation();
|
|
2404
1964
|
if (command.text)
|
|
@@ -2412,13 +1972,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2412
1972
|
browserBridge?.startRun();
|
|
2413
1973
|
terminal?.setStatus({ contextUsed: 0 });
|
|
2414
1974
|
}
|
|
2415
|
-
// A cleared conversation starts over, without the skill the old one was following.
|
|
2416
1975
|
if (line.trim() === '/clear' && savedSession)
|
|
2417
1976
|
await removeSessionSkill(directory, savedSession.id).catch(() => { });
|
|
2418
1977
|
if (command.compact && state.history?.length) {
|
|
2419
1978
|
state.history = compactHistory(state.history);
|
|
2420
|
-
// Until the next request reports the real input size, show the compacted
|
|
2421
|
-
// seed's estimated footprint so the utilization meter drops immediately.
|
|
2422
1979
|
contextUsedTokens = compactedContextEstimate(state.history);
|
|
2423
1980
|
terminal?.setStatus({ contextUsed: contextUsedTokens });
|
|
2424
1981
|
}
|
|
@@ -2431,9 +1988,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2431
1988
|
const adapter = createAdapter(config.providers.find(p => p.id === config.provider));
|
|
2432
1989
|
if (!adapter.listModels)
|
|
2433
1990
|
print('Model discovery unavailable. Select a model with /model <id>.');
|
|
2434
|
-
// Only the user's own cancellation is passed through: the adapter bounds the listing
|
|
2435
|
-
// itself (MODEL_LISTING_TIMEOUT_MS) and reports that deadline as a timeout, whereas a
|
|
2436
|
-
// timer armed here would fire first and be reported as a user cancellation.
|
|
2437
1991
|
else
|
|
2438
1992
|
print((await adapter.listModels(active.signal)).join('\n'));
|
|
2439
1993
|
}
|
|
@@ -2459,11 +2013,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2459
2013
|
}
|
|
2460
2014
|
finally {
|
|
2461
2015
|
const cleanupErrors = [];
|
|
2462
|
-
// Each resource must be released even when another close rejects. In
|
|
2463
|
-
// particular, an app persistence error must not strand the CLI bridge.
|
|
2464
2016
|
for (const cleanup of [
|
|
2465
|
-
// The panel's Git read is a display-only child process: it must not keep the process
|
|
2466
|
-
// alive behind a slow or network-backed worktree once the session is closing.
|
|
2467
2017
|
() => {
|
|
2468
2018
|
panelReads.abort();
|
|
2469
2019
|
if (terminalsTimer)
|
|
@@ -2477,8 +2027,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2477
2027
|
() => browserBridge?.close(),
|
|
2478
2028
|
() => tabTitle.close(),
|
|
2479
2029
|
() => sessionEndedRecord(),
|
|
2480
|
-
// The session-start enqueue is part of the session's records: an exit that skips it leaves a
|
|
2481
|
-
// conversation the user created out of the counts, so this path waits for it like the flush.
|
|
2482
2030
|
() => sessionStarted,
|
|
2483
2031
|
() => trajectory.flush(),
|
|
2484
2032
|
() => { if (accountPolling)
|
|
@@ -2487,7 +2035,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2487
2035
|
() => terminal?.close(),
|
|
2488
2036
|
() => graphEditor.close(),
|
|
2489
2037
|
() => codeIntel.dispose(),
|
|
2490
|
-
|
|
2038
|
+
() => modelHealth.flush(),
|
|
2491
2039
|
() => Promise.all([disposeAllQaProcesses(), disposeAllQaPtys(), disposePooledPowerShell()]).catch(() => { }),
|
|
2492
2040
|
]) {
|
|
2493
2041
|
try {
|
|
@@ -2497,9 +2045,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
|
|
|
2497
2045
|
cleanupErrors.push(error);
|
|
2498
2046
|
}
|
|
2499
2047
|
}
|
|
2500
|
-
// The hard-exit backstop stays armed through the cleanup above: a hung trajectory
|
|
2501
|
-
// flush, editor close or code-intel dispose must not outlive the user's kill. It is
|
|
2502
|
-
// disarmed only once every await has settled, and reset so a later kill() can re-arm.
|
|
2503
2048
|
if (killBackstop) {
|
|
2504
2049
|
clearTimeout(killBackstop);
|
|
2505
2050
|
killBackstop = undefined;
|
|
@@ -2514,13 +2059,6 @@ if (process.argv[1] && await realpath(fileURLToPath(import.meta.url)) === await
|
|
|
2514
2059
|
process.exitCode = 1;
|
|
2515
2060
|
});
|
|
2516
2061
|
}
|
|
2517
|
-
/**
|
|
2518
|
-
* The exit code a finished subagent command reports.
|
|
2519
|
-
*
|
|
2520
|
-
* A signal that arrived while the records were still being written is still a signal: the
|
|
2521
|
-
* supervisor that sent it is told the run was interrupted, not that it succeeded. The run's own
|
|
2522
|
-
* cancellation is refused that late, and the refusal must not turn into a success.
|
|
2523
|
-
*/
|
|
2524
2062
|
export function subagentExitCode(outcome, signals) {
|
|
2525
2063
|
if (signals.interrupted)
|
|
2526
2064
|
return 130;
|
|
@@ -2532,26 +2070,12 @@ export function subagentExitCode(outcome, signals) {
|
|
|
2532
2070
|
return 143;
|
|
2533
2071
|
return 1;
|
|
2534
2072
|
}
|
|
2535
|
-
/**
|
|
2536
|
-
* `andorra subagent`: one Andorra run driven by an external host (Claude CLI, Codex CLI).
|
|
2537
|
-
*
|
|
2538
|
-
* The graph is always the bundled Andorra Agent harness and the provider/model is mandatory:
|
|
2539
|
-
* the call's own flags win, the saved `/subagent` setting is next, and with neither the command
|
|
2540
|
-
* answers on stdout with the PROVIDER_NOT_SET envelope carrying every configured provider and
|
|
2541
|
-
* model, so a Bash-spawning host can ask its user and retry with the pick. Stdout stays reserved
|
|
2542
|
-
* for machine-readable output — one JSON line either way; progress notes go to stderr.
|
|
2543
|
-
*/
|
|
2544
2073
|
async function runSubagentCommand(argv) {
|
|
2545
2074
|
const accepted = ['--prompt', '-p', '--provider', '--model', '--read-only', '--cwd', '--json', '--help', '-h'];
|
|
2546
|
-
// Every failure of this command answers on stdout with the same JSON envelope, so a host that
|
|
2547
|
-
// always parses a result-or-error line is not left with a bare stderr message.
|
|
2548
2075
|
const fail = (code, message, extra = {}, exit = 1) => {
|
|
2549
2076
|
process.stdout.write(JSON.stringify({ ok: false, error: { code, message, ...extra } }) + '\n');
|
|
2550
2077
|
return exit;
|
|
2551
2078
|
};
|
|
2552
|
-
// The options that take a value. The value that follows one is the option's value, even when it
|
|
2553
|
-
// begins with a hyphen: a prompt may well start with one, and the configuration permits a
|
|
2554
|
-
// provider or model id that does.
|
|
2555
2079
|
const valued = new Set(['--prompt', '-p', '--provider', '--model', '--cwd']);
|
|
2556
2080
|
for (let index = 0; index < argv.length; index += 1) {
|
|
2557
2081
|
const argument = argv[index];
|
|
@@ -2574,10 +2098,6 @@ async function runSubagentCommand(argv) {
|
|
|
2574
2098
|
} }));
|
|
2575
2099
|
}
|
|
2576
2100
|
catch (error) {
|
|
2577
|
-
// The parser refuses a malformed invocation — an option without its value, an unknown one it
|
|
2578
|
-
// did not see — and that refusal is an answer this command owes on stdout, like every other
|
|
2579
|
-
// failure of it: a host that parses a result-or-error line must not be left with a bare
|
|
2580
|
-
// stderr message.
|
|
2581
2101
|
fail('INVALID_ARGUMENTS', error instanceof Error ? error.message : String(error));
|
|
2582
2102
|
return 1;
|
|
2583
2103
|
}
|
|
@@ -2595,9 +2115,6 @@ async function runSubagentCommand(argv) {
|
|
|
2595
2115
|
fail('INVALID_ARGUMENTS', 'andorra subagent requires --prompt "task".');
|
|
2596
2116
|
return 1;
|
|
2597
2117
|
}
|
|
2598
|
-
// The same bound the MCP tools apply, checked before the run is prepared: a task this long is
|
|
2599
|
-
// persisted and turned into model context, and the CLI path must refuse it the way the MCP
|
|
2600
|
-
// path does rather than write it out and refuse later.
|
|
2601
2118
|
if (values.prompt.length > MAX_SUBAGENT_TASK_CHARS) {
|
|
2602
2119
|
fail('INVALID_ARGUMENTS', `The task must be at most ${MAX_SUBAGENT_TASK_CHARS} characters.`);
|
|
2603
2120
|
return 1;
|
|
@@ -2608,10 +2125,6 @@ async function runSubagentCommand(argv) {
|
|
|
2608
2125
|
const cancel = () => { runner.cancel(); };
|
|
2609
2126
|
const onInterrupt = () => { interrupted = true; cancel(); };
|
|
2610
2127
|
const onTerminate = () => { terminated = true; cancel(); };
|
|
2611
|
-
// The handlers are installed before the first asynchronous work: a signal that arrives while
|
|
2612
|
-
// the command resolves its workspace or classifies the attempts a previous process left in
|
|
2613
|
-
// flight would otherwise terminate the process directly, and the command would promise neither
|
|
2614
|
-
// its JSON error line nor its exit code.
|
|
2615
2128
|
process.once('SIGINT', onInterrupt);
|
|
2616
2129
|
process.once('SIGTERM', onTerminate);
|
|
2617
2130
|
try {
|
|
@@ -2622,8 +2135,6 @@ async function runSubagentCommand(argv) {
|
|
|
2622
2135
|
throw new Error('--cwd must be a directory');
|
|
2623
2136
|
}
|
|
2624
2137
|
catch (error) {
|
|
2625
|
-
// A signal that arrived while the workspace was resolved is the command's to answer: the
|
|
2626
|
-
// filesystem error is not what the supervisor asked about.
|
|
2627
2138
|
const signalled = subagentExitCode({ status: 'infrastructure_error' }, { interrupted, terminated });
|
|
2628
2139
|
if (signalled !== 1) {
|
|
2629
2140
|
return fail(interrupted ? 'CANCELLED' : 'TERMINATED', interrupted ? 'The run was interrupted before it started.' : 'The run was terminated before it started.', {}, signalled);
|
|
@@ -2631,22 +2142,11 @@ async function runSubagentCommand(argv) {
|
|
|
2631
2142
|
fail('INVALID_ARGUMENTS', error instanceof Error ? error.message : String(error));
|
|
2632
2143
|
return 1;
|
|
2633
2144
|
}
|
|
2634
|
-
// Attempts a previous process left in flight are classified before this one starts: this
|
|
2635
|
-
// command returns before the CLI's own startup recovery, so without this pass a crashed
|
|
2636
|
-
// subagent run would keep its record and its session turn `running` until an unrelated
|
|
2637
|
-
// interactive CLI or app-server was opened. Best effort: a damaged home must not block the run.
|
|
2638
|
-
// A run this process is still executing is not debris: an embedding process can call this
|
|
2639
|
-
// command while another engine works in the same home, and terminalizing that run would
|
|
2640
|
-
// remove the claim that holds its session and let a mutation in while it saves over it.
|
|
2641
2145
|
try {
|
|
2642
2146
|
const recovered = await reconcileInterruptedRuns(configDirectory(), undefined, { skipOwnProcess: true, includePending: true });
|
|
2643
|
-
// The reconciliation has already rewritten these records, so a later interactive startup
|
|
2644
|
-
// will not see them again: the finish is owed here or the start stays unmatched forever.
|
|
2645
2147
|
await reportInterruptedRuns({ home: configDirectory(), surface: configuredSurface('subagent') }, recovered.interrupted);
|
|
2646
2148
|
}
|
|
2647
|
-
catch {
|
|
2648
|
-
// A signal that arrived while the command was preparing is the command's to answer: a run that
|
|
2649
|
-
// starts now would be a full-access, billable run after the supervisor asked it to stop.
|
|
2149
|
+
catch { }
|
|
2650
2150
|
const signalled = subagentExitCode({ status: 'infrastructure_error' }, { interrupted, terminated });
|
|
2651
2151
|
if (signalled !== 1) {
|
|
2652
2152
|
return fail(interrupted ? 'CANCELLED' : 'TERMINATED', interrupted ? 'The run was interrupted before it started.' : 'The run was terminated before it started.', {}, signalled);
|
|
@@ -2662,18 +2162,11 @@ async function runSubagentCommand(argv) {
|
|
|
2662
2162
|
while (outcome.state === 'running')
|
|
2663
2163
|
outcome = await runner.result(60_000);
|
|
2664
2164
|
process.stdout.write(JSON.stringify(outcome.result ?? { status: outcome.status, ...(outcome.reason !== undefined ? { reason: outcome.reason } : {}) }) + '\n');
|
|
2665
|
-
// A signal that arrived while the records were still being written is still a signal: the
|
|
2666
|
-
// supervisor that sent it is told the run was interrupted, not that it succeeded. The run's
|
|
2667
|
-
// own cancellation is refused that late, and the refusal must not turn into a success.
|
|
2668
2165
|
return subagentExitCode(outcome, { interrupted, terminated });
|
|
2669
2166
|
}
|
|
2670
2167
|
catch (error) {
|
|
2671
|
-
// A signal that arrived while the start was preparing is still a signal: the supervising host
|
|
2672
|
-
// is told the run was interrupted, not that it failed for some reason of its own.
|
|
2673
2168
|
const signalled = subagentExitCode({ status: 'infrastructure_error' }, { interrupted, terminated });
|
|
2674
2169
|
if (signalled !== 1) {
|
|
2675
|
-
// The command promises one JSON line on stdout: a host that parses a result-or-error line
|
|
2676
|
-
// must not be left with an empty answer.
|
|
2677
2170
|
return fail(interrupted ? 'CANCELLED' : 'TERMINATED', interrupted ? 'The run was interrupted before it started.' : 'The run was terminated before it started.', {}, signalled);
|
|
2678
2171
|
}
|
|
2679
2172
|
if (error instanceof SubagentProviderNotSetError)
|
|
@@ -2687,8 +2180,6 @@ async function runSubagentCommand(argv) {
|
|
|
2687
2180
|
return fail('SUBAGENT_FAILED', error instanceof Error ? error.message : String(error));
|
|
2688
2181
|
}
|
|
2689
2182
|
finally {
|
|
2690
|
-
// Only this command own handlers go: an embedding process may have listeners of its own,
|
|
2691
|
-
// and they are not this command to remove.
|
|
2692
2183
|
process.removeListener('SIGINT', onInterrupt);
|
|
2693
2184
|
process.removeListener('SIGTERM', onTerminate);
|
|
2694
2185
|
}
|