@andorra-labs/code 0.1.5 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/account-presentation.js +3 -3
- package/dist/src/agent-execution.d.ts +2 -0
- package/dist/src/agent-execution.js +526 -41
- package/dist/src/agent-mcp-catalog.d.ts +21 -0
- package/dist/src/agent-mcp-catalog.js +40 -0
- package/dist/src/agent-mcp.d.ts +36 -3
- package/dist/src/agent-mcp.js +114 -45
- package/dist/src/app-server/protocol.d.ts +57 -5
- package/dist/src/app-server/protocol.js +18 -1
- package/dist/src/app-server/workspace.d.ts +9 -1
- package/dist/src/app-server/workspace.js +50 -3
- package/dist/src/app-server.d.ts +115 -41
- package/dist/src/app-server.js +1316 -221
- package/dist/src/auth/AuthManager.d.ts +33 -1
- package/dist/src/auth/AuthManager.js +138 -10
- package/dist/src/auth/callback-page.d.ts +4 -0
- package/dist/src/auth/callback-page.js +70 -0
- package/dist/src/auth/callback.d.ts +39 -0
- package/dist/src/auth/callback.js +146 -22
- package/dist/src/auth/index.d.ts +10 -6
- package/dist/src/auth/index.js +2 -2
- package/dist/src/auth/store.d.ts +142 -3
- package/dist/src/auth/store.js +334 -13
- package/dist/src/auth/types.d.ts +17 -1
- package/dist/src/auth-commands.d.ts +11 -2
- package/dist/src/auth-commands.js +14 -7
- package/dist/src/automation-runner.d.ts +9 -0
- package/dist/src/automation-runner.js +22 -1
- package/dist/src/automation-tool.js +18 -3
- package/dist/src/automations.d.ts +5 -0
- package/dist/src/automations.js +11 -1
- package/dist/src/browser-captcha-tool.d.ts +54 -0
- package/dist/src/browser-captcha-tool.js +374 -0
- package/dist/src/browser-panel-tool.d.ts +7 -0
- package/dist/src/browser-panel-tool.js +74 -3
- package/dist/src/browser-runner.js +19 -4
- package/dist/src/browser-server.js +21 -1
- package/dist/src/browser-session.d.ts +16 -0
- package/dist/src/browser-session.js +35 -0
- package/dist/src/browser-ui/app.js +193 -3
- package/dist/src/browser-ui/style.css +15 -1
- package/dist/src/browser-view.d.ts +72 -4
- package/dist/src/browser-view.js +229 -17
- package/dist/src/capabilities.d.ts +9 -3
- package/dist/src/capabilities.js +20 -5
- package/dist/src/capsolver.d.ts +60 -0
- package/dist/src/capsolver.js +101 -0
- package/dist/src/claude-provider.d.ts +6 -0
- package/dist/src/claude-provider.js +34 -3
- package/dist/src/cli-executable.d.ts +33 -0
- package/dist/src/cli-executable.js +64 -0
- package/dist/src/cli-process.d.ts +47 -0
- package/dist/src/cli-process.js +113 -0
- package/dist/src/cli-sign-in.d.ts +68 -0
- package/dist/src/cli-sign-in.js +224 -0
- package/dist/src/cli.js +84 -26
- package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
- package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
- package/dist/src/codex-provider.js +12 -0
- package/dist/src/coding-tools.d.ts +5 -0
- package/dist/src/coding-tools.js +98 -53
- package/dist/src/command-output-tap.d.ts +16 -0
- package/dist/src/command-output-tap.js +45 -0
- package/dist/src/command-screens.js +3 -3
- package/dist/src/commands.d.ts +15 -2
- package/dist/src/commands.js +14 -13
- package/dist/src/completion.d.ts +23 -5
- package/dist/src/completion.js +380 -17
- package/dist/src/config.d.ts +61 -0
- package/dist/src/config.js +276 -12
- package/dist/src/context-budget.d.ts +7 -0
- package/dist/src/context-budget.js +18 -1
- package/dist/src/deadline.js +6 -0
- package/dist/src/decision/FactContinuations.d.ts +41 -6
- package/dist/src/decision/FactContinuations.js +211 -64
- package/dist/src/decision/PreparedSteps.js +3 -1
- package/dist/src/decision/checks.d.ts +25 -0
- package/dist/src/decision/checks.js +77 -6
- package/dist/src/delegation-changes.d.ts +109 -0
- package/dist/src/delegation-changes.js +431 -0
- package/dist/src/extensions.d.ts +1 -0
- package/dist/src/extensions.js +16 -3
- package/dist/src/graph-provider-portability.js +2 -2
- package/dist/src/graph-quota.d.ts +1 -1
- package/dist/src/graph-quota.js +1 -1
- package/dist/src/graph-runner.js +35 -21
- package/dist/src/graph-selection.d.ts +6 -0
- package/dist/src/graph-selection.js +10 -0
- package/dist/src/graph-server.d.ts +8 -0
- package/dist/src/graph-server.js +76 -6
- package/dist/src/graph-sync.d.ts +65 -0
- package/dist/src/graph-sync.js +433 -13
- package/dist/src/graph-tool.d.ts +52 -0
- package/dist/src/graph-tool.js +136 -0
- package/dist/src/graph-ui/app.js +272 -50
- package/dist/src/graph-ui/controls.js +6 -0
- package/dist/src/graph-ui/drafts.js +39 -0
- package/dist/src/graph-ui/embed.js +1 -1
- package/dist/src/graph-ui/icons.js +1 -0
- package/dist/src/graph-ui/index.html +2 -2
- package/dist/src/graph-ui/skill-picker.js +242 -0
- package/dist/src/graph-ui/studio.css +7 -5
- package/dist/src/graph-ui/style.css +65 -12
- package/dist/src/graphs.d.ts +60 -5
- package/dist/src/graphs.js +191 -37
- package/dist/src/grok-provider.d.ts +50 -0
- package/dist/src/grok-provider.js +186 -0
- package/dist/src/handoffs.d.ts +13 -0
- package/dist/src/handoffs.js +31 -1
- package/dist/src/hardened-runtime.d.ts +4 -4
- package/dist/src/hardened-runtime.js +109 -9
- package/dist/src/managed-sign-in.d.ts +38 -0
- package/dist/src/managed-sign-in.js +169 -0
- package/dist/src/markdown.d.ts +5 -0
- package/dist/src/markdown.js +5 -2
- package/dist/src/mcp.js +11 -0
- package/dist/src/membership.d.ts +8 -1
- package/dist/src/membership.js +15 -5
- package/dist/src/model-metadata.js +14 -2
- package/dist/src/model-override.d.ts +10 -0
- package/dist/src/model-override.js +20 -0
- package/dist/src/opencode-cli-provider.d.ts +122 -0
- package/dist/src/opencode-cli-provider.js +415 -0
- package/dist/src/opencode-provider.js +23 -8
- package/dist/src/palette.d.ts +2 -0
- package/dist/src/palette.js +2 -0
- package/dist/src/permissions.d.ts +19 -1
- package/dist/src/permissions.js +30 -1
- package/dist/src/powershell-pool.d.ts +11 -2
- package/dist/src/powershell-pool.js +34 -5
- package/dist/src/provider-connection.js +36 -0
- package/dist/src/provider-engine.d.ts +2 -1
- package/dist/src/provider-engine.js +64 -13
- package/dist/src/provider-import.js +6 -1
- package/dist/src/provider-keys.d.ts +48 -0
- package/dist/src/provider-keys.js +121 -0
- package/dist/src/provider-settings.js +22 -3
- package/dist/src/providers.d.ts +12 -1
- package/dist/src/providers.js +27 -8
- package/dist/src/pull-requests.d.ts +123 -20
- package/dist/src/pull-requests.js +334 -84
- package/dist/src/qa/qa-authorize.js +9 -1
- package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
- package/dist/src/qa/runtime/ProcessManager.js +16 -0
- package/dist/src/react-runtime.js +106 -7
- package/dist/src/read-image.d.ts +30 -0
- package/dist/src/read-image.js +97 -0
- package/dist/src/remote/engine-pool.js +1 -1
- package/dist/src/run-progress.js +6 -1
- package/dist/src/run-records.d.ts +133 -27
- package/dist/src/run-records.js +320 -40
- package/dist/src/runtime.d.ts +38 -1
- package/dist/src/runtime.js +27 -4
- package/dist/src/save-lock.d.ts +11 -0
- package/dist/src/save-lock.js +29 -2
- package/dist/src/secret-redaction.d.ts +13 -0
- package/dist/src/secret-redaction.js +71 -0
- package/dist/src/session-summary.d.ts +10 -4
- package/dist/src/session-summary.js +14 -7
- package/dist/src/sessions.js +8 -2
- package/dist/src/shell.js +4 -1
- package/dist/src/side-panel.d.ts +1 -1
- package/dist/src/side-panel.js +1 -1
- package/dist/src/skill-commands.d.ts +2 -0
- package/dist/src/skill-commands.js +2 -0
- package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
- package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
- package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
- package/dist/src/skills/bundled/graph-manager/SKILL.md +100 -0
- package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
- package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
- package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
- package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
- package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
- package/dist/src/skills/bundled/provenance.json +50 -0
- package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
- package/dist/src/skills/invocable-skills.d.ts +41 -0
- package/dist/src/skills/invocable-skills.js +49 -0
- package/dist/src/skills/prompt-skills.d.ts +1 -0
- package/dist/src/skills/prompt-skills.js +33 -0
- package/dist/src/skills/runtime-skills.d.ts +4 -0
- package/dist/src/skills/runtime-skills.js +21 -0
- package/dist/src/structured-step.d.ts +55 -0
- package/dist/src/structured-step.js +85 -0
- package/dist/src/subagent-run.d.ts +1 -1
- package/dist/src/subagent-run.js +29 -33
- package/dist/src/telemetry/schema.d.ts +2 -2
- package/dist/src/telemetry/schema.js +3 -2
- package/dist/src/terminal-ui.d.ts +38 -0
- package/dist/src/terminal-ui.js +126 -28
- package/dist/src/timers.d.ts +21 -2
- package/dist/src/timers.js +12 -4
- package/dist/src/tool-dependencies.js +4 -0
- package/dist/src/tool-names.d.ts +18 -0
- package/dist/src/tool-names.js +26 -0
- package/dist/src/tools.d.ts +9 -0
- package/dist/src/tools.js +159 -20
- package/dist/src/trajectory.js +32 -12
- package/dist/src/transcript.js +5 -0
- package/dist/src/types.d.ts +36 -0
- package/dist/src/web-search.d.ts +59 -0
- package/dist/src/web-search.js +216 -0
- package/docs/agents/README.md +2 -2
- package/docs/agents/mcp-server.md +28 -3
- package/docs/agents/subagent-mode.md +7 -4
- package/docs/concepts/README.md +1 -1
- package/docs/concepts/security.md +4 -2
- package/docs/getting-started/accounts.md +15 -4
- package/docs/getting-started/configure-providers.md +30 -3
- package/docs/guides/README.md +1 -0
- package/docs/guides/browser.md +12 -0
- package/docs/guides/desktop-app.md +11 -4
- package/docs/guides/graph-builder.md +9 -1
- package/docs/guides/web-search.md +47 -0
- package/docs/reference/cli.md +4 -3
- package/docs/reference/config.md +4 -4
- package/docs/reference/slash-commands.md +2 -1
- package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
- package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
- package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
- package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
- package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
- package/package.json +1 -1
- package/tests/permissions-test-plan.md +2 -1
package/dist/src/app-server.js
CHANGED
|
@@ -1,26 +1,30 @@
|
|
|
1
1
|
import { createInterface } from 'node:readline';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { bootMark } from './boot-trace.js';
|
|
4
|
-
import {
|
|
4
|
+
import { mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
|
|
5
5
|
import { homedir } from 'node:os';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
7
|
import { join, resolve } from 'node:path';
|
|
8
|
-
import { changeConfigFile, configDirectory, ConfigConflictError, loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer } from './config.js';
|
|
8
|
+
import { changeConfigFile, configDirectory, ConfigConflictError, loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer, checkSearxngUrl, validateWebSearchConfig, WEB_SEARCH_FIELDS, WEB_SEARCH_KEY_FIELDS, WEB_SEARCH_PROVIDERS } from './config.js';
|
|
9
9
|
import { isUnlimitedAlias } from './limits.js';
|
|
10
10
|
import { isPermissionMode, workspacePermissionKey } from './permissions.js';
|
|
11
|
-
import {
|
|
11
|
+
import { RunControl } from './run-control.js';
|
|
12
|
+
import { allocateCodexAccountSlots, createAdapter, isSignInProviderType, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS } from './providers.js';
|
|
12
13
|
import { droppedCodexSlots, removeCodexAccount } from './codex-auth.js';
|
|
13
14
|
import { testProviderConnection } from './provider-connection.js';
|
|
14
15
|
import { CodexAccountAuth } from './codex-browser-auth.js';
|
|
15
16
|
import { AnthropicConsoleAuth, droppedAnthropicAccounts } from './anthropic-console-auth.js';
|
|
17
|
+
import { claudeSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
|
|
18
|
+
import { OPENCODE_BASE_URL, sharedOpenCodeServer } from './opencode-cli-provider.js';
|
|
19
|
+
import { GROK_BASE_URL } from './grok-provider.js';
|
|
16
20
|
import { anthropicAccountHome } from './anthropic-credentials.js';
|
|
17
21
|
import { codexAccountHome } from './codex-rpc.js';
|
|
18
22
|
import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext } from './model-metadata.js';
|
|
19
|
-
import { graphLeavesNodesToSession, listGraphs, loadGraph, maxNodeVisitsOf } from './graphs.js';
|
|
23
|
+
import { graphLeavesNodesToSession, isDeletedGraph, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
|
|
20
24
|
import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
|
|
21
25
|
import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
|
|
22
26
|
import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
|
|
23
|
-
import { applyModelOverride } from './model-override.js';
|
|
27
|
+
import { applyModelOverride, applyNodeModelOverrides } from './model-override.js';
|
|
24
28
|
import { freeTierGraphViolation, readGraphQuota } from './graph-quota.js';
|
|
25
29
|
import { ANDORRA_GRAPH_SELECTION, SOFTWARE_ENGINEER_HARNESS, getAndorraHarness, getMembership, loadAccessibleGraph } from './membership.js';
|
|
26
30
|
import { loadProfile, saveProfile, ProfileAccountError, ProfileTextError } from './profile.js';
|
|
@@ -35,11 +39,11 @@ import { writePendingAgentInteraction, removePendingAgentInteraction } from './s
|
|
|
35
39
|
import { summarizeSessionPrompt, titleRequestSupported } from './session-summary.js';
|
|
36
40
|
import { createTools } from './tools.js';
|
|
37
41
|
import { TimerRegistry, WAKE_RETRY_MS } from './timers.js';
|
|
38
|
-
import {
|
|
42
|
+
import { confirmAutoFixWake, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, noAccountMessage, readPullRequestAsAnyAccount, withPullRequest, writePullRequest } from './pull-requests.js';
|
|
39
43
|
import { AutomationStore } from './automations.js';
|
|
40
44
|
import { executeAutomation } from './automation-runner.js';
|
|
41
45
|
import { automationService, automationServiceRunning, reconcileAutomationService } from './automation-service.js';
|
|
42
|
-
import { runGraph, stopReasonPhrase } from './runtime.js';
|
|
46
|
+
import { runGraph, stopReasonPhrase, timerReminderText } from './runtime.js';
|
|
43
47
|
import { configuredSurface, createRunHandle, drainTelemetry, graphShape, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
|
|
44
48
|
import { telemetryGate } from './telemetry/gate.js';
|
|
45
49
|
import { analyticsGenerationFor, resolveAnalyticsConfig } from './analytics.js';
|
|
@@ -48,7 +52,7 @@ import { recordPreference } from './telemetry/state.js';
|
|
|
48
52
|
import { createRunTelemetry, recordModelUse } from './telemetry/capture.js';
|
|
49
53
|
import { pricingFor } from './model-tiers.js';
|
|
50
54
|
import { purgeOutbox } from './telemetry/outbox.js';
|
|
51
|
-
import { acquireSessionMutationLock,
|
|
55
|
+
import { acquireSessionMutationLock, checkpointFailure, claimProcessWorkspace, createCheckpointFailureTracker, createRunJournalWriter, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
|
|
52
56
|
import { ArtifactStore } from './artifacts.js';
|
|
53
57
|
import { mergeRunProgress, replayRunJournal } from './run-progress.js';
|
|
54
58
|
import { readFavicon } from './favicons.js';
|
|
@@ -68,7 +72,9 @@ import { createSessionTrajectory } from './trajectory.js';
|
|
|
68
72
|
import { readUsageAnalytics } from './usage-analytics.js';
|
|
69
73
|
import { TerminalFlow, TerminalManager } from './app-server/terminal.js';
|
|
70
74
|
import { BrowserViewManager, browserViewUrl } from './browser-view.js';
|
|
71
|
-
import { createBrowserPanelTool, runPanelOperation, validatePanelArguments } from './browser-panel-tool.js';
|
|
75
|
+
import { createBrowserIncognitoTool, createBrowserPanelTool, runPanelOperation, validatePanelArguments } from './browser-panel-tool.js';
|
|
76
|
+
import { resolveCapsolverKey } from './capsolver.js';
|
|
77
|
+
import { resolveWebSearchProvider } from './web-search.js';
|
|
72
78
|
import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, readTree, readWorkspaceFile, summarizeMcpServer, workspaceRoot } from './app-server/workspace.js';
|
|
73
79
|
import { withReasoningEvents } from './app-server/reasoning.js';
|
|
74
80
|
import { APP_SERVER_PROTOCOL_VERSION, APP_SERVER_CAPABILITIES, } from './app-server/protocol.js';
|
|
@@ -105,6 +111,8 @@ class AppServerError extends Error {
|
|
|
105
111
|
}
|
|
106
112
|
const SESSION_HISTORY_TURNS = 6;
|
|
107
113
|
const MAX_TASK_CHARS = 100_000;
|
|
114
|
+
/** The automation context rides `run.start` beside the task, bounded well under the task limit. */
|
|
115
|
+
const AUTOMATION_CONTEXT_CHARS = 4_000;
|
|
108
116
|
/**
|
|
109
117
|
* The engine's own budget for one workspace probe, set below the desktop's 200-second client budget.
|
|
110
118
|
*
|
|
@@ -150,7 +158,7 @@ const RELAY_LONG_DEADLINE_MS = 1_260_000;
|
|
|
150
158
|
*/
|
|
151
159
|
const MAX_RESUME_LINEAGE = 32;
|
|
152
160
|
/** Fields a client may change through `config.set`. Anything else is rejected rather than merged. */
|
|
153
|
-
const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'limits', 'workspacePermissions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays'];
|
|
161
|
+
const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'limits', 'workspacePermissions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays', 'browser', 'webSearch'];
|
|
154
162
|
function message(error) { return error instanceof Error ? error.message : String(error); }
|
|
155
163
|
/** Project an owned authentication result instead of forwarding any official CLI payload wholesale. */
|
|
156
164
|
function providerAuthView(view, includeUrl) {
|
|
@@ -200,6 +208,72 @@ function providerAuthView(view, includeUrl) {
|
|
|
200
208
|
}
|
|
201
209
|
return result;
|
|
202
210
|
}
|
|
211
|
+
/** The sign-in page hosts each CLI-run sign-in may name. OpenCode's vary by upstream provider. */
|
|
212
|
+
const MANAGED_SIGN_IN_HOSTS = {
|
|
213
|
+
claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], opencode: undefined,
|
|
214
|
+
};
|
|
215
|
+
/** Project a CLI-run sign-in the same way: display fields only, the page URL only to its starter. */
|
|
216
|
+
function managedAuthView(type, view, includeUrl) {
|
|
217
|
+
if (!['signedOut', 'starting', 'waiting', 'signedIn', 'cancelled', 'error'].includes(view.state))
|
|
218
|
+
throw new Error('Invalid authentication state');
|
|
219
|
+
const text = (value, max) => typeof value === 'string' && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value) ? value : undefined;
|
|
220
|
+
const result = { state: view.state };
|
|
221
|
+
if (view.reason && ['unavailable', 'timeout', 'denied', 'unsupported', 'busy', 'unverified', 'logoutFailed'].includes(view.reason))
|
|
222
|
+
result.reason = view.reason;
|
|
223
|
+
const attemptId = text(view.attemptId, 128);
|
|
224
|
+
if (attemptId)
|
|
225
|
+
result.attemptId = attemptId;
|
|
226
|
+
const note = text(view.message, 1000);
|
|
227
|
+
if (note)
|
|
228
|
+
result.message = note;
|
|
229
|
+
if (view.state === 'signedIn') {
|
|
230
|
+
const email = text(view.email, 320);
|
|
231
|
+
const planType = text(view.planType, 100);
|
|
232
|
+
if (email)
|
|
233
|
+
result.email = email;
|
|
234
|
+
if (planType)
|
|
235
|
+
result.planType = planType;
|
|
236
|
+
}
|
|
237
|
+
if (view.state === 'waiting') {
|
|
238
|
+
if (view.acceptsCode === true)
|
|
239
|
+
result.acceptsCode = true;
|
|
240
|
+
const code = text(view.userCode, 32);
|
|
241
|
+
if (code && /^[A-Z0-9-]+$/.test(code))
|
|
242
|
+
result.userCode = code;
|
|
243
|
+
}
|
|
244
|
+
const provider = text(view.signInProvider, 100);
|
|
245
|
+
if (provider)
|
|
246
|
+
result.signInProvider = provider;
|
|
247
|
+
if (Array.isArray(view.connected))
|
|
248
|
+
result.connected = view.connected.slice(0, 500).flatMap(item => {
|
|
249
|
+
const id = text(item?.id, 100);
|
|
250
|
+
const name = text(item?.name, 200);
|
|
251
|
+
return id ? [{ id, name: name ?? id }] : [];
|
|
252
|
+
});
|
|
253
|
+
if (Array.isArray(view.signInOptions))
|
|
254
|
+
result.signInOptions = view.signInOptions.slice(0, 500).flatMap(option => {
|
|
255
|
+
const providerId = text(option?.providerId, 100);
|
|
256
|
+
const label = text(option?.label, 200);
|
|
257
|
+
if (!providerId || !label || !Number.isSafeInteger(option.method) || option.method < 0)
|
|
258
|
+
return [];
|
|
259
|
+
return [{ providerId, providerName: text(option.providerName, 200) ?? providerId, method: option.method, label, connected: option.connected === true }];
|
|
260
|
+
});
|
|
261
|
+
if (includeUrl && view.state === 'waiting' && view.authUrl !== undefined) {
|
|
262
|
+
const raw = text(view.authUrl, 16_384);
|
|
263
|
+
let url;
|
|
264
|
+
try {
|
|
265
|
+
url = raw ? new URL(raw) : undefined;
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
url = undefined;
|
|
269
|
+
}
|
|
270
|
+
const hosts = MANAGED_SIGN_IN_HOSTS[type];
|
|
271
|
+
if (url && url.protocol === 'https:' && !url.username && !url.password && !url.port
|
|
272
|
+
&& (hosts === undefined || hosts.some(host => url.hostname === host || url.hostname.endsWith(`.${host}`))))
|
|
273
|
+
result.authUrl = url.href;
|
|
274
|
+
}
|
|
275
|
+
return result;
|
|
276
|
+
}
|
|
203
277
|
/**
|
|
204
278
|
* The account a profile request is about.
|
|
205
279
|
*
|
|
@@ -278,7 +352,7 @@ function viewUrl(value) {
|
|
|
278
352
|
}
|
|
279
353
|
function permissionMode(value) {
|
|
280
354
|
if (!isPermissionMode(value))
|
|
281
|
-
throw new AppServerError('invalid-params', 'permissions must be read-only, ask-for-approval, approve-for-me, or full-access');
|
|
355
|
+
throw new AppServerError('invalid-params', 'permissions must be read-only, plan, ask-for-approval, approve-for-me, or full-access');
|
|
282
356
|
return value;
|
|
283
357
|
}
|
|
284
358
|
/** One run's thinking effort; the selected adapter validates model support. */
|
|
@@ -376,8 +450,99 @@ function configView(config, analytics) {
|
|
|
376
450
|
...(config.externalSubagent === undefined ? {} : { externalSubagent: { ...config.externalSubagent } }),
|
|
377
451
|
...(config.systemPromptOverride === undefined ? {} : { systemPromptOverride: config.systemPromptOverride }),
|
|
378
452
|
...(config.autoArchiveDays === undefined ? {} : { autoArchiveDays: config.autoArchiveDays }),
|
|
453
|
+
...(resolveCapsolverKey(config) ? { browser: browserConfigView(config) } : {}),
|
|
454
|
+
...webSearchConfigView(config),
|
|
379
455
|
};
|
|
380
456
|
}
|
|
457
|
+
/** The Browser page's view: whether a CapSolver key exists and which one is used, never the key. No key at all omits the block. */
|
|
458
|
+
function browserConfigView(config) {
|
|
459
|
+
const key = resolveCapsolverKey(config);
|
|
460
|
+
return { hasCapsolverKey: !!config.browser?.capsolverApiKey, ...(key ? { capsolverKeySource: key.source } : {}) };
|
|
461
|
+
}
|
|
462
|
+
/**
|
|
463
|
+
* Apply a `browser` patch to the stored block.
|
|
464
|
+
*
|
|
465
|
+
* The view never carries the key, so a patch names only what changes: a string saves a key, `null`
|
|
466
|
+
* removes it, and an omitted field keeps what is stored. An empty block is dropped.
|
|
467
|
+
*/
|
|
468
|
+
function mergeBrowserConfig(current, patch) {
|
|
469
|
+
if (!patch || typeof patch !== 'object' || Array.isArray(patch))
|
|
470
|
+
throw new AppServerError('invalid-params', 'browser must be an object');
|
|
471
|
+
const fields = patch;
|
|
472
|
+
if (Object.keys(fields).some(key => key !== 'capsolverApiKey'))
|
|
473
|
+
throw new AppServerError('invalid-params', 'browser accepts only capsolverApiKey');
|
|
474
|
+
const next = { ...current };
|
|
475
|
+
if (fields.capsolverApiKey === null)
|
|
476
|
+
delete next.capsolverApiKey;
|
|
477
|
+
else if (fields.capsolverApiKey !== undefined) {
|
|
478
|
+
if (typeof fields.capsolverApiKey !== 'string' || !fields.capsolverApiKey.trim())
|
|
479
|
+
throw new AppServerError('invalid-params', 'capsolverApiKey must be a nonempty string, or null to remove it');
|
|
480
|
+
next.capsolverApiKey = fields.capsolverApiKey.trim();
|
|
481
|
+
}
|
|
482
|
+
return Object.keys(next).length ? next : undefined;
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* The Web Search page's view: for each service whether a value is saved and which one the tool would
|
|
486
|
+
* use, the non-secret values as saved, and the chosen default. Never a key. Nothing saved or found in
|
|
487
|
+
* the environment omits the block.
|
|
488
|
+
*/
|
|
489
|
+
function webSearchConfigView(config) {
|
|
490
|
+
const saved = config.webSearch ?? {};
|
|
491
|
+
const providers = Object.fromEntries(WEB_SEARCH_PROVIDERS.map(id => {
|
|
492
|
+
const resolved = resolveWebSearchProvider(id, config);
|
|
493
|
+
const stored = id === 'searxng' ? !!saved.searxngUrl : !!saved[WEB_SEARCH_KEY_FIELDS[id]];
|
|
494
|
+
return [id, { saved: stored, ...(resolved ? { source: resolved.source } : {}) }];
|
|
495
|
+
}));
|
|
496
|
+
if (!config.webSearch && !Object.values(providers).some(provider => provider.source))
|
|
497
|
+
return {};
|
|
498
|
+
return { webSearch: {
|
|
499
|
+
providers,
|
|
500
|
+
...(saved.defaultProvider ? { defaultProvider: saved.defaultProvider } : {}),
|
|
501
|
+
...(saved.googleSearchEngineId ? { googleSearchEngineId: saved.googleSearchEngineId } : {}),
|
|
502
|
+
...(saved.searxngUrl ? { searxngUrl: saved.searxngUrl } : {}),
|
|
503
|
+
} };
|
|
504
|
+
}
|
|
505
|
+
/**
|
|
506
|
+
* Apply a `webSearch` patch to the stored block.
|
|
507
|
+
*
|
|
508
|
+
* Like `browser`, a patch names only what changes: a string saves a value, `null` removes it, and an
|
|
509
|
+
* omitted field keeps what is stored, because the view never carries the keys back. An empty block
|
|
510
|
+
* is dropped.
|
|
511
|
+
*/
|
|
512
|
+
function mergeWebSearchConfig(current, patch) {
|
|
513
|
+
if (!patch || typeof patch !== 'object' || Array.isArray(patch))
|
|
514
|
+
throw new AppServerError('invalid-params', 'webSearch must be an object');
|
|
515
|
+
const fields = patch;
|
|
516
|
+
const unknown = Object.keys(fields).filter(key => !WEB_SEARCH_FIELDS.includes(key));
|
|
517
|
+
if (unknown.length)
|
|
518
|
+
throw new AppServerError('invalid-params', `webSearch accepts only ${WEB_SEARCH_FIELDS.join(', ')}`);
|
|
519
|
+
const next = { ...current };
|
|
520
|
+
for (const [field, value] of Object.entries(fields)) {
|
|
521
|
+
if (value === null) {
|
|
522
|
+
delete next[field];
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
525
|
+
if (value === undefined)
|
|
526
|
+
continue;
|
|
527
|
+
if (typeof value !== 'string' || !value.trim())
|
|
528
|
+
throw new AppServerError('invalid-params', `webSearch.${field} must be a nonempty string, or null to remove it`);
|
|
529
|
+
if (field === 'searxngUrl') {
|
|
530
|
+
const checked = checkSearxngUrl(value);
|
|
531
|
+
if ('error' in checked)
|
|
532
|
+
throw new AppServerError('invalid-params', checked.error);
|
|
533
|
+
next[field] = checked.url;
|
|
534
|
+
}
|
|
535
|
+
else
|
|
536
|
+
next[field] = value.trim();
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
validateWebSearchConfig(next);
|
|
540
|
+
}
|
|
541
|
+
catch (error) {
|
|
542
|
+
throw new AppServerError('invalid-params', message(error));
|
|
543
|
+
}
|
|
544
|
+
return Object.keys(next).length ? next : undefined;
|
|
545
|
+
}
|
|
381
546
|
/**
|
|
382
547
|
* Merge a client's provider list with the stored secrets.
|
|
383
548
|
*
|
|
@@ -418,7 +583,7 @@ export function mergeProviderSecrets(stored, incoming) {
|
|
|
418
583
|
if (source[field] !== undefined)
|
|
419
584
|
provider[field] = source[field];
|
|
420
585
|
const previousEntry = typeof provider.id === 'string' ? previous.get(provider.id) : undefined;
|
|
421
|
-
const inherited = provider.type
|
|
586
|
+
const inherited = isSignInProviderType(provider.type) ? undefined : previousEntry;
|
|
422
587
|
const crossesGo = previousEntry !== undefined && previousEntry.type !== provider.type
|
|
423
588
|
&& (previousEntry.type === 'opencode-go' || provider.type === 'opencode-go');
|
|
424
589
|
// A hidden key is not consent to send that credential to a different provider. Older clients
|
|
@@ -523,6 +688,19 @@ function foldUsage(target, delta) {
|
|
|
523
688
|
* wake that had to wait for a run must not re-check itself every millisecond while that run holds the engine.
|
|
524
689
|
*/
|
|
525
690
|
const TIMER_DELIVERY_RETRY_MS = 1_000;
|
|
691
|
+
/**
|
|
692
|
+
* How long an Auto-fix wake waits when GitHub could not confirm its PR is still open: about one watcher poll, so an
|
|
693
|
+
* outage or a signed-out account is asked about once a minute rather than on every delivery pass.
|
|
694
|
+
*/
|
|
695
|
+
const AUTO_FIX_CONFIRM_RETRY_MS = 60_000;
|
|
696
|
+
/**
|
|
697
|
+
* A session's PR as clients are sent it. A desktop built while Auto-archive existed accepts a record only when it
|
|
698
|
+
* carries an `autoArchive` flag, and would drop the whole Pull request row without one, so the flag is still sent:
|
|
699
|
+
* always false, since nothing archives a session on merge any more.
|
|
700
|
+
*/
|
|
701
|
+
function pullRequestForClients(pullRequest) {
|
|
702
|
+
return pullRequest ? { ...pullRequest, autoArchive: false } : null;
|
|
703
|
+
}
|
|
526
704
|
function sessionSummary(record) {
|
|
527
705
|
// The newest attempt is what a row says the task did. A turn keeps a status only when it ended without
|
|
528
706
|
// completing, so an absent one is a normal completion; reading it off the saved record is what makes a
|
|
@@ -539,7 +717,9 @@ function sessionSummary(record) {
|
|
|
539
717
|
// is the stopped attempt's, and search and tooltips must find the words the user actually sent.
|
|
540
718
|
...(record.history?.length ? { lastTask: record.history[record.history.length - 1].direction ?? record.history[record.history.length - 1].task } : {}),
|
|
541
719
|
...(finished === undefined ? {} : { lastTurnStatus: finished }),
|
|
542
|
-
usage: { inputTokens: record.usage.inputTokens, outputTokens: record.usage.outputTokens, requests: record.usage.requests, ...(record.usage.cacheRead === undefined ? {} : { cacheRead: record.usage.cacheRead }), ...(record.usage.cacheWrite === undefined ? {} : { cacheWrite: record.usage.cacheWrite })
|
|
720
|
+
usage: { inputTokens: record.usage.inputTokens, outputTokens: record.usage.outputTokens, requests: record.usage.requests, ...(record.usage.cacheRead === undefined ? {} : { cacheRead: record.usage.cacheRead }), ...(record.usage.cacheWrite === undefined ? {} : { cacheWrite: record.usage.cacheWrite }),
|
|
721
|
+
...(record.usage.localCacheInputTokens === undefined ? {} : { localCacheInputTokens: record.usage.localCacheInputTokens }),
|
|
722
|
+
...(record.usage.localCacheReadTokens === undefined ? {} : { localCacheReadTokens: record.usage.localCacheReadTokens }) },
|
|
543
723
|
};
|
|
544
724
|
}
|
|
545
725
|
/**
|
|
@@ -568,10 +748,21 @@ function sessionSummary(record) {
|
|
|
568
748
|
* agent asked to be woken for is the more expensive guess.
|
|
569
749
|
*/
|
|
570
750
|
/** Exported because the table is the part a delivery must not get wrong; the protocol test pins it. */
|
|
751
|
+
/** A restored conversation's state with its spent allowance cleared: no iterations used, no remaining-budget caps. */
|
|
752
|
+
function freshAllowance(state) {
|
|
753
|
+
const { remainingToolCalls: _tools, remainingWallTimeMs: _wall, ...rest } = state;
|
|
754
|
+
return { ...rest, iterations: 0, ...(state.copies === undefined ? {} : { copies: state.copies.map(copy => ({ ...copy, state: freshAllowance(copy.state) })) }) };
|
|
755
|
+
}
|
|
756
|
+
/** A direction's recorded provenance, kept only when it names a wake this engine knows. */
|
|
757
|
+
function wakeProvenance(wake, node) {
|
|
758
|
+
if (wake !== 'timer' && wake !== 'auto-fix')
|
|
759
|
+
return {};
|
|
760
|
+
return { wake, ...(typeof node === 'string' && node ? { node } : {}) };
|
|
761
|
+
}
|
|
571
762
|
export function isFinalWakeRefusal(error) {
|
|
572
763
|
return error instanceof AppServerError
|
|
573
764
|
&& (error.code === 'invalid-params' || error.code === 'not-found' || error.code === 'remote'
|
|
574
|
-
|| error.code === 'unknown-method' || error.code === 'auth');
|
|
765
|
+
|| error.code === 'unknown-method' || error.code === 'auth' || error.code === 'nothing-to-continue');
|
|
575
766
|
}
|
|
576
767
|
/** How a stopped attempt reads to the next turn, mirroring the TUI's history entries. */
|
|
577
768
|
function outcomeCompletion(status, reason, limits) {
|
|
@@ -644,6 +835,23 @@ export function withoutRunMarker(record, runId) {
|
|
|
644
835
|
...(contextHistory === undefined ? {} : { contextHistory: strip(contextHistory) }),
|
|
645
836
|
};
|
|
646
837
|
}
|
|
838
|
+
/** A run record's `nodeModelOverrides` — node id → explicit pair — or undefined when absent or malformed. */
|
|
839
|
+
function readNodeModelOverrides(value) {
|
|
840
|
+
if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value))
|
|
841
|
+
return undefined;
|
|
842
|
+
let read;
|
|
843
|
+
for (const [id, entry] of Object.entries(value)) {
|
|
844
|
+
if (entry === null || typeof entry !== 'object' || Array.isArray(entry))
|
|
845
|
+
continue;
|
|
846
|
+
const provider = entry.provider;
|
|
847
|
+
const model = entry.model;
|
|
848
|
+
if (typeof provider !== 'string' || !provider || typeof model !== 'string' || !model)
|
|
849
|
+
continue;
|
|
850
|
+
read ??= {};
|
|
851
|
+
read[id] = { provider, model };
|
|
852
|
+
}
|
|
853
|
+
return read;
|
|
854
|
+
}
|
|
647
855
|
export class AppServer {
|
|
648
856
|
automationCheck;
|
|
649
857
|
/** The daily auto-archive pass; a change to the setting runs one immediately as well. */
|
|
@@ -657,14 +865,18 @@ export class AppServer {
|
|
|
657
865
|
output;
|
|
658
866
|
error;
|
|
659
867
|
checkGraphHealth;
|
|
868
|
+
createCodeIntelligence;
|
|
660
869
|
loadGraph;
|
|
661
870
|
codexAuth;
|
|
662
871
|
anthropicAuth;
|
|
872
|
+
claudeSignIn;
|
|
873
|
+
grokSignIn;
|
|
874
|
+
openCodeSignIn;
|
|
663
875
|
/** Retires a removed provider's slot home; a seam so a test never has to spawn the Codex CLI. */
|
|
664
876
|
retireCodexAccount;
|
|
665
877
|
/** The `gh` the pull request settings and watcher run through. */
|
|
666
878
|
gh;
|
|
667
|
-
/** Polls the PRs whose sessions asked for Auto-fix
|
|
879
|
+
/** Polls the PRs whose sessions asked for Auto-fix; one engine per home actually polls. */
|
|
668
880
|
pullRequestWatcher;
|
|
669
881
|
/** The wakes this engine armed for Auto-fix, checked against the PR record again before delivery. */
|
|
670
882
|
autoFixWakes = new Set();
|
|
@@ -751,18 +963,11 @@ export class AppServer {
|
|
|
751
963
|
*/
|
|
752
964
|
startingSession;
|
|
753
965
|
/**
|
|
754
|
-
*
|
|
755
|
-
*
|
|
756
|
-
* and a marker file carry
|
|
966
|
+
* Each live run's journal writer. A writer holds the events its file refused and writes them once
|
|
967
|
+
* appends succeed again, so it is also what knows, at finalization, whether the journal is a
|
|
968
|
+
* complete account (the record and a marker file carry the answer past a crash).
|
|
757
969
|
*/
|
|
758
|
-
|
|
759
|
-
/**
|
|
760
|
-
* Runs whose checkpoint sink failed mid-attempt. A checkpoint is the conversation a resume
|
|
761
|
-
* re-enters the node with, so a run whose checkpoint could not be written is one no resume may
|
|
762
|
-
* replay: the resume would re-enter the node from its opening task and repeat the tool calls it
|
|
763
|
-
* had already made. The record and a marker file carry the failure past a crash.
|
|
764
|
-
*/
|
|
765
|
-
checkpointFailures = new Set();
|
|
970
|
+
journals = new Map();
|
|
766
971
|
/**
|
|
767
972
|
* The session trajectory of the run in flight: one sanitized debug log per session
|
|
768
973
|
* (`trajectories/<sessionId>.jsonl` in this home), appended by every run and resume of that
|
|
@@ -835,26 +1040,18 @@ export class AppServer {
|
|
|
835
1040
|
this.output = options.output;
|
|
836
1041
|
this.error = options.error;
|
|
837
1042
|
this.checkGraphHealth = options.checkGraphHealth ?? checkGraphModelHealth;
|
|
1043
|
+
this.createCodeIntelligence = options.createCodeIntelligence ?? (managerOptions => CodeIntelligenceManager.create(managerOptions));
|
|
838
1044
|
this.loadGraph = options.loadGraph ?? loadAccessibleGraph;
|
|
839
1045
|
this.codexAuth = options.codexAuth ?? new CodexAccountAuth();
|
|
840
1046
|
this.anthropicAuth = options.anthropicAuth ?? new AnthropicConsoleAuth();
|
|
1047
|
+
this.claudeSignIn = options.managedSignIn?.claude ?? claudeSignIn();
|
|
1048
|
+
this.grokSignIn = options.managedSignIn?.grok ?? grokSignIn();
|
|
1049
|
+
this.openCodeSignIn = options.managedSignIn?.opencode ?? new OpenCodeSignIn();
|
|
841
1050
|
this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
|
|
842
1051
|
this.gh = options.gh ?? runGh;
|
|
843
1052
|
this.pullRequestWatcher = new PullRequestWatcher({
|
|
844
1053
|
home: this.directory, gh: this.gh, intervalMs: options.pullRequestPollMs,
|
|
845
1054
|
onUpdated: (sessionId, pullRequest) => this.emitPullRequest(sessionId, pullRequest),
|
|
846
|
-
archive: async (sessionId) => {
|
|
847
|
-
// A running session is not archived mid-run; that is a "not yet", retried when the run ends.
|
|
848
|
-
try {
|
|
849
|
-
await this.setSessionArchived({ id: sessionId, archived: true });
|
|
850
|
-
return true;
|
|
851
|
-
}
|
|
852
|
-
catch (error) {
|
|
853
|
-
if (error instanceof AppServerError && error.code === 'busy')
|
|
854
|
-
return false;
|
|
855
|
-
throw error;
|
|
856
|
-
}
|
|
857
|
-
},
|
|
858
1055
|
wake: (sessionId, prompt, carry) => this.wakeForPullRequest(sessionId, prompt, carry),
|
|
859
1056
|
wakePending: id => this.timers.list().some(timer => timer.id === id),
|
|
860
1057
|
log: (level, detail) => this.log(level, detail),
|
|
@@ -867,7 +1064,16 @@ export class AppServer {
|
|
|
867
1064
|
data: (id, chunk) => this.emit('terminal.data', { id, data: chunk }),
|
|
868
1065
|
exit: (id, code, signal) => this.emit('terminal.exit', { id, code, ...(signal === undefined ? {} : { signal }) }),
|
|
869
1066
|
});
|
|
870
|
-
|
|
1067
|
+
// One persistent browser profile per project, kept in this engine's home: a session's panel
|
|
1068
|
+
// browser opens on its project's profile, so logins and history carry across that project's
|
|
1069
|
+
// sessions and restarts while other projects stay apart.
|
|
1070
|
+
this.browserViews = new BrowserViewManager((event, data) => this.emit(event, data), undefined, {
|
|
1071
|
+
profileFor: async (sessionId) => {
|
|
1072
|
+
const record = await this.readSession(sessionId);
|
|
1073
|
+
const key = record.projectId !== undefined && /^[a-f0-9]{16}$/.test(record.projectId) ? record.projectId : projectIdentity(record.workspace);
|
|
1074
|
+
return { key, directory: join(this.directory, 'browser-profiles', key) };
|
|
1075
|
+
},
|
|
1076
|
+
});
|
|
871
1077
|
// A wake that comes due is the engine's business here: it delivers the prompt itself, because this
|
|
872
1078
|
// process is the one a window talks to and nothing else is watching the deadline.
|
|
873
1079
|
this.timers.onDue = () => this.checkTimers();
|
|
@@ -1112,6 +1318,7 @@ export class AppServer {
|
|
|
1112
1318
|
case 'providers.auth.start': return this.providerAuth('start', params);
|
|
1113
1319
|
case 'providers.auth.cancel': return this.providerAuth('cancel', params);
|
|
1114
1320
|
case 'providers.auth.logout': return this.providerAuth('logout', params);
|
|
1321
|
+
case 'providers.auth.submit': return this.providerAuth('submit', params);
|
|
1115
1322
|
case 'account.status': return this.accountStatus();
|
|
1116
1323
|
case 'account.login': return this.signIn();
|
|
1117
1324
|
case 'account.logout': return this.signOut();
|
|
@@ -1137,7 +1344,7 @@ export class AppServer {
|
|
|
1137
1344
|
case 'sessions.rename': return { session: this.summary(await this.renameSession(params)) };
|
|
1138
1345
|
case 'sessions.setArchived': return { session: this.summary(await this.setSessionArchived(params)) };
|
|
1139
1346
|
case 'sessions.delete': return this.deleteSession(params);
|
|
1140
|
-
case 'sessions.pullRequest.get': return { pullRequest: (await readPullRequest(this.directory, identifier(params.id, 'id')))
|
|
1347
|
+
case 'sessions.pullRequest.get': return { pullRequest: pullRequestForClients(await readPullRequest(this.directory, identifier(params.id, 'id'))) };
|
|
1141
1348
|
case 'sessions.pullRequest.update': {
|
|
1142
1349
|
let settings;
|
|
1143
1350
|
try {
|
|
@@ -1146,7 +1353,7 @@ export class AppServer {
|
|
|
1146
1353
|
catch (error) {
|
|
1147
1354
|
throw new AppServerError('invalid-params', message(error));
|
|
1148
1355
|
}
|
|
1149
|
-
return { pullRequest: await this.updatePullRequest(identifier(params.id, 'id'), settings) };
|
|
1356
|
+
return { pullRequest: pullRequestForClients(await this.updatePullRequest(identifier(params.id, 'id'), settings)) };
|
|
1150
1357
|
}
|
|
1151
1358
|
case 'sessions.pullRequest.dismiss':
|
|
1152
1359
|
await this.dismissPullRequest(identifier(params.id, 'id'));
|
|
@@ -1156,6 +1363,7 @@ export class AppServer {
|
|
|
1156
1363
|
case 'run.resume': return this.resumeRun(params);
|
|
1157
1364
|
case 'run.cancel': return this.cancelRun(params.runId);
|
|
1158
1365
|
case 'run.setModel': return this.setRunModel(params);
|
|
1366
|
+
case 'run.setPermissions': return this.setRunPermissions(params);
|
|
1159
1367
|
case 'run.steer': return this.steerRun(params);
|
|
1160
1368
|
case 'run.approve': return this.settleApproval(params);
|
|
1161
1369
|
case 'run.answer': return this.settleAnswer(params);
|
|
@@ -1568,6 +1776,20 @@ export class AppServer {
|
|
|
1568
1776
|
delete merged.systemPromptOverride;
|
|
1569
1777
|
if (patch.autoArchiveDays === null)
|
|
1570
1778
|
delete merged.autoArchiveDays;
|
|
1779
|
+
if (Object.hasOwn(patch, 'webSearch')) {
|
|
1780
|
+
const webSearch = mergeWebSearchConfig(current.webSearch, patch.webSearch);
|
|
1781
|
+
if (webSearch)
|
|
1782
|
+
merged.webSearch = webSearch;
|
|
1783
|
+
else
|
|
1784
|
+
delete merged.webSearch;
|
|
1785
|
+
}
|
|
1786
|
+
if (Object.hasOwn(patch, 'browser')) {
|
|
1787
|
+
const browser = mergeBrowserConfig(current.browser, patch.browser);
|
|
1788
|
+
if (browser)
|
|
1789
|
+
merged.browser = browser;
|
|
1790
|
+
else
|
|
1791
|
+
delete merged.browser;
|
|
1792
|
+
}
|
|
1571
1793
|
if (Array.isArray(patch.providers)) {
|
|
1572
1794
|
merged.providers = allocateCodexAccountSlots(current.providers, mergeProviderSecrets(current.providers, patch.providers));
|
|
1573
1795
|
// A whole-array save can remove a linked account too. Bindings, not ids, decide which
|
|
@@ -1941,11 +2163,12 @@ export class AppServer {
|
|
|
1941
2163
|
if (params.providerType !== undefined) {
|
|
1942
2164
|
// Fixed-provider catalogs do not read a configured model or provider credential. Browse one
|
|
1943
2165
|
// before the first model is selected without storing an unusable provider or forwarding a key.
|
|
1944
|
-
|
|
1945
|
-
|
|
2166
|
+
const catalogs = { claude: 'https://api.anthropic.com', 'opencode-go': 'https://opencode.ai/inference/go', grok: GROK_BASE_URL, opencode: OPENCODE_BASE_URL };
|
|
2167
|
+
if (params.providerId !== undefined || typeof params.providerType !== 'string' || !Object.hasOwn(catalogs, params.providerType)) {
|
|
2168
|
+
throw new AppServerError('invalid-params', 'providerType must be claude, grok, opencode or opencode-go, without providerId');
|
|
1946
2169
|
}
|
|
1947
|
-
|
|
1948
|
-
|
|
2170
|
+
const type = params.providerType;
|
|
2171
|
+
provider = { id: 'catalog', type, model: type === 'opencode' ? 'catalog/catalog' : 'catalog', baseUrl: catalogs[type] };
|
|
1949
2172
|
}
|
|
1950
2173
|
else {
|
|
1951
2174
|
const config = await loadConfig(this.directory);
|
|
@@ -1967,6 +2190,10 @@ export class AppServer {
|
|
|
1967
2190
|
}
|
|
1968
2191
|
/** Local-client only. The remote engine relay deliberately does not admit these methods. */
|
|
1969
2192
|
async providerAuth(action, params) {
|
|
2193
|
+
if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'opencode')
|
|
2194
|
+
return this.managedProviderAuth(action, params);
|
|
2195
|
+
if (action === 'submit')
|
|
2196
|
+
throw new AppServerError('invalid-params', 'Only Claude, Grok and OpenCode sign-ins accept a pasted code.');
|
|
1970
2197
|
if (params.providerType === 'anthropic')
|
|
1971
2198
|
return this.anthropicProviderAuth(action, params);
|
|
1972
2199
|
if (params.providerType !== 'codex' || Object.keys(params).some(key => !['providerType', 'attemptId', 'providerId'].includes(key))) {
|
|
@@ -2002,6 +2229,60 @@ export class AppServer {
|
|
|
2002
2229
|
throw new AppServerError('auth', 'ChatGPT sign-in could not be completed. Check the official Codex CLI and try again.');
|
|
2003
2230
|
}
|
|
2004
2231
|
}
|
|
2232
|
+
/**
|
|
2233
|
+
* Subscription sign-in through a vendor CLI's own login: Claude Code, Grok, or one of OpenCode's
|
|
2234
|
+
* upstream providers. Local-client only, like the others. Each of these logins belongs to the CLI
|
|
2235
|
+
* on this machine rather than to one provider entry, so the draft a person is adding can sign in
|
|
2236
|
+
* before it is saved; a providerId is accepted and ignored.
|
|
2237
|
+
*/
|
|
2238
|
+
async managedProviderAuth(action, params) {
|
|
2239
|
+
const type = params.providerType;
|
|
2240
|
+
const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : 'OpenCode';
|
|
2241
|
+
const allowed = ['providerType', 'attemptId', 'providerId', 'code', ...(type === 'opencode' ? ['signInProvider', 'signInMethod'] : [])];
|
|
2242
|
+
if (Object.keys(params).some(key => !allowed.includes(key))) {
|
|
2243
|
+
throw new AppServerError('invalid-params', `${product} sign-in accepts providerType, an optional attemptId and providerId${type === 'opencode' ? ', signInProvider and signInMethod' : ''}, and a code to submit.`);
|
|
2244
|
+
}
|
|
2245
|
+
const id = params.attemptId;
|
|
2246
|
+
if ((id !== undefined && (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)))
|
|
2247
|
+
|| ((action === 'start' || action === 'cancel' || action === 'submit') && id === undefined) || (action === 'logout' && id !== undefined)) {
|
|
2248
|
+
throw new AppServerError('invalid-params', 'A valid sign-in attemptId is required.');
|
|
2249
|
+
}
|
|
2250
|
+
optionalIdentifier(params.providerId, 'providerId');
|
|
2251
|
+
const code = params.code;
|
|
2252
|
+
if (action === 'submit' ? typeof code !== 'string' || !code.trim() || code.length > 2000 : code !== undefined) {
|
|
2253
|
+
throw new AppServerError('invalid-params', action === 'submit' ? 'A sign-in code is required.' : 'Only providers.auth.submit takes a code.');
|
|
2254
|
+
}
|
|
2255
|
+
if (params.signInMethod !== undefined && (!Number.isSafeInteger(params.signInMethod) || params.signInMethod < 0)) {
|
|
2256
|
+
throw new AppServerError('invalid-params', 'signInMethod must be a sign-in option index.');
|
|
2257
|
+
}
|
|
2258
|
+
if (params.signInProvider !== undefined && (typeof params.signInProvider !== 'string' || !/^[\w.@-]{1,100}$/.test(params.signInProvider))) {
|
|
2259
|
+
throw new AppServerError('invalid-params', 'signInProvider must be an OpenCode provider id.');
|
|
2260
|
+
}
|
|
2261
|
+
try {
|
|
2262
|
+
let view;
|
|
2263
|
+
if (type === 'opencode') {
|
|
2264
|
+
const service = this.openCodeSignIn;
|
|
2265
|
+
view = action === 'start' ? await service.start(id, params.signInProvider, params.signInMethod)
|
|
2266
|
+
: action === 'cancel' ? await service.cancel(id)
|
|
2267
|
+
: action === 'submit' ? await service.submitCode(id, code)
|
|
2268
|
+
: action === 'logout' ? await service.logout(params.signInProvider)
|
|
2269
|
+
: await service.status(id);
|
|
2270
|
+
}
|
|
2271
|
+
else {
|
|
2272
|
+
const service = type === 'claude' ? this.claudeSignIn : this.grokSignIn;
|
|
2273
|
+
view = action === 'start' ? await service.start(id)
|
|
2274
|
+
: action === 'cancel' ? await service.cancel(id)
|
|
2275
|
+
: action === 'submit' ? await service.submitCode(id, code)
|
|
2276
|
+
: action === 'logout' ? await service.logout()
|
|
2277
|
+
: await service.status(id);
|
|
2278
|
+
}
|
|
2279
|
+
return managedAuthView(type, view, action === 'start');
|
|
2280
|
+
}
|
|
2281
|
+
catch {
|
|
2282
|
+
// Vendor CLI output can carry account details; an unexpected failure never forwards it.
|
|
2283
|
+
throw new AppServerError('auth', `${product} sign-in could not be completed. Check its CLI and try again.`);
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2005
2286
|
/**
|
|
2006
2287
|
* Claude Console sign-in for one configured Anthropic provider. Local-client only, like Codex
|
|
2007
2288
|
* sign-in: the remote engine relay does not admit these methods.
|
|
@@ -2479,6 +2760,14 @@ export class AppServer {
|
|
|
2479
2760
|
if (params.continueSession === true && typeof params.sessionId !== 'string') {
|
|
2480
2761
|
throw new AppServerError('invalid-params', 'continueSession needs the session it continues.');
|
|
2481
2762
|
}
|
|
2763
|
+
// A switch to another graph mid-session: the new graph's entry node is handed the session's
|
|
2764
|
+
// history whatever its own policy says. It only means something for a session that has one.
|
|
2765
|
+
if (params.entryHistory !== undefined && typeof params.entryHistory !== 'boolean') {
|
|
2766
|
+
throw new AppServerError('invalid-params', 'entryHistory must be a boolean.');
|
|
2767
|
+
}
|
|
2768
|
+
if (params.entryHistory === true && typeof params.sessionId !== 'string') {
|
|
2769
|
+
throw new AppServerError('invalid-params', 'entryHistory needs the session whose history it hands on.');
|
|
2770
|
+
}
|
|
2482
2771
|
// Background jobs choose a mode for this attempt, never the interactive workspace default.
|
|
2483
2772
|
// Validate before preparation can save anything, including a competing persistent selection.
|
|
2484
2773
|
if (params.runPermissions !== undefined && params.permissions !== undefined) {
|
|
@@ -2515,7 +2804,7 @@ export class AppServer {
|
|
|
2515
2804
|
* after this point is `run.start`'s own path — same events, same client run flow, one-run-per-
|
|
2516
2805
|
* engine guard included.
|
|
2517
2806
|
*/
|
|
2518
|
-
async resumeRun(params) {
|
|
2807
|
+
async resumeRun(params, internal) {
|
|
2519
2808
|
// The same refusal split `run.start` uses: a second task is refused with `engine-busy`, which
|
|
2520
2809
|
// the desktop answers by looking for (or spawning) another engine, while a checkout conflict
|
|
2521
2810
|
// is `busy` — a condition of this engine's own work that retrying elsewhere cannot fix.
|
|
@@ -2560,6 +2849,16 @@ export class AppServer {
|
|
|
2560
2849
|
const task = turn?.task;
|
|
2561
2850
|
if (typeof task !== 'string' || !task)
|
|
2562
2851
|
throw new AppServerError('invalid-params', 'That session no longer carries the stopped attempt, so it cannot be resumed.');
|
|
2852
|
+
// The automation context rode the combined task into session history, but the source record
|
|
2853
|
+
// keeps the parts apart: a resume re-sends them separately, because the combined text of a
|
|
2854
|
+
// limit-length prompt would fail the task validation the raw prompt passes. The suffix is
|
|
2855
|
+
// checked exactly, so a task that merely resembles the context stays whole.
|
|
2856
|
+
let resumeTask = task;
|
|
2857
|
+
let resumeAutomationContext;
|
|
2858
|
+
if (typeof source.automationContext === 'string' && task.endsWith(`\n\n${source.automationContext}`)) {
|
|
2859
|
+
resumeTask = task.slice(0, task.length - source.automationContext.length - 2);
|
|
2860
|
+
resumeAutomationContext = source.automationContext;
|
|
2861
|
+
}
|
|
2563
2862
|
// Directions a previous continuation armed and never got to persist: each is drained at the
|
|
2564
2863
|
// agent's first turn boundary, and a crash before the next checkpoint leaves the restored
|
|
2565
2864
|
// conversation without it — the record is the durable copy of what the user said. Every
|
|
@@ -2581,18 +2880,27 @@ export class AppServer {
|
|
|
2581
2880
|
if (typeof entry.runId !== 'string' || typeof entry.direction !== 'string' || entry.direction.length === 0)
|
|
2582
2881
|
continue;
|
|
2583
2882
|
const id = typeof entry.id === 'string' && entry.id ? entry.id : `${entry.runId}#own`;
|
|
2584
|
-
recordedDirections.push({ runId: entry.runId, direction: entry.direction, id, ...(recordedAttachments(entry.runId) === undefined ? {} : { attachments: recordedAttachments(entry.runId) }) });
|
|
2883
|
+
recordedDirections.push({ runId: entry.runId, direction: entry.direction, id, ...(recordedAttachments(entry.runId) === undefined ? {} : { attachments: recordedAttachments(entry.runId) }), ...wakeProvenance(entry.wake, entry.node) });
|
|
2585
2884
|
}
|
|
2586
2885
|
if (typeof source.direction === 'string' && source.direction.length > 0) {
|
|
2587
|
-
|
|
2886
|
+
// A reminder a timer delivered stays the agent's own, and its node's, when a later resume recovers it.
|
|
2887
|
+
recordedDirections.push({ runId: originalRunId, direction: source.direction, id: `${originalRunId}#own`, ...(turn?.attachments?.length ? { attachments: turn.attachments } : {}), ...wakeProvenance(source.wake, source.directionNode) });
|
|
2588
2888
|
}
|
|
2589
2889
|
// A resume with no message of its own continues the newest recorded direction: it becomes this
|
|
2590
2890
|
// attempt's own message — the turn it records, with that direction's own attachments — while
|
|
2591
2891
|
// the older recorded ones queue ahead of it. With a message of its own, every recorded one is
|
|
2592
2892
|
// carried ahead of it, newest last.
|
|
2593
2893
|
const recoveredOwnDirection = direction === undefined && recordedDirections.length > 0;
|
|
2594
|
-
|
|
2595
|
-
|
|
2894
|
+
// A recovered direction keeps the provenance it was recorded with; a message sent with this resume is the
|
|
2895
|
+
// user's own and carries none.
|
|
2896
|
+
let recoveredWake = {};
|
|
2897
|
+
if (recoveredOwnDirection) {
|
|
2898
|
+
const recovered = recordedDirections.pop();
|
|
2899
|
+
direction = recovered.direction;
|
|
2900
|
+
recoveredWake = { ...(recovered.wake === undefined ? {} : { wake: recovered.wake }), ...(recovered.node === undefined ? {} : { node: recovered.node }) };
|
|
2901
|
+
}
|
|
2902
|
+
const ownWake = internal?.wake ?? recoveredWake.wake;
|
|
2903
|
+
const ownWakeNode = internal?.wakeNode ?? recoveredWake.node;
|
|
2596
2904
|
const carried = [...recordedDirections];
|
|
2597
2905
|
// The turn a direction is being re-armed from must not also seed the model's history: its
|
|
2598
2906
|
// stored direction renders through `turnModelTask`, and leaving it in the fresh seed would
|
|
@@ -2665,13 +2973,19 @@ export class AppServer {
|
|
|
2665
2973
|
// configuration once and judges the model against the same snapshot it resolves the
|
|
2666
2974
|
// provider and the model from, so the two cannot disagree.
|
|
2667
2975
|
const carriedModel = typeof source.model === 'string' && source.model ? source.model : undefined;
|
|
2976
|
+
// Nodes the stopped attempt switched mid-run, keyed by node id: the resumed graph re-applies
|
|
2977
|
+
// them on top of its own binding, so the switched nodes keep their new pairs while every
|
|
2978
|
+
// other node runs as the graph names. They compose with a carried whole-run override — the
|
|
2979
|
+
// flag below rebuilds every node first, and the switches then move their nodes.
|
|
2980
|
+
const carriedNodeModelOverrides = readNodeModelOverrides(source.nodeModelOverrides);
|
|
2668
2981
|
// Reserve the session for the whole preparation, not only from the moment the run exists: the
|
|
2669
2982
|
// resumed attempt saves the record it read here, so a rename or delete accepted in between is
|
|
2670
2983
|
// lost — and a protocol client can send one, since the desktop's own reservation cannot.
|
|
2671
2984
|
this.startingSession = sessionId;
|
|
2672
2985
|
try {
|
|
2673
2986
|
return await this.prepareRun({
|
|
2674
|
-
workspace: existing.workspace, task, sessionId,
|
|
2987
|
+
workspace: existing.workspace, task: resumeTask, sessionId,
|
|
2988
|
+
...(resumeAutomationContext === undefined ? {} : { automationContext: resumeAutomationContext }),
|
|
2675
2989
|
...(typeof graphId === 'string' ? { graph: graphId } : {}),
|
|
2676
2990
|
...(params.provider !== undefined ? { provider: params.provider } : typeof source.provider === 'string' ? { provider: source.provider } : {}),
|
|
2677
2991
|
...(params.model === undefined ? {} : { model: params.model }),
|
|
@@ -2691,12 +3005,19 @@ export class AppServer {
|
|
|
2691
3005
|
// re-runs the graph, and without this the nodes would go back to the models the graph
|
|
2692
3006
|
// names for themselves — a different model than the attempt being continued ran on.
|
|
2693
3007
|
...(params.overrideAllNodes === undefined ? (source.overrideAllNodes === true ? { overrideAllNodes: true } : {}) : { overrideAllNodes: params.overrideAllNodes }),
|
|
3008
|
+
// An explicit all-node resume replaces every node's model: the stopped attempt's per-node
|
|
3009
|
+
// switches named the pairs it was leaving, and forwarding them would outrank the pair the
|
|
3010
|
+
// caller just chose. An ordinary resume keeps them.
|
|
3011
|
+
...(params.overrideAllNodes === true || carriedNodeModelOverrides === undefined ? {} : { nodeModelOverrides: carriedNodeModelOverrides }),
|
|
3012
|
+
// An attempt that switched the session onto its graph keeps the entry node's seed: the
|
|
3013
|
+
// runner gives it only to an entry visit that has no saved conversation to re-enter.
|
|
3014
|
+
...(source.entryHistory === true ? { entryHistory: true } : {}),
|
|
2694
3015
|
...(params.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}),
|
|
2695
3016
|
...(params.permissions === undefined ? {} : { permissions: params.permissions }),
|
|
2696
3017
|
// Attachments composed beside the message: they are this turn's own, and only `prepareRun`
|
|
2697
3018
|
// can resolve them — the descriptor is spooled or validated against the workspace there.
|
|
2698
3019
|
...(sentAttachments === undefined ? {} : { attachments: sentAttachments }),
|
|
2699
|
-
}, { sameSession: sessionId, resumedFrom: originalRunId, ...(inheritedPermissions === undefined ? {} : { inheritedPermissions }), ...(direction === undefined ? {} : { direction }), ...(recoveredOwnDirection ? { recoveredDirection: true } : {}), ...(carried.length === 0 ? {} : { carried }), ...(armedRunIds.length === 0 ? {} : { armedRunIds }), ...(resumedAttachments === undefined ? {} : { attachments: resumedAttachments }), ...(carriedModel === undefined || params.model !== undefined || params.provider !== undefined ? {} : { carriedModel }), ...(stoppedTurnAttachments === undefined ? {} : { stoppedTurnAttachments }), ...(params.model === undefined && params.provider === undefined && source.liveModelChanged !== true ? {} : { explicitPair: true }) });
|
|
3020
|
+
}, { sameSession: sessionId, resumedFrom: originalRunId, ...(inheritedPermissions === undefined ? {} : { inheritedPermissions }), ...(direction === undefined ? {} : { direction }), ...(recoveredOwnDirection ? { recoveredDirection: true } : {}), ...(carried.length === 0 ? {} : { carried }), ...(armedRunIds.length === 0 ? {} : { armedRunIds }), ...(resumedAttachments === undefined ? {} : { attachments: resumedAttachments }), ...(carriedModel === undefined || params.model !== undefined || params.provider !== undefined ? {} : { carriedModel }), ...(stoppedTurnAttachments === undefined ? {} : { stoppedTurnAttachments }), ...(params.model === undefined && params.provider === undefined && source.liveModelChanged !== true ? {} : { explicitPair: true }), ...(ownWake === undefined ? {} : { wake: ownWake }), ...(ownWakeNode === undefined ? {} : { wakeNode: ownWakeNode }), ...(internal?.freshAllowance === true ? { freshAllowance: true } : {}) });
|
|
2700
3021
|
}
|
|
2701
3022
|
catch (error) {
|
|
2702
3023
|
// Preparation refused before a run existed to own the claim; whoever asks next must not be
|
|
@@ -2819,15 +3140,55 @@ export class AppServer {
|
|
|
2819
3140
|
* the graph is loaded — is what keeps the runner, the resume guard and the health preflight from
|
|
2820
3141
|
* disagreeing about the model a node runs, because all three read this same graph.
|
|
2821
3142
|
*/
|
|
2822
|
-
graphForRun(graph, overrideAllNodes, provider, model) {
|
|
3143
|
+
graphForRun(graph, overrideAllNodes, provider, model, nodeModelOverrides) {
|
|
2823
3144
|
const execution = overrideAllNodes ? applyModelOverride(graph, { provider, model }) : graph;
|
|
2824
|
-
|
|
2825
|
-
|
|
3145
|
+
const switches = nodeModelOverrides === undefined ? execution : applyNodeModelOverrides(execution, nodeModelOverrides);
|
|
3146
|
+
// The original a later whole-run switch rebuilds from is the graph as it was loaded, before
|
|
3147
|
+
// both kinds of live switch: the whole-run override rewrote this copy's nodes, and the node
|
|
3148
|
+
// switches rode on top of it. Keyed by the object the run executes, so `executeRun` finds it.
|
|
3149
|
+
this.originalModelGraphs.set(switches, structuredClone(graph));
|
|
3150
|
+
return switches;
|
|
3151
|
+
}
|
|
3152
|
+
/**
|
|
3153
|
+
* The graph a resume replays against, with carried node switches applied before its remaining
|
|
3154
|
+
* provider references are bound.
|
|
3155
|
+
*
|
|
3156
|
+
* A node moved to provider B survives provider A leaving the configuration: the carried provider
|
|
3157
|
+
* replaces the switched node's reference before the binder validates what is left, so the
|
|
3158
|
+
* obsolete pin cannot fail the load. The carried model travels after the bind — the binder offers
|
|
3159
|
+
* only models a provider's configuration lists, and a live switch may have named a model the
|
|
3160
|
+
* endpoint serves without the configuration listing it, which `resolveModel` accepted. A
|
|
3161
|
+
* whole-run override sets every reference aside instead, so it binds nothing, as before.
|
|
3162
|
+
*/
|
|
3163
|
+
async loadResumeGraph(selection, signal, overrideAllNodes, nodeModelOverrides, config) {
|
|
3164
|
+
if (overrideAllNodes || nodeModelOverrides === undefined) {
|
|
3165
|
+
return this.loadGraph(selection, signal, undefined, { bindProviders: !overrideAllNodes, allowDeleted: true });
|
|
3166
|
+
}
|
|
3167
|
+
const raw = await this.loadGraph(selection, signal, undefined, { bindProviders: false, allowDeleted: true });
|
|
3168
|
+
// The carried provider replaces the switched node's reference before binding, and the model
|
|
3169
|
+
// field steps aside so the binder does not demand it from the provider's configured pool; the
|
|
3170
|
+
// full carried pair is applied to the bound copy below.
|
|
3171
|
+
const prebound = structuredClone(raw);
|
|
3172
|
+
for (const [nodeId, pair] of Object.entries(nodeModelOverrides)) {
|
|
3173
|
+
const node = prebound.nodes[nodeId];
|
|
3174
|
+
if (node?.type === 'agent') {
|
|
3175
|
+
node.provider = pair.provider;
|
|
3176
|
+
delete node.model;
|
|
3177
|
+
}
|
|
3178
|
+
}
|
|
3179
|
+
return applyNodeModelOverrides(bindPortableGraphProviders(prebound, config), nodeModelOverrides);
|
|
2826
3180
|
}
|
|
2827
3181
|
async prepareRunValidated(params, internal, createdSpools) {
|
|
2828
3182
|
const root = await workspaceRoot(params.workspace);
|
|
2829
3183
|
this.assertRunning();
|
|
2830
|
-
const
|
|
3184
|
+
const submitted = text(params.task, 'task', MAX_TASK_CHARS);
|
|
3185
|
+
// An automation's awareness rides its own validated channel instead of inside the task: appending
|
|
3186
|
+
// it to a task near the store's prompt limit would invalidate prompts `run.start` accepted before
|
|
3187
|
+
// the channel existed. The combined text is what the session records and the engine receives.
|
|
3188
|
+
const automationContext = params.automationContext === undefined
|
|
3189
|
+
? undefined
|
|
3190
|
+
: text(params.automationContext, 'automationContext', AUTOMATION_CONTEXT_CHARS);
|
|
3191
|
+
const task = automationContext === undefined ? submitted : `${submitted}\n\n${automationContext}`;
|
|
2831
3192
|
// Attachments arrive as pending wire items from a client, or as already-resolved refs when
|
|
2832
3193
|
// `run.resume` continues a stopped attempt's own turn; both resolve once, here, so every
|
|
2833
3194
|
// record below names the same disk-backed set.
|
|
@@ -2898,12 +3259,18 @@ export class AppServer {
|
|
|
2898
3259
|
// this run only. The saved graph is untouched — the override is applied to the copy the run
|
|
2899
3260
|
// executes, so the next run of the same graph keeps its own selections.
|
|
2900
3261
|
const overrideAllNodes = params.overrideAllNodes === true;
|
|
3262
|
+
// Node pairs a resume carries from the attempt it continues (see `run.resume`); a fresh start
|
|
3263
|
+
// sends none. They compose with a whole-run override rather than excluding it: the whole-run
|
|
3264
|
+
// rebuild answers for every node first, and the carried switches move their nodes on top.
|
|
3265
|
+
const nodeModelOverrides = readNodeModelOverrides(params.nodeModelOverrides);
|
|
2901
3266
|
// A run that names its model or provider made an explicit choice too, like the CLI's --model:
|
|
2902
3267
|
// adaptive routing must not re-tier the nodes that inherit it, even when the graph's own pins stay.
|
|
2903
3268
|
const modelPinned = overrideAllNodes || params.model !== undefined || params.provider !== undefined;
|
|
2904
3269
|
// The desktop sets this for engines that do not own the session's panel browser: their runs
|
|
2905
3270
|
// relay every browser.panel operation to the owning engine through the window.
|
|
2906
3271
|
const panelRelay = params.panelBrowserRelay === true;
|
|
3272
|
+
// Validated in `startRun`; a resume carries the flag from the attempt it continues.
|
|
3273
|
+
const entryHistory = params.entryHistory === true;
|
|
2907
3274
|
// The run's full scope for `$run.input.*`/`$run.state.*` edge mappings. `run.resume` passes the
|
|
2908
3275
|
// stopped attempt's persisted scope through here; a plain object from either caller is taken as
|
|
2909
3276
|
// given (cloned, so nothing downstream can mutate the caller's object), anything else is absent.
|
|
@@ -2911,7 +3278,12 @@ export class AppServer {
|
|
|
2911
3278
|
? structuredClone(params.input) : undefined;
|
|
2912
3279
|
const runState = params.state !== undefined && typeof params.state === 'object' && params.state !== null && !Array.isArray(params.state)
|
|
2913
3280
|
? structuredClone(params.state) : undefined;
|
|
2914
|
-
const
|
|
3281
|
+
const implicit = params.graph === undefined || params.graph === '';
|
|
3282
|
+
let selection = implicit ? configuredGraphSelection(config, await currentGraphSubject()) : identifier(params.graph, 'graph');
|
|
3283
|
+
// A saved default that was deleted falls back to Default, as the listing reports it; a run that
|
|
3284
|
+
// names the deleted graph explicitly is still refused when it loads.
|
|
3285
|
+
if (implicit && await this.selectionIsDeleted(selection))
|
|
3286
|
+
selection = 'default';
|
|
2915
3287
|
const requested = params.permissions === undefined ? undefined : permissionMode(params.permissions);
|
|
2916
3288
|
if (requested) {
|
|
2917
3289
|
// Serialized with every other configuration write, so a permission change cannot discard a
|
|
@@ -3012,6 +3384,9 @@ export class AppServer {
|
|
|
3012
3384
|
// The whole `resumedFrom` lineage, as the chain walk below leaves it: a successful resume has to
|
|
3013
3385
|
// clear every attempt's checkpoint, not just the one hop above it.
|
|
3014
3386
|
let lineage = [];
|
|
3387
|
+
// What this resume could not rule out about the stopped attempt, recorded as warnings in the new
|
|
3388
|
+
// attempt's journal: the resume goes ahead regardless, and the user reads why a step may repeat.
|
|
3389
|
+
let resumeWarnings = [];
|
|
3015
3390
|
// The journals the lineage walk read, kept for the failure path's question whether the lineage
|
|
3016
3391
|
// proved completed work — which is what decides refusal over a plain restart.
|
|
3017
3392
|
const lineageJournals = new Map();
|
|
@@ -3043,8 +3418,18 @@ export class AppServer {
|
|
|
3043
3418
|
try {
|
|
3044
3419
|
// The pinned graph the replay runs against, loaded here so a journal the replay cannot
|
|
3045
3420
|
// reconcile with it refuses the REQUEST instead of starting a run that immediately fails
|
|
3046
|
-
// (or, worse, would have restarted from the entry and repeated completed work).
|
|
3047
|
-
|
|
3421
|
+
// (or, worse, would have restarted from the entry and repeated completed work). The stopped
|
|
3422
|
+
// attempt's node switches ride on top of the bound graph — after a whole-run override when
|
|
3423
|
+
// one was carried — so the switched nodes keep their new pairs, and their checkpoints read
|
|
3424
|
+
// the new pair as the node's identity in the guards below. A carried switch replaces the
|
|
3425
|
+
// switched node's provider reference before the graph's remaining provider references are
|
|
3426
|
+
// bound: a node moved to provider B survives provider A leaving the configuration, while
|
|
3427
|
+
// the nodes still naming A are validated against it as before. The carried model travels
|
|
3428
|
+
// after the bind — the binder offers only models a provider's configuration lists, and a
|
|
3429
|
+
// live switch may have named a model the endpoint serves without the configuration listing
|
|
3430
|
+
// it, which `resolveModel` accepted. A whole-run override sets every reference aside
|
|
3431
|
+
// instead, so it binds nothing, as before.
|
|
3432
|
+
const graph = resumedGraph = this.graphForRun(await this.loadResumeGraph(selection, controller.signal, overrideAllNodes, nodeModelOverrides, config), overrideAllNodes, provider.id, modelId, nodeModelOverrides);
|
|
3048
3433
|
// Each attempt's journal carries only its own events: the progress it inherited came
|
|
3049
3434
|
// through seeding, not through anything replayable from its file. So the whole
|
|
3050
3435
|
// `resumedFrom` chain is walked and replayed oldest-to-newest, folding each attempt's
|
|
@@ -3087,35 +3472,78 @@ export class AppServer {
|
|
|
3087
3472
|
const runScope = { input: { ...(runInput ?? {}), task }, state: runState ?? {} };
|
|
3088
3473
|
let progress = replayRunJournal([], graph, runScope);
|
|
3089
3474
|
const collected = new Map();
|
|
3090
|
-
|
|
3475
|
+
// Which attempt (by its place in the oldest-first walk) each collected checkpoint came from.
|
|
3476
|
+
const collectedFrom = new Map();
|
|
3477
|
+
// The attempts whose records could not all be written. A session must always be resumable,
|
|
3478
|
+
// so neither refuses the resume: each becomes a warning the user reads in the transcript.
|
|
3479
|
+
const journalGaps = [];
|
|
3480
|
+
const checkpointGaps = [];
|
|
3481
|
+
for (const [index, attempt] of chain.reverse().entries()) {
|
|
3091
3482
|
const journalText = await readFile(runRecordPath(this.directory, attempt, 'jsonl'), 'utf8').catch(() => '');
|
|
3092
3483
|
lineageJournals.set(attempt, journalText);
|
|
3093
|
-
// A journal whose
|
|
3094
|
-
// are present, so the file parses as a complete account while a completed
|
|
3095
|
-
// activation)
|
|
3096
|
-
//
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
throw new AppServerError('invalid-params', `That attempt cannot be resumed: the journal of ${attempt} recorded a write failure, so its events cannot be trusted. Start a new run instead.`);
|
|
3100
|
-
}
|
|
3484
|
+
// A journal whose writer gave events up, or died holding them, has an interior hole: the
|
|
3485
|
+
// events after it are present, so the file parses as a complete account while a completed
|
|
3486
|
+
// node (or an activation) may simply be missing. The replay below can then sit behind
|
|
3487
|
+
// the real position, and the resumed run may repeat a step that had finished.
|
|
3488
|
+
if (await journalWriteFailed(this.directory, attempt))
|
|
3489
|
+
journalGaps.push(attempt);
|
|
3101
3490
|
// A checkpoint that could not be written is the conversation the resume re-enters the
|
|
3102
|
-
// node with
|
|
3103
|
-
//
|
|
3104
|
-
|
|
3105
|
-
if (
|
|
3106
|
-
|
|
3107
|
-
}
|
|
3491
|
+
// node with. Whether that still matters is decided once every attempt's checkpoints are
|
|
3492
|
+
// collected: a later write of the same node may already have replaced it.
|
|
3493
|
+
const checkpointGap = await checkpointFailure(this.directory, attempt);
|
|
3494
|
+
if (checkpointGap !== undefined)
|
|
3495
|
+
checkpointGaps.push({ index, failure: checkpointGap });
|
|
3108
3496
|
progress = mergeRunProgress(progress, replayRunJournal(journalText.split('\n').filter(Boolean), graph, runScope));
|
|
3109
3497
|
// Every attempt in the lineage may hold a branch's only conversation: a parallel
|
|
3110
3498
|
// branch the parent attempt re-entered (or never reached) checkpoints itself, not its
|
|
3111
3499
|
// successor. Newest wins per node — the chain walks oldest first — and a checkpoint
|
|
3112
3500
|
// naming a node the current graph no longer has cannot re-enter anything.
|
|
3113
3501
|
for (const checkpoint of await readRunCheckpoints(this.directory, attempt)) {
|
|
3114
|
-
if (graph.nodes[checkpoint.nodeId])
|
|
3502
|
+
if (graph.nodes[checkpoint.nodeId]) {
|
|
3115
3503
|
collected.set(checkpoint.nodeId, checkpoint);
|
|
3504
|
+
collectedFrom.set(checkpoint.nodeId, index);
|
|
3505
|
+
}
|
|
3116
3506
|
}
|
|
3117
3507
|
}
|
|
3118
3508
|
lineage = [...chain];
|
|
3509
|
+
// A timer continuation is the agent coming back, on its own deadline, to work it was waiting on - and
|
|
3510
|
+
// the attempt it continues usually stopped because it ran out of budget. Restored as-is, a spent
|
|
3511
|
+
// allowance would end the node before it read the reminder, so the resume would be refused and the
|
|
3512
|
+
// reminder lost. It gets a fresh allowance instead: every restored conversation keeps all its messages
|
|
3513
|
+
// and the completed work stays completed (nothing is replayed), but the counters it spent are cleared
|
|
3514
|
+
// and the lineage's tool spend no longer counts against the new run.
|
|
3515
|
+
if (internal?.freshAllowance === true) {
|
|
3516
|
+
for (const [nodeId, checkpoint] of collected)
|
|
3517
|
+
collected.set(nodeId, { ...checkpoint, state: freshAllowance(checkpoint.state) });
|
|
3518
|
+
}
|
|
3519
|
+
const warnings = [];
|
|
3520
|
+
if (journalGaps.length > 0) {
|
|
3521
|
+
warnings.push('Part of this task\'s journal could not be saved while it ran (the disk may have been full), so this resume may repeat a step that had already finished.');
|
|
3522
|
+
}
|
|
3523
|
+
// A failed checkpoint matters only for a visit this resume re-enters, and only while no
|
|
3524
|
+
// checkpoint of that same visit written after the failure (by the same attempt or a later
|
|
3525
|
+
// one) replaced it. The visit is matched by generation where both sides know it: a node in
|
|
3526
|
+
// a cycle keeps one checkpoint file, and a file holding another generation's conversation
|
|
3527
|
+
// is skipped by the runner for this one, so it covers nothing here.
|
|
3528
|
+
const reentered = progress.pending.map(activation => ({ nodeId: activation.nodeId, generation: activation.generation ?? 0 }));
|
|
3529
|
+
const sameVisit = (a, b) => a.nodeId === b.nodeId && (a.generation === undefined || b.generation === undefined || a.generation === b.generation);
|
|
3530
|
+
const unsaved = new Set();
|
|
3531
|
+
for (const { index, failure } of checkpointGaps) {
|
|
3532
|
+
for (const visit of failure.visits ?? reentered) {
|
|
3533
|
+
if (!reentered.some(pending => sameVisit(visit, pending)))
|
|
3534
|
+
continue;
|
|
3535
|
+
const saved = collected.get(visit.nodeId);
|
|
3536
|
+
const replaced = saved !== undefined && sameVisit(visit, saved)
|
|
3537
|
+
&& ((collectedFrom.get(visit.nodeId) ?? -1) > index
|
|
3538
|
+
|| (failure.at !== undefined && Date.parse(saved.savedAt) > Date.parse(failure.at)));
|
|
3539
|
+
if (!replaced)
|
|
3540
|
+
unsaved.add(visit.nodeId);
|
|
3541
|
+
}
|
|
3542
|
+
}
|
|
3543
|
+
if (unsaved.size > 0) {
|
|
3544
|
+
const names = [...unsaved].map(nodeId => `"${graph.nodes[nodeId]?.name ?? nodeId}"`).join(', ');
|
|
3545
|
+
warnings.push(`The latest conversation of ${names} could not be saved while it ran (the disk may have been full), so ${unsaved.size === 1 ? 'it continues' : 'they continue'} from an earlier point and may repeat work.`);
|
|
3546
|
+
}
|
|
3119
3547
|
// The model identity this run would execute a node with, mirroring the resolution the
|
|
3120
3548
|
// runner's identical guard applies (`node.provider ?? run provider`, and the model the
|
|
3121
3549
|
// node declares or the resolved provider's configured one).
|
|
@@ -3385,7 +3813,9 @@ export class AppServer {
|
|
|
3385
3813
|
// identity-less (legacy) entry falls back to the complete-message rule.
|
|
3386
3814
|
if (entry.id !== undefined && (!Array.isArray(checkpoint.steeringDelivered) || !checkpoint.steeringDelivered.includes(entry.id)))
|
|
3387
3815
|
return false;
|
|
3388
|
-
|
|
3816
|
+
// A timer's direction reached the node in the agent's own reminder wording, so that is the text a
|
|
3817
|
+
// conversation that received it carries.
|
|
3818
|
+
return carriesText(asUserMessages(messages), entry.wake === 'timer' ? timerReminderText(entry.direction) : entry.direction);
|
|
3389
3819
|
};
|
|
3390
3820
|
const checkpointProves = (checkpoint, entry) => {
|
|
3391
3821
|
const parallel = graph.nodes[checkpoint.nodeId]?.modifiers?.parallel;
|
|
@@ -3411,7 +3841,7 @@ export class AppServer {
|
|
|
3411
3841
|
// so a repeated instruction cannot pass on an older conversation's words.
|
|
3412
3842
|
const ownDirection = internal?.direction;
|
|
3413
3843
|
const recoveredId = internal?.resumedFrom === undefined ? undefined : `${internal.resumedFrom}#own`;
|
|
3414
|
-
if (internal?.recoveredDirection === true && ownDirection !== undefined && reenteredCheckpoints.some(checkpoint => checkpointProves(checkpoint, { direction: ownDirection, id: recoveredId }))) {
|
|
3844
|
+
if (internal?.recoveredDirection === true && ownDirection !== undefined && reenteredCheckpoints.some(checkpoint => checkpointProves(checkpoint, { direction: ownDirection, id: recoveredId, ...(internal.wake === undefined ? {} : { wake: internal.wake }) }))) {
|
|
3415
3845
|
resumedDirection = undefined;
|
|
3416
3846
|
}
|
|
3417
3847
|
// The resume still owes a message: is there any node left that could read it? A node the run
|
|
@@ -3425,7 +3855,7 @@ export class AppServer {
|
|
|
3425
3855
|
// completion and polls the queue first.
|
|
3426
3856
|
const toolCeilings = [runLimits.maxToolCalls, graph.limits?.maxToolCalls]
|
|
3427
3857
|
.filter((value) => typeof value === 'number' && !isUnlimitedAlias('maxToolCalls', value));
|
|
3428
|
-
if (toolCeilings.length > 0 && (progress.toolCalls ?? 0) > Math.min(...toolCeilings)) {
|
|
3858
|
+
if (toolCeilings.length > 0 && (internal?.freshAllowance === true ? 0 : progress.toolCalls ?? 0) > Math.min(...toolCeilings)) {
|
|
3429
3859
|
throw new AppServerError('nothing-to-continue', 'That attempt has already spent its tool-call allowance, so a resume would end before any node could read your instruction. Send it as a new task instead.');
|
|
3430
3860
|
}
|
|
3431
3861
|
const spentNodes = new Set(reenteredCheckpoints
|
|
@@ -3530,7 +3960,8 @@ export class AppServer {
|
|
|
3530
3960
|
lineageArtifacts = new ArtifactStore(runId);
|
|
3531
3961
|
for (const attempt of chain)
|
|
3532
3962
|
await lineageArtifacts.importFrom(attempt).catch(() => { });
|
|
3533
|
-
|
|
3963
|
+
resumeWarnings = warnings;
|
|
3964
|
+
resumeFrom = { progress: internal?.freshAllowance === true ? { ...progress, toolCalls: 0 } : progress, ...(collected.size === 0 ? {} : { checkpoints: [...collected.values()] }) };
|
|
3534
3965
|
}
|
|
3535
3966
|
catch (error) {
|
|
3536
3967
|
// A refusal this path already made is an answer, not a fallback: rethrow it rather than
|
|
@@ -3558,7 +3989,14 @@ export class AppServer {
|
|
|
3558
3989
|
// behind, and that is how recovery can find the session and classify the run
|
|
3559
3990
|
// (`reconcileInterruptedRuns`). Without them a killed run is a transcript with a silent gap and a
|
|
3560
3991
|
// journal nothing indexes.
|
|
3561
|
-
|
|
3992
|
+
// A wake's message is the agent's own reminder (or the comments Auto-fix brought), not the user's words. The
|
|
3993
|
+
// mark goes with the text it describes: the task of a fresh start, or the direction of a continuation - a
|
|
3994
|
+
// continuation whose direction was proven delivered by an earlier attempt opens with no text to mark.
|
|
3995
|
+
const wake = internal?.wake !== undefined && (internal.resumedFrom === undefined || resumedDirection !== undefined) ? internal.wake : undefined;
|
|
3996
|
+
// The node a timer's continuation direction belongs to: read only by that node, and recorded so a later
|
|
3997
|
+
// resume that recovers the direction still knows whose it is.
|
|
3998
|
+
const directionNode = wake === 'timer' && resumedDirection !== undefined ? internal?.wakeNode : undefined;
|
|
3999
|
+
const marker = { task, completion: { summary: RUNNING_TURN_SUMMARY, tests: [], status: 'running' }, runId, ...(internal?.resumedFrom === undefined ? {} : { resumed: true }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(wake === undefined ? {} : { wake }) };
|
|
3562
4000
|
// The marker lands in both arrays, exactly as the CLI's persistence path writes it: `history` is
|
|
3563
4001
|
// the transcript a client reads, and `contextHistory` is the model context a later run seeds
|
|
3564
4002
|
// from. A resumed session already carries the second, and a marker missing from it would leave
|
|
@@ -3592,6 +4030,10 @@ export class AppServer {
|
|
|
3592
4030
|
// before finalizing must still be resumable with its full `$run.input.*`/`$run.state.*`
|
|
3593
4031
|
// scope under the same model behavior, not just the task.
|
|
3594
4032
|
...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? {} : { reasoningEffort: effort }),
|
|
4033
|
+
// The automation context rides the open record too: a resumed attempt re-sends it beside the
|
|
4034
|
+
// raw task, because the combined text in session history would fail the task validation a
|
|
4035
|
+
// limit-length prompt must still pass.
|
|
4036
|
+
...(automationContext === undefined ? {} : { automationContext }),
|
|
3595
4037
|
// A bound permission rides in the open record from the first moment: an attempt that dies
|
|
3596
4038
|
// before finalizing must still be resumable under the permission it was bound to, and a
|
|
3597
4039
|
// resume of it inherits that permission again.
|
|
@@ -3599,15 +4041,24 @@ export class AppServer {
|
|
|
3599
4041
|
// The override rides in the open record too: a resumed attempt re-runs the graph, and without
|
|
3600
4042
|
// this the nodes would go back to the models the graph names for themselves.
|
|
3601
4043
|
...(overrideAllNodes ? { overrideAllNodes: true } : {}),
|
|
4044
|
+
// So do the per-node switches a resume carries: without them the switched nodes alone would
|
|
4045
|
+
// come back on the models the graph names for themselves.
|
|
4046
|
+
...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }),
|
|
4047
|
+
// So does a graph switch: an attempt stopped before its entry node saved a conversation is
|
|
4048
|
+
// resumed into that node afresh, and it is owed the session's history again.
|
|
4049
|
+
...(entryHistory ? { entryHistory: true } : {}),
|
|
3602
4050
|
...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }),
|
|
3603
4051
|
// The continuation's message rides the open record exactly as `resumedFrom` does: an attempt
|
|
3604
4052
|
// that stops or crashes leaves this record standing as the account of the run, and the
|
|
3605
4053
|
// instruction the user sent to continue it belongs to that account, not only the finalizer's.
|
|
3606
4054
|
...(resumedDirection === undefined ? {} : { direction: resumedDirection }),
|
|
4055
|
+
// Which wake delivered the message, so a record read back never presents the reminder as the user's.
|
|
4056
|
+
...(wake === undefined ? {} : { wake }),
|
|
4057
|
+
...(directionNode === undefined ? {} : { directionNode }),
|
|
3607
4058
|
// Every carried direction still needing arming is named too, oldest first: a crash before the
|
|
3608
4059
|
// next checkpoint leaves this record as the only account of what was queued, and the newest
|
|
3609
4060
|
// message alone would drop the older instruction behind it.
|
|
3610
|
-
...(armedCarried.length === 0 ? {} : { pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }) })) }) };
|
|
4061
|
+
...(armedCarried.length === 0 ? {} : { pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }) };
|
|
3611
4062
|
bootMark('run.prepare.record-write.start');
|
|
3612
4063
|
await writeOpenRunRecord(this.directory, openRecord)
|
|
3613
4064
|
.catch(async (error) => {
|
|
@@ -3668,17 +4119,39 @@ export class AppServer {
|
|
|
3668
4119
|
// the run's own poll drains it at turn boundaries: a message typed during the run redirects the
|
|
3669
4120
|
// node that is working instead of ending the attempt and starting it over.
|
|
3670
4121
|
const liveSteers = [];
|
|
3671
|
-
|
|
4122
|
+
const permissionControl = new RunControl();
|
|
4123
|
+
permissionControl.permissions = effective;
|
|
4124
|
+
permissionControl.yolo = effective === 'full-access';
|
|
4125
|
+
this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, steersClosed: false,
|
|
4126
|
+
permissionControl, permissionRevision: 0, approvals: new Set(), boundPermissions: internal?.inheritedPermissions !== undefined,
|
|
4127
|
+
codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }) };
|
|
4128
|
+
// This run is now the session's newest turn. A wake armed by an attempt this run does not continue was a
|
|
4129
|
+
// reminder about work this turn has replaced, so it is spent here rather than left on the row's clock only
|
|
4130
|
+
// to be dropped at its deadline. A wake a delivery is holding is that delivery's to decide.
|
|
4131
|
+
{
|
|
4132
|
+
const continues = new Set([runId, ...lineage]);
|
|
4133
|
+
for (const timer of this.timers.list(record.id)) {
|
|
4134
|
+
if (timer.origin === undefined || continues.has(timer.origin.runId) || this.timers.isHeld(timer.id))
|
|
4135
|
+
continue;
|
|
4136
|
+
this.spendWake(timer, 'a newer turn in this session replaced the attempt that set it');
|
|
4137
|
+
}
|
|
4138
|
+
}
|
|
3672
4139
|
this.emit('session.updated', { session: sessionSummary(record) });
|
|
3673
|
-
this.emit('run.started', { runId, sessionId: record.id, task, graph: selection, provider: provider.id, model: modelId, workspace: root, permissions: effective, session: sessionSummary(record), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}) });
|
|
4140
|
+
this.emit('run.started', { runId, sessionId: record.id, task, graph: selection, provider: provider.id, model: modelId, workspace: root, permissions: effective, session: sessionSummary(record), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(wake === undefined ? {} : { wake }) });
|
|
3674
4141
|
bootMark('run.started.emitted');
|
|
4142
|
+
// Queued before the run itself records anything, so the journal's ordered writer puts the
|
|
4143
|
+
// warnings at the top of this attempt: the transcript shows them where the resume began, and a
|
|
4144
|
+
// reload rebuilds them from the journal.
|
|
4145
|
+
for (const text of resumeWarnings) {
|
|
4146
|
+
void this.recordRunEvent(runId, { type: 'run.resume.warning', time: new Date().toISOString(), data: { runId, sessionId: record.id, text } });
|
|
4147
|
+
}
|
|
3675
4148
|
// A session born from this start gets its real name from one small model request summarizing
|
|
3676
4149
|
// the prompt, replacing the local word-slice as soon as the run's first turn has answered the
|
|
3677
4150
|
// provider — and keeping it even if the run is stopped afterwards. Registered before the run is
|
|
3678
4151
|
// dispatched, so the naming request waits for a signal this run publishes.
|
|
3679
4152
|
if (params.sessionId === undefined)
|
|
3680
4153
|
this.titleSessionFromPrompt(record, task, provider, modelId, runId);
|
|
3681
|
-
const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), task, selection, providerId: provider.id, modelId, root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(panelRelay ? { panelBrowserRelay: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(armedCarried.length === 0 ? {} : { carriedDirections: armedCarried, pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }) })) }), ownDirectionId: `${runId}#own`, ...(seedExclusions.length === 0 ? {} : { armedRunIds: seedExclusions }), ...(openingAttachments === undefined ? {} : { openingAttachments }), record, controller, ...(attachments === undefined ? {} : { attachments }), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumeFrom === undefined ? {} : { resumeFrom }), lineage, ...(lineageArtifacts === undefined ? {} : { lineageArtifacts }), ...(resumedGraph === undefined ? {} : { prepared: resumedGraph }) })
|
|
4154
|
+
const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), task, selection, providerId: provider.id, modelId, root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: true } : {}), ...(entryHistory ? { entryHistory: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(automationContext === undefined ? {} : { automationContext }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(wake === undefined ? {} : { wake }), ...(directionNode === undefined ? {} : { directionNode }), ...(armedCarried.length === 0 ? {} : { carriedDirections: armedCarried, pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }), ownDirectionId: `${runId}#own`, ...(seedExclusions.length === 0 ? {} : { armedRunIds: seedExclusions }), ...(openingAttachments === undefined ? {} : { openingAttachments }), record, controller, ...(attachments === undefined ? {} : { attachments }), ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }), ...(resumeFrom === undefined ? {} : { resumeFrom }), lineage, ...(lineageArtifacts === undefined ? {} : { lineageArtifacts }), ...(resumedGraph === undefined ? {} : { prepared: resumedGraph }) })
|
|
3682
4155
|
.catch(error => this.log('error', `Run ${runId} failed: ${message(error)}`));
|
|
3683
4156
|
// The finally sits outside the awaited chain so the settle can name the exact promise this
|
|
3684
4157
|
// attempt owns: the finalizer now releases the live-run slot before the terminal events, so a
|
|
@@ -3800,16 +4273,18 @@ export class AppServer {
|
|
|
3800
4273
|
this.sessionTitles.clear();
|
|
3801
4274
|
}
|
|
3802
4275
|
async executeRun(input) {
|
|
3803
|
-
const { runId, startedAt, telemetryRunId, accountSubject, task, selection, providerId, modelId, root, permissions, liveSteers, boundPermissions, reasoningEffort, overrideAllNodes = false, modelPinned = overrideAllNodes, panelBrowserRelay = false, runInput, runState, direction, carriedDirections, ownDirectionId, armedRunIds, pendingDirections, controller, attachments, openingAttachments, resumedFrom, resumeFrom, lineage, lineageArtifacts, prepared } = input;
|
|
4276
|
+
const { runId, startedAt, telemetryRunId, accountSubject, task, selection, providerId, modelId, root, permissions, liveSteers, boundPermissions, reasoningEffort, overrideAllNodes = false, modelPinned = overrideAllNodes, panelBrowserRelay = false, entryHistory = false, runInput, runState, automationContext, direction, wake, carriedDirections, ownDirectionId, armedRunIds, pendingDirections, directionNode, controller, attachments, openingAttachments, resumedFrom, resumeFrom, lineage, lineageArtifacts, prepared, nodeModelOverrides } = input;
|
|
3804
4277
|
const signal = controller.signal;
|
|
3805
4278
|
const liveRun = this.run?.runId === runId ? this.run : undefined;
|
|
3806
4279
|
if (liveRun)
|
|
3807
4280
|
liveRun.graphSelection = selection;
|
|
3808
|
-
const journal = runRecordPath(this.directory, runId, 'jsonl');
|
|
3809
4281
|
// Checkpoints land one at a time, newest last: the runner calls back synchronously from
|
|
3810
4282
|
// several nodes, and an unserialized write could leave an older conversation as the file's
|
|
3811
4283
|
// final content. Failures are logged, never fatal — durability is a convenience, not the run.
|
|
3812
4284
|
let checkpointWrites = Promise.resolve();
|
|
4285
|
+
// Which nodes' newest checkpoint write failed. Each write replaces the node's whole file, so a
|
|
4286
|
+
// later write of the same node that succeeds heals the failure.
|
|
4287
|
+
const checkpointHealth = createCheckpointFailureTracker(this.directory, runId);
|
|
3813
4288
|
const persistCheckpoint = (nodeId, messages, state, meta) => {
|
|
3814
4289
|
checkpointWrites = checkpointWrites
|
|
3815
4290
|
.then(() => writeRunCheckpoint(this.directory, runId, { nodeId, messages, state, revision: state.directionRevision, savedAt: new Date().toISOString(),
|
|
@@ -3825,13 +4300,12 @@ export class AppServer {
|
|
|
3825
4300
|
// What this attempt had handed to a node before this write, by identity: a later resume proves
|
|
3826
4301
|
// delivery from this marker, so the same words sent twice are told apart by their revision.
|
|
3827
4302
|
...(deliveredIds.size === 0 ? {} : { steeringDelivered: [...deliveredIds] }) }))
|
|
3828
|
-
.
|
|
3829
|
-
// The run keeps working (a storage hiccup must not kill the user's work)
|
|
3830
|
-
//
|
|
3831
|
-
//
|
|
3832
|
-
//
|
|
3833
|
-
|
|
3834
|
-
await noteCheckpointWriteFailure(this.directory, runId, message(error));
|
|
4303
|
+
.then(() => checkpointHealth.succeeded({ nodeId, generation: meta?.generation }), async (error) => {
|
|
4304
|
+
// The run keeps working (a storage hiccup must not kill the user's work). A checkpoint
|
|
4305
|
+
// that could not be written is the conversation a resume re-enters the node with, so the
|
|
4306
|
+
// node is marked until one of its later writes lands; a resume of an attempt that
|
|
4307
|
+
// stopped while it was still marked warns that the node may repeat work.
|
|
4308
|
+
await checkpointHealth.failed({ nodeId, generation: meta?.generation }, error);
|
|
3835
4309
|
this.log('warn', `Could not write the run checkpoint: ${message(error)}`);
|
|
3836
4310
|
});
|
|
3837
4311
|
// The write is handed back so the runtime can await it: the checkpoint is the conversation a
|
|
@@ -3853,6 +4327,10 @@ export class AppServer {
|
|
|
3853
4327
|
let contextUsedTokens = 0;
|
|
3854
4328
|
let contextWindow;
|
|
3855
4329
|
let contextCacheRead;
|
|
4330
|
+
// Session-wide eligible cache totals. Only local requests that reported a cache-read
|
|
4331
|
+
// counter contribute; a switched model's cold miss is counted, not used to reset history.
|
|
4332
|
+
let localCacheInputTokens = 0;
|
|
4333
|
+
let localCacheReadTokens = 0;
|
|
3856
4334
|
// The preflight is outside `runGraph`, so its spend is kept separately: a completed attempt's
|
|
3857
4335
|
// result carries only the graph's own calls, and finalization folds this into the record and
|
|
3858
4336
|
// the session totals alongside it.
|
|
@@ -3898,15 +4376,31 @@ export class AppServer {
|
|
|
3898
4376
|
// delivery to a later resume, by identity rather than by words.
|
|
3899
4377
|
const deliveredIds = new Set((resumeFrom?.checkpoints ?? []).flatMap(checkpoint => checkpoint.steeringDelivered ?? []));
|
|
3900
4378
|
const armed = [];
|
|
4379
|
+
// A direction a timer delivered belongs to the node that set it: it is armed for that node and read on the
|
|
4380
|
+
// node channel, so a sibling branch that owns the shared queue cannot take it. Any other direction is the
|
|
4381
|
+
// user's and goes on the shared queue as before.
|
|
4382
|
+
const nodeArmed = new Map();
|
|
4383
|
+
const arm = (node, entry) => {
|
|
4384
|
+
if (node === undefined) {
|
|
4385
|
+
armed.push(entry);
|
|
4386
|
+
return;
|
|
4387
|
+
}
|
|
4388
|
+
const list = nodeArmed.get(node) ?? [];
|
|
4389
|
+
list.push(entry);
|
|
4390
|
+
nodeArmed.set(node, list);
|
|
4391
|
+
};
|
|
3901
4392
|
for (const entry of carriedDirections ?? []) {
|
|
3902
4393
|
const refs = entry.attachments ?? [];
|
|
3903
4394
|
const images = refs.length ? await loadResolvedImages(this.directory, root, refs) : [];
|
|
3904
|
-
|
|
4395
|
+
const said = entry.wake === 'timer' ? timerReminderText(entry.direction) : entry.direction;
|
|
4396
|
+
arm(entry.wake === 'timer' ? entry.node : undefined, { ...(entry.id === undefined ? {} : { id: entry.id }), content: refs.length ? `${said}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : said, images });
|
|
3905
4397
|
}
|
|
3906
4398
|
if (direction !== undefined) {
|
|
3907
4399
|
const refs = attachments?.refs ?? [];
|
|
3908
4400
|
const images = attachments?.images ?? [];
|
|
3909
|
-
|
|
4401
|
+
// A continuation a timer delivered opens with the agent's own reminder, read as one rather than as the user's words.
|
|
4402
|
+
const said = wake === 'timer' ? timerReminderText(direction) : direction;
|
|
4403
|
+
arm(wake === 'timer' ? directionNode : undefined, { ...(ownDirectionId === undefined ? {} : { id: ownDirectionId }), content: refs.length ? `${said}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : said, images });
|
|
3910
4404
|
}
|
|
3911
4405
|
const steering = armed.length === 0 ? undefined : armed;
|
|
3912
4406
|
// The messages the user typed into the live attempt, in the order the runtime read them. Each
|
|
@@ -3914,6 +4408,13 @@ export class AppServer {
|
|
|
3914
4408
|
// of the transcript; the ones still queued when the run ends are reported instead, because a
|
|
3915
4409
|
// message the agent never read is not part of the work that happened.
|
|
3916
4410
|
const deliveredSteers = [];
|
|
4411
|
+
/** Remove and return the queued messages `wanted` selects, in queue order; synchronous, so a poll never yields holding them. */
|
|
4412
|
+
const takeSteers = (wanted) => {
|
|
4413
|
+
const taken = liveSteers.filter(wanted);
|
|
4414
|
+
for (const entry of taken)
|
|
4415
|
+
liveSteers.splice(liveSteers.indexOf(entry), 1);
|
|
4416
|
+
return taken;
|
|
4417
|
+
};
|
|
3917
4418
|
let mcp;
|
|
3918
4419
|
let commandMemory;
|
|
3919
4420
|
let result;
|
|
@@ -4151,7 +4652,22 @@ export class AppServer {
|
|
|
4151
4652
|
for (const notice of extension.notices)
|
|
4152
4653
|
this.emit('log', { level: 'info', message: notice });
|
|
4153
4654
|
bootMark('run.exec.extensions.loaded');
|
|
4154
|
-
|
|
4655
|
+
// In the mode the run holds now: a live change can land before the manager exists (see
|
|
4656
|
+
// `ActiveRun.codeIntelPermissions`), and one that lands while it is being prepared is applied
|
|
4657
|
+
// once it does.
|
|
4658
|
+
// A change that tightens the mode waits for this creation (`codeIntelReady`) before it is saved
|
|
4659
|
+
// or acknowledged, so a manager started in the earlier mode is suspended first.
|
|
4660
|
+
const codeIntelMode = liveRun?.codeIntelPermissions ?? permissions;
|
|
4661
|
+
const creating = this.codeIntelligence(root, codeIntelMode, signal).then(manager => {
|
|
4662
|
+
if (manager && liveRun)
|
|
4663
|
+
liveRun.codeIntelApplied = codeIntelMode;
|
|
4664
|
+
return manager;
|
|
4665
|
+
});
|
|
4666
|
+
if (liveRun)
|
|
4667
|
+
liveRun.codeIntelReady = creating.then(() => undefined, () => undefined);
|
|
4668
|
+
const codeIntel = await creating;
|
|
4669
|
+
if (codeIntel && liveRun)
|
|
4670
|
+
await this.syncCodeIntelPermissions(liveRun).catch(error => this.log('warn', `Could not bring code intelligence to the run's mode: ${message(error)}`));
|
|
4155
4671
|
bootMark('run.exec.code-intel.ready');
|
|
4156
4672
|
const membership = await getMembership(signal, this.directory);
|
|
4157
4673
|
bootMark('run.exec.membership.read');
|
|
@@ -4189,12 +4705,16 @@ export class AppServer {
|
|
|
4189
4705
|
const pullRequestDetector = new PullRequestCreateDetector();
|
|
4190
4706
|
const toolContext = {
|
|
4191
4707
|
workspace: root, signal, userSignal: signal, yolo: permissions === 'full-access', permissions, approvalMode: 'interactive',
|
|
4708
|
+
// The live mode: `run.setPermissions` changes it on the control, and every copy of this context
|
|
4709
|
+
// reads it from there, so a tool already waiting on a prompt sees the change.
|
|
4710
|
+
...(liveRun ? { runControl: liveRun.permissionControl } : {}),
|
|
4192
4711
|
attachmentRoots,
|
|
4193
4712
|
approve: (name, args, toolSignal) => this.approve(runId, name, args, toolSignal),
|
|
4194
4713
|
askUser: (question, toolSignal, choices) => this.ask(runId, question, choices, toolSignal),
|
|
4714
|
+
...(liveRun ? { approvePlan: () => this.approvePlan(liveRun) } : {}),
|
|
4195
4715
|
onApprovalEvent: (type, data) => {
|
|
4196
4716
|
const event = { type, time: new Date().toISOString(), data };
|
|
4197
|
-
void this.recordRunEvent(runId,
|
|
4717
|
+
void this.recordRunEvent(runId, event);
|
|
4198
4718
|
void this.trajectory?.recordEvent(event);
|
|
4199
4719
|
},
|
|
4200
4720
|
onBrowserEvent: async (type, data) => {
|
|
@@ -4203,7 +4723,7 @@ export class AppServer {
|
|
|
4203
4723
|
// a late notification after run.completed has no live owner in the desktop.
|
|
4204
4724
|
const event = { type, time: new Date().toISOString(), data: { ...data, sessionId: input.record.id } };
|
|
4205
4725
|
await Promise.allSettled([
|
|
4206
|
-
this.recordRunEvent(runId,
|
|
4726
|
+
this.recordRunEvent(runId, event),
|
|
4207
4727
|
this.trajectory?.recordEvent(event),
|
|
4208
4728
|
]);
|
|
4209
4729
|
},
|
|
@@ -4233,7 +4753,8 @@ export class AppServer {
|
|
|
4233
4753
|
// desktop relay to the engine that does. It is keyed to the saved session id both the pane
|
|
4234
4754
|
// and this run's browser events already use, so agent-driven tabs are the pane's tabs. The
|
|
4235
4755
|
// CLI builds its toolset without an app-server and never sees it.
|
|
4236
|
-
tools: [...createTools(), createBrowserPanelTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined),
|
|
4756
|
+
tools: [...createTools(), createBrowserPanelTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined),
|
|
4757
|
+
createBrowserIncognitoTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined), ...extension.tools, ...(mcp?.tools ?? [])], installedSkillClaims: extension.claimsSkillName, history: contextSeed,
|
|
4237
4758
|
...(invocation ? { inheritedSkills: [invocation.id], skillInvocationInstruction: invocation.task } : {}),
|
|
4238
4759
|
instructions: `${await loadWorkspaceInstructions(root, signal, config.systemPromptOverride)}\n${QA_SYSTEM_GUIDANCE}${extension.instructions}`,
|
|
4239
4760
|
codeIntel, todoStore: new TodoStore(), ...(commandMemory ? { commandMemory } : {}),
|
|
@@ -4243,6 +4764,7 @@ export class AppServer {
|
|
|
4243
4764
|
// "Use this model for every node" and a run that named its model are the user's explicit
|
|
4244
4765
|
// choices; adaptive routing leaves them alone.
|
|
4245
4766
|
modelPinned: modelPinned || overrideAllNodes,
|
|
4767
|
+
...(entryHistory ? { entryHistory: true } : {}),
|
|
4246
4768
|
configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
|
|
4247
4769
|
// The executor resolves its own model rather than reusing `adapter`, so the task's effort is
|
|
4248
4770
|
// handed to it as well — for the run's own provider and model only: a node that pins another
|
|
@@ -4261,10 +4783,20 @@ export class AppServer {
|
|
|
4261
4783
|
const [rootId, roleId] = (nodeId ?? '').split('/');
|
|
4262
4784
|
const fallback = roleId?.endsWith('#fallback') || rootId.endsWith('#fallback');
|
|
4263
4785
|
const own = liveRun?.modelGraph?.nodes[rootId.replace(/#fallback$/, '')];
|
|
4786
|
+
// A node the user switched mid-run answers from the override, ahead of the graph's own
|
|
4787
|
+
// fields: the pair names both provider and model, and it is what the delegating children
|
|
4788
|
+
// of this node inherit, while a role that pins a pair of its own keeps it below.
|
|
4789
|
+
const nodeOverride = current.nodeOverrides?.[rootId.replace(/#fallback$/, '')];
|
|
4790
|
+
// A selection that exists only because one node was switched answers for that node and
|
|
4791
|
+
// the children that inherit it — nobody else. A node without an override and without a
|
|
4792
|
+
// graph pin had no selection before, so it keeps the adaptive routing that was serving
|
|
4793
|
+
// it instead of falling to the run's baseline pair.
|
|
4794
|
+
if (current.nodeOnly === true && nodeOverride === undefined && own?.provider === undefined)
|
|
4795
|
+
return undefined;
|
|
4264
4796
|
const policy = own?.subagents;
|
|
4265
4797
|
const role = policy?.roles?.find(item => item.id === roleId?.replace(/#fallback$/, ''));
|
|
4266
|
-
const parentProvider = own?.provider ?? current.provider;
|
|
4267
|
-
const parentModel = own?.model ?? (own?.provider === undefined ? current.model : undefined);
|
|
4798
|
+
const parentProvider = nodeOverride?.provider ?? own?.provider ?? current.provider;
|
|
4799
|
+
const parentModel = nodeOverride?.model ?? own?.model ?? (own?.provider === undefined ? current.model : undefined);
|
|
4268
4800
|
let targetProvider = parentProvider, targetModel = parentModel;
|
|
4269
4801
|
// The parent's effective pair comes first: a retried attempt continues its fallback, and
|
|
4270
4802
|
// that pair is what a child inherits. The child's own delegation policy is applied on
|
|
@@ -4284,7 +4816,11 @@ export class AppServer {
|
|
|
4284
4816
|
targetProvider = role?.provider ?? inheritedProvider;
|
|
4285
4817
|
targetModel = role?.model ?? (targetProvider === inheritedProvider ? inheritedModel : undefined);
|
|
4286
4818
|
}
|
|
4287
|
-
|
|
4819
|
+
// A whole-run override answers for every node that has no switch of its own: a node
|
|
4820
|
+
// the user moved mid-run keeps the pair they picked, even under an override that was
|
|
4821
|
+
// active when the pick landed — the override's run pair is what the switched node
|
|
4822
|
+
// left behind, not what it joined.
|
|
4823
|
+
if (current.overrideAllNodes && nodeOverride === undefined) {
|
|
4288
4824
|
targetProvider = current.provider;
|
|
4289
4825
|
targetModel = current.model;
|
|
4290
4826
|
}
|
|
@@ -4311,8 +4847,26 @@ export class AppServer {
|
|
|
4311
4847
|
const window = event.data.contextWindow;
|
|
4312
4848
|
contextWindow = typeof window === 'number' && Number.isSafeInteger(window) && window > 0 ? window : undefined;
|
|
4313
4849
|
}
|
|
4314
|
-
await this.recordRunEvent(runId,
|
|
4850
|
+
await this.recordRunEvent(runId, event);
|
|
4315
4851
|
await this.trajectory?.recordEvent(event);
|
|
4852
|
+
// The node that armed a wake finished its work: the reminder was about that work, and no later node
|
|
4853
|
+
// or later run is where it belongs.
|
|
4854
|
+
if (event.type === 'graph.node.completed' && typeof event.data.nodeId === 'string') {
|
|
4855
|
+
const nodeId = event.data.nodeId;
|
|
4856
|
+
const attempts = new Set([runId, ...lineage]);
|
|
4857
|
+
const finished = 'the node that set it has finished its work';
|
|
4858
|
+
this.spendAttemptWakes(input.record.id, attempts, finished, origin => origin.nodeId === nodeId);
|
|
4859
|
+
// A reminder already handed to this run but not yet read is the same promise: left in the queue, the
|
|
4860
|
+
// next node's first turn boundary would read a stale instruction about work that is done. The emit
|
|
4861
|
+
// that brought this event is awaited before the graph moves on, so it is pulled here, before any
|
|
4862
|
+
// later node polls. Its row is withdrawn from the journal the way an unread steer's is.
|
|
4863
|
+
const stale = liveSteers.filter(entry => entry.wake?.origin !== undefined && entry.wake.origin.nodeId === nodeId && attempts.has(entry.wake.origin.runId));
|
|
4864
|
+
for (const entry of stale) {
|
|
4865
|
+
liveSteers.splice(liveSteers.indexOf(entry), 1);
|
|
4866
|
+
await this.recordRunEvent(runId, { type: 'run.steer-returned', time: new Date().toISOString(), data: { runId, sessionId: input.record.id, steerId: entry.id } });
|
|
4867
|
+
this.spendWake(entry.wake, finished);
|
|
4868
|
+
}
|
|
4869
|
+
}
|
|
4316
4870
|
// A `gh pr create` the agent ran puts the PR it opened on the session's Plan card.
|
|
4317
4871
|
const created = pullRequestDetector.observe(event);
|
|
4318
4872
|
if (created)
|
|
@@ -4320,13 +4874,17 @@ export class AppServer {
|
|
|
4320
4874
|
},
|
|
4321
4875
|
onUsage: (delta, origin) => {
|
|
4322
4876
|
foldUsage(runUsage, delta);
|
|
4877
|
+
if (origin?.localModel === true && delta.inputTokens > 0 && delta.cacheRead !== undefined) {
|
|
4878
|
+
localCacheInputTokens += delta.inputTokens;
|
|
4879
|
+
localCacheReadTokens += Math.min(delta.inputTokens, Math.max(0, delta.cacheRead));
|
|
4880
|
+
}
|
|
4323
4881
|
// A delta that reports no prompt is transport bookkeeping, not an empty context. The
|
|
4324
4882
|
// reading's cache hits travel with it, and an absent split stays absent, not zero.
|
|
4325
4883
|
if (delta.inputTokens !== undefined && delta.inputTokens > 0) {
|
|
4326
4884
|
contextUsedTokens = delta.inputTokens;
|
|
4327
4885
|
contextCacheRead = delta.cacheRead;
|
|
4328
4886
|
}
|
|
4329
|
-
this.emit('run.usage', { runId, usage: delta, ...(origin?.invocationId === undefined ? {} : { invocationId: origin.invocationId }), final: origin?.final === true });
|
|
4887
|
+
this.emit('run.usage', { runId, usage: delta, ...(origin?.invocationId === undefined ? {} : { invocationId: origin.invocationId }), final: origin?.final === true, ...(origin?.localModel === true ? { localModel: true } : {}) });
|
|
4330
4888
|
},
|
|
4331
4889
|
// Every node's furthest conversation, persisted as it is reached: an attempt that dies
|
|
4332
4890
|
// leaves a checkpoint behind that `run.resume` re-enters, and the successful attempt
|
|
@@ -4339,7 +4897,9 @@ export class AppServer {
|
|
|
4339
4897
|
// not a standing prompt. A live message's own spooled files join the tool context here,
|
|
4340
4898
|
// before the model that may ask a tool to read them next sees the message.
|
|
4341
4899
|
getSteeringMessages: async () => {
|
|
4342
|
-
|
|
4900
|
+
// The shared queue carries what the user typed. A reminder a node set for itself is read only by that
|
|
4901
|
+
// node, through `getNodeSteeringMessages`, never by whichever branch owns this queue.
|
|
4902
|
+
const live = takeSteers(entry => entry.wake === undefined);
|
|
4343
4903
|
for (const entry of live) {
|
|
4344
4904
|
// A message's spooled files are readable by the tools its text may ask for. The array is
|
|
4345
4905
|
// the one the tool contexts hold — they copy the reference, not its contents — so pushing
|
|
@@ -4361,6 +4921,19 @@ export class AppServer {
|
|
|
4361
4921
|
deliveredIds.add(entry.id);
|
|
4362
4922
|
return [...armedBatch, ...live].map(entry => ({ role: 'user', content: entry.content, ...(entry.images.length ? { images: entry.images } : {}) }));
|
|
4363
4923
|
},
|
|
4924
|
+
// A `set_timer` reminder goes back to the node that set it, polled by that node whether or not its branch
|
|
4925
|
+
// owns the shared queue. It must not yield before returning, for the same reason as the shared poll.
|
|
4926
|
+
getNodeSteeringMessages: async (nodeId) => {
|
|
4927
|
+
const own = takeSteers(entry => entry.wake?.origin?.nodeId === nodeId);
|
|
4928
|
+
for (const entry of own)
|
|
4929
|
+
deliveredSteers.push(entry);
|
|
4930
|
+
// A continuation's reminder for this node, with its identity marked delivered as the shared queue's are.
|
|
4931
|
+
const directed = nodeArmed.get(nodeId)?.splice(0) ?? [];
|
|
4932
|
+
for (const entry of directed)
|
|
4933
|
+
if (entry.id !== undefined)
|
|
4934
|
+
deliveredIds.add(entry.id);
|
|
4935
|
+
return [...directed, ...own].map(entry => ({ role: 'user', content: entry.content, ...(entry.images.length ? { images: entry.images } : {}) }));
|
|
4936
|
+
},
|
|
4364
4937
|
...(resumeFrom === undefined ? {} : { resumeFrom }),
|
|
4365
4938
|
...(lineageArtifacts === undefined ? {} : { artifactStore: lineageArtifacts }),
|
|
4366
4939
|
};
|
|
@@ -4380,7 +4953,7 @@ export class AppServer {
|
|
|
4380
4953
|
// a failure rather than a success that hides it: the transcript shows the turn stopped short of
|
|
4381
4954
|
// the message, the record keeps the direction, and the next resume re-delivers it (or the user
|
|
4382
4955
|
// sends it as a follow-up).
|
|
4383
|
-
if (steering?.length) {
|
|
4956
|
+
if (steering?.length || [...nodeArmed.values()].some(list => list.length > 0)) {
|
|
4384
4957
|
this.log('warn', `The direction sent with the resume was not delivered: the continued attempt reached no agent turn boundary to read it. Send it again as a follow-up.`);
|
|
4385
4958
|
if (result && result.status === 'succeeded')
|
|
4386
4959
|
result = { ...result, status: 'infrastructure_error', reason: DIRECTION_UNDELIVERED_REASON, completion: undefined };
|
|
@@ -4393,10 +4966,24 @@ export class AppServer {
|
|
|
4393
4966
|
// is refused rather than appended to a queue this finalizer has already emptied.
|
|
4394
4967
|
if (this.run?.runId === runId)
|
|
4395
4968
|
this.run.steersClosed = true;
|
|
4969
|
+
// Close permission admission before draining: changes already accepted must finish before
|
|
4970
|
+
// the terminal snapshot, while later requests are refused by setRunPermissions above.
|
|
4971
|
+
await liveRun?.permissionChanges;
|
|
4396
4972
|
// A selection accepted while the last model request was completing may still be
|
|
4397
4973
|
// committing its open record. Settle it before deriving the terminal model identity.
|
|
4398
4974
|
await liveRun?.recordWrites;
|
|
4399
|
-
const
|
|
4975
|
+
const returnedSteers = liveSteers.splice(0);
|
|
4976
|
+
// A reminder the run ended before reading is not the user's message: it goes back on the registry once the
|
|
4977
|
+
// attempt is put away (see `publishFinalized`), where the rules for an attempt that has ended decide whether
|
|
4978
|
+
// it continues the attempt or is spent, rather than being handed to the window for the user's composer.
|
|
4979
|
+
const returnedWakes = returnedSteers.flatMap(entry => entry.wake === undefined ? [] : [entry.wake]);
|
|
4980
|
+
const undeliveredSteers = returnedSteers.filter(entry => entry.wake === undefined);
|
|
4981
|
+
// The journal drops the row of every message the run never read, reminders included.
|
|
4982
|
+
for (const entry of returnedSteers) {
|
|
4983
|
+
if (entry.wake === undefined)
|
|
4984
|
+
continue;
|
|
4985
|
+
await this.recordRunEvent(runId, { type: 'run.steer-returned', time: new Date().toISOString(), data: { runId, sessionId: input.record.id, steerId: entry.id } });
|
|
4986
|
+
}
|
|
4400
4987
|
if (undeliveredSteers.length) {
|
|
4401
4988
|
this.log('warn', `${undeliveredSteers.length} steering message${undeliveredSteers.length === 1 ? ' was' : 's were'} not delivered: the run ended before its next turn boundary.`);
|
|
4402
4989
|
// The `run.steered` line recorded when the message was queued is what drew its row, and a
|
|
@@ -4404,7 +4991,7 @@ export class AppServer {
|
|
|
4404
4991
|
// the return is recorded beside it so the fold drops the row, and a client that missed the
|
|
4405
4992
|
// live event tells the same story after a reload.
|
|
4406
4993
|
for (const entry of undeliveredSteers) {
|
|
4407
|
-
await this.recordRunEvent(runId,
|
|
4994
|
+
await this.recordRunEvent(runId, {
|
|
4408
4995
|
type: 'run.steer-returned',
|
|
4409
4996
|
time: new Date().toISOString(),
|
|
4410
4997
|
data: { runId, sessionId: input.record.id, steerId: entry.id },
|
|
@@ -4433,6 +5020,10 @@ export class AppServer {
|
|
|
4433
5020
|
if (result)
|
|
4434
5021
|
foldUsage(result.usage, probeUsage);
|
|
4435
5022
|
foldUsage(usage, result?.usage ?? runUsage);
|
|
5023
|
+
if (localCacheInputTokens > 0) {
|
|
5024
|
+
usage.localCacheInputTokens = (usage.localCacheInputTokens ?? 0) + localCacheInputTokens;
|
|
5025
|
+
usage.localCacheReadTokens = (usage.localCacheReadTokens ?? 0) + localCacheReadTokens;
|
|
5026
|
+
}
|
|
4436
5027
|
// The session trajectory closes with the attempt that opened it: the marker says how the run
|
|
4437
5028
|
// ended for a reader scanning one session's calls, and the flush waits out the append queue
|
|
4438
5029
|
// so a client saving the file right after `run.completed` reads every record.
|
|
@@ -4455,9 +5046,9 @@ export class AppServer {
|
|
|
4455
5046
|
// task and direction instead of losing what the user said mid-run. The text is stored apart
|
|
4456
5047
|
// from the model-facing content: the reference block names spooled files that may since have
|
|
4457
5048
|
// been pruned, and a reloaded transcript shows the words and the chips, not the block.
|
|
4458
|
-
const steers = deliveredSteers.map(entry => ({ text: entry.text, ...(entry.refs?.length ? { attachments: entry.refs } : {}) }));
|
|
4459
|
-
archive.push({ task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}) });
|
|
4460
|
-
history = [...history, { task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}) }].slice(-SESSION_HISTORY_TURNS);
|
|
5049
|
+
const steers = deliveredSteers.map(entry => ({ text: entry.text, ...(entry.refs?.length ? { attachments: entry.refs } : {}), ...(entry.wake === undefined ? {} : { wake: 'timer' }) }));
|
|
5050
|
+
archive.push({ task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}), ...(wake === undefined ? {} : { wake }) });
|
|
5051
|
+
history = [...history, { task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}), ...(wake === undefined ? {} : { wake }) }].slice(-SESSION_HISTORY_TURNS);
|
|
4461
5052
|
const record = { ...input.record, history: archive, contextHistory: history, updatedAt: new Date().toISOString(), usage,
|
|
4462
5053
|
// The run's final widget values are the session's newest, so the record carries them for
|
|
4463
5054
|
// clients that rebuild the conversation from disk. A result without widgets (a graph that
|
|
@@ -4476,6 +5067,9 @@ export class AppServer {
|
|
|
4476
5067
|
...(closedWithRun ? { reason: APP_CLOSED_REASON } : controller.signal.aborted ? {} : { reason: message(failure) }),
|
|
4477
5068
|
usage: runUsage, toolCalls: 0, completion,
|
|
4478
5069
|
};
|
|
5070
|
+
// Whether the journal is a complete account. The writer retries what it still holds first:
|
|
5071
|
+
// space freed since the last refused append lets the journal finish whole.
|
|
5072
|
+
const journalIntact = await (this.journals.get(runId)?.settle() ?? Promise.resolve(true));
|
|
4479
5073
|
try {
|
|
4480
5074
|
await this.ensureRunRecords();
|
|
4481
5075
|
// The finalizer overwrites the open record; it carries its identity fields forward so the
|
|
@@ -4493,6 +5087,10 @@ export class AppServer {
|
|
|
4493
5087
|
// resume reads when the marker file itself was never written.
|
|
4494
5088
|
// A result the abort answered with `cancelled` is the same shutdown-cut attempt as the
|
|
4495
5089
|
// fallback above: the record says interrupted, with the reason recovery would have written.
|
|
5090
|
+
// The node map the record carries: a selection this attempt published is the authority —
|
|
5091
|
+
// including its absence, which is how a whole-run switch says the map was cleared — and
|
|
5092
|
+
// only an attempt that switched nothing forwards the map it itself was resumed with.
|
|
5093
|
+
const liveNodeOverrides = liveRun?.modelSelection !== undefined ? liveRun.modelSelection.nodeOverrides : nodeModelOverrides;
|
|
4496
5094
|
const finalRecord = { ...recordResult,
|
|
4497
5095
|
...(closedWithRun && recordResult.status === 'cancelled' ? { status: 'interrupted', reason: APP_CLOSED_REASON } : {}),
|
|
4498
5096
|
provider: liveRun?.modelSelection?.provider ?? providerId, model: liveRun?.modelSelection?.model ?? modelId,
|
|
@@ -4502,6 +5100,9 @@ export class AppServer {
|
|
|
4502
5100
|
graphSelection: selection, ...(accountSubject ? { accountSubject } : {}),
|
|
4503
5101
|
sessionId: record.id, startedAt, ...(runInput === undefined ? {} : { runInput }),
|
|
4504
5102
|
...(runState === undefined ? {} : { runState }),
|
|
5103
|
+
// The automation context carries forward like the run scope above it: a resume of this
|
|
5104
|
+
// attempt re-sends it beside the raw task instead of re-validating the combined text.
|
|
5105
|
+
...(automationContext === undefined ? {} : { automationContext }),
|
|
4505
5106
|
// A selection may have been published while the previous model request was still
|
|
4506
5107
|
// running. Its checkpoint then retains the old model stamp. Record the transition so
|
|
4507
5108
|
// ordinary resume reconciles that checkpoint instead of replaying completed tools.
|
|
@@ -4513,14 +5114,24 @@ export class AppServer {
|
|
|
4513
5114
|
// The override is part of the attempt's identity: a resume re-runs the graph, and a record
|
|
4514
5115
|
// that dropped this flag would bring the nodes back to the models the graph names.
|
|
4515
5116
|
...((liveRun?.modelSelection?.overrideAllNodes ?? overrideAllNodes) ? { overrideAllNodes: true } : {}),
|
|
5117
|
+
// So is each node a live switch moved: a resume re-applies the map on the bound graph. A
|
|
5118
|
+
// selection this attempt published is the authority — including its absence, which is how
|
|
5119
|
+
// a whole-run switch says the node map was cleared — and only an attempt that switched
|
|
5120
|
+
// nothing forwards the map it itself was resumed with, untouched.
|
|
5121
|
+
...((liveNodeOverrides !== undefined && Object.keys(liveNodeOverrides).length > 0)
|
|
5122
|
+
? { nodeModelOverrides: liveNodeOverrides } : {}),
|
|
5123
|
+
...(entryHistory ? { entryHistory: true } : {}),
|
|
4516
5124
|
...(direction === undefined ? {} : { direction }),
|
|
5125
|
+
...(wake === undefined ? {} : { wake }),
|
|
5126
|
+
...(directionNode === undefined ? {} : { directionNode }),
|
|
4517
5127
|
...(pendingDirections === undefined || pendingDirections.length === 0 ? {} : { pendingDirections }),
|
|
4518
5128
|
...(resumedFrom === undefined ? {} : { resumedFrom }),
|
|
4519
|
-
...(
|
|
4520
|
-
...(
|
|
5129
|
+
...(journalIntact ? {} : { journalIntegrity: 'failed' }),
|
|
5130
|
+
...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
|
|
4521
5131
|
// A bound permission is carried forward: a resume of this attempt inherits the
|
|
4522
|
-
// permission it ran under, so a chain of resumes of a host-bound attempt keeps it.
|
|
4523
|
-
|
|
5132
|
+
// permission it ran under, so a chain of resumes of a host-bound attempt keeps it. A live
|
|
5133
|
+
// change replaced the mode it ran under, so the mode it ended under is the one carried.
|
|
5134
|
+
...(boundPermissions === undefined ? {} : { permissions: liveRun?.permissionControl.permissions ?? boundPermissions }) };
|
|
4524
5135
|
const writeFinal = () => writeFile(runRecordPath(this.directory, runId, 'json'), `${JSON.stringify(finalRecord, null, 2)}\n`, { mode: 0o600 });
|
|
4525
5136
|
if (liveRun)
|
|
4526
5137
|
await this.serializeRunRecordWrite(liveRun, writeFinal);
|
|
@@ -4568,9 +5179,24 @@ export class AppServer {
|
|
|
4568
5179
|
if (this.run?.runId === runId)
|
|
4569
5180
|
this.run = undefined;
|
|
4570
5181
|
releaseProcessWorkspace(root, runId);
|
|
4571
|
-
//
|
|
4572
|
-
//
|
|
4573
|
-
// left the
|
|
5182
|
+
// A wake a node of this attempt (or of an attempt it continues) armed is a reminder about that node's
|
|
5183
|
+
// work, and it is delivered only as a continuation of this attempt. An attempt that finished has nothing
|
|
5184
|
+
// left to continue, and one the user stopped was stopped on purpose: their wakes are spent now, said
|
|
5185
|
+
// where the user sees it, instead of waiting out a deadline only to restart work that is over. An
|
|
5186
|
+
// attempt that ended any other way - out of budget, failed, interrupted - keeps them: on the deadline
|
|
5187
|
+
// the reminder continues it from the arming node (see `wakeContinuation`).
|
|
5188
|
+
const finishedOwn = result?.status === 'succeeded' ? 'the attempt that set it has finished'
|
|
5189
|
+
: controller.signal.aborted && this.runAbort === 'user' ? 'the attempt that set it was stopped' : undefined;
|
|
5190
|
+
for (const timer of returnedWakes) {
|
|
5191
|
+
this.timers.restore(timer);
|
|
5192
|
+
if (finishedOwn === undefined)
|
|
5193
|
+
void writeWakeClaim(this.directory, record.id, timer.id).catch(() => { });
|
|
5194
|
+
}
|
|
5195
|
+
if (finishedOwn !== undefined)
|
|
5196
|
+
this.spendAttemptWakes(record.id, new Set([runId, ...lineage]), finishedOwn);
|
|
5197
|
+
// Whatever else is armed now belongs to the session rather than to the run: a prompt the agent asked
|
|
5198
|
+
// to be woken for is expected to arrive after the turn that armed it is over. While one is left the
|
|
5199
|
+
// session is waiting, not finished, and only the engine can still deliver it.
|
|
4574
5200
|
this.settleSessionTimers(record.id);
|
|
4575
5201
|
// The summaries are built without the live-run override: this callback runs while `this.run`
|
|
4576
5202
|
// still names the attempt that just ended, and stamping `running` onto a terminal record
|
|
@@ -4622,6 +5248,9 @@ export class AppServer {
|
|
|
4622
5248
|
this.finishingRunId = undefined;
|
|
4623
5249
|
this.finishingSessionId = undefined;
|
|
4624
5250
|
}
|
|
5251
|
+
// Nothing records into this attempt's journal from here: its record already said whether the
|
|
5252
|
+
// journal is whole.
|
|
5253
|
+
this.journals.delete(runId);
|
|
4625
5254
|
// A record that never reached the disk is not the session: publishing it would have the client reload
|
|
4626
5255
|
// the older record and drop the turn it just watched, and after a restart the turn would be gone while
|
|
4627
5256
|
// the run was reported as completed. The failure is reported instead, with the transcript left alone.
|
|
@@ -4688,10 +5317,13 @@ export class AppServer {
|
|
|
4688
5317
|
const run = this.run;
|
|
4689
5318
|
if (!run || params.runId !== run.runId || run.steersClosed)
|
|
4690
5319
|
throw new AppServerError('invalid-params', 'That run is no longer active.');
|
|
4691
|
-
if (typeof params.overrideAllNodes !== 'boolean')
|
|
4692
|
-
throw new AppServerError('invalid-params', 'overrideAllNodes must be a boolean');
|
|
4693
5320
|
const provider = identifier(params.provider, 'provider');
|
|
4694
5321
|
const model = text(params.model, 'model', 200);
|
|
5322
|
+
// A switch that names a node changes that one node's pair — and what its delegating children
|
|
5323
|
+
// inherit — and ignores the whole-run flag; without a node the switch is the run's own scope.
|
|
5324
|
+
const scopedNode = params.nodeId === undefined ? undefined : identifier(params.nodeId, 'nodeId');
|
|
5325
|
+
if (scopedNode === undefined && typeof params.overrideAllNodes !== 'boolean')
|
|
5326
|
+
throw new AppServerError('invalid-params', 'overrideAllNodes must be a boolean');
|
|
4695
5327
|
const generation = run.modelChangeGeneration = (run.modelChangeGeneration ?? 0) + 1;
|
|
4696
5328
|
const config = await loadConfig(this.directory);
|
|
4697
5329
|
if (!config.providers.some(item => item.id === provider))
|
|
@@ -4701,10 +5333,15 @@ export class AppServer {
|
|
|
4701
5333
|
const original = run.originalModelGraph;
|
|
4702
5334
|
if (!original || !run.modelGraph)
|
|
4703
5335
|
throw new AppServerError('busy', 'The graph is still loading; retry the model change in a moment.');
|
|
4704
|
-
|
|
5336
|
+
if (scopedNode !== undefined && run.modelGraph.nodes[scopedNode]?.type !== 'agent')
|
|
5337
|
+
throw new AppServerError('invalid-params', `Unknown agent node: ${scopedNode}`);
|
|
5338
|
+
const replacement = scopedNode === undefined
|
|
5339
|
+
? params.overrideAllNodes ? applyModelOverride(original, { provider, model }) : bindPortableGraphProviders(original, config)
|
|
5340
|
+
: undefined;
|
|
4705
5341
|
// The run's open record is also the crash-recovery source of its model identity. Persist
|
|
4706
5342
|
// the accepted selection *before* publishing it to the turn-boundary resolver: a model B
|
|
4707
5343
|
// checkpoint must never outlive a record that still claims the run used model A.
|
|
5344
|
+
let switched;
|
|
4708
5345
|
await this.serializeRunRecordWrite(run, async () => {
|
|
4709
5346
|
if (this.run !== run || run.controller.signal.aborted || run.steersClosed)
|
|
4710
5347
|
throw new AppServerError('invalid-params', 'That run is no longer active.');
|
|
@@ -4714,47 +5351,72 @@ export class AppServer {
|
|
|
4714
5351
|
const existing = JSON.parse(await readFile(path, 'utf8'));
|
|
4715
5352
|
if (existing.status !== 'running')
|
|
4716
5353
|
throw new AppServerError('invalid-params', 'That run is no longer active.');
|
|
4717
|
-
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
|
|
4722
|
-
|
|
4723
|
-
|
|
4724
|
-
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
|
|
5354
|
+
if (scopedNode !== undefined) {
|
|
5355
|
+
// The run's own pair stands: only the named node's pair is recorded, so a resume re-applies
|
|
5356
|
+
// it on top of the bound graph and everything else runs as the graph names. The run-scoped
|
|
5357
|
+
// branch below rebuilds from the graph's own selections, which is why it clears the map.
|
|
5358
|
+
const node = run.modelGraph.nodes[scopedNode];
|
|
5359
|
+
// The node's effective pair is what a previous switch moved it to, not what the graph
|
|
5360
|
+
// originally pinned: `modelGraph` is left untouched by a node switch, so the map it wrote
|
|
5361
|
+
// is the only place the first switch's pair still lives.
|
|
5362
|
+
const existingOverride = existing.nodeModelOverrides?.[scopedNode];
|
|
5363
|
+
const previousProvider = existingOverride?.provider ?? (typeof node.provider === 'string' ? node.provider : String(existing.provider ?? ''));
|
|
5364
|
+
const previousModel = existingOverride?.model ?? (typeof node.model === 'string' ? node.model
|
|
5365
|
+
: node.provider === undefined ? existing.model
|
|
5366
|
+
: config.providers.find(item => item.id === node.provider)?.model);
|
|
5367
|
+
existing.nodeModelOverrides = { ...(existing.nodeModelOverrides ?? {}), [scopedNode]: { provider, model } };
|
|
5368
|
+
// The switch still moved a model under a checkpoint, so a resume owes that node the same
|
|
5369
|
+
// reconciliation a run-level switch gets; the record's own pair is what it stays.
|
|
5370
|
+
existing.liveModelChanged = true;
|
|
5371
|
+
switched = { scope: 'node', from: { provider: previousProvider, ...(previousModel === undefined ? {} : { model: String(previousModel) }) }, nodeName: node.name };
|
|
5372
|
+
}
|
|
5373
|
+
else {
|
|
5374
|
+
switched = { scope: 'run', from: { provider: String(existing.provider ?? ''), ...(existing.model === undefined ? {} : { model: String(existing.model) }) } };
|
|
5375
|
+
existing.provider = provider;
|
|
5376
|
+
existing.model = model;
|
|
5377
|
+
existing.liveModelChanged = true;
|
|
5378
|
+
if (params.overrideAllNodes)
|
|
5379
|
+
existing.overrideAllNodes = true;
|
|
5380
|
+
else
|
|
5381
|
+
delete existing.overrideAllNodes;
|
|
5382
|
+
delete existing.nodeModelOverrides;
|
|
5383
|
+
// Effort from a previous provider is invalid on providers that do not support it.
|
|
5384
|
+
// The open record must be as resumable as the terminal record.
|
|
5385
|
+
if (!['openai-compatible', 'opencode-go'].includes(config.providers.find(item => item.id === provider)?.type ?? ''))
|
|
5386
|
+
delete existing.reasoningEffort;
|
|
5387
|
+
}
|
|
4728
5388
|
await writeOpenRunRecord(this.directory, existing);
|
|
4729
5389
|
// No await after durability: a model call now either sees the previously persisted pair
|
|
4730
5390
|
// or this one, including its override scope. An unsuccessful write never mutates the
|
|
4731
5391
|
// graph, the live resolver, or the timer carry.
|
|
4732
|
-
|
|
4733
|
-
const
|
|
4734
|
-
|
|
4735
|
-
|
|
4736
|
-
|
|
4737
|
-
|
|
4738
|
-
|
|
4739
|
-
|
|
4740
|
-
target[key] = source[key];
|
|
4741
|
-
}
|
|
4742
|
-
if (target.retry && source.retry)
|
|
4743
|
-
target.retry.fallback = structuredClone(source.retry.fallback);
|
|
4744
|
-
if (target.subagents && source.subagents) {
|
|
4745
|
-
for (const key of ['provider', 'model', 'modelPolicy']) {
|
|
4746
|
-
if (source.subagents[key] === undefined)
|
|
4747
|
-
delete target.subagents[key];
|
|
5392
|
+
if (replacement !== undefined) {
|
|
5393
|
+
for (const [id, source] of Object.entries(replacement.nodes)) {
|
|
5394
|
+
const target = run.modelGraph.nodes[id];
|
|
5395
|
+
if (!target || target.type !== 'agent')
|
|
5396
|
+
continue;
|
|
5397
|
+
for (const key of ['provider', 'model']) {
|
|
5398
|
+
if (source[key] === undefined)
|
|
5399
|
+
delete target[key];
|
|
4748
5400
|
else
|
|
4749
|
-
|
|
5401
|
+
target[key] = source[key];
|
|
4750
5402
|
}
|
|
4751
|
-
|
|
4752
|
-
|
|
4753
|
-
|
|
4754
|
-
|
|
4755
|
-
|
|
5403
|
+
if (target.retry && source.retry)
|
|
5404
|
+
target.retry.fallback = structuredClone(source.retry.fallback);
|
|
5405
|
+
if (target.subagents && source.subagents) {
|
|
5406
|
+
for (const key of ['provider', 'model', 'modelPolicy']) {
|
|
5407
|
+
if (source.subagents[key] === undefined)
|
|
5408
|
+
delete target.subagents[key];
|
|
4756
5409
|
else
|
|
4757
|
-
|
|
5410
|
+
Object.assign(target.subagents, { [key]: source.subagents[key] });
|
|
5411
|
+
}
|
|
5412
|
+
for (const role of target.subagents.roles ?? []) {
|
|
5413
|
+
const originalRole = source.subagents.roles?.find(item => item.id === role.id);
|
|
5414
|
+
for (const key of ['provider', 'model']) {
|
|
5415
|
+
if (originalRole?.[key] === undefined)
|
|
5416
|
+
delete role[key];
|
|
5417
|
+
else
|
|
5418
|
+
role[key] = originalRole[key];
|
|
5419
|
+
}
|
|
4758
5420
|
}
|
|
4759
5421
|
}
|
|
4760
5422
|
}
|
|
@@ -4763,12 +5425,37 @@ export class AppServer {
|
|
|
4763
5425
|
// and later switches must not resurrect an effort already removed from that record.
|
|
4764
5426
|
const liveEffort = typeof existing.reasoningEffort === 'string'
|
|
4765
5427
|
? reasoningEffort(existing.reasoningEffort) : undefined;
|
|
4766
|
-
|
|
4767
|
-
|
|
4768
|
-
|
|
5428
|
+
if (scopedNode !== undefined) {
|
|
5429
|
+
// The scalar pair is the run's own (or its first selection when none exists): a per-node
|
|
5430
|
+
// pick must not read as the pair every other node resolves to.
|
|
5431
|
+
const previous = run.modelSelection;
|
|
5432
|
+
run.modelSelection = {
|
|
5433
|
+
provider: previous?.provider ?? String(existing.provider),
|
|
5434
|
+
model: previous?.model ?? String(existing.model),
|
|
5435
|
+
// The whole-run scope is what it was: a switch that names a node does not widen or clear
|
|
5436
|
+
// it — the resolver gives the node's own override precedence, and every other node keeps
|
|
5437
|
+
// answering from this scope, which is what a whole-run switch rebuilt the graph to.
|
|
5438
|
+
overrideAllNodes: previous?.overrideAllNodes ?? existing.overrideAllNodes === true,
|
|
5439
|
+
// Node-only only while no run-level selection exists: a previous run-scoped pick or
|
|
5440
|
+
// whole-run override already answers for the nodes this switch leaves alone.
|
|
5441
|
+
nodeOnly: previous === undefined ? true : previous.nodeOnly === true,
|
|
5442
|
+
config,
|
|
5443
|
+
...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
|
|
5444
|
+
// The record's map is the union: it holds what a resume carried before this switch, so
|
|
5445
|
+
// the finalizer's copy — which prefers this map — cannot drop a carried node.
|
|
5446
|
+
nodeOverrides: { ...(existing.nodeModelOverrides ?? previous?.nodeOverrides ?? {}), [scopedNode]: { provider, model } },
|
|
5447
|
+
revision: (previous?.revision ?? 0) + 1,
|
|
5448
|
+
};
|
|
5449
|
+
}
|
|
5450
|
+
else {
|
|
5451
|
+
run.modelSelection = { provider, model, overrideAllNodes: params.overrideAllNodes, config,
|
|
5452
|
+
...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
|
|
5453
|
+
revision: (run.modelSelection?.revision ?? 0) + 1 };
|
|
5454
|
+
}
|
|
4769
5455
|
// Timers armed after the change inherit its pair; already-armed timers retained their
|
|
4770
|
-
// cloned carry. Effort is reconciled by the same provider eligibility as the record.
|
|
4771
|
-
|
|
5456
|
+
// cloned carry. Effort is reconciled by the same provider eligibility as the record. A
|
|
5457
|
+
// per-node switch is not the run's pair, so a timer keeps the pair it would have run on.
|
|
5458
|
+
if (replacement !== undefined && run.wakeCarry) {
|
|
4772
5459
|
if (liveEffort === undefined)
|
|
4773
5460
|
delete run.wakeCarry.reasoningEffort;
|
|
4774
5461
|
else
|
|
@@ -4781,8 +5468,173 @@ export class AppServer {
|
|
|
4781
5468
|
delete run.wakeCarry.overrideAllNodes;
|
|
4782
5469
|
}
|
|
4783
5470
|
});
|
|
5471
|
+
// A marker outside the durability window: the record already guarantees the pair, and the row
|
|
5472
|
+
// only names the switch to the timeline. A run-scoped switch carries no node, so it splits no
|
|
5473
|
+
// card; a node-scoped one is attributed and the timeline starts a new card at it.
|
|
5474
|
+
if (switched !== undefined) {
|
|
5475
|
+
await this.recordRunEvent(run.runId, { type: 'run.model.switched', time: new Date().toISOString(), data: {
|
|
5476
|
+
runId: run.runId,
|
|
5477
|
+
scope: switched.scope,
|
|
5478
|
+
...(switched.scope === 'node' && scopedNode !== undefined ? { nodeId: scopedNode, nodeName: switched.nodeName } : {}),
|
|
5479
|
+
from: switched.from,
|
|
5480
|
+
to: { provider, model },
|
|
5481
|
+
} });
|
|
5482
|
+
}
|
|
4784
5483
|
return { ok: true };
|
|
4785
5484
|
}
|
|
5485
|
+
/**
|
|
5486
|
+
* Change the permission mode a live attempt runs under, without interrupting it.
|
|
5487
|
+
*
|
|
5488
|
+
* The new mode reaches the attempt through its permission control (`ActiveRun.permissionControl`): a
|
|
5489
|
+
* tool call that has not decided yet decides under it, and every approval the attempt is waiting on
|
|
5490
|
+
* is handed back as `policy-changed`, so its tool decides again — a prompt the new mode answers goes
|
|
5491
|
+
* away, and one the new mode still requires is asked again. The mode is saved where the attempt read
|
|
5492
|
+
* it from, so the next task, a resume and a terminal on the same project agree with what is running.
|
|
5493
|
+
*/
|
|
5494
|
+
async setRunPermissions(params) {
|
|
5495
|
+
const runId = text(params.runId, 'runId', 200);
|
|
5496
|
+
const next = permissionMode(params.permissions);
|
|
5497
|
+
const live = this.run;
|
|
5498
|
+
if (live === undefined || live.runId !== runId || live.controller.signal.aborted || live.steersClosed) {
|
|
5499
|
+
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
5500
|
+
}
|
|
5501
|
+
const change = (live.permissionChanges ?? Promise.resolve()).then(() => this.applyRunPermissions(live, next));
|
|
5502
|
+
live.permissionChanges = change.then(() => undefined, () => undefined);
|
|
5503
|
+
return change;
|
|
5504
|
+
}
|
|
5505
|
+
async applyRunPermissions(live, next) {
|
|
5506
|
+
const stillLive = () => this.run === live && !live.controller.signal.aborted;
|
|
5507
|
+
if (!stillLive())
|
|
5508
|
+
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
5509
|
+
const previous = live.permissionControl.permissions ?? 'ask-for-approval';
|
|
5510
|
+
try {
|
|
5511
|
+
// The index cache writes into the workspace, so it stops before Read Only is saved or reaches a
|
|
5512
|
+
// tool, and resumes only after a wider mode is in force — the order `/permissions` keeps too. The
|
|
5513
|
+
// target is set on the run before anything awaits, so a manager the run creates from here on
|
|
5514
|
+
// starts in it; one already being created started in the earlier mode, so the change waits for it
|
|
5515
|
+
// and suspends it before Read Only is acknowledged.
|
|
5516
|
+
if (next === 'read-only' || next === 'plan') {
|
|
5517
|
+
live.codeIntelPermissions = next;
|
|
5518
|
+
await live.codeIntelReady;
|
|
5519
|
+
await this.syncCodeIntelPermissions(live);
|
|
5520
|
+
}
|
|
5521
|
+
await this.saveRunPermissions(live, next, stillLive);
|
|
5522
|
+
}
|
|
5523
|
+
catch (error) {
|
|
5524
|
+
// Nothing was saved, or the index could not be suspended: the run keeps its mode, and the index
|
|
5525
|
+
// goes back to that mode, so a later pick of it, or a retry, starts from a manager in step.
|
|
5526
|
+
live.codeIntelPermissions = live.permissionControl.permissions ?? previous;
|
|
5527
|
+
await live.codeIntelReady;
|
|
5528
|
+
await this.syncCodeIntelPermissions(live).catch(syncError => this.log('warn', `Could not restore code intelligence after a refused mode change: ${message(syncError)}`));
|
|
5529
|
+
throw error;
|
|
5530
|
+
}
|
|
5531
|
+
// The run may have ended while the mode was being saved. The saved mode still governs the next
|
|
5532
|
+
// task, which is what the caller asked for once this attempt is gone.
|
|
5533
|
+
if (!stillLive())
|
|
5534
|
+
return { ok: true, permissions: next, settled: [] };
|
|
5535
|
+
// A pick of the mode the run already has changes nothing in it: re-asking its open prompts would
|
|
5536
|
+
// only make them flicker. The index is still brought in step below.
|
|
5537
|
+
const settled = await this.switchLiveRunPermissions(live, next, previous);
|
|
5538
|
+
live.codeIntelPermissions = next;
|
|
5539
|
+
await live.codeIntelReady;
|
|
5540
|
+
await this.syncCodeIntelPermissions(live).catch(error => this.log('warn', `Could not apply the new mode to code intelligence: ${message(error)}`));
|
|
5541
|
+
return { ok: true, permissions: next, settled };
|
|
5542
|
+
}
|
|
5543
|
+
/**
|
|
5544
|
+
* Move a live run's control to `next` and journal the change, settling any prompt that waited
|
|
5545
|
+
* across it. Shared by the saved switch (`run.setPermissions`) and the run-scoped plan-approval
|
|
5546
|
+
* flip: neither re-asks a mode the run already has.
|
|
5547
|
+
*/
|
|
5548
|
+
async switchLiveRunPermissions(live, next, previous) {
|
|
5549
|
+
if (next === previous)
|
|
5550
|
+
return [];
|
|
5551
|
+
live.permissionControl.permissions = next;
|
|
5552
|
+
live.permissionControl.yolo = next === 'full-access';
|
|
5553
|
+
live.permissionRevision += 1;
|
|
5554
|
+
const settled = [...live.approvals];
|
|
5555
|
+
// Journaled before the prompts are handed back, so the record reads as the change and then the
|
|
5556
|
+
// decisions it led to. The same record emits `run.event`, which is how every window — including
|
|
5557
|
+
// one that did not make the change — drops the prompts it no longer has to show.
|
|
5558
|
+
await this.recordRunEvent(live.runId, {
|
|
5559
|
+
type: 'run.permissions.changed',
|
|
5560
|
+
time: new Date().toISOString(),
|
|
5561
|
+
data: { runId: live.runId, sessionId: live.sessionId, permissions: next, previous, settled },
|
|
5562
|
+
});
|
|
5563
|
+
for (const id of settled)
|
|
5564
|
+
this.pending.get(id)?.('policy-changed');
|
|
5565
|
+
return settled;
|
|
5566
|
+
}
|
|
5567
|
+
/**
|
|
5568
|
+
* The plan-approval flip. Unlike `run.setPermissions` it is run-scoped only: approving a plan
|
|
5569
|
+
* never rewrites the saved workspace default, so the next task plans again. The run continues in
|
|
5570
|
+
* the workspace's saved default when that is an editing mode, and in Ask for approval otherwise.
|
|
5571
|
+
*/
|
|
5572
|
+
async approvePlan(live) {
|
|
5573
|
+
const change = (live.permissionChanges ?? Promise.resolve()).then(async () => {
|
|
5574
|
+
if (this.run !== live || live.controller.signal.aborted)
|
|
5575
|
+
throw new AppServerError('not-found', 'That task is not running on this engine. The plan applies to the next task.');
|
|
5576
|
+
const config = await loadConfig(this.directory);
|
|
5577
|
+
const saved = config.workspacePermissions?.[workspacePermissionKey(live.workspace)];
|
|
5578
|
+
const next = saved === 'ask-for-approval' || saved === 'approve-for-me' || saved === 'full-access' ? saved : 'ask-for-approval';
|
|
5579
|
+
await this.switchLiveRunPermissions(live, next, live.permissionControl.permissions ?? 'ask-for-approval');
|
|
5580
|
+
live.codeIntelPermissions = next;
|
|
5581
|
+
await live.codeIntelReady;
|
|
5582
|
+
await this.syncCodeIntelPermissions(live).catch(error => this.log('warn', `Could not apply the new mode to code intelligence: ${message(error)}`));
|
|
5583
|
+
return next;
|
|
5584
|
+
});
|
|
5585
|
+
live.permissionChanges = change.then(() => undefined, () => undefined);
|
|
5586
|
+
return change;
|
|
5587
|
+
}
|
|
5588
|
+
/** Save a live mode where the attempt reads it from: its own record when bound, the workspace default otherwise. */
|
|
5589
|
+
async saveRunPermissions(live, next, stillLive) {
|
|
5590
|
+
if (live.boundPermissions) {
|
|
5591
|
+
// The attempt's own record is where a resume reads a bound mode back from.
|
|
5592
|
+
await this.serializeRunRecordWrite(live, async () => {
|
|
5593
|
+
if (!stillLive())
|
|
5594
|
+
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
5595
|
+
const existing = JSON.parse(await readFile(runRecordPath(this.directory, live.runId, 'json'), 'utf8'));
|
|
5596
|
+
if (existing.status !== 'running')
|
|
5597
|
+
throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
|
|
5598
|
+
existing.permissions = next;
|
|
5599
|
+
await writeOpenRunRecord(this.directory, existing);
|
|
5600
|
+
});
|
|
5601
|
+
}
|
|
5602
|
+
else {
|
|
5603
|
+
// Serialized with every other configuration write, exactly as `run.start` saves a picked mode.
|
|
5604
|
+
const saved = await this.serializeConfig(async () => {
|
|
5605
|
+
try {
|
|
5606
|
+
return await changeConfigFile(this.directory, current => ({ ...current, workspacePermissions: { ...current.workspacePermissions, [workspacePermissionKey(live.workspace)]: next } }));
|
|
5607
|
+
}
|
|
5608
|
+
catch (error) {
|
|
5609
|
+
if (error instanceof AppServerError)
|
|
5610
|
+
throw error;
|
|
5611
|
+
throw error instanceof ConfigConflictError ? new AppServerError('busy', message(error)) : new AppServerError('invalid-params', message(error));
|
|
5612
|
+
}
|
|
5613
|
+
});
|
|
5614
|
+
this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
|
|
5615
|
+
}
|
|
5616
|
+
}
|
|
5617
|
+
/**
|
|
5618
|
+
* Bring the workspace's code-intelligence manager, once it exists, to the mode the run holds for it.
|
|
5619
|
+
*
|
|
5620
|
+
* One change at a time, each reading the target when it runs, so the last one leaves the manager on
|
|
5621
|
+
* the latest target. A manager already on the target is left alone; one whose change failed is in an
|
|
5622
|
+
* unknown mode, so the next sync applies the target again rather than trusting it.
|
|
5623
|
+
*/
|
|
5624
|
+
syncCodeIntelPermissions(live) {
|
|
5625
|
+
const apply = async () => {
|
|
5626
|
+
const manager = this.codeIntel?.workspace === live.workspace ? this.codeIntel.manager : undefined;
|
|
5627
|
+
const target = live.codeIntelPermissions;
|
|
5628
|
+
if (!manager || live.codeIntelApplied === target)
|
|
5629
|
+
return;
|
|
5630
|
+
live.codeIntelApplied = undefined;
|
|
5631
|
+
await manager.setPermissions(target);
|
|
5632
|
+
live.codeIntelApplied = target;
|
|
5633
|
+
};
|
|
5634
|
+
const step = (live.codeIntelSync ?? Promise.resolve()).then(apply);
|
|
5635
|
+
live.codeIntelSync = step.then(() => undefined, () => undefined);
|
|
5636
|
+
return step;
|
|
5637
|
+
}
|
|
4786
5638
|
async resolveModel(config, id, model, signal, reasoningEffort) {
|
|
4787
5639
|
const provider = config.providers.find(item => item.id === id);
|
|
4788
5640
|
if (!provider)
|
|
@@ -4851,14 +5703,14 @@ export class AppServer {
|
|
|
4851
5703
|
}
|
|
4852
5704
|
// The manager takes its own read-only branch and its own disabled branch, so it is always
|
|
4853
5705
|
// created; what matters is that both guards reach it rather than indexing by default.
|
|
4854
|
-
const manager = await
|
|
5706
|
+
const manager = await this.createCodeIntelligence({ workspace: root, config, permissions, onEvent: event => { this.runEvent(event); } });
|
|
4855
5707
|
this.codeIntel = { workspace: root, signature, manager };
|
|
4856
5708
|
return manager;
|
|
4857
5709
|
}
|
|
4858
5710
|
/** Code-intelligence events belong to the active run's stream when one is running. */
|
|
4859
5711
|
runEvent(event) {
|
|
4860
5712
|
if (this.run) {
|
|
4861
|
-
void this.recordRunEvent(this.run.runId,
|
|
5713
|
+
void this.recordRunEvent(this.run.runId, event);
|
|
4862
5714
|
// Code intelligence reports through this separate sink, not GraphRunOptions.onEvent.
|
|
4863
5715
|
// Keep the session-wide debug account complete as well as the resumable run journal.
|
|
4864
5716
|
void this.trajectory?.recordEvent(event);
|
|
@@ -4866,32 +5718,33 @@ export class AppServer {
|
|
|
4866
5718
|
else
|
|
4867
5719
|
this.emit('codeintel.event', { event });
|
|
4868
5720
|
}
|
|
5721
|
+
/** The journal writer of one run, created on its first event. */
|
|
5722
|
+
journalFor(runId) {
|
|
5723
|
+
let writer = this.journals.get(runId);
|
|
5724
|
+
if (writer === undefined) {
|
|
5725
|
+
// The run keeps going when an append fails (a storage hiccup must not kill the user's work).
|
|
5726
|
+
// The writer holds the event and writes it once the file accepts appends again, so a disk
|
|
5727
|
+
// that filled for a minute leaves a complete journal rather than one no resume can trust.
|
|
5728
|
+
writer = createRunJournalWriter(this.directory, runId, { onFailure: error => this.log('warn', `Could not append to the run journal: ${message(error)}`) });
|
|
5729
|
+
this.journals.set(runId, writer);
|
|
5730
|
+
}
|
|
5731
|
+
return writer;
|
|
5732
|
+
}
|
|
4869
5733
|
/**
|
|
4870
5734
|
* Journal first, then the client: a client that missed an event can re-read the record.
|
|
4871
5735
|
*
|
|
4872
|
-
* `runs/`
|
|
4873
|
-
* and this mode returns before that code runs, so a fresh configuration home
|
|
4874
|
-
* fail every append with ENOENT
|
|
5736
|
+
* The writer creates `runs/` when the first append finds it missing: the terminal client creates
|
|
5737
|
+
* it during startup, and this mode returns before that code runs, so a fresh configuration home
|
|
5738
|
+
* would otherwise fail every append with ENOENT. Appends are ordered: the filesystem does not
|
|
5739
|
+
* finish concurrent appends in the order they were started.
|
|
4875
5740
|
*/
|
|
4876
|
-
async recordRunEvent(runId,
|
|
5741
|
+
async recordRunEvent(runId, event) {
|
|
4877
5742
|
// The provider answered once, so a naming request queued behind this turn no longer competes
|
|
4878
5743
|
// with the run's opening request: from here the run works through the turn's tools, and the
|
|
4879
5744
|
// title can take the endpoint without delaying the work it names.
|
|
4880
5745
|
if (event.type === 'agent.model.completed')
|
|
4881
5746
|
this.releaseTitleWaiter(runId);
|
|
4882
|
-
|
|
4883
|
-
await this.ensureRunRecords();
|
|
4884
|
-
await appendFile(journal, `${JSON.stringify(event)}\n`, { mode: 0o600 });
|
|
4885
|
-
}
|
|
4886
|
-
catch (error) {
|
|
4887
|
-
// The run keeps going (a storage hiccup must not kill the user's work) but the journal is no
|
|
4888
|
-
// longer a complete account: the events after this failure are written, so nothing in the
|
|
4889
|
-
// file itself reveals the hole. Left unmarked, a crashed attempt would replay to a position
|
|
4890
|
-
// missing whatever this append ate and resume by repeating that work.
|
|
4891
|
-
this.journalFailures.add(runId);
|
|
4892
|
-
await noteJournalWriteFailure(this.directory, runId, message(error));
|
|
4893
|
-
this.log('warn', `Could not append to the run journal: ${message(error)}`);
|
|
4894
|
-
}
|
|
5747
|
+
await this.journalFor(runId).append(event);
|
|
4895
5748
|
if (event.type === 'graph.started' || event.type === 'graph.node.started')
|
|
4896
5749
|
bootMark(`run.event.${event.type}`, typeof event.data?.nodeId === 'string' ? `node=${event.data.nodeId}` : undefined);
|
|
4897
5750
|
this.emit('run.event', { runId, event });
|
|
@@ -4917,18 +5770,34 @@ export class AppServer {
|
|
|
4917
5770
|
async approve(runId, name, args, signal) {
|
|
4918
5771
|
const id = randomUUID();
|
|
4919
5772
|
const sessionId = this.run?.sessionId;
|
|
5773
|
+
// The tool decided to ask under the mode in force now. A live change that lands while the prompt
|
|
5774
|
+
// is still being recorded finds nothing pending to hand back, so the prompt checks for itself
|
|
5775
|
+
// before it is shown: asking under a mode the user has already left is the prompt they switched
|
|
5776
|
+
// modes to get rid of.
|
|
5777
|
+
const live = this.run?.runId === runId ? this.run : undefined;
|
|
5778
|
+
const revision = live?.permissionRevision;
|
|
4920
5779
|
if (sessionId)
|
|
4921
5780
|
await writePendingAgentInteraction(this.directory, {
|
|
4922
5781
|
version: 1, id, runId, sessionId, kind: 'approval',
|
|
4923
5782
|
prompt: 'Approval required for tool ' + name, createdAt: new Date().toISOString(),
|
|
4924
5783
|
}).catch(error => this.log('warn', 'Could not record pending approval: ' + message(error)));
|
|
5784
|
+
if (live !== undefined && live.permissionRevision !== revision) {
|
|
5785
|
+
if (sessionId)
|
|
5786
|
+
await removePendingAgentInteraction(this.directory, runId, id)
|
|
5787
|
+
.catch(error => this.log('warn', 'Could not clear pending approval: ' + message(error)));
|
|
5788
|
+
return 'policy-changed';
|
|
5789
|
+
}
|
|
4925
5790
|
this.emit('run.approval', { runId, id, name, arguments: args });
|
|
4926
5791
|
this.emit('run.state', { runId, state: 'awaiting-approval' });
|
|
4927
5792
|
let answer;
|
|
4928
5793
|
try {
|
|
4929
|
-
|
|
5794
|
+
// Registered in the same turn the prompt becomes pending, so no live change can fall between.
|
|
5795
|
+
const answered = this.interaction(id, signal);
|
|
5796
|
+
live?.approvals.add(id);
|
|
5797
|
+
answer = await answered;
|
|
4930
5798
|
}
|
|
4931
5799
|
finally {
|
|
5800
|
+
live?.approvals.delete(id);
|
|
4932
5801
|
if (sessionId)
|
|
4933
5802
|
await removePendingAgentInteraction(this.directory, runId, id)
|
|
4934
5803
|
.catch(error => this.log('warn', 'Could not clear pending approval: ' + message(error)));
|
|
@@ -5100,7 +5969,7 @@ export class AppServer {
|
|
|
5100
5969
|
// from that journal, so the user's own message stays where it was said even after the attempt
|
|
5101
5970
|
// stops and its card is replaced by the work it did. The same record emits `run.event`, which
|
|
5102
5971
|
// is what draws the row live.
|
|
5103
|
-
await this.recordRunEvent(runId,
|
|
5972
|
+
await this.recordRunEvent(runId, {
|
|
5104
5973
|
type: 'run.steered',
|
|
5105
5974
|
time: entry.at,
|
|
5106
5975
|
data: { runId, sessionId: live.sessionId, steerId: entry.id, text: entry.text, ...(refs.length ? { attachments: refs } : {}) },
|
|
@@ -5123,6 +5992,18 @@ export class AppServer {
|
|
|
5123
5992
|
* them into B's account. `graphStorageAccess` claims an unclaimed directory for a confirmed account —
|
|
5124
5993
|
* the account the builder claims it for — and reports the ones that are still shared.
|
|
5125
5994
|
*/
|
|
5995
|
+
/** Whether a stored graph selection names a graph whose latest revision is soft-deleted. */
|
|
5996
|
+
async selectionIsDeleted(selection) {
|
|
5997
|
+
if (selection === 'default' || selection.includes(':'))
|
|
5998
|
+
return false;
|
|
5999
|
+
try {
|
|
6000
|
+
const { directory } = await this.graphDirectory();
|
|
6001
|
+
return isDeletedGraph(await loadGraph(selection, undefined, directory));
|
|
6002
|
+
}
|
|
6003
|
+
catch {
|
|
6004
|
+
return false;
|
|
6005
|
+
}
|
|
6006
|
+
}
|
|
5126
6007
|
async graphDirectory(canClaim = false) {
|
|
5127
6008
|
const subject = await currentGraphSubject();
|
|
5128
6009
|
// Signed-in graphs live under the account's storage; the local directory is the fallback and the
|
|
@@ -5171,7 +6052,8 @@ export class AppServer {
|
|
|
5171
6052
|
const kept = confirmed ? (await readGraphQuota(directory, saved)).freeGraphId : undefined;
|
|
5172
6053
|
if (status.signedIn && !free)
|
|
5173
6054
|
graphs.push({ id: ANDORRA_GRAPH_SELECTION, name: 'Andorra', revision: getAndorraHarness().revision, preset: true });
|
|
5174
|
-
|
|
6055
|
+
// Deleted graphs leave the picker; the quota above still counts them.
|
|
6056
|
+
for (const graph of withoutDeletedGraphs(saved)) {
|
|
5175
6057
|
// A kept graph over the allowance (one saved on a paid plan) stays editable but is not offered to run.
|
|
5176
6058
|
if (graph.id === 'default' || (free && (graph.id !== kept || freeTierGraphViolation(graph) !== undefined)))
|
|
5177
6059
|
continue;
|
|
@@ -5181,7 +6063,11 @@ export class AppServer {
|
|
|
5181
6063
|
// The identity this listing belongs to travels with it: a client reads the listing and its own account
|
|
5182
6064
|
// in one refresh, and an account that changed between the two requests would otherwise be hidden —
|
|
5183
6065
|
// one account's plan published with the other account's graph names.
|
|
5184
|
-
|
|
6066
|
+
// A saved selection that names a deleted graph reads as Default until the graph is restored; the
|
|
6067
|
+
// selection itself is kept, so restoring brings it back.
|
|
6068
|
+
const configured = configuredGraphSelection(await loadConfig(this.directory), subject);
|
|
6069
|
+
const selected = saved.some(graph => graph.id === configured && isDeletedGraph(graph)) ? 'default' : configured;
|
|
6070
|
+
return { graphs, selected, paid: membership.paid === true, ...(subject === undefined ? {} : { subject }) };
|
|
5185
6071
|
}
|
|
5186
6072
|
/**
|
|
5187
6073
|
* The shareable file of one library Agent, for the desktop's Share action to write into the
|
|
@@ -5237,7 +6123,21 @@ export class AppServer {
|
|
|
5237
6123
|
if (subject !== undefined && await currentGraphSubject() !== subject) {
|
|
5238
6124
|
throw new AppServerError('auth', 'the signed-in account changed during the read; read the graph again');
|
|
5239
6125
|
}
|
|
5240
|
-
|
|
6126
|
+
// The copy a run would bind, beside the saved definition the editor and export read: a start
|
|
6127
|
+
// resolves the saved provider references through this installation's providers (the way
|
|
6128
|
+
// `loadAccessibleGraph` does) — aliasing a recorded identity this machine lacks and pinning its
|
|
6129
|
+
// recorded model — so a client previewing the graph's models names the pair that actually
|
|
6130
|
+
// executes rather than the saved references. A definition that cannot bind here refuses its run
|
|
6131
|
+
// outright, so the field is omitted and the client previews the saved references instead.
|
|
6132
|
+
let execution;
|
|
6133
|
+
try {
|
|
6134
|
+
execution = bindPortableGraphProviders(graph, await loadConfig(this.directory));
|
|
6135
|
+
}
|
|
6136
|
+
catch (error) {
|
|
6137
|
+
if (!(error instanceof GraphProviderUnavailableError))
|
|
6138
|
+
throw error;
|
|
6139
|
+
}
|
|
6140
|
+
return { graph, ...(execution !== undefined ? { execution } : {}), ...(subject === undefined ? {} : { subject }) };
|
|
5241
6141
|
}
|
|
5242
6142
|
/**
|
|
5243
6143
|
* Persist the installation's graph selection.
|
|
@@ -6079,7 +6979,7 @@ export class AppServer {
|
|
|
6079
6979
|
}
|
|
6080
6980
|
/** Say what a session is waiting on. An empty list is a real answer: it is what ends a wait. */
|
|
6081
6981
|
emitPullRequest(sessionId, pullRequest) {
|
|
6082
|
-
this.emit('session.pullRequest.updated', { sessionId, pullRequest });
|
|
6982
|
+
this.emit('session.pullRequest.updated', { sessionId, pullRequest: pullRequestForClients(pullRequest) });
|
|
6083
6983
|
}
|
|
6084
6984
|
/**
|
|
6085
6985
|
* Start tracking `ref` for the session. A PR already tracked under the same URL keeps its settings, so a
|
|
@@ -6089,17 +6989,24 @@ export class AppServer {
|
|
|
6089
6989
|
const attached = await withPullRequest(this.directory, sessionId, async () => {
|
|
6090
6990
|
const current = await readPullRequest(this.directory, sessionId);
|
|
6091
6991
|
let next = current?.url === ref.url ? current : newPullRequest(ref);
|
|
6092
|
-
// The title, state and auto-merge are read once on attach
|
|
6992
|
+
// The title, state and auto-merge are read once on attach, as an account that can see the PR, and that account
|
|
6993
|
+
// is kept for every later call. A PR that cannot be read is still tracked, as open: when no signed-in account
|
|
6994
|
+
// can read it the row says so, and an outage is logged and left to the next read (the watcher's poll, or a
|
|
6995
|
+
// draft or auto-merge change).
|
|
6093
6996
|
if (next !== current) {
|
|
6094
|
-
const
|
|
6095
|
-
if (seen)
|
|
6096
|
-
next = { ...next, title: seen.title, state: seen.state, mergeWhenReady: seen.autoMerge };
|
|
6997
|
+
const read = await readPullRequestAsAnyAccount(this.gh, ref.url);
|
|
6998
|
+
if (read.seen)
|
|
6999
|
+
next = { ...next, title: read.seen.title, state: read.seen.state, mergeWhenReady: read.seen.autoMerge, ...(read.ghUser === undefined ? {} : { ghUser: read.ghUser }) };
|
|
7000
|
+
else if (read.unreadable)
|
|
7001
|
+
next = { ...next, watchError: noAccountMessage(ref.url) };
|
|
7002
|
+
else if ('failed' in read)
|
|
7003
|
+
this.log('warn', `Could not read ${ref.url} while attaching it: ${message(read.failed)}`);
|
|
6097
7004
|
}
|
|
6098
7005
|
// The run that attached it names the graph, model and effort an Auto-fix run continues under.
|
|
6099
7006
|
if (carry !== undefined)
|
|
6100
7007
|
next = { ...next, carry: structuredClone(carry) };
|
|
6101
7008
|
if (Object.keys(settings).length)
|
|
6102
|
-
next = await
|
|
7009
|
+
next = await applyPullRequestSettingsAsReadableAccount(this.gh, next, settings);
|
|
6103
7010
|
await writePullRequest(this.directory, sessionId, next);
|
|
6104
7011
|
return next;
|
|
6105
7012
|
});
|
|
@@ -6115,7 +7022,7 @@ export class AppServer {
|
|
|
6115
7022
|
throw new AppServerError('not-found', 'This session has no pull request.');
|
|
6116
7023
|
let next;
|
|
6117
7024
|
try {
|
|
6118
|
-
next = await
|
|
7025
|
+
next = await applyPullRequestSettingsAsReadableAccount(this.gh, current, settings);
|
|
6119
7026
|
}
|
|
6120
7027
|
catch (error) {
|
|
6121
7028
|
throw new AppServerError('remote', message(error));
|
|
@@ -6193,8 +7100,6 @@ export class AppServer {
|
|
|
6193
7100
|
settleSessionTimers(sessionId) {
|
|
6194
7101
|
this.emitTimers(sessionId);
|
|
6195
7102
|
this.armTimerCheck();
|
|
6196
|
-
// An Auto-archive the run held off (a session is not archived mid-run) is owed now, not a poll later.
|
|
6197
|
-
void this.pullRequestWatcher.poll();
|
|
6198
7103
|
}
|
|
6199
7104
|
/** Arm the next deadline check, across every session this engine holds wakes for. */
|
|
6200
7105
|
armTimerCheck(minimumDelayMs = 1) {
|
|
@@ -6240,6 +7145,134 @@ export class AppServer {
|
|
|
6240
7145
|
.catch(error => this.log('error', `Self-wake delivery failed: ${message(error)}`))
|
|
6241
7146
|
.finally(() => { this.timerDeliveryTask = undefined; });
|
|
6242
7147
|
}
|
|
7148
|
+
/**
|
|
7149
|
+
* Say a wake will never be delivered: drop it, publish the shorter wait list, and tell the user why.
|
|
7150
|
+
*
|
|
7151
|
+
* A wake is the agent's own reminder about work that is over or was replaced, and starting it as a new task
|
|
7152
|
+
* would restart that work behind the user's back. Dropping it silently would hide a promise the agent made,
|
|
7153
|
+
* so the reason goes out with `timers.spent` - which a window shows as a notice - and into the log.
|
|
7154
|
+
*/
|
|
7155
|
+
spendWake(timer, reason) {
|
|
7156
|
+
this.timers.settle(timer.id);
|
|
7157
|
+
this.autoFixWakes.delete(timer.id);
|
|
7158
|
+
this.log('info', `Self-wake ${timer.id} was not delivered: ${reason}`);
|
|
7159
|
+
const sessionId = timer.owner;
|
|
7160
|
+
if (sessionId === undefined)
|
|
7161
|
+
return;
|
|
7162
|
+
void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
|
|
7163
|
+
this.emit('timers.spent', { sessionId, timerId: timer.id, prompt: timer.prompt, reason });
|
|
7164
|
+
this.emitTimers(sessionId);
|
|
7165
|
+
}
|
|
7166
|
+
/**
|
|
7167
|
+
* Spend the session's node-armed wakes that belong to an attempt in `attempts` and satisfy `spent`.
|
|
7168
|
+
*
|
|
7169
|
+
* Wakes another surface is in the middle of delivering are left alone: that delivery decides what became of
|
|
7170
|
+
* them. Wakes no graph node armed are never touched here.
|
|
7171
|
+
*/
|
|
7172
|
+
spendAttemptWakes(sessionId, attempts, reason, spent = () => true) {
|
|
7173
|
+
for (const timer of this.timers.list(sessionId)) {
|
|
7174
|
+
if (timer.origin === undefined || !attempts.has(timer.origin.runId) || this.timers.isHeld(timer.id))
|
|
7175
|
+
continue;
|
|
7176
|
+
if (spent(timer.origin))
|
|
7177
|
+
this.spendWake(timer, reason);
|
|
7178
|
+
}
|
|
7179
|
+
}
|
|
7180
|
+
/**
|
|
7181
|
+
* Hand every due wake the live run itself armed (or an attempt that run continues) to that run, as a
|
|
7182
|
+
* steering message its working node reads at the next turn boundary.
|
|
7183
|
+
*
|
|
7184
|
+
* The wake is settled once the message is queued: from there the run owns it. One the run ends before
|
|
7185
|
+
* reading is put back on the registry by the finalizer, where the rules for a finished run decide it.
|
|
7186
|
+
*/
|
|
7187
|
+
steerDueWakes(live) {
|
|
7188
|
+
if (live.steersClosed || live.controller.signal.aborted)
|
|
7189
|
+
return;
|
|
7190
|
+
const own = new Set([live.runId, ...(live.lineage ?? [])]);
|
|
7191
|
+
for (;;) {
|
|
7192
|
+
const timer = this.timers.takeDueOne(Date.now(), live.sessionId, candidate => candidate.origin !== undefined && own.has(candidate.origin.runId));
|
|
7193
|
+
if (timer === undefined)
|
|
7194
|
+
return;
|
|
7195
|
+
const at = new Date().toISOString();
|
|
7196
|
+
const entry = { id: `${live.runId}#wake-${timer.id}`, text: timer.prompt,
|
|
7197
|
+
// The model reads it as its own reminder, not as the user speaking.
|
|
7198
|
+
content: timerReminderText(timer.prompt), images: [], at, wake: timer };
|
|
7199
|
+
live.steers.push(entry);
|
|
7200
|
+
this.timers.settle(timer.id);
|
|
7201
|
+
void clearWakeClaim(this.directory, live.sessionId, timer.id).catch(() => { });
|
|
7202
|
+
this.log('info', `Delivering self-wake ${timer.id} into the running attempt ${live.runId}`);
|
|
7203
|
+
// Journaled like a steer the user typed, so the transcript keeps the reminder where the node read it -
|
|
7204
|
+
// marked as a wake, so no window draws it as the user's message.
|
|
7205
|
+
void this.recordRunEvent(live.runId, { type: 'run.steered', time: at,
|
|
7206
|
+
data: { runId: live.runId, sessionId: live.sessionId, steerId: entry.id, text: entry.text, wake: 'timer' } });
|
|
7207
|
+
this.emitTimers(live.sessionId);
|
|
7208
|
+
}
|
|
7209
|
+
}
|
|
7210
|
+
/**
|
|
7211
|
+
* Where a node-armed wake goes once no run has the engine: the attempt to continue, a reason it is spent, or
|
|
7212
|
+
* a reason to wait.
|
|
7213
|
+
*
|
|
7214
|
+
* It continues only the session's newest attempt, and only when that attempt is the one that armed it or a
|
|
7215
|
+
* continuation of it, the attempt stopped without finishing, the user did not stop it, and the arming node
|
|
7216
|
+
* has not finished since the wake was armed. Anything else means the work the reminder was about is over or
|
|
7217
|
+
* was replaced by a newer turn, and it is spent.
|
|
7218
|
+
*/
|
|
7219
|
+
async wakeContinuation(timer, origin, record) {
|
|
7220
|
+
const newest = record.history?.at(-1)?.runId;
|
|
7221
|
+
if (newest === undefined)
|
|
7222
|
+
return { spent: 'the session no longer has the attempt that set it' };
|
|
7223
|
+
// The newest attempt's lineage, newest first: the reminder belongs to it only when the attempt that armed
|
|
7224
|
+
// it is in that chain.
|
|
7225
|
+
const chain = [];
|
|
7226
|
+
let newestRecord;
|
|
7227
|
+
for (let cursor = newest; cursor !== undefined && chain.length < MAX_RESUME_LINEAGE && !chain.includes(cursor);) {
|
|
7228
|
+
chain.push(cursor);
|
|
7229
|
+
if (cursor === origin.runId)
|
|
7230
|
+
break;
|
|
7231
|
+
let value;
|
|
7232
|
+
try {
|
|
7233
|
+
value = JSON.parse(await readFile(runRecordPath(this.directory, cursor, 'json'), 'utf8'));
|
|
7234
|
+
}
|
|
7235
|
+
catch {
|
|
7236
|
+
break;
|
|
7237
|
+
}
|
|
7238
|
+
if (cursor === newest)
|
|
7239
|
+
newestRecord = value;
|
|
7240
|
+
cursor = typeof value.resumedFrom === 'string' ? value.resumedFrom : undefined;
|
|
7241
|
+
}
|
|
7242
|
+
if (!chain.includes(origin.runId))
|
|
7243
|
+
return { spent: 'a newer turn in this session replaced the attempt that set it' };
|
|
7244
|
+
newestRecord ??= JSON.parse(await readFile(runRecordPath(this.directory, newest, 'json'), 'utf8'));
|
|
7245
|
+
const status = typeof newestRecord.status === 'string' ? newestRecord.status : undefined;
|
|
7246
|
+
if (status === 'succeeded')
|
|
7247
|
+
return { spent: 'the attempt that set it has finished' };
|
|
7248
|
+
if (status === 'cancelled')
|
|
7249
|
+
return { spent: 'the attempt that set it was stopped' };
|
|
7250
|
+
if (status === 'running' && typeof newestRecord.pid === 'number' && isPidAlive(newestRecord.pid))
|
|
7251
|
+
return { wait: 'its attempt is still running in another engine' };
|
|
7252
|
+
// The node finished after the reminder was set: what it was waiting on is behind it, and continuing the
|
|
7253
|
+
// attempt from wherever it stopped would hand the reminder to work it was never about.
|
|
7254
|
+
const armedAt = timer.fireAt - timer.seconds * 1_000;
|
|
7255
|
+
for (const attempt of chain) {
|
|
7256
|
+
const journal = await readFile(runRecordPath(this.directory, attempt, 'jsonl'), 'utf8').catch(() => '');
|
|
7257
|
+
for (const line of journal.split('\n')) {
|
|
7258
|
+
if (!line.includes('"graph.node.completed"') || !line.includes(origin.nodeId))
|
|
7259
|
+
continue;
|
|
7260
|
+
let event;
|
|
7261
|
+
try {
|
|
7262
|
+
event = JSON.parse(line);
|
|
7263
|
+
}
|
|
7264
|
+
catch {
|
|
7265
|
+
continue;
|
|
7266
|
+
}
|
|
7267
|
+
if (event.type !== 'graph.node.completed' || event.data?.nodeId !== origin.nodeId)
|
|
7268
|
+
continue;
|
|
7269
|
+
const time = typeof event.time === 'string' ? Date.parse(event.time) : Number.NaN;
|
|
7270
|
+
if (Number.isNaN(time) || time >= armedAt)
|
|
7271
|
+
return { spent: 'the node that set it has finished its work' };
|
|
7272
|
+
}
|
|
7273
|
+
}
|
|
7274
|
+
return { resume: newest };
|
|
7275
|
+
}
|
|
6243
7276
|
/**
|
|
6244
7277
|
* Give every wake that has come due to the session that armed it, one run at a time.
|
|
6245
7278
|
*
|
|
@@ -6263,6 +7296,11 @@ export class AppServer {
|
|
|
6263
7296
|
// A wake waits out a run that is already going: a deadline says the earliest a prompt may be given,
|
|
6264
7297
|
// not the moment it is. Look again when that run ends, or on the retry below if it never says so.
|
|
6265
7298
|
if (this.run !== undefined || this.starting) {
|
|
7299
|
+
// ...unless the run that has the engine is the wake's own work: a reminder the arming node set while
|
|
7300
|
+
// it waits on something is read by that node at its next turn boundary, the way a message the user
|
|
7301
|
+
// types into the live run is. Every other wake waits for the run to end.
|
|
7302
|
+
if (this.run !== undefined && !this.starting)
|
|
7303
|
+
this.steerDueWakes(this.run);
|
|
6266
7304
|
this.armTimerCheck();
|
|
6267
7305
|
return;
|
|
6268
7306
|
}
|
|
@@ -6305,41 +7343,93 @@ export class AppServer {
|
|
|
6305
7343
|
this.emitTimers(sessionId);
|
|
6306
7344
|
continue;
|
|
6307
7345
|
}
|
|
6308
|
-
// An Auto-fix wake is delivered only while the session still wants it
|
|
6309
|
-
// replaced or had Auto-fix switched off — here or in another
|
|
6310
|
-
//
|
|
6311
|
-
// mark on the next poll.
|
|
6312
|
-
if (this.autoFixWakes.has(timer.id)
|
|
6313
|
-
|
|
6314
|
-
|
|
6315
|
-
|
|
6316
|
-
|
|
6317
|
-
|
|
6318
|
-
|
|
7346
|
+
// An Auto-fix wake is delivered only while the session still wants it and GitHub, asked now, says the PR is
|
|
7347
|
+
// still open: the PR may have been dismissed, replaced or had Auto-fix switched off — here or in another
|
|
7348
|
+
// engine — or been merged or closed by hand while the wake waited out a run. A wake dropped here costs nothing
|
|
7349
|
+
// it should keep: a still-wanted fix is re-armed from the record's pending mark on the next poll.
|
|
7350
|
+
if (this.autoFixWakes.has(timer.id)) {
|
|
7351
|
+
let confirmed;
|
|
7352
|
+
try {
|
|
7353
|
+
confirmed = await confirmAutoFixWake(this.directory, this.gh, sessionId, timer.id);
|
|
7354
|
+
}
|
|
7355
|
+
catch (error) {
|
|
7356
|
+
// Not sent unconfirmed: the wake is kept and GitHub is asked again later. One withdrawn while GitHub was
|
|
7357
|
+
// being asked (Auto-fix switched off, the PR dismissed) is not brought back.
|
|
7358
|
+
if (this.timers.get(timer.id) !== undefined)
|
|
7359
|
+
this.timers.restore(timer, AUTO_FIX_CONFIRM_RETRY_MS);
|
|
7360
|
+
nextCheckIn = WAKE_RETRY_MS;
|
|
7361
|
+
this.log('warn', `Auto-fix wake ${timer.id} waits: GitHub could not confirm the pull request is still open (${message(error)})`);
|
|
7362
|
+
continue;
|
|
7363
|
+
}
|
|
7364
|
+
if (confirmed.pullRequest)
|
|
7365
|
+
this.emitPullRequest(sessionId, confirmed.pullRequest);
|
|
7366
|
+
if (!confirmed.deliver) {
|
|
7367
|
+
this.autoFixWakes.delete(timer.id);
|
|
7368
|
+
this.timers.settle(timer.id);
|
|
7369
|
+
void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
|
|
7370
|
+
this.emitTimers(sessionId);
|
|
7371
|
+
this.log('info', confirmed.pullRequest
|
|
7372
|
+
? `Dropped Auto-fix wake ${timer.id}: ${confirmed.pullRequest.url} is ${confirmed.pullRequest.state}, so Auto-fix is off`
|
|
7373
|
+
: `Dropped Auto-fix wake ${timer.id}: session ${sessionId} no longer asks for it`);
|
|
7374
|
+
continue;
|
|
7375
|
+
}
|
|
6319
7376
|
}
|
|
6320
|
-
|
|
7377
|
+
// A wake a graph node armed goes back to that node's work: as a continuation of the attempt it armed, from
|
|
7378
|
+
// that node's checkpoint. One with nothing left to continue is spent, never started as a new task that
|
|
7379
|
+
// enters the graph at its entry node with the agent's reminder for a prompt.
|
|
7380
|
+
let resume;
|
|
7381
|
+
if (timer.origin !== undefined) {
|
|
7382
|
+
let plan;
|
|
7383
|
+
try {
|
|
7384
|
+
plan = await this.wakeContinuation(timer, timer.origin, record);
|
|
7385
|
+
}
|
|
7386
|
+
catch (error) {
|
|
7387
|
+
plan = { wait: `its attempt could not be read (${message(error)})` };
|
|
7388
|
+
}
|
|
7389
|
+
if ('wait' in plan) {
|
|
7390
|
+
this.timers.restore(timer);
|
|
7391
|
+
nextCheckIn = WAKE_RETRY_MS;
|
|
7392
|
+
this.log('info', `Self-wake ${timer.id} waits: ${plan.wait}`);
|
|
7393
|
+
continue;
|
|
7394
|
+
}
|
|
7395
|
+
if ('spent' in plan) {
|
|
7396
|
+
this.spendWake(timer, plan.spent);
|
|
7397
|
+
continue;
|
|
7398
|
+
}
|
|
7399
|
+
resume = plan.resume;
|
|
7400
|
+
}
|
|
7401
|
+
this.log('info', resume === undefined ? `Delivering self-wake ${timer.id} to session ${sessionId}` : `Delivering self-wake ${timer.id} to session ${sessionId} as a continuation of ${resume}`);
|
|
6321
7402
|
// The row keeps saying the session is waiting until a run is really there to carry the prompt. The list
|
|
6322
7403
|
// is republished after the attempt rather than before it, so there is no moment between the deadline and
|
|
6323
7404
|
// `run.started` in which the session reads as done with the user while its prompt has gone nowhere.
|
|
6324
7405
|
try {
|
|
6325
7406
|
const carry = timer.carry;
|
|
6326
|
-
// The wake carries the selections of the run that armed it (see `WakeCarry`). Starting it with only the
|
|
6327
|
-
// workspace, session and prompt would hand the continuation whatever the configuration says today: a
|
|
6328
|
-
// different graph, model or thinking effort means different tools, behavior and cost than the work the
|
|
6329
|
-
// agent was woken to continue.
|
|
6330
7407
|
// The wake is settled below, once this call has returned: a run of this session then carries the
|
|
6331
7408
|
// prompt, and only then is the wake no longer owed. Until that point it stays on the list, including
|
|
6332
7409
|
// while this start is still preparing — which is what tells a window reattaching in that moment that the
|
|
6333
7410
|
// wake is this engine's, and that its session is still waiting rather than free.
|
|
6334
|
-
|
|
6335
|
-
|
|
6336
|
-
|
|
6337
|
-
|
|
6338
|
-
|
|
6339
|
-
|
|
6340
|
-
|
|
6341
|
-
|
|
6342
|
-
|
|
7411
|
+
if (resume !== undefined) {
|
|
7412
|
+
// The continuation runs under the attempt's own recorded selections (`resumeRun` reads them from its
|
|
7413
|
+
// record), with the reminder as the direction the re-entered node reads at its first turn boundary.
|
|
7414
|
+
// Only the panel relay is this engine's own and not the record's, so it rides along.
|
|
7415
|
+
await this.resumeRun({ runId: resume, direction: timer.prompt,
|
|
7416
|
+
...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake: 'timer', wakeNode: timer.origin.nodeId, freshAllowance: true });
|
|
7417
|
+
}
|
|
7418
|
+
else {
|
|
7419
|
+
// A wake no graph node armed - an Auto-fix wake, or one held from before wakes named their node -
|
|
7420
|
+
// starts a run the way it always did. It carries the selections of the run that armed it (see
|
|
7421
|
+
// `WakeCarry`): starting it with only the workspace, session and prompt would hand it whatever the
|
|
7422
|
+
// configuration says today.
|
|
7423
|
+
await this.startRun({ workspace: record.workspace, sessionId, task: timer.prompt,
|
|
7424
|
+
...(carry?.graph === undefined ? {} : { graph: carry.graph }),
|
|
7425
|
+
...(carry?.provider === undefined ? {} : { provider: carry.provider }),
|
|
7426
|
+
...(carry?.model === undefined ? {} : { model: carry.model }),
|
|
7427
|
+
...(carry?.reasoningEffort === undefined ? {} : { reasoningEffort: carry.reasoningEffort }),
|
|
7428
|
+
...(carry?.overrideAllNodes === undefined ? {} : { overrideAllNodes: carry.overrideAllNodes }),
|
|
7429
|
+
...(carry?.panelBrowserRelay === undefined ? {} : { panelBrowserRelay: carry.panelBrowserRelay }),
|
|
7430
|
+
...(carry?.input === undefined ? {} : { input: carry.input }),
|
|
7431
|
+
...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: this.autoFixWakes.has(timer.id) ? 'auto-fix' : 'timer' });
|
|
7432
|
+
}
|
|
6343
7433
|
// Given: a run of this session carries the prompt, so the wake is no longer owed and the row stops waiting.
|
|
6344
7434
|
this.timers.settle(timer.id);
|
|
6345
7435
|
this.autoFixWakes.delete(timer.id);
|
|
@@ -6374,11 +7464,12 @@ export class AppServer {
|
|
|
6374
7464
|
this.log('info', `Self-wake ${timer.id} waits: ${message(error)}`);
|
|
6375
7465
|
break;
|
|
6376
7466
|
}
|
|
6377
|
-
// Any other refusal describes the task, not the moment
|
|
7467
|
+
// Any other refusal describes the task, not the moment — for a continuation, that the attempt has
|
|
7468
|
+
// nothing left to continue. The wake is spent, said where the user sees it, and a row must not keep
|
|
6378
7469
|
// waiting on one that will never be delivered.
|
|
6379
7470
|
this.log('error', `Self-wake ${timer.id} could not start: ${message(error)}`);
|
|
6380
|
-
this.
|
|
6381
|
-
|
|
7471
|
+
this.spendWake(timer, message(error));
|
|
7472
|
+
continue;
|
|
6382
7473
|
}
|
|
6383
7474
|
// One fewer wake the row is waiting on — said once the attempt is over, whether it landed or was spent.
|
|
6384
7475
|
this.emitTimers(sessionId);
|
|
@@ -6455,6 +7546,10 @@ export class AppServer {
|
|
|
6455
7546
|
this.closed = true;
|
|
6456
7547
|
await this.codexAuth.close().catch(() => { });
|
|
6457
7548
|
await this.anthropicAuth.close().catch(() => { });
|
|
7549
|
+
await this.claudeSignIn.close().catch(() => { });
|
|
7550
|
+
await this.grokSignIn.close().catch(() => { });
|
|
7551
|
+
await this.openCodeSignIn.close().catch(() => { });
|
|
7552
|
+
await sharedOpenCodeServer().close().catch(() => { });
|
|
6458
7553
|
if (this.automationCheck)
|
|
6459
7554
|
clearInterval(this.automationCheck);
|
|
6460
7555
|
await this.pullRequestWatcher.stop().catch(() => { });
|