@andorra-labs/code 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (171) hide show
  1. package/dist/src/account-presentation.js +3 -3
  2. package/dist/src/agent-execution.d.ts +2 -0
  3. package/dist/src/agent-execution.js +126 -20
  4. package/dist/src/agent-mcp.d.ts +18 -1
  5. package/dist/src/agent-mcp.js +103 -8
  6. package/dist/src/app-server/protocol.d.ts +33 -3
  7. package/dist/src/app-server/protocol.js +14 -1
  8. package/dist/src/app-server/workspace.d.ts +1 -0
  9. package/dist/src/app-server/workspace.js +7 -1
  10. package/dist/src/app-server.d.ts +115 -41
  11. package/dist/src/app-server.js +1229 -219
  12. package/dist/src/automation-runner.d.ts +9 -0
  13. package/dist/src/automation-runner.js +22 -1
  14. package/dist/src/automation-tool.js +8 -1
  15. package/dist/src/automations.js +1 -1
  16. package/dist/src/browser-captcha-tool.d.ts +54 -0
  17. package/dist/src/browser-captcha-tool.js +374 -0
  18. package/dist/src/browser-panel-tool.d.ts +7 -0
  19. package/dist/src/browser-panel-tool.js +74 -3
  20. package/dist/src/browser-runner.js +19 -4
  21. package/dist/src/browser-server.js +21 -1
  22. package/dist/src/browser-session.d.ts +16 -0
  23. package/dist/src/browser-session.js +35 -0
  24. package/dist/src/browser-ui/app.js +193 -3
  25. package/dist/src/browser-ui/style.css +15 -1
  26. package/dist/src/browser-view.d.ts +72 -4
  27. package/dist/src/browser-view.js +229 -17
  28. package/dist/src/capabilities.js +13 -2
  29. package/dist/src/capsolver.d.ts +60 -0
  30. package/dist/src/capsolver.js +101 -0
  31. package/dist/src/claude-provider.d.ts +6 -0
  32. package/dist/src/claude-provider.js +34 -3
  33. package/dist/src/cli-executable.d.ts +33 -0
  34. package/dist/src/cli-executable.js +64 -0
  35. package/dist/src/cli-process.d.ts +47 -0
  36. package/dist/src/cli-process.js +113 -0
  37. package/dist/src/cli-sign-in.d.ts +68 -0
  38. package/dist/src/cli-sign-in.js +224 -0
  39. package/dist/src/cli.js +54 -23
  40. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
  41. package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
  42. package/dist/src/coding-tools.js +44 -5
  43. package/dist/src/command-output-tap.d.ts +16 -0
  44. package/dist/src/command-output-tap.js +45 -0
  45. package/dist/src/command-screens.js +3 -3
  46. package/dist/src/commands.d.ts +10 -1
  47. package/dist/src/commands.js +7 -7
  48. package/dist/src/completion.d.ts +23 -5
  49. package/dist/src/completion.js +334 -17
  50. package/dist/src/config.d.ts +13 -0
  51. package/dist/src/config.js +28 -2
  52. package/dist/src/deadline.js +6 -0
  53. package/dist/src/extensions.d.ts +1 -0
  54. package/dist/src/extensions.js +16 -3
  55. package/dist/src/graph-provider-portability.js +2 -2
  56. package/dist/src/graph-quota.d.ts +1 -1
  57. package/dist/src/graph-quota.js +1 -1
  58. package/dist/src/graph-runner.js +35 -21
  59. package/dist/src/graph-selection.d.ts +6 -0
  60. package/dist/src/graph-selection.js +10 -0
  61. package/dist/src/graph-server.d.ts +7 -0
  62. package/dist/src/graph-server.js +61 -3
  63. package/dist/src/graph-sync.d.ts +50 -0
  64. package/dist/src/graph-sync.js +383 -12
  65. package/dist/src/graph-ui/app.js +61 -8
  66. package/dist/src/graph-ui/icons.js +1 -0
  67. package/dist/src/graph-ui/index.html +1 -1
  68. package/dist/src/graph-ui/skill-picker.js +242 -0
  69. package/dist/src/graph-ui/style.css +19 -0
  70. package/dist/src/graphs.d.ts +46 -4
  71. package/dist/src/graphs.js +152 -27
  72. package/dist/src/grok-provider.d.ts +50 -0
  73. package/dist/src/grok-provider.js +186 -0
  74. package/dist/src/handoffs.d.ts +13 -0
  75. package/dist/src/handoffs.js +31 -1
  76. package/dist/src/managed-sign-in.d.ts +38 -0
  77. package/dist/src/managed-sign-in.js +169 -0
  78. package/dist/src/markdown.d.ts +5 -0
  79. package/dist/src/markdown.js +5 -2
  80. package/dist/src/mcp.js +11 -0
  81. package/dist/src/membership.d.ts +8 -1
  82. package/dist/src/membership.js +15 -5
  83. package/dist/src/model-metadata.js +14 -2
  84. package/dist/src/model-override.d.ts +10 -0
  85. package/dist/src/model-override.js +20 -0
  86. package/dist/src/opencode-cli-provider.d.ts +122 -0
  87. package/dist/src/opencode-cli-provider.js +415 -0
  88. package/dist/src/opencode-provider.js +23 -8
  89. package/dist/src/palette.d.ts +2 -0
  90. package/dist/src/palette.js +2 -0
  91. package/dist/src/permissions.d.ts +19 -1
  92. package/dist/src/permissions.js +30 -1
  93. package/dist/src/powershell-pool.d.ts +2 -2
  94. package/dist/src/powershell-pool.js +18 -5
  95. package/dist/src/provider-connection.js +36 -0
  96. package/dist/src/provider-engine.d.ts +2 -1
  97. package/dist/src/provider-engine.js +64 -13
  98. package/dist/src/provider-import.js +6 -1
  99. package/dist/src/provider-settings.js +22 -3
  100. package/dist/src/providers.d.ts +12 -1
  101. package/dist/src/providers.js +27 -8
  102. package/dist/src/pull-requests.d.ts +111 -17
  103. package/dist/src/pull-requests.js +308 -76
  104. package/dist/src/qa/qa-authorize.js +9 -1
  105. package/dist/src/react-runtime.js +76 -5
  106. package/dist/src/remote/engine-pool.js +1 -1
  107. package/dist/src/run-progress.js +6 -1
  108. package/dist/src/run-records.d.ts +133 -27
  109. package/dist/src/run-records.js +320 -40
  110. package/dist/src/runtime.d.ts +38 -1
  111. package/dist/src/runtime.js +27 -4
  112. package/dist/src/save-lock.d.ts +11 -0
  113. package/dist/src/save-lock.js +29 -2
  114. package/dist/src/sessions.js +4 -1
  115. package/dist/src/shell.js +4 -1
  116. package/dist/src/side-panel.d.ts +1 -1
  117. package/dist/src/side-panel.js +1 -1
  118. package/dist/src/skill-commands.d.ts +2 -0
  119. package/dist/src/skill-commands.js +2 -0
  120. package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
  121. package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
  122. package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
  123. package/dist/src/skills/bundled/graph-manager/SKILL.md +97 -0
  124. package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
  125. package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
  126. package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
  127. package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
  128. package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
  129. package/dist/src/skills/bundled/provenance.json +50 -0
  130. package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
  131. package/dist/src/skills/invocable-skills.d.ts +41 -0
  132. package/dist/src/skills/invocable-skills.js +49 -0
  133. package/dist/src/skills/prompt-skills.d.ts +1 -0
  134. package/dist/src/skills/prompt-skills.js +33 -0
  135. package/dist/src/skills/runtime-skills.d.ts +4 -0
  136. package/dist/src/skills/runtime-skills.js +21 -0
  137. package/dist/src/structured-step.d.ts +55 -0
  138. package/dist/src/structured-step.js +85 -0
  139. package/dist/src/subagent-run.d.ts +1 -1
  140. package/dist/src/subagent-run.js +29 -33
  141. package/dist/src/telemetry/schema.d.ts +2 -2
  142. package/dist/src/telemetry/schema.js +3 -2
  143. package/dist/src/terminal-ui.d.ts +29 -0
  144. package/dist/src/terminal-ui.js +112 -28
  145. package/dist/src/timers.d.ts +21 -2
  146. package/dist/src/timers.js +12 -4
  147. package/dist/src/tool-names.d.ts +18 -0
  148. package/dist/src/tool-names.js +26 -0
  149. package/dist/src/tools.js +45 -11
  150. package/dist/src/trajectory.js +32 -12
  151. package/dist/src/types.d.ts +23 -0
  152. package/dist/src/update.d.ts +26 -16
  153. package/dist/src/update.js +232 -275
  154. package/docs/agents/install-for-agents.md +15 -24
  155. package/docs/agents/mcp-server.md +13 -1
  156. package/docs/agents/subagent-mode.md +7 -4
  157. package/docs/concepts/security.md +2 -0
  158. package/docs/getting-started/README.md +14 -6
  159. package/docs/getting-started/configure-providers.md +29 -2
  160. package/docs/guides/README.md +1 -1
  161. package/docs/guides/browser.md +12 -0
  162. package/docs/guides/desktop-app.md +45 -9
  163. package/docs/guides/graph-builder.md +8 -0
  164. package/docs/guides/update.md +37 -16
  165. package/docs/reference/cli.md +1 -1
  166. package/docs/reference/config.md +2 -2
  167. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  168. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  169. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  170. package/package.json +1 -1
  171. package/tests/permissions-test-plan.md +2 -1
@@ -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 { appendFile, mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
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
8
  import { changeConfigFile, configDirectory, ConfigConflictError, loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer } from './config.js';
9
9
  import { isUnlimitedAlias } from './limits.js';
10
10
  import { isPermissionMode, workspacePermissionKey } from './permissions.js';
11
- import { allocateCodexAccountSlots, createAdapter, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS } from './providers.js';
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 { applyPullRequestSettings, autoFixWakeWanted, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, readPullRequest, removePullRequest, runGh, viewPullRequest, withPullRequest, writePullRequest } from './pull-requests.js';
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, checkpointWriteFailed, claimProcessWorkspace, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, noteCheckpointWriteFailure, noteJournalWriteFailure, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
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,8 @@ 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';
72
77
  import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, readTree, readWorkspaceFile, summarizeMcpServer, workspaceRoot } from './app-server/workspace.js';
73
78
  import { withReasoningEvents } from './app-server/reasoning.js';
74
79
  import { APP_SERVER_PROTOCOL_VERSION, APP_SERVER_CAPABILITIES, } from './app-server/protocol.js';
@@ -105,6 +110,8 @@ class AppServerError extends Error {
105
110
  }
106
111
  const SESSION_HISTORY_TURNS = 6;
107
112
  const MAX_TASK_CHARS = 100_000;
113
+ /** The automation context rides `run.start` beside the task, bounded well under the task limit. */
114
+ const AUTOMATION_CONTEXT_CHARS = 4_000;
108
115
  /**
109
116
  * The engine's own budget for one workspace probe, set below the desktop's 200-second client budget.
110
117
  *
@@ -150,7 +157,7 @@ const RELAY_LONG_DEADLINE_MS = 1_260_000;
150
157
  */
151
158
  const MAX_RESUME_LINEAGE = 32;
152
159
  /** 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'];
160
+ const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'limits', 'workspacePermissions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays', 'browser'];
154
161
  function message(error) { return error instanceof Error ? error.message : String(error); }
155
162
  /** Project an owned authentication result instead of forwarding any official CLI payload wholesale. */
156
163
  function providerAuthView(view, includeUrl) {
@@ -200,6 +207,72 @@ function providerAuthView(view, includeUrl) {
200
207
  }
201
208
  return result;
202
209
  }
210
+ /** The sign-in page hosts each CLI-run sign-in may name. OpenCode's vary by upstream provider. */
211
+ const MANAGED_SIGN_IN_HOSTS = {
212
+ claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], opencode: undefined,
213
+ };
214
+ /** Project a CLI-run sign-in the same way: display fields only, the page URL only to its starter. */
215
+ function managedAuthView(type, view, includeUrl) {
216
+ if (!['signedOut', 'starting', 'waiting', 'signedIn', 'cancelled', 'error'].includes(view.state))
217
+ throw new Error('Invalid authentication state');
218
+ const text = (value, max) => typeof value === 'string' && value.length <= max && !/[\u0000-\u001f\u007f]/.test(value) ? value : undefined;
219
+ const result = { state: view.state };
220
+ if (view.reason && ['unavailable', 'timeout', 'denied', 'unsupported', 'busy', 'unverified', 'logoutFailed'].includes(view.reason))
221
+ result.reason = view.reason;
222
+ const attemptId = text(view.attemptId, 128);
223
+ if (attemptId)
224
+ result.attemptId = attemptId;
225
+ const note = text(view.message, 1000);
226
+ if (note)
227
+ result.message = note;
228
+ if (view.state === 'signedIn') {
229
+ const email = text(view.email, 320);
230
+ const planType = text(view.planType, 100);
231
+ if (email)
232
+ result.email = email;
233
+ if (planType)
234
+ result.planType = planType;
235
+ }
236
+ if (view.state === 'waiting') {
237
+ if (view.acceptsCode === true)
238
+ result.acceptsCode = true;
239
+ const code = text(view.userCode, 32);
240
+ if (code && /^[A-Z0-9-]+$/.test(code))
241
+ result.userCode = code;
242
+ }
243
+ const provider = text(view.signInProvider, 100);
244
+ if (provider)
245
+ result.signInProvider = provider;
246
+ if (Array.isArray(view.connected))
247
+ result.connected = view.connected.slice(0, 500).flatMap(item => {
248
+ const id = text(item?.id, 100);
249
+ const name = text(item?.name, 200);
250
+ return id ? [{ id, name: name ?? id }] : [];
251
+ });
252
+ if (Array.isArray(view.signInOptions))
253
+ result.signInOptions = view.signInOptions.slice(0, 500).flatMap(option => {
254
+ const providerId = text(option?.providerId, 100);
255
+ const label = text(option?.label, 200);
256
+ if (!providerId || !label || !Number.isSafeInteger(option.method) || option.method < 0)
257
+ return [];
258
+ return [{ providerId, providerName: text(option.providerName, 200) ?? providerId, method: option.method, label, connected: option.connected === true }];
259
+ });
260
+ if (includeUrl && view.state === 'waiting' && view.authUrl !== undefined) {
261
+ const raw = text(view.authUrl, 16_384);
262
+ let url;
263
+ try {
264
+ url = raw ? new URL(raw) : undefined;
265
+ }
266
+ catch {
267
+ url = undefined;
268
+ }
269
+ const hosts = MANAGED_SIGN_IN_HOSTS[type];
270
+ if (url && url.protocol === 'https:' && !url.username && !url.password && !url.port
271
+ && (hosts === undefined || hosts.some(host => url.hostname === host || url.hostname.endsWith(`.${host}`))))
272
+ result.authUrl = url.href;
273
+ }
274
+ return result;
275
+ }
203
276
  /**
204
277
  * The account a profile request is about.
205
278
  *
@@ -278,7 +351,7 @@ function viewUrl(value) {
278
351
  }
279
352
  function permissionMode(value) {
280
353
  if (!isPermissionMode(value))
281
- throw new AppServerError('invalid-params', 'permissions must be read-only, ask-for-approval, approve-for-me, or full-access');
354
+ throw new AppServerError('invalid-params', 'permissions must be read-only, plan, ask-for-approval, approve-for-me, or full-access');
282
355
  return value;
283
356
  }
284
357
  /** One run's thinking effort; the selected adapter validates model support. */
@@ -376,8 +449,36 @@ function configView(config, analytics) {
376
449
  ...(config.externalSubagent === undefined ? {} : { externalSubagent: { ...config.externalSubagent } }),
377
450
  ...(config.systemPromptOverride === undefined ? {} : { systemPromptOverride: config.systemPromptOverride }),
378
451
  ...(config.autoArchiveDays === undefined ? {} : { autoArchiveDays: config.autoArchiveDays }),
452
+ ...(resolveCapsolverKey(config) ? { browser: browserConfigView(config) } : {}),
379
453
  };
380
454
  }
455
+ /** 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. */
456
+ function browserConfigView(config) {
457
+ const key = resolveCapsolverKey(config);
458
+ return { hasCapsolverKey: !!config.browser?.capsolverApiKey, ...(key ? { capsolverKeySource: key.source } : {}) };
459
+ }
460
+ /**
461
+ * Apply a `browser` patch to the stored block.
462
+ *
463
+ * The view never carries the key, so a patch names only what changes: a string saves a key, `null`
464
+ * removes it, and an omitted field keeps what is stored. An empty block is dropped.
465
+ */
466
+ function mergeBrowserConfig(current, patch) {
467
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch))
468
+ throw new AppServerError('invalid-params', 'browser must be an object');
469
+ const fields = patch;
470
+ if (Object.keys(fields).some(key => key !== 'capsolverApiKey'))
471
+ throw new AppServerError('invalid-params', 'browser accepts only capsolverApiKey');
472
+ const next = { ...current };
473
+ if (fields.capsolverApiKey === null)
474
+ delete next.capsolverApiKey;
475
+ else if (fields.capsolverApiKey !== undefined) {
476
+ if (typeof fields.capsolverApiKey !== 'string' || !fields.capsolverApiKey.trim())
477
+ throw new AppServerError('invalid-params', 'capsolverApiKey must be a nonempty string, or null to remove it');
478
+ next.capsolverApiKey = fields.capsolverApiKey.trim();
479
+ }
480
+ return Object.keys(next).length ? next : undefined;
481
+ }
381
482
  /**
382
483
  * Merge a client's provider list with the stored secrets.
383
484
  *
@@ -418,7 +519,7 @@ export function mergeProviderSecrets(stored, incoming) {
418
519
  if (source[field] !== undefined)
419
520
  provider[field] = source[field];
420
521
  const previousEntry = typeof provider.id === 'string' ? previous.get(provider.id) : undefined;
421
- const inherited = provider.type === 'codex' || provider.type === 'claude' ? undefined : previousEntry;
522
+ const inherited = isSignInProviderType(provider.type) ? undefined : previousEntry;
422
523
  const crossesGo = previousEntry !== undefined && previousEntry.type !== provider.type
423
524
  && (previousEntry.type === 'opencode-go' || provider.type === 'opencode-go');
424
525
  // A hidden key is not consent to send that credential to a different provider. Older clients
@@ -523,6 +624,19 @@ function foldUsage(target, delta) {
523
624
  * wake that had to wait for a run must not re-check itself every millisecond while that run holds the engine.
524
625
  */
525
626
  const TIMER_DELIVERY_RETRY_MS = 1_000;
627
+ /**
628
+ * How long an Auto-fix wake waits when GitHub could not confirm its PR is still open: about one watcher poll, so an
629
+ * outage or a signed-out account is asked about once a minute rather than on every delivery pass.
630
+ */
631
+ const AUTO_FIX_CONFIRM_RETRY_MS = 60_000;
632
+ /**
633
+ * A session's PR as clients are sent it. A desktop built while Auto-archive existed accepts a record only when it
634
+ * carries an `autoArchive` flag, and would drop the whole Pull request row without one, so the flag is still sent:
635
+ * always false, since nothing archives a session on merge any more.
636
+ */
637
+ function pullRequestForClients(pullRequest) {
638
+ return pullRequest ? { ...pullRequest, autoArchive: false } : null;
639
+ }
526
640
  function sessionSummary(record) {
527
641
  // The newest attempt is what a row says the task did. A turn keeps a status only when it ended without
528
642
  // completing, so an absent one is a normal completion; reading it off the saved record is what makes a
@@ -539,7 +653,9 @@ function sessionSummary(record) {
539
653
  // is the stopped attempt's, and search and tooltips must find the words the user actually sent.
540
654
  ...(record.history?.length ? { lastTask: record.history[record.history.length - 1].direction ?? record.history[record.history.length - 1].task } : {}),
541
655
  ...(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 }) },
656
+ 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 }),
657
+ ...(record.usage.localCacheInputTokens === undefined ? {} : { localCacheInputTokens: record.usage.localCacheInputTokens }),
658
+ ...(record.usage.localCacheReadTokens === undefined ? {} : { localCacheReadTokens: record.usage.localCacheReadTokens }) },
543
659
  };
544
660
  }
545
661
  /**
@@ -568,10 +684,21 @@ function sessionSummary(record) {
568
684
  * agent asked to be woken for is the more expensive guess.
569
685
  */
570
686
  /** Exported because the table is the part a delivery must not get wrong; the protocol test pins it. */
687
+ /** A restored conversation's state with its spent allowance cleared: no iterations used, no remaining-budget caps. */
688
+ function freshAllowance(state) {
689
+ const { remainingToolCalls: _tools, remainingWallTimeMs: _wall, ...rest } = state;
690
+ return { ...rest, iterations: 0, ...(state.copies === undefined ? {} : { copies: state.copies.map(copy => ({ ...copy, state: freshAllowance(copy.state) })) }) };
691
+ }
692
+ /** A direction's recorded provenance, kept only when it names a wake this engine knows. */
693
+ function wakeProvenance(wake, node) {
694
+ if (wake !== 'timer' && wake !== 'auto-fix')
695
+ return {};
696
+ return { wake, ...(typeof node === 'string' && node ? { node } : {}) };
697
+ }
571
698
  export function isFinalWakeRefusal(error) {
572
699
  return error instanceof AppServerError
573
700
  && (error.code === 'invalid-params' || error.code === 'not-found' || error.code === 'remote'
574
- || error.code === 'unknown-method' || error.code === 'auth');
701
+ || error.code === 'unknown-method' || error.code === 'auth' || error.code === 'nothing-to-continue');
575
702
  }
576
703
  /** How a stopped attempt reads to the next turn, mirroring the TUI's history entries. */
577
704
  function outcomeCompletion(status, reason, limits) {
@@ -644,6 +771,23 @@ export function withoutRunMarker(record, runId) {
644
771
  ...(contextHistory === undefined ? {} : { contextHistory: strip(contextHistory) }),
645
772
  };
646
773
  }
774
+ /** A run record's `nodeModelOverrides` — node id → explicit pair — or undefined when absent or malformed. */
775
+ function readNodeModelOverrides(value) {
776
+ if (value === undefined || value === null || typeof value !== 'object' || Array.isArray(value))
777
+ return undefined;
778
+ let read;
779
+ for (const [id, entry] of Object.entries(value)) {
780
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry))
781
+ continue;
782
+ const provider = entry.provider;
783
+ const model = entry.model;
784
+ if (typeof provider !== 'string' || !provider || typeof model !== 'string' || !model)
785
+ continue;
786
+ read ??= {};
787
+ read[id] = { provider, model };
788
+ }
789
+ return read;
790
+ }
647
791
  export class AppServer {
648
792
  automationCheck;
649
793
  /** The daily auto-archive pass; a change to the setting runs one immediately as well. */
@@ -657,14 +801,18 @@ export class AppServer {
657
801
  output;
658
802
  error;
659
803
  checkGraphHealth;
804
+ createCodeIntelligence;
660
805
  loadGraph;
661
806
  codexAuth;
662
807
  anthropicAuth;
808
+ claudeSignIn;
809
+ grokSignIn;
810
+ openCodeSignIn;
663
811
  /** Retires a removed provider's slot home; a seam so a test never has to spawn the Codex CLI. */
664
812
  retireCodexAccount;
665
813
  /** The `gh` the pull request settings and watcher run through. */
666
814
  gh;
667
- /** Polls the PRs whose sessions asked for Auto-fix or Auto-archive; one engine per home actually polls. */
815
+ /** Polls the PRs whose sessions asked for Auto-fix; one engine per home actually polls. */
668
816
  pullRequestWatcher;
669
817
  /** The wakes this engine armed for Auto-fix, checked against the PR record again before delivery. */
670
818
  autoFixWakes = new Set();
@@ -751,18 +899,11 @@ export class AppServer {
751
899
  */
752
900
  startingSession;
753
901
  /**
754
- * Runs whose journal sink failed mid-attempt. The journal keeps being written after the failure,
755
- * so it looks complete; this is what marks the attempt as one no resume may replay (the record
756
- * and a marker file carry it past a crash).
902
+ * Each live run's journal writer. A writer holds the events its file refused and writes them once
903
+ * appends succeed again, so it is also what knows, at finalization, whether the journal is a
904
+ * complete account (the record and a marker file carry the answer past a crash).
757
905
  */
758
- journalFailures = new Set();
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();
906
+ journals = new Map();
766
907
  /**
767
908
  * The session trajectory of the run in flight: one sanitized debug log per session
768
909
  * (`trajectories/<sessionId>.jsonl` in this home), appended by every run and resume of that
@@ -835,26 +976,18 @@ export class AppServer {
835
976
  this.output = options.output;
836
977
  this.error = options.error;
837
978
  this.checkGraphHealth = options.checkGraphHealth ?? checkGraphModelHealth;
979
+ this.createCodeIntelligence = options.createCodeIntelligence ?? (managerOptions => CodeIntelligenceManager.create(managerOptions));
838
980
  this.loadGraph = options.loadGraph ?? loadAccessibleGraph;
839
981
  this.codexAuth = options.codexAuth ?? new CodexAccountAuth();
840
982
  this.anthropicAuth = options.anthropicAuth ?? new AnthropicConsoleAuth();
983
+ this.claudeSignIn = options.managedSignIn?.claude ?? claudeSignIn();
984
+ this.grokSignIn = options.managedSignIn?.grok ?? grokSignIn();
985
+ this.openCodeSignIn = options.managedSignIn?.opencode ?? new OpenCodeSignIn();
841
986
  this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
842
987
  this.gh = options.gh ?? runGh;
843
988
  this.pullRequestWatcher = new PullRequestWatcher({
844
989
  home: this.directory, gh: this.gh, intervalMs: options.pullRequestPollMs,
845
990
  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
991
  wake: (sessionId, prompt, carry) => this.wakeForPullRequest(sessionId, prompt, carry),
859
992
  wakePending: id => this.timers.list().some(timer => timer.id === id),
860
993
  log: (level, detail) => this.log(level, detail),
@@ -867,7 +1000,16 @@ export class AppServer {
867
1000
  data: (id, chunk) => this.emit('terminal.data', { id, data: chunk }),
868
1001
  exit: (id, code, signal) => this.emit('terminal.exit', { id, code, ...(signal === undefined ? {} : { signal }) }),
869
1002
  });
870
- this.browserViews = new BrowserViewManager((event, data) => this.emit(event, data));
1003
+ // One persistent browser profile per project, kept in this engine's home: a session's panel
1004
+ // browser opens on its project's profile, so logins and history carry across that project's
1005
+ // sessions and restarts while other projects stay apart.
1006
+ this.browserViews = new BrowserViewManager((event, data) => this.emit(event, data), undefined, {
1007
+ profileFor: async (sessionId) => {
1008
+ const record = await this.readSession(sessionId);
1009
+ const key = record.projectId !== undefined && /^[a-f0-9]{16}$/.test(record.projectId) ? record.projectId : projectIdentity(record.workspace);
1010
+ return { key, directory: join(this.directory, 'browser-profiles', key) };
1011
+ },
1012
+ });
871
1013
  // A wake that comes due is the engine's business here: it delivers the prompt itself, because this
872
1014
  // process is the one a window talks to and nothing else is watching the deadline.
873
1015
  this.timers.onDue = () => this.checkTimers();
@@ -1112,6 +1254,7 @@ export class AppServer {
1112
1254
  case 'providers.auth.start': return this.providerAuth('start', params);
1113
1255
  case 'providers.auth.cancel': return this.providerAuth('cancel', params);
1114
1256
  case 'providers.auth.logout': return this.providerAuth('logout', params);
1257
+ case 'providers.auth.submit': return this.providerAuth('submit', params);
1115
1258
  case 'account.status': return this.accountStatus();
1116
1259
  case 'account.login': return this.signIn();
1117
1260
  case 'account.logout': return this.signOut();
@@ -1137,7 +1280,7 @@ export class AppServer {
1137
1280
  case 'sessions.rename': return { session: this.summary(await this.renameSession(params)) };
1138
1281
  case 'sessions.setArchived': return { session: this.summary(await this.setSessionArchived(params)) };
1139
1282
  case 'sessions.delete': return this.deleteSession(params);
1140
- case 'sessions.pullRequest.get': return { pullRequest: (await readPullRequest(this.directory, identifier(params.id, 'id'))) ?? null };
1283
+ case 'sessions.pullRequest.get': return { pullRequest: pullRequestForClients(await readPullRequest(this.directory, identifier(params.id, 'id'))) };
1141
1284
  case 'sessions.pullRequest.update': {
1142
1285
  let settings;
1143
1286
  try {
@@ -1146,7 +1289,7 @@ export class AppServer {
1146
1289
  catch (error) {
1147
1290
  throw new AppServerError('invalid-params', message(error));
1148
1291
  }
1149
- return { pullRequest: await this.updatePullRequest(identifier(params.id, 'id'), settings) };
1292
+ return { pullRequest: pullRequestForClients(await this.updatePullRequest(identifier(params.id, 'id'), settings)) };
1150
1293
  }
1151
1294
  case 'sessions.pullRequest.dismiss':
1152
1295
  await this.dismissPullRequest(identifier(params.id, 'id'));
@@ -1156,6 +1299,7 @@ export class AppServer {
1156
1299
  case 'run.resume': return this.resumeRun(params);
1157
1300
  case 'run.cancel': return this.cancelRun(params.runId);
1158
1301
  case 'run.setModel': return this.setRunModel(params);
1302
+ case 'run.setPermissions': return this.setRunPermissions(params);
1159
1303
  case 'run.steer': return this.steerRun(params);
1160
1304
  case 'run.approve': return this.settleApproval(params);
1161
1305
  case 'run.answer': return this.settleAnswer(params);
@@ -1568,6 +1712,13 @@ export class AppServer {
1568
1712
  delete merged.systemPromptOverride;
1569
1713
  if (patch.autoArchiveDays === null)
1570
1714
  delete merged.autoArchiveDays;
1715
+ if (Object.hasOwn(patch, 'browser')) {
1716
+ const browser = mergeBrowserConfig(current.browser, patch.browser);
1717
+ if (browser)
1718
+ merged.browser = browser;
1719
+ else
1720
+ delete merged.browser;
1721
+ }
1571
1722
  if (Array.isArray(patch.providers)) {
1572
1723
  merged.providers = allocateCodexAccountSlots(current.providers, mergeProviderSecrets(current.providers, patch.providers));
1573
1724
  // A whole-array save can remove a linked account too. Bindings, not ids, decide which
@@ -1941,11 +2092,12 @@ export class AppServer {
1941
2092
  if (params.providerType !== undefined) {
1942
2093
  // Fixed-provider catalogs do not read a configured model or provider credential. Browse one
1943
2094
  // before the first model is selected without storing an unusable provider or forwarding a key.
1944
- if (params.providerId !== undefined || (params.providerType !== 'claude' && params.providerType !== 'opencode-go')) {
1945
- throw new AppServerError('invalid-params', 'providerType must be claude or opencode-go, without providerId');
2095
+ const catalogs = { claude: 'https://api.anthropic.com', 'opencode-go': 'https://opencode.ai/inference/go', grok: GROK_BASE_URL, opencode: OPENCODE_BASE_URL };
2096
+ if (params.providerId !== undefined || typeof params.providerType !== 'string' || !Object.hasOwn(catalogs, params.providerType)) {
2097
+ throw new AppServerError('invalid-params', 'providerType must be claude, grok, opencode or opencode-go, without providerId');
1946
2098
  }
1947
- provider = { id: 'catalog', type: params.providerType, model: 'catalog',
1948
- baseUrl: params.providerType === 'claude' ? 'https://api.anthropic.com' : 'https://opencode.ai/inference/go' };
2099
+ const type = params.providerType;
2100
+ provider = { id: 'catalog', type, model: type === 'opencode' ? 'catalog/catalog' : 'catalog', baseUrl: catalogs[type] };
1949
2101
  }
1950
2102
  else {
1951
2103
  const config = await loadConfig(this.directory);
@@ -1967,6 +2119,10 @@ export class AppServer {
1967
2119
  }
1968
2120
  /** Local-client only. The remote engine relay deliberately does not admit these methods. */
1969
2121
  async providerAuth(action, params) {
2122
+ if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'opencode')
2123
+ return this.managedProviderAuth(action, params);
2124
+ if (action === 'submit')
2125
+ throw new AppServerError('invalid-params', 'Only Claude, Grok and OpenCode sign-ins accept a pasted code.');
1970
2126
  if (params.providerType === 'anthropic')
1971
2127
  return this.anthropicProviderAuth(action, params);
1972
2128
  if (params.providerType !== 'codex' || Object.keys(params).some(key => !['providerType', 'attemptId', 'providerId'].includes(key))) {
@@ -2002,6 +2158,60 @@ export class AppServer {
2002
2158
  throw new AppServerError('auth', 'ChatGPT sign-in could not be completed. Check the official Codex CLI and try again.');
2003
2159
  }
2004
2160
  }
2161
+ /**
2162
+ * Subscription sign-in through a vendor CLI's own login: Claude Code, Grok, or one of OpenCode's
2163
+ * upstream providers. Local-client only, like the others. Each of these logins belongs to the CLI
2164
+ * on this machine rather than to one provider entry, so the draft a person is adding can sign in
2165
+ * before it is saved; a providerId is accepted and ignored.
2166
+ */
2167
+ async managedProviderAuth(action, params) {
2168
+ const type = params.providerType;
2169
+ const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : 'OpenCode';
2170
+ const allowed = ['providerType', 'attemptId', 'providerId', 'code', ...(type === 'opencode' ? ['signInProvider', 'signInMethod'] : [])];
2171
+ if (Object.keys(params).some(key => !allowed.includes(key))) {
2172
+ 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.`);
2173
+ }
2174
+ const id = params.attemptId;
2175
+ if ((id !== undefined && (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(id)))
2176
+ || ((action === 'start' || action === 'cancel' || action === 'submit') && id === undefined) || (action === 'logout' && id !== undefined)) {
2177
+ throw new AppServerError('invalid-params', 'A valid sign-in attemptId is required.');
2178
+ }
2179
+ optionalIdentifier(params.providerId, 'providerId');
2180
+ const code = params.code;
2181
+ if (action === 'submit' ? typeof code !== 'string' || !code.trim() || code.length > 2000 : code !== undefined) {
2182
+ throw new AppServerError('invalid-params', action === 'submit' ? 'A sign-in code is required.' : 'Only providers.auth.submit takes a code.');
2183
+ }
2184
+ if (params.signInMethod !== undefined && (!Number.isSafeInteger(params.signInMethod) || params.signInMethod < 0)) {
2185
+ throw new AppServerError('invalid-params', 'signInMethod must be a sign-in option index.');
2186
+ }
2187
+ if (params.signInProvider !== undefined && (typeof params.signInProvider !== 'string' || !/^[\w.@-]{1,100}$/.test(params.signInProvider))) {
2188
+ throw new AppServerError('invalid-params', 'signInProvider must be an OpenCode provider id.');
2189
+ }
2190
+ try {
2191
+ let view;
2192
+ if (type === 'opencode') {
2193
+ const service = this.openCodeSignIn;
2194
+ view = action === 'start' ? await service.start(id, params.signInProvider, params.signInMethod)
2195
+ : action === 'cancel' ? await service.cancel(id)
2196
+ : action === 'submit' ? await service.submitCode(id, code)
2197
+ : action === 'logout' ? await service.logout(params.signInProvider)
2198
+ : await service.status(id);
2199
+ }
2200
+ else {
2201
+ const service = type === 'claude' ? this.claudeSignIn : this.grokSignIn;
2202
+ view = action === 'start' ? await service.start(id)
2203
+ : action === 'cancel' ? await service.cancel(id)
2204
+ : action === 'submit' ? await service.submitCode(id, code)
2205
+ : action === 'logout' ? await service.logout()
2206
+ : await service.status(id);
2207
+ }
2208
+ return managedAuthView(type, view, action === 'start');
2209
+ }
2210
+ catch {
2211
+ // Vendor CLI output can carry account details; an unexpected failure never forwards it.
2212
+ throw new AppServerError('auth', `${product} sign-in could not be completed. Check its CLI and try again.`);
2213
+ }
2214
+ }
2005
2215
  /**
2006
2216
  * Claude Console sign-in for one configured Anthropic provider. Local-client only, like Codex
2007
2217
  * sign-in: the remote engine relay does not admit these methods.
@@ -2479,6 +2689,14 @@ export class AppServer {
2479
2689
  if (params.continueSession === true && typeof params.sessionId !== 'string') {
2480
2690
  throw new AppServerError('invalid-params', 'continueSession needs the session it continues.');
2481
2691
  }
2692
+ // A switch to another graph mid-session: the new graph's entry node is handed the session's
2693
+ // history whatever its own policy says. It only means something for a session that has one.
2694
+ if (params.entryHistory !== undefined && typeof params.entryHistory !== 'boolean') {
2695
+ throw new AppServerError('invalid-params', 'entryHistory must be a boolean.');
2696
+ }
2697
+ if (params.entryHistory === true && typeof params.sessionId !== 'string') {
2698
+ throw new AppServerError('invalid-params', 'entryHistory needs the session whose history it hands on.');
2699
+ }
2482
2700
  // Background jobs choose a mode for this attempt, never the interactive workspace default.
2483
2701
  // Validate before preparation can save anything, including a competing persistent selection.
2484
2702
  if (params.runPermissions !== undefined && params.permissions !== undefined) {
@@ -2515,7 +2733,7 @@ export class AppServer {
2515
2733
  * after this point is `run.start`'s own path — same events, same client run flow, one-run-per-
2516
2734
  * engine guard included.
2517
2735
  */
2518
- async resumeRun(params) {
2736
+ async resumeRun(params, internal) {
2519
2737
  // The same refusal split `run.start` uses: a second task is refused with `engine-busy`, which
2520
2738
  // the desktop answers by looking for (or spawning) another engine, while a checkout conflict
2521
2739
  // is `busy` — a condition of this engine's own work that retrying elsewhere cannot fix.
@@ -2560,6 +2778,16 @@ export class AppServer {
2560
2778
  const task = turn?.task;
2561
2779
  if (typeof task !== 'string' || !task)
2562
2780
  throw new AppServerError('invalid-params', 'That session no longer carries the stopped attempt, so it cannot be resumed.');
2781
+ // The automation context rode the combined task into session history, but the source record
2782
+ // keeps the parts apart: a resume re-sends them separately, because the combined text of a
2783
+ // limit-length prompt would fail the task validation the raw prompt passes. The suffix is
2784
+ // checked exactly, so a task that merely resembles the context stays whole.
2785
+ let resumeTask = task;
2786
+ let resumeAutomationContext;
2787
+ if (typeof source.automationContext === 'string' && task.endsWith(`\n\n${source.automationContext}`)) {
2788
+ resumeTask = task.slice(0, task.length - source.automationContext.length - 2);
2789
+ resumeAutomationContext = source.automationContext;
2790
+ }
2563
2791
  // Directions a previous continuation armed and never got to persist: each is drained at the
2564
2792
  // agent's first turn boundary, and a crash before the next checkpoint leaves the restored
2565
2793
  // conversation without it — the record is the durable copy of what the user said. Every
@@ -2581,18 +2809,27 @@ export class AppServer {
2581
2809
  if (typeof entry.runId !== 'string' || typeof entry.direction !== 'string' || entry.direction.length === 0)
2582
2810
  continue;
2583
2811
  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) }) });
2812
+ recordedDirections.push({ runId: entry.runId, direction: entry.direction, id, ...(recordedAttachments(entry.runId) === undefined ? {} : { attachments: recordedAttachments(entry.runId) }), ...wakeProvenance(entry.wake, entry.node) });
2585
2813
  }
2586
2814
  if (typeof source.direction === 'string' && source.direction.length > 0) {
2587
- recordedDirections.push({ runId: originalRunId, direction: source.direction, id: `${originalRunId}#own`, ...(turn?.attachments?.length ? { attachments: turn.attachments } : {}) });
2815
+ // A reminder a timer delivered stays the agent's own, and its node's, when a later resume recovers it.
2816
+ recordedDirections.push({ runId: originalRunId, direction: source.direction, id: `${originalRunId}#own`, ...(turn?.attachments?.length ? { attachments: turn.attachments } : {}), ...wakeProvenance(source.wake, source.directionNode) });
2588
2817
  }
2589
2818
  // A resume with no message of its own continues the newest recorded direction: it becomes this
2590
2819
  // attempt's own message — the turn it records, with that direction's own attachments — while
2591
2820
  // the older recorded ones queue ahead of it. With a message of its own, every recorded one is
2592
2821
  // carried ahead of it, newest last.
2593
2822
  const recoveredOwnDirection = direction === undefined && recordedDirections.length > 0;
2594
- if (recoveredOwnDirection)
2595
- direction = recordedDirections.pop().direction;
2823
+ // A recovered direction keeps the provenance it was recorded with; a message sent with this resume is the
2824
+ // user's own and carries none.
2825
+ let recoveredWake = {};
2826
+ if (recoveredOwnDirection) {
2827
+ const recovered = recordedDirections.pop();
2828
+ direction = recovered.direction;
2829
+ recoveredWake = { ...(recovered.wake === undefined ? {} : { wake: recovered.wake }), ...(recovered.node === undefined ? {} : { node: recovered.node }) };
2830
+ }
2831
+ const ownWake = internal?.wake ?? recoveredWake.wake;
2832
+ const ownWakeNode = internal?.wakeNode ?? recoveredWake.node;
2596
2833
  const carried = [...recordedDirections];
2597
2834
  // The turn a direction is being re-armed from must not also seed the model's history: its
2598
2835
  // stored direction renders through `turnModelTask`, and leaving it in the fresh seed would
@@ -2665,13 +2902,19 @@ export class AppServer {
2665
2902
  // configuration once and judges the model against the same snapshot it resolves the
2666
2903
  // provider and the model from, so the two cannot disagree.
2667
2904
  const carriedModel = typeof source.model === 'string' && source.model ? source.model : undefined;
2905
+ // Nodes the stopped attempt switched mid-run, keyed by node id: the resumed graph re-applies
2906
+ // them on top of its own binding, so the switched nodes keep their new pairs while every
2907
+ // other node runs as the graph names. They compose with a carried whole-run override — the
2908
+ // flag below rebuilds every node first, and the switches then move their nodes.
2909
+ const carriedNodeModelOverrides = readNodeModelOverrides(source.nodeModelOverrides);
2668
2910
  // Reserve the session for the whole preparation, not only from the moment the run exists: the
2669
2911
  // resumed attempt saves the record it read here, so a rename or delete accepted in between is
2670
2912
  // lost — and a protocol client can send one, since the desktop's own reservation cannot.
2671
2913
  this.startingSession = sessionId;
2672
2914
  try {
2673
2915
  return await this.prepareRun({
2674
- workspace: existing.workspace, task, sessionId,
2916
+ workspace: existing.workspace, task: resumeTask, sessionId,
2917
+ ...(resumeAutomationContext === undefined ? {} : { automationContext: resumeAutomationContext }),
2675
2918
  ...(typeof graphId === 'string' ? { graph: graphId } : {}),
2676
2919
  ...(params.provider !== undefined ? { provider: params.provider } : typeof source.provider === 'string' ? { provider: source.provider } : {}),
2677
2920
  ...(params.model === undefined ? {} : { model: params.model }),
@@ -2691,12 +2934,19 @@ export class AppServer {
2691
2934
  // re-runs the graph, and without this the nodes would go back to the models the graph
2692
2935
  // names for themselves — a different model than the attempt being continued ran on.
2693
2936
  ...(params.overrideAllNodes === undefined ? (source.overrideAllNodes === true ? { overrideAllNodes: true } : {}) : { overrideAllNodes: params.overrideAllNodes }),
2937
+ // An explicit all-node resume replaces every node's model: the stopped attempt's per-node
2938
+ // switches named the pairs it was leaving, and forwarding them would outrank the pair the
2939
+ // caller just chose. An ordinary resume keeps them.
2940
+ ...(params.overrideAllNodes === true || carriedNodeModelOverrides === undefined ? {} : { nodeModelOverrides: carriedNodeModelOverrides }),
2941
+ // An attempt that switched the session onto its graph keeps the entry node's seed: the
2942
+ // runner gives it only to an entry visit that has no saved conversation to re-enter.
2943
+ ...(source.entryHistory === true ? { entryHistory: true } : {}),
2694
2944
  ...(params.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}),
2695
2945
  ...(params.permissions === undefined ? {} : { permissions: params.permissions }),
2696
2946
  // Attachments composed beside the message: they are this turn's own, and only `prepareRun`
2697
2947
  // can resolve them — the descriptor is spooled or validated against the workspace there.
2698
2948
  ...(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 }) });
2949
+ }, { 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
2950
  }
2701
2951
  catch (error) {
2702
2952
  // Preparation refused before a run existed to own the claim; whoever asks next must not be
@@ -2819,15 +3069,55 @@ export class AppServer {
2819
3069
  * the graph is loaded — is what keeps the runner, the resume guard and the health preflight from
2820
3070
  * disagreeing about the model a node runs, because all three read this same graph.
2821
3071
  */
2822
- graphForRun(graph, overrideAllNodes, provider, model) {
3072
+ graphForRun(graph, overrideAllNodes, provider, model, nodeModelOverrides) {
2823
3073
  const execution = overrideAllNodes ? applyModelOverride(graph, { provider, model }) : graph;
2824
- this.originalModelGraphs.set(execution, structuredClone(graph));
2825
- return execution;
3074
+ const switches = nodeModelOverrides === undefined ? execution : applyNodeModelOverrides(execution, nodeModelOverrides);
3075
+ // The original a later whole-run switch rebuilds from is the graph as it was loaded, before
3076
+ // both kinds of live switch: the whole-run override rewrote this copy's nodes, and the node
3077
+ // switches rode on top of it. Keyed by the object the run executes, so `executeRun` finds it.
3078
+ this.originalModelGraphs.set(switches, structuredClone(graph));
3079
+ return switches;
3080
+ }
3081
+ /**
3082
+ * The graph a resume replays against, with carried node switches applied before its remaining
3083
+ * provider references are bound.
3084
+ *
3085
+ * A node moved to provider B survives provider A leaving the configuration: the carried provider
3086
+ * replaces the switched node's reference before the binder validates what is left, so the
3087
+ * obsolete pin cannot fail the load. The carried model travels after the bind — the binder offers
3088
+ * only models a provider's configuration lists, and a live switch may have named a model the
3089
+ * endpoint serves without the configuration listing it, which `resolveModel` accepted. A
3090
+ * whole-run override sets every reference aside instead, so it binds nothing, as before.
3091
+ */
3092
+ async loadResumeGraph(selection, signal, overrideAllNodes, nodeModelOverrides, config) {
3093
+ if (overrideAllNodes || nodeModelOverrides === undefined) {
3094
+ return this.loadGraph(selection, signal, undefined, { bindProviders: !overrideAllNodes, allowDeleted: true });
3095
+ }
3096
+ const raw = await this.loadGraph(selection, signal, undefined, { bindProviders: false, allowDeleted: true });
3097
+ // The carried provider replaces the switched node's reference before binding, and the model
3098
+ // field steps aside so the binder does not demand it from the provider's configured pool; the
3099
+ // full carried pair is applied to the bound copy below.
3100
+ const prebound = structuredClone(raw);
3101
+ for (const [nodeId, pair] of Object.entries(nodeModelOverrides)) {
3102
+ const node = prebound.nodes[nodeId];
3103
+ if (node?.type === 'agent') {
3104
+ node.provider = pair.provider;
3105
+ delete node.model;
3106
+ }
3107
+ }
3108
+ return applyNodeModelOverrides(bindPortableGraphProviders(prebound, config), nodeModelOverrides);
2826
3109
  }
2827
3110
  async prepareRunValidated(params, internal, createdSpools) {
2828
3111
  const root = await workspaceRoot(params.workspace);
2829
3112
  this.assertRunning();
2830
- const task = text(params.task, 'task', MAX_TASK_CHARS);
3113
+ const submitted = text(params.task, 'task', MAX_TASK_CHARS);
3114
+ // An automation's awareness rides its own validated channel instead of inside the task: appending
3115
+ // it to a task near the store's prompt limit would invalidate prompts `run.start` accepted before
3116
+ // the channel existed. The combined text is what the session records and the engine receives.
3117
+ const automationContext = params.automationContext === undefined
3118
+ ? undefined
3119
+ : text(params.automationContext, 'automationContext', AUTOMATION_CONTEXT_CHARS);
3120
+ const task = automationContext === undefined ? submitted : `${submitted}\n\n${automationContext}`;
2831
3121
  // Attachments arrive as pending wire items from a client, or as already-resolved refs when
2832
3122
  // `run.resume` continues a stopped attempt's own turn; both resolve once, here, so every
2833
3123
  // record below names the same disk-backed set.
@@ -2898,12 +3188,18 @@ export class AppServer {
2898
3188
  // this run only. The saved graph is untouched — the override is applied to the copy the run
2899
3189
  // executes, so the next run of the same graph keeps its own selections.
2900
3190
  const overrideAllNodes = params.overrideAllNodes === true;
3191
+ // Node pairs a resume carries from the attempt it continues (see `run.resume`); a fresh start
3192
+ // sends none. They compose with a whole-run override rather than excluding it: the whole-run
3193
+ // rebuild answers for every node first, and the carried switches move their nodes on top.
3194
+ const nodeModelOverrides = readNodeModelOverrides(params.nodeModelOverrides);
2901
3195
  // A run that names its model or provider made an explicit choice too, like the CLI's --model:
2902
3196
  // adaptive routing must not re-tier the nodes that inherit it, even when the graph's own pins stay.
2903
3197
  const modelPinned = overrideAllNodes || params.model !== undefined || params.provider !== undefined;
2904
3198
  // The desktop sets this for engines that do not own the session's panel browser: their runs
2905
3199
  // relay every browser.panel operation to the owning engine through the window.
2906
3200
  const panelRelay = params.panelBrowserRelay === true;
3201
+ // Validated in `startRun`; a resume carries the flag from the attempt it continues.
3202
+ const entryHistory = params.entryHistory === true;
2907
3203
  // The run's full scope for `$run.input.*`/`$run.state.*` edge mappings. `run.resume` passes the
2908
3204
  // stopped attempt's persisted scope through here; a plain object from either caller is taken as
2909
3205
  // given (cloned, so nothing downstream can mutate the caller's object), anything else is absent.
@@ -2911,7 +3207,12 @@ export class AppServer {
2911
3207
  ? structuredClone(params.input) : undefined;
2912
3208
  const runState = params.state !== undefined && typeof params.state === 'object' && params.state !== null && !Array.isArray(params.state)
2913
3209
  ? structuredClone(params.state) : undefined;
2914
- const selection = params.graph === undefined || params.graph === '' ? configuredGraphSelection(config, await currentGraphSubject()) : identifier(params.graph, 'graph');
3210
+ const implicit = params.graph === undefined || params.graph === '';
3211
+ let selection = implicit ? configuredGraphSelection(config, await currentGraphSubject()) : identifier(params.graph, 'graph');
3212
+ // A saved default that was deleted falls back to Default, as the listing reports it; a run that
3213
+ // names the deleted graph explicitly is still refused when it loads.
3214
+ if (implicit && await this.selectionIsDeleted(selection))
3215
+ selection = 'default';
2915
3216
  const requested = params.permissions === undefined ? undefined : permissionMode(params.permissions);
2916
3217
  if (requested) {
2917
3218
  // Serialized with every other configuration write, so a permission change cannot discard a
@@ -3012,6 +3313,9 @@ export class AppServer {
3012
3313
  // The whole `resumedFrom` lineage, as the chain walk below leaves it: a successful resume has to
3013
3314
  // clear every attempt's checkpoint, not just the one hop above it.
3014
3315
  let lineage = [];
3316
+ // What this resume could not rule out about the stopped attempt, recorded as warnings in the new
3317
+ // attempt's journal: the resume goes ahead regardless, and the user reads why a step may repeat.
3318
+ let resumeWarnings = [];
3015
3319
  // The journals the lineage walk read, kept for the failure path's question whether the lineage
3016
3320
  // proved completed work — which is what decides refusal over a plain restart.
3017
3321
  const lineageJournals = new Map();
@@ -3043,8 +3347,18 @@ export class AppServer {
3043
3347
  try {
3044
3348
  // The pinned graph the replay runs against, loaded here so a journal the replay cannot
3045
3349
  // 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
- const graph = resumedGraph = this.graphForRun(await this.loadGraph(selection, controller.signal, undefined, { bindProviders: !overrideAllNodes }), overrideAllNodes, provider.id, modelId);
3350
+ // (or, worse, would have restarted from the entry and repeated completed work). The stopped
3351
+ // attempt's node switches ride on top of the bound graph — after a whole-run override when
3352
+ // one was carried — so the switched nodes keep their new pairs, and their checkpoints read
3353
+ // the new pair as the node's identity in the guards below. A carried switch replaces the
3354
+ // switched node's provider reference before the graph's remaining provider references are
3355
+ // bound: a node moved to provider B survives provider A leaving the configuration, while
3356
+ // the nodes still naming A are validated against it as before. The carried model travels
3357
+ // after the bind — the binder offers only models a provider's configuration lists, and a
3358
+ // live switch may have named a model the endpoint serves without the configuration listing
3359
+ // it, which `resolveModel` accepted. A whole-run override sets every reference aside
3360
+ // instead, so it binds nothing, as before.
3361
+ const graph = resumedGraph = this.graphForRun(await this.loadResumeGraph(selection, controller.signal, overrideAllNodes, nodeModelOverrides, config), overrideAllNodes, provider.id, modelId, nodeModelOverrides);
3048
3362
  // Each attempt's journal carries only its own events: the progress it inherited came
3049
3363
  // through seeding, not through anything replayable from its file. So the whole
3050
3364
  // `resumedFrom` chain is walked and replayed oldest-to-newest, folding each attempt's
@@ -3087,35 +3401,78 @@ export class AppServer {
3087
3401
  const runScope = { input: { ...(runInput ?? {}), task }, state: runState ?? {} };
3088
3402
  let progress = replayRunJournal([], graph, runScope);
3089
3403
  const collected = new Map();
3090
- for (const attempt of chain.reverse()) {
3404
+ // Which attempt (by its place in the oldest-first walk) each collected checkpoint came from.
3405
+ const collectedFrom = new Map();
3406
+ // The attempts whose records could not all be written. A session must always be resumable,
3407
+ // so neither refuses the resume: each becomes a warning the user reads in the transcript.
3408
+ const journalGaps = [];
3409
+ const checkpointGaps = [];
3410
+ for (const [index, attempt] of chain.reverse().entries()) {
3091
3411
  const journalText = await readFile(runRecordPath(this.directory, attempt, 'jsonl'), 'utf8').catch(() => '');
3092
3412
  lineageJournals.set(attempt, journalText);
3093
- // A journal whose sink failed mid-run has an interior hole: the events after the failure
3094
- // are present, so the file parses as a complete account while a completed node (or an
3095
- // activation) is simply missing. Replaying it would hand the resumed scheduler a
3096
- // position that is wrong in the direction of repeating work, so the lineage is refused
3097
- // instead — the marker file and the record both carry the failure for exactly this read.
3098
- if (await journalWriteFailed(this.directory, attempt)) {
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
- }
3413
+ // A journal whose writer gave events up, or died holding them, has an interior hole: the
3414
+ // events after it are present, so the file parses as a complete account while a completed
3415
+ // node (or an activation) may simply be missing. The replay below can then sit behind
3416
+ // the real position, and the resumed run may repeat a step that had finished.
3417
+ if (await journalWriteFailed(this.directory, attempt))
3418
+ journalGaps.push(attempt);
3101
3419
  // A checkpoint that could not be written is the conversation the resume re-enters the
3102
- // node with: without it the node is re-entered from its opening task, and the tool calls
3103
- // it had already made happen again. The lineage is refused instead, for the same reason
3104
- // a hole in the journal is.
3105
- if (await checkpointWriteFailed(this.directory, attempt)) {
3106
- throw new AppServerError('invalid-params', `That attempt cannot be resumed: a checkpoint of ${attempt} could not be written, so its conversation cannot be trusted. Start a new run instead.`);
3107
- }
3420
+ // node with. Whether that still matters is decided once every attempt's checkpoints are
3421
+ // collected: a later write of the same node may already have replaced it.
3422
+ const checkpointGap = await checkpointFailure(this.directory, attempt);
3423
+ if (checkpointGap !== undefined)
3424
+ checkpointGaps.push({ index, failure: checkpointGap });
3108
3425
  progress = mergeRunProgress(progress, replayRunJournal(journalText.split('\n').filter(Boolean), graph, runScope));
3109
3426
  // Every attempt in the lineage may hold a branch's only conversation: a parallel
3110
3427
  // branch the parent attempt re-entered (or never reached) checkpoints itself, not its
3111
3428
  // successor. Newest wins per node — the chain walks oldest first — and a checkpoint
3112
3429
  // naming a node the current graph no longer has cannot re-enter anything.
3113
3430
  for (const checkpoint of await readRunCheckpoints(this.directory, attempt)) {
3114
- if (graph.nodes[checkpoint.nodeId])
3431
+ if (graph.nodes[checkpoint.nodeId]) {
3115
3432
  collected.set(checkpoint.nodeId, checkpoint);
3433
+ collectedFrom.set(checkpoint.nodeId, index);
3434
+ }
3116
3435
  }
3117
3436
  }
3118
3437
  lineage = [...chain];
3438
+ // A timer continuation is the agent coming back, on its own deadline, to work it was waiting on - and
3439
+ // the attempt it continues usually stopped because it ran out of budget. Restored as-is, a spent
3440
+ // allowance would end the node before it read the reminder, so the resume would be refused and the
3441
+ // reminder lost. It gets a fresh allowance instead: every restored conversation keeps all its messages
3442
+ // and the completed work stays completed (nothing is replayed), but the counters it spent are cleared
3443
+ // and the lineage's tool spend no longer counts against the new run.
3444
+ if (internal?.freshAllowance === true) {
3445
+ for (const [nodeId, checkpoint] of collected)
3446
+ collected.set(nodeId, { ...checkpoint, state: freshAllowance(checkpoint.state) });
3447
+ }
3448
+ const warnings = [];
3449
+ if (journalGaps.length > 0) {
3450
+ 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.');
3451
+ }
3452
+ // A failed checkpoint matters only for a visit this resume re-enters, and only while no
3453
+ // checkpoint of that same visit written after the failure (by the same attempt or a later
3454
+ // one) replaced it. The visit is matched by generation where both sides know it: a node in
3455
+ // a cycle keeps one checkpoint file, and a file holding another generation's conversation
3456
+ // is skipped by the runner for this one, so it covers nothing here.
3457
+ const reentered = progress.pending.map(activation => ({ nodeId: activation.nodeId, generation: activation.generation ?? 0 }));
3458
+ const sameVisit = (a, b) => a.nodeId === b.nodeId && (a.generation === undefined || b.generation === undefined || a.generation === b.generation);
3459
+ const unsaved = new Set();
3460
+ for (const { index, failure } of checkpointGaps) {
3461
+ for (const visit of failure.visits ?? reentered) {
3462
+ if (!reentered.some(pending => sameVisit(visit, pending)))
3463
+ continue;
3464
+ const saved = collected.get(visit.nodeId);
3465
+ const replaced = saved !== undefined && sameVisit(visit, saved)
3466
+ && ((collectedFrom.get(visit.nodeId) ?? -1) > index
3467
+ || (failure.at !== undefined && Date.parse(saved.savedAt) > Date.parse(failure.at)));
3468
+ if (!replaced)
3469
+ unsaved.add(visit.nodeId);
3470
+ }
3471
+ }
3472
+ if (unsaved.size > 0) {
3473
+ const names = [...unsaved].map(nodeId => `"${graph.nodes[nodeId]?.name ?? nodeId}"`).join(', ');
3474
+ 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.`);
3475
+ }
3119
3476
  // The model identity this run would execute a node with, mirroring the resolution the
3120
3477
  // runner's identical guard applies (`node.provider ?? run provider`, and the model the
3121
3478
  // node declares or the resolved provider's configured one).
@@ -3385,7 +3742,9 @@ export class AppServer {
3385
3742
  // identity-less (legacy) entry falls back to the complete-message rule.
3386
3743
  if (entry.id !== undefined && (!Array.isArray(checkpoint.steeringDelivered) || !checkpoint.steeringDelivered.includes(entry.id)))
3387
3744
  return false;
3388
- return carriesText(asUserMessages(messages), entry.direction);
3745
+ // A timer's direction reached the node in the agent's own reminder wording, so that is the text a
3746
+ // conversation that received it carries.
3747
+ return carriesText(asUserMessages(messages), entry.wake === 'timer' ? timerReminderText(entry.direction) : entry.direction);
3389
3748
  };
3390
3749
  const checkpointProves = (checkpoint, entry) => {
3391
3750
  const parallel = graph.nodes[checkpoint.nodeId]?.modifiers?.parallel;
@@ -3411,7 +3770,7 @@ export class AppServer {
3411
3770
  // so a repeated instruction cannot pass on an older conversation's words.
3412
3771
  const ownDirection = internal?.direction;
3413
3772
  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 }))) {
3773
+ if (internal?.recoveredDirection === true && ownDirection !== undefined && reenteredCheckpoints.some(checkpoint => checkpointProves(checkpoint, { direction: ownDirection, id: recoveredId, ...(internal.wake === undefined ? {} : { wake: internal.wake }) }))) {
3415
3774
  resumedDirection = undefined;
3416
3775
  }
3417
3776
  // The resume still owes a message: is there any node left that could read it? A node the run
@@ -3425,7 +3784,7 @@ export class AppServer {
3425
3784
  // completion and polls the queue first.
3426
3785
  const toolCeilings = [runLimits.maxToolCalls, graph.limits?.maxToolCalls]
3427
3786
  .filter((value) => typeof value === 'number' && !isUnlimitedAlias('maxToolCalls', value));
3428
- if (toolCeilings.length > 0 && (progress.toolCalls ?? 0) > Math.min(...toolCeilings)) {
3787
+ if (toolCeilings.length > 0 && (internal?.freshAllowance === true ? 0 : progress.toolCalls ?? 0) > Math.min(...toolCeilings)) {
3429
3788
  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
3789
  }
3431
3790
  const spentNodes = new Set(reenteredCheckpoints
@@ -3530,7 +3889,8 @@ export class AppServer {
3530
3889
  lineageArtifacts = new ArtifactStore(runId);
3531
3890
  for (const attempt of chain)
3532
3891
  await lineageArtifacts.importFrom(attempt).catch(() => { });
3533
- resumeFrom = { progress, ...(collected.size === 0 ? {} : { checkpoints: [...collected.values()] }) };
3892
+ resumeWarnings = warnings;
3893
+ resumeFrom = { progress: internal?.freshAllowance === true ? { ...progress, toolCalls: 0 } : progress, ...(collected.size === 0 ? {} : { checkpoints: [...collected.values()] }) };
3534
3894
  }
3535
3895
  catch (error) {
3536
3896
  // A refusal this path already made is an answer, not a fallback: rethrow it rather than
@@ -3558,7 +3918,14 @@ export class AppServer {
3558
3918
  // behind, and that is how recovery can find the session and classify the run
3559
3919
  // (`reconcileInterruptedRuns`). Without them a killed run is a transcript with a silent gap and a
3560
3920
  // journal nothing indexes.
3561
- 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 } : {}) };
3921
+ // A wake's message is the agent's own reminder (or the comments Auto-fix brought), not the user's words. The
3922
+ // mark goes with the text it describes: the task of a fresh start, or the direction of a continuation - a
3923
+ // continuation whose direction was proven delivered by an earlier attempt opens with no text to mark.
3924
+ const wake = internal?.wake !== undefined && (internal.resumedFrom === undefined || resumedDirection !== undefined) ? internal.wake : undefined;
3925
+ // The node a timer's continuation direction belongs to: read only by that node, and recorded so a later
3926
+ // resume that recovers the direction still knows whose it is.
3927
+ const directionNode = wake === 'timer' && resumedDirection !== undefined ? internal?.wakeNode : undefined;
3928
+ 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
3929
  // The marker lands in both arrays, exactly as the CLI's persistence path writes it: `history` is
3563
3930
  // the transcript a client reads, and `contextHistory` is the model context a later run seeds
3564
3931
  // from. A resumed session already carries the second, and a marker missing from it would leave
@@ -3592,6 +3959,10 @@ export class AppServer {
3592
3959
  // before finalizing must still be resumable with its full `$run.input.*`/`$run.state.*`
3593
3960
  // scope under the same model behavior, not just the task.
3594
3961
  ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? {} : { reasoningEffort: effort }),
3962
+ // The automation context rides the open record too: a resumed attempt re-sends it beside the
3963
+ // raw task, because the combined text in session history would fail the task validation a
3964
+ // limit-length prompt must still pass.
3965
+ ...(automationContext === undefined ? {} : { automationContext }),
3595
3966
  // A bound permission rides in the open record from the first moment: an attempt that dies
3596
3967
  // before finalizing must still be resumable under the permission it was bound to, and a
3597
3968
  // resume of it inherits that permission again.
@@ -3599,15 +3970,24 @@ export class AppServer {
3599
3970
  // The override rides in the open record too: a resumed attempt re-runs the graph, and without
3600
3971
  // this the nodes would go back to the models the graph names for themselves.
3601
3972
  ...(overrideAllNodes ? { overrideAllNodes: true } : {}),
3973
+ // So do the per-node switches a resume carries: without them the switched nodes alone would
3974
+ // come back on the models the graph names for themselves.
3975
+ ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }),
3976
+ // So does a graph switch: an attempt stopped before its entry node saved a conversation is
3977
+ // resumed into that node afresh, and it is owed the session's history again.
3978
+ ...(entryHistory ? { entryHistory: true } : {}),
3602
3979
  ...(internal?.resumedFrom === undefined ? {} : { resumedFrom: internal.resumedFrom }),
3603
3980
  // The continuation's message rides the open record exactly as `resumedFrom` does: an attempt
3604
3981
  // that stops or crashes leaves this record standing as the account of the run, and the
3605
3982
  // instruction the user sent to continue it belongs to that account, not only the finalizer's.
3606
3983
  ...(resumedDirection === undefined ? {} : { direction: resumedDirection }),
3984
+ // Which wake delivered the message, so a record read back never presents the reminder as the user's.
3985
+ ...(wake === undefined ? {} : { wake }),
3986
+ ...(directionNode === undefined ? {} : { directionNode }),
3607
3987
  // Every carried direction still needing arming is named too, oldest first: a crash before the
3608
3988
  // next checkpoint leaves this record as the only account of what was queued, and the newest
3609
3989
  // 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 }) })) }) };
3990
+ ...(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
3991
  bootMark('run.prepare.record-write.start');
3612
3992
  await writeOpenRunRecord(this.directory, openRecord)
3613
3993
  .catch(async (error) => {
@@ -3668,17 +4048,39 @@ export class AppServer {
3668
4048
  // the run's own poll drains it at turn boundaries: a message typed during the run redirects the
3669
4049
  // node that is working instead of ending the attempt and starting it over.
3670
4050
  const liveSteers = [];
3671
- this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, steersClosed: false };
4051
+ const permissionControl = new RunControl();
4052
+ permissionControl.permissions = effective;
4053
+ permissionControl.yolo = effective === 'full-access';
4054
+ this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, steersClosed: false,
4055
+ permissionControl, permissionRevision: 0, approvals: new Set(), boundPermissions: internal?.inheritedPermissions !== undefined,
4056
+ codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }) };
4057
+ // This run is now the session's newest turn. A wake armed by an attempt this run does not continue was a
4058
+ // reminder about work this turn has replaced, so it is spent here rather than left on the row's clock only
4059
+ // to be dropped at its deadline. A wake a delivery is holding is that delivery's to decide.
4060
+ {
4061
+ const continues = new Set([runId, ...lineage]);
4062
+ for (const timer of this.timers.list(record.id)) {
4063
+ if (timer.origin === undefined || continues.has(timer.origin.runId) || this.timers.isHeld(timer.id))
4064
+ continue;
4065
+ this.spendWake(timer, 'a newer turn in this session replaced the attempt that set it');
4066
+ }
4067
+ }
3672
4068
  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 } : {}) });
4069
+ 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
4070
  bootMark('run.started.emitted');
4071
+ // Queued before the run itself records anything, so the journal's ordered writer puts the
4072
+ // warnings at the top of this attempt: the transcript shows them where the resume began, and a
4073
+ // reload rebuilds them from the journal.
4074
+ for (const text of resumeWarnings) {
4075
+ void this.recordRunEvent(runId, { type: 'run.resume.warning', time: new Date().toISOString(), data: { runId, sessionId: record.id, text } });
4076
+ }
3675
4077
  // A session born from this start gets its real name from one small model request summarizing
3676
4078
  // the prompt, replacing the local word-slice as soon as the run's first turn has answered the
3677
4079
  // provider — and keeping it even if the run is stopped afterwards. Registered before the run is
3678
4080
  // dispatched, so the naming request waits for a signal this run publishes.
3679
4081
  if (params.sessionId === undefined)
3680
4082
  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 }) })
4083
+ 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
4084
  .catch(error => this.log('error', `Run ${runId} failed: ${message(error)}`));
3683
4085
  // The finally sits outside the awaited chain so the settle can name the exact promise this
3684
4086
  // attempt owns: the finalizer now releases the live-run slot before the terminal events, so a
@@ -3800,16 +4202,18 @@ export class AppServer {
3800
4202
  this.sessionTitles.clear();
3801
4203
  }
3802
4204
  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;
4205
+ 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
4206
  const signal = controller.signal;
3805
4207
  const liveRun = this.run?.runId === runId ? this.run : undefined;
3806
4208
  if (liveRun)
3807
4209
  liveRun.graphSelection = selection;
3808
- const journal = runRecordPath(this.directory, runId, 'jsonl');
3809
4210
  // Checkpoints land one at a time, newest last: the runner calls back synchronously from
3810
4211
  // several nodes, and an unserialized write could leave an older conversation as the file's
3811
4212
  // final content. Failures are logged, never fatal — durability is a convenience, not the run.
3812
4213
  let checkpointWrites = Promise.resolve();
4214
+ // Which nodes' newest checkpoint write failed. Each write replaces the node's whole file, so a
4215
+ // later write of the same node that succeeds heals the failure.
4216
+ const checkpointHealth = createCheckpointFailureTracker(this.directory, runId);
3813
4217
  const persistCheckpoint = (nodeId, messages, state, meta) => {
3814
4218
  checkpointWrites = checkpointWrites
3815
4219
  .then(() => writeRunCheckpoint(this.directory, runId, { nodeId, messages, state, revision: state.directionRevision, savedAt: new Date().toISOString(),
@@ -3825,13 +4229,12 @@ export class AppServer {
3825
4229
  // What this attempt had handed to a node before this write, by identity: a later resume proves
3826
4230
  // delivery from this marker, so the same words sent twice are told apart by their revision.
3827
4231
  ...(deliveredIds.size === 0 ? {} : { steeringDelivered: [...deliveredIds] }) }))
3828
- .catch(async (error) => {
3829
- // The run keeps working (a storage hiccup must not kill the user's work) but a
3830
- // checkpoint that could not be written is the conversation a resume re-enters the node
3831
- // with: without it the resume re-enters from the node's opening task and repeats the
3832
- // tool calls that already ran. The attempt is marked, and a resume of it is refused.
3833
- this.checkpointFailures.add(runId);
3834
- await noteCheckpointWriteFailure(this.directory, runId, message(error));
4232
+ .then(() => checkpointHealth.succeeded({ nodeId, generation: meta?.generation }), async (error) => {
4233
+ // The run keeps working (a storage hiccup must not kill the user's work). A checkpoint
4234
+ // that could not be written is the conversation a resume re-enters the node with, so the
4235
+ // node is marked until one of its later writes lands; a resume of an attempt that
4236
+ // stopped while it was still marked warns that the node may repeat work.
4237
+ await checkpointHealth.failed({ nodeId, generation: meta?.generation }, error);
3835
4238
  this.log('warn', `Could not write the run checkpoint: ${message(error)}`);
3836
4239
  });
3837
4240
  // The write is handed back so the runtime can await it: the checkpoint is the conversation a
@@ -3853,6 +4256,10 @@ export class AppServer {
3853
4256
  let contextUsedTokens = 0;
3854
4257
  let contextWindow;
3855
4258
  let contextCacheRead;
4259
+ // Session-wide eligible cache totals. Only local requests that reported a cache-read
4260
+ // counter contribute; a switched model's cold miss is counted, not used to reset history.
4261
+ let localCacheInputTokens = 0;
4262
+ let localCacheReadTokens = 0;
3856
4263
  // The preflight is outside `runGraph`, so its spend is kept separately: a completed attempt's
3857
4264
  // result carries only the graph's own calls, and finalization folds this into the record and
3858
4265
  // the session totals alongside it.
@@ -3898,15 +4305,31 @@ export class AppServer {
3898
4305
  // delivery to a later resume, by identity rather than by words.
3899
4306
  const deliveredIds = new Set((resumeFrom?.checkpoints ?? []).flatMap(checkpoint => checkpoint.steeringDelivered ?? []));
3900
4307
  const armed = [];
4308
+ // A direction a timer delivered belongs to the node that set it: it is armed for that node and read on the
4309
+ // node channel, so a sibling branch that owns the shared queue cannot take it. Any other direction is the
4310
+ // user's and goes on the shared queue as before.
4311
+ const nodeArmed = new Map();
4312
+ const arm = (node, entry) => {
4313
+ if (node === undefined) {
4314
+ armed.push(entry);
4315
+ return;
4316
+ }
4317
+ const list = nodeArmed.get(node) ?? [];
4318
+ list.push(entry);
4319
+ nodeArmed.set(node, list);
4320
+ };
3901
4321
  for (const entry of carriedDirections ?? []) {
3902
4322
  const refs = entry.attachments ?? [];
3903
4323
  const images = refs.length ? await loadResolvedImages(this.directory, root, refs) : [];
3904
- armed.push({ ...(entry.id === undefined ? {} : { id: entry.id }), content: refs.length ? `${entry.direction}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : entry.direction, images });
4324
+ const said = entry.wake === 'timer' ? timerReminderText(entry.direction) : entry.direction;
4325
+ 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
4326
  }
3906
4327
  if (direction !== undefined) {
3907
4328
  const refs = attachments?.refs ?? [];
3908
4329
  const images = attachments?.images ?? [];
3909
- armed.push({ ...(ownDirectionId === undefined ? {} : { id: ownDirectionId }), content: refs.length ? `${direction}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : direction, images });
4330
+ // A continuation a timer delivered opens with the agent's own reminder, read as one rather than as the user's words.
4331
+ const said = wake === 'timer' ? timerReminderText(direction) : direction;
4332
+ arm(wake === 'timer' ? directionNode : undefined, { ...(ownDirectionId === undefined ? {} : { id: ownDirectionId }), content: refs.length ? `${said}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : said, images });
3910
4333
  }
3911
4334
  const steering = armed.length === 0 ? undefined : armed;
3912
4335
  // The messages the user typed into the live attempt, in the order the runtime read them. Each
@@ -3914,6 +4337,13 @@ export class AppServer {
3914
4337
  // of the transcript; the ones still queued when the run ends are reported instead, because a
3915
4338
  // message the agent never read is not part of the work that happened.
3916
4339
  const deliveredSteers = [];
4340
+ /** Remove and return the queued messages `wanted` selects, in queue order; synchronous, so a poll never yields holding them. */
4341
+ const takeSteers = (wanted) => {
4342
+ const taken = liveSteers.filter(wanted);
4343
+ for (const entry of taken)
4344
+ liveSteers.splice(liveSteers.indexOf(entry), 1);
4345
+ return taken;
4346
+ };
3917
4347
  let mcp;
3918
4348
  let commandMemory;
3919
4349
  let result;
@@ -4151,7 +4581,22 @@ export class AppServer {
4151
4581
  for (const notice of extension.notices)
4152
4582
  this.emit('log', { level: 'info', message: notice });
4153
4583
  bootMark('run.exec.extensions.loaded');
4154
- const codeIntel = await this.codeIntelligence(root, permissions, signal);
4584
+ // In the mode the run holds now: a live change can land before the manager exists (see
4585
+ // `ActiveRun.codeIntelPermissions`), and one that lands while it is being prepared is applied
4586
+ // once it does.
4587
+ // A change that tightens the mode waits for this creation (`codeIntelReady`) before it is saved
4588
+ // or acknowledged, so a manager started in the earlier mode is suspended first.
4589
+ const codeIntelMode = liveRun?.codeIntelPermissions ?? permissions;
4590
+ const creating = this.codeIntelligence(root, codeIntelMode, signal).then(manager => {
4591
+ if (manager && liveRun)
4592
+ liveRun.codeIntelApplied = codeIntelMode;
4593
+ return manager;
4594
+ });
4595
+ if (liveRun)
4596
+ liveRun.codeIntelReady = creating.then(() => undefined, () => undefined);
4597
+ const codeIntel = await creating;
4598
+ if (codeIntel && liveRun)
4599
+ await this.syncCodeIntelPermissions(liveRun).catch(error => this.log('warn', `Could not bring code intelligence to the run's mode: ${message(error)}`));
4155
4600
  bootMark('run.exec.code-intel.ready');
4156
4601
  const membership = await getMembership(signal, this.directory);
4157
4602
  bootMark('run.exec.membership.read');
@@ -4189,12 +4634,16 @@ export class AppServer {
4189
4634
  const pullRequestDetector = new PullRequestCreateDetector();
4190
4635
  const toolContext = {
4191
4636
  workspace: root, signal, userSignal: signal, yolo: permissions === 'full-access', permissions, approvalMode: 'interactive',
4637
+ // The live mode: `run.setPermissions` changes it on the control, and every copy of this context
4638
+ // reads it from there, so a tool already waiting on a prompt sees the change.
4639
+ ...(liveRun ? { runControl: liveRun.permissionControl } : {}),
4192
4640
  attachmentRoots,
4193
4641
  approve: (name, args, toolSignal) => this.approve(runId, name, args, toolSignal),
4194
4642
  askUser: (question, toolSignal, choices) => this.ask(runId, question, choices, toolSignal),
4643
+ ...(liveRun ? { approvePlan: () => this.approvePlan(liveRun) } : {}),
4195
4644
  onApprovalEvent: (type, data) => {
4196
4645
  const event = { type, time: new Date().toISOString(), data };
4197
- void this.recordRunEvent(runId, journal, event);
4646
+ void this.recordRunEvent(runId, event);
4198
4647
  void this.trajectory?.recordEvent(event);
4199
4648
  },
4200
4649
  onBrowserEvent: async (type, data) => {
@@ -4203,7 +4652,7 @@ export class AppServer {
4203
4652
  // a late notification after run.completed has no live owner in the desktop.
4204
4653
  const event = { type, time: new Date().toISOString(), data: { ...data, sessionId: input.record.id } };
4205
4654
  await Promise.allSettled([
4206
- this.recordRunEvent(runId, journal, event),
4655
+ this.recordRunEvent(runId, event),
4207
4656
  this.trajectory?.recordEvent(event),
4208
4657
  ]);
4209
4658
  },
@@ -4233,7 +4682,8 @@ export class AppServer {
4233
4682
  // desktop relay to the engine that does. It is keyed to the saved session id both the pane
4234
4683
  // and this run's browser events already use, so agent-driven tabs are the pane's tabs. The
4235
4684
  // 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), ...extension.tools, ...(mcp?.tools ?? [])], history: contextSeed,
4685
+ tools: [...createTools(), createBrowserPanelTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined),
4686
+ createBrowserIncognitoTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined), ...extension.tools, ...(mcp?.tools ?? [])], installedSkillClaims: extension.claimsSkillName, history: contextSeed,
4237
4687
  ...(invocation ? { inheritedSkills: [invocation.id], skillInvocationInstruction: invocation.task } : {}),
4238
4688
  instructions: `${await loadWorkspaceInstructions(root, signal, config.systemPromptOverride)}\n${QA_SYSTEM_GUIDANCE}${extension.instructions}`,
4239
4689
  codeIntel, todoStore: new TodoStore(), ...(commandMemory ? { commandMemory } : {}),
@@ -4243,6 +4693,7 @@ export class AppServer {
4243
4693
  // "Use this model for every node" and a run that named its model are the user's explicit
4244
4694
  // choices; adaptive routing leaves them alone.
4245
4695
  modelPinned: modelPinned || overrideAllNodes,
4696
+ ...(entryHistory ? { entryHistory: true } : {}),
4246
4697
  configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
4247
4698
  // The executor resolves its own model rather than reusing `adapter`, so the task's effort is
4248
4699
  // handed to it as well — for the run's own provider and model only: a node that pins another
@@ -4261,10 +4712,20 @@ export class AppServer {
4261
4712
  const [rootId, roleId] = (nodeId ?? '').split('/');
4262
4713
  const fallback = roleId?.endsWith('#fallback') || rootId.endsWith('#fallback');
4263
4714
  const own = liveRun?.modelGraph?.nodes[rootId.replace(/#fallback$/, '')];
4715
+ // A node the user switched mid-run answers from the override, ahead of the graph's own
4716
+ // fields: the pair names both provider and model, and it is what the delegating children
4717
+ // of this node inherit, while a role that pins a pair of its own keeps it below.
4718
+ const nodeOverride = current.nodeOverrides?.[rootId.replace(/#fallback$/, '')];
4719
+ // A selection that exists only because one node was switched answers for that node and
4720
+ // the children that inherit it — nobody else. A node without an override and without a
4721
+ // graph pin had no selection before, so it keeps the adaptive routing that was serving
4722
+ // it instead of falling to the run's baseline pair.
4723
+ if (current.nodeOnly === true && nodeOverride === undefined && own?.provider === undefined)
4724
+ return undefined;
4264
4725
  const policy = own?.subagents;
4265
4726
  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);
4727
+ const parentProvider = nodeOverride?.provider ?? own?.provider ?? current.provider;
4728
+ const parentModel = nodeOverride?.model ?? own?.model ?? (own?.provider === undefined ? current.model : undefined);
4268
4729
  let targetProvider = parentProvider, targetModel = parentModel;
4269
4730
  // The parent's effective pair comes first: a retried attempt continues its fallback, and
4270
4731
  // that pair is what a child inherits. The child's own delegation policy is applied on
@@ -4284,7 +4745,11 @@ export class AppServer {
4284
4745
  targetProvider = role?.provider ?? inheritedProvider;
4285
4746
  targetModel = role?.model ?? (targetProvider === inheritedProvider ? inheritedModel : undefined);
4286
4747
  }
4287
- if (current.overrideAllNodes) {
4748
+ // A whole-run override answers for every node that has no switch of its own: a node
4749
+ // the user moved mid-run keeps the pair they picked, even under an override that was
4750
+ // active when the pick landed — the override's run pair is what the switched node
4751
+ // left behind, not what it joined.
4752
+ if (current.overrideAllNodes && nodeOverride === undefined) {
4288
4753
  targetProvider = current.provider;
4289
4754
  targetModel = current.model;
4290
4755
  }
@@ -4311,8 +4776,26 @@ export class AppServer {
4311
4776
  const window = event.data.contextWindow;
4312
4777
  contextWindow = typeof window === 'number' && Number.isSafeInteger(window) && window > 0 ? window : undefined;
4313
4778
  }
4314
- await this.recordRunEvent(runId, journal, event);
4779
+ await this.recordRunEvent(runId, event);
4315
4780
  await this.trajectory?.recordEvent(event);
4781
+ // The node that armed a wake finished its work: the reminder was about that work, and no later node
4782
+ // or later run is where it belongs.
4783
+ if (event.type === 'graph.node.completed' && typeof event.data.nodeId === 'string') {
4784
+ const nodeId = event.data.nodeId;
4785
+ const attempts = new Set([runId, ...lineage]);
4786
+ const finished = 'the node that set it has finished its work';
4787
+ this.spendAttemptWakes(input.record.id, attempts, finished, origin => origin.nodeId === nodeId);
4788
+ // A reminder already handed to this run but not yet read is the same promise: left in the queue, the
4789
+ // next node's first turn boundary would read a stale instruction about work that is done. The emit
4790
+ // that brought this event is awaited before the graph moves on, so it is pulled here, before any
4791
+ // later node polls. Its row is withdrawn from the journal the way an unread steer's is.
4792
+ const stale = liveSteers.filter(entry => entry.wake?.origin !== undefined && entry.wake.origin.nodeId === nodeId && attempts.has(entry.wake.origin.runId));
4793
+ for (const entry of stale) {
4794
+ liveSteers.splice(liveSteers.indexOf(entry), 1);
4795
+ await this.recordRunEvent(runId, { type: 'run.steer-returned', time: new Date().toISOString(), data: { runId, sessionId: input.record.id, steerId: entry.id } });
4796
+ this.spendWake(entry.wake, finished);
4797
+ }
4798
+ }
4316
4799
  // A `gh pr create` the agent ran puts the PR it opened on the session's Plan card.
4317
4800
  const created = pullRequestDetector.observe(event);
4318
4801
  if (created)
@@ -4320,13 +4803,17 @@ export class AppServer {
4320
4803
  },
4321
4804
  onUsage: (delta, origin) => {
4322
4805
  foldUsage(runUsage, delta);
4806
+ if (origin?.localModel === true && delta.inputTokens > 0 && delta.cacheRead !== undefined) {
4807
+ localCacheInputTokens += delta.inputTokens;
4808
+ localCacheReadTokens += Math.min(delta.inputTokens, Math.max(0, delta.cacheRead));
4809
+ }
4323
4810
  // A delta that reports no prompt is transport bookkeeping, not an empty context. The
4324
4811
  // reading's cache hits travel with it, and an absent split stays absent, not zero.
4325
4812
  if (delta.inputTokens !== undefined && delta.inputTokens > 0) {
4326
4813
  contextUsedTokens = delta.inputTokens;
4327
4814
  contextCacheRead = delta.cacheRead;
4328
4815
  }
4329
- this.emit('run.usage', { runId, usage: delta, ...(origin?.invocationId === undefined ? {} : { invocationId: origin.invocationId }), final: origin?.final === true });
4816
+ this.emit('run.usage', { runId, usage: delta, ...(origin?.invocationId === undefined ? {} : { invocationId: origin.invocationId }), final: origin?.final === true, ...(origin?.localModel === true ? { localModel: true } : {}) });
4330
4817
  },
4331
4818
  // Every node's furthest conversation, persisted as it is reached: an attempt that dies
4332
4819
  // leaves a checkpoint behind that `run.resume` re-enters, and the successful attempt
@@ -4339,7 +4826,9 @@ export class AppServer {
4339
4826
  // not a standing prompt. A live message's own spooled files join the tool context here,
4340
4827
  // before the model that may ask a tool to read them next sees the message.
4341
4828
  getSteeringMessages: async () => {
4342
- const live = liveSteers.splice(0);
4829
+ // The shared queue carries what the user typed. A reminder a node set for itself is read only by that
4830
+ // node, through `getNodeSteeringMessages`, never by whichever branch owns this queue.
4831
+ const live = takeSteers(entry => entry.wake === undefined);
4343
4832
  for (const entry of live) {
4344
4833
  // A message's spooled files are readable by the tools its text may ask for. The array is
4345
4834
  // the one the tool contexts hold — they copy the reference, not its contents — so pushing
@@ -4361,6 +4850,19 @@ export class AppServer {
4361
4850
  deliveredIds.add(entry.id);
4362
4851
  return [...armedBatch, ...live].map(entry => ({ role: 'user', content: entry.content, ...(entry.images.length ? { images: entry.images } : {}) }));
4363
4852
  },
4853
+ // A `set_timer` reminder goes back to the node that set it, polled by that node whether or not its branch
4854
+ // owns the shared queue. It must not yield before returning, for the same reason as the shared poll.
4855
+ getNodeSteeringMessages: async (nodeId) => {
4856
+ const own = takeSteers(entry => entry.wake?.origin?.nodeId === nodeId);
4857
+ for (const entry of own)
4858
+ deliveredSteers.push(entry);
4859
+ // A continuation's reminder for this node, with its identity marked delivered as the shared queue's are.
4860
+ const directed = nodeArmed.get(nodeId)?.splice(0) ?? [];
4861
+ for (const entry of directed)
4862
+ if (entry.id !== undefined)
4863
+ deliveredIds.add(entry.id);
4864
+ return [...directed, ...own].map(entry => ({ role: 'user', content: entry.content, ...(entry.images.length ? { images: entry.images } : {}) }));
4865
+ },
4364
4866
  ...(resumeFrom === undefined ? {} : { resumeFrom }),
4365
4867
  ...(lineageArtifacts === undefined ? {} : { artifactStore: lineageArtifacts }),
4366
4868
  };
@@ -4380,7 +4882,7 @@ export class AppServer {
4380
4882
  // a failure rather than a success that hides it: the transcript shows the turn stopped short of
4381
4883
  // the message, the record keeps the direction, and the next resume re-delivers it (or the user
4382
4884
  // sends it as a follow-up).
4383
- if (steering?.length) {
4885
+ if (steering?.length || [...nodeArmed.values()].some(list => list.length > 0)) {
4384
4886
  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
4887
  if (result && result.status === 'succeeded')
4386
4888
  result = { ...result, status: 'infrastructure_error', reason: DIRECTION_UNDELIVERED_REASON, completion: undefined };
@@ -4393,10 +4895,24 @@ export class AppServer {
4393
4895
  // is refused rather than appended to a queue this finalizer has already emptied.
4394
4896
  if (this.run?.runId === runId)
4395
4897
  this.run.steersClosed = true;
4898
+ // Close permission admission before draining: changes already accepted must finish before
4899
+ // the terminal snapshot, while later requests are refused by setRunPermissions above.
4900
+ await liveRun?.permissionChanges;
4396
4901
  // A selection accepted while the last model request was completing may still be
4397
4902
  // committing its open record. Settle it before deriving the terminal model identity.
4398
4903
  await liveRun?.recordWrites;
4399
- const undeliveredSteers = liveSteers.splice(0);
4904
+ const returnedSteers = liveSteers.splice(0);
4905
+ // A reminder the run ended before reading is not the user's message: it goes back on the registry once the
4906
+ // attempt is put away (see `publishFinalized`), where the rules for an attempt that has ended decide whether
4907
+ // it continues the attempt or is spent, rather than being handed to the window for the user's composer.
4908
+ const returnedWakes = returnedSteers.flatMap(entry => entry.wake === undefined ? [] : [entry.wake]);
4909
+ const undeliveredSteers = returnedSteers.filter(entry => entry.wake === undefined);
4910
+ // The journal drops the row of every message the run never read, reminders included.
4911
+ for (const entry of returnedSteers) {
4912
+ if (entry.wake === undefined)
4913
+ continue;
4914
+ await this.recordRunEvent(runId, { type: 'run.steer-returned', time: new Date().toISOString(), data: { runId, sessionId: input.record.id, steerId: entry.id } });
4915
+ }
4400
4916
  if (undeliveredSteers.length) {
4401
4917
  this.log('warn', `${undeliveredSteers.length} steering message${undeliveredSteers.length === 1 ? ' was' : 's were'} not delivered: the run ended before its next turn boundary.`);
4402
4918
  // The `run.steered` line recorded when the message was queued is what drew its row, and a
@@ -4404,7 +4920,7 @@ export class AppServer {
4404
4920
  // the return is recorded beside it so the fold drops the row, and a client that missed the
4405
4921
  // live event tells the same story after a reload.
4406
4922
  for (const entry of undeliveredSteers) {
4407
- await this.recordRunEvent(runId, journal, {
4923
+ await this.recordRunEvent(runId, {
4408
4924
  type: 'run.steer-returned',
4409
4925
  time: new Date().toISOString(),
4410
4926
  data: { runId, sessionId: input.record.id, steerId: entry.id },
@@ -4433,6 +4949,10 @@ export class AppServer {
4433
4949
  if (result)
4434
4950
  foldUsage(result.usage, probeUsage);
4435
4951
  foldUsage(usage, result?.usage ?? runUsage);
4952
+ if (localCacheInputTokens > 0) {
4953
+ usage.localCacheInputTokens = (usage.localCacheInputTokens ?? 0) + localCacheInputTokens;
4954
+ usage.localCacheReadTokens = (usage.localCacheReadTokens ?? 0) + localCacheReadTokens;
4955
+ }
4436
4956
  // The session trajectory closes with the attempt that opened it: the marker says how the run
4437
4957
  // ended for a reader scanning one session's calls, and the flush waits out the append queue
4438
4958
  // so a client saving the file right after `run.completed` reads every record.
@@ -4455,9 +4975,9 @@ export class AppServer {
4455
4975
  // task and direction instead of losing what the user said mid-run. The text is stored apart
4456
4976
  // from the model-facing content: the reference block names spooled files that may since have
4457
4977
  // 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);
4978
+ const steers = deliveredSteers.map(entry => ({ text: entry.text, ...(entry.refs?.length ? { attachments: entry.refs } : {}), ...(entry.wake === undefined ? {} : { wake: 'timer' }) }));
4979
+ archive.push({ task, completion, runId, ...(resumedFrom === undefined ? {} : { resumed: true }), ...(direction === undefined ? {} : { direction }), ...(attachments?.refs.length ? { attachments: attachments.refs } : {}), ...(steers.length ? { steers } : {}), ...(wake === undefined ? {} : { wake }) });
4980
+ 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
4981
  const record = { ...input.record, history: archive, contextHistory: history, updatedAt: new Date().toISOString(), usage,
4462
4982
  // The run's final widget values are the session's newest, so the record carries them for
4463
4983
  // clients that rebuild the conversation from disk. A result without widgets (a graph that
@@ -4476,6 +4996,9 @@ export class AppServer {
4476
4996
  ...(closedWithRun ? { reason: APP_CLOSED_REASON } : controller.signal.aborted ? {} : { reason: message(failure) }),
4477
4997
  usage: runUsage, toolCalls: 0, completion,
4478
4998
  };
4999
+ // Whether the journal is a complete account. The writer retries what it still holds first:
5000
+ // space freed since the last refused append lets the journal finish whole.
5001
+ const journalIntact = await (this.journals.get(runId)?.settle() ?? Promise.resolve(true));
4479
5002
  try {
4480
5003
  await this.ensureRunRecords();
4481
5004
  // The finalizer overwrites the open record; it carries its identity fields forward so the
@@ -4493,6 +5016,10 @@ export class AppServer {
4493
5016
  // resume reads when the marker file itself was never written.
4494
5017
  // A result the abort answered with `cancelled` is the same shutdown-cut attempt as the
4495
5018
  // fallback above: the record says interrupted, with the reason recovery would have written.
5019
+ // The node map the record carries: a selection this attempt published is the authority —
5020
+ // including its absence, which is how a whole-run switch says the map was cleared — and
5021
+ // only an attempt that switched nothing forwards the map it itself was resumed with.
5022
+ const liveNodeOverrides = liveRun?.modelSelection !== undefined ? liveRun.modelSelection.nodeOverrides : nodeModelOverrides;
4496
5023
  const finalRecord = { ...recordResult,
4497
5024
  ...(closedWithRun && recordResult.status === 'cancelled' ? { status: 'interrupted', reason: APP_CLOSED_REASON } : {}),
4498
5025
  provider: liveRun?.modelSelection?.provider ?? providerId, model: liveRun?.modelSelection?.model ?? modelId,
@@ -4502,6 +5029,9 @@ export class AppServer {
4502
5029
  graphSelection: selection, ...(accountSubject ? { accountSubject } : {}),
4503
5030
  sessionId: record.id, startedAt, ...(runInput === undefined ? {} : { runInput }),
4504
5031
  ...(runState === undefined ? {} : { runState }),
5032
+ // The automation context carries forward like the run scope above it: a resume of this
5033
+ // attempt re-sends it beside the raw task instead of re-validating the combined text.
5034
+ ...(automationContext === undefined ? {} : { automationContext }),
4505
5035
  // A selection may have been published while the previous model request was still
4506
5036
  // running. Its checkpoint then retains the old model stamp. Record the transition so
4507
5037
  // ordinary resume reconciles that checkpoint instead of replaying completed tools.
@@ -4513,14 +5043,24 @@ export class AppServer {
4513
5043
  // The override is part of the attempt's identity: a resume re-runs the graph, and a record
4514
5044
  // that dropped this flag would bring the nodes back to the models the graph names.
4515
5045
  ...((liveRun?.modelSelection?.overrideAllNodes ?? overrideAllNodes) ? { overrideAllNodes: true } : {}),
5046
+ // So is each node a live switch moved: a resume re-applies the map on the bound graph. A
5047
+ // selection this attempt published is the authority — including its absence, which is how
5048
+ // a whole-run switch says the node map was cleared — and only an attempt that switched
5049
+ // nothing forwards the map it itself was resumed with, untouched.
5050
+ ...((liveNodeOverrides !== undefined && Object.keys(liveNodeOverrides).length > 0)
5051
+ ? { nodeModelOverrides: liveNodeOverrides } : {}),
5052
+ ...(entryHistory ? { entryHistory: true } : {}),
4516
5053
  ...(direction === undefined ? {} : { direction }),
5054
+ ...(wake === undefined ? {} : { wake }),
5055
+ ...(directionNode === undefined ? {} : { directionNode }),
4517
5056
  ...(pendingDirections === undefined || pendingDirections.length === 0 ? {} : { pendingDirections }),
4518
5057
  ...(resumedFrom === undefined ? {} : { resumedFrom }),
4519
- ...(this.journalFailures.has(runId) ? { journalIntegrity: 'failed' } : {}),
4520
- ...(this.checkpointFailures.has(runId) ? { checkpointIntegrity: 'failed' } : {}),
5058
+ ...(journalIntact ? {} : { journalIntegrity: 'failed' }),
5059
+ ...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
4521
5060
  // 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
- ...(boundPermissions === undefined ? {} : { permissions: boundPermissions }) };
5061
+ // permission it ran under, so a chain of resumes of a host-bound attempt keeps it. A live
5062
+ // change replaced the mode it ran under, so the mode it ended under is the one carried.
5063
+ ...(boundPermissions === undefined ? {} : { permissions: liveRun?.permissionControl.permissions ?? boundPermissions }) };
4524
5064
  const writeFinal = () => writeFile(runRecordPath(this.directory, runId, 'json'), `${JSON.stringify(finalRecord, null, 2)}\n`, { mode: 0o600 });
4525
5065
  if (liveRun)
4526
5066
  await this.serializeRunRecordWrite(liveRun, writeFinal);
@@ -4568,9 +5108,24 @@ export class AppServer {
4568
5108
  if (this.run?.runId === runId)
4569
5109
  this.run = undefined;
4570
5110
  releaseProcessWorkspace(root, runId);
4571
- // Whatever this run armed now belongs to the session rather than to the run: a prompt the agent
4572
- // asked to be woken for is expected to arrive after the turn that armed it is over. While one is
4573
- // left the session is waiting, not finished, and only the engine can still deliver it.
5111
+ // A wake a node of this attempt (or of an attempt it continues) armed is a reminder about that node's
5112
+ // work, and it is delivered only as a continuation of this attempt. An attempt that finished has nothing
5113
+ // left to continue, and one the user stopped was stopped on purpose: their wakes are spent now, said
5114
+ // where the user sees it, instead of waiting out a deadline only to restart work that is over. An
5115
+ // attempt that ended any other way - out of budget, failed, interrupted - keeps them: on the deadline
5116
+ // the reminder continues it from the arming node (see `wakeContinuation`).
5117
+ const finishedOwn = result?.status === 'succeeded' ? 'the attempt that set it has finished'
5118
+ : controller.signal.aborted && this.runAbort === 'user' ? 'the attempt that set it was stopped' : undefined;
5119
+ for (const timer of returnedWakes) {
5120
+ this.timers.restore(timer);
5121
+ if (finishedOwn === undefined)
5122
+ void writeWakeClaim(this.directory, record.id, timer.id).catch(() => { });
5123
+ }
5124
+ if (finishedOwn !== undefined)
5125
+ this.spendAttemptWakes(record.id, new Set([runId, ...lineage]), finishedOwn);
5126
+ // Whatever else is armed now belongs to the session rather than to the run: a prompt the agent asked
5127
+ // to be woken for is expected to arrive after the turn that armed it is over. While one is left the
5128
+ // session is waiting, not finished, and only the engine can still deliver it.
4574
5129
  this.settleSessionTimers(record.id);
4575
5130
  // The summaries are built without the live-run override: this callback runs while `this.run`
4576
5131
  // still names the attempt that just ended, and stamping `running` onto a terminal record
@@ -4622,6 +5177,9 @@ export class AppServer {
4622
5177
  this.finishingRunId = undefined;
4623
5178
  this.finishingSessionId = undefined;
4624
5179
  }
5180
+ // Nothing records into this attempt's journal from here: its record already said whether the
5181
+ // journal is whole.
5182
+ this.journals.delete(runId);
4625
5183
  // A record that never reached the disk is not the session: publishing it would have the client reload
4626
5184
  // the older record and drop the turn it just watched, and after a restart the turn would be gone while
4627
5185
  // the run was reported as completed. The failure is reported instead, with the transcript left alone.
@@ -4688,10 +5246,13 @@ export class AppServer {
4688
5246
  const run = this.run;
4689
5247
  if (!run || params.runId !== run.runId || run.steersClosed)
4690
5248
  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
5249
  const provider = identifier(params.provider, 'provider');
4694
5250
  const model = text(params.model, 'model', 200);
5251
+ // A switch that names a node changes that one node's pair — and what its delegating children
5252
+ // inherit — and ignores the whole-run flag; without a node the switch is the run's own scope.
5253
+ const scopedNode = params.nodeId === undefined ? undefined : identifier(params.nodeId, 'nodeId');
5254
+ if (scopedNode === undefined && typeof params.overrideAllNodes !== 'boolean')
5255
+ throw new AppServerError('invalid-params', 'overrideAllNodes must be a boolean');
4695
5256
  const generation = run.modelChangeGeneration = (run.modelChangeGeneration ?? 0) + 1;
4696
5257
  const config = await loadConfig(this.directory);
4697
5258
  if (!config.providers.some(item => item.id === provider))
@@ -4701,10 +5262,15 @@ export class AppServer {
4701
5262
  const original = run.originalModelGraph;
4702
5263
  if (!original || !run.modelGraph)
4703
5264
  throw new AppServerError('busy', 'The graph is still loading; retry the model change in a moment.');
4704
- const replacement = params.overrideAllNodes ? applyModelOverride(original, { provider, model }) : bindPortableGraphProviders(original, config);
5265
+ if (scopedNode !== undefined && run.modelGraph.nodes[scopedNode]?.type !== 'agent')
5266
+ throw new AppServerError('invalid-params', `Unknown agent node: ${scopedNode}`);
5267
+ const replacement = scopedNode === undefined
5268
+ ? params.overrideAllNodes ? applyModelOverride(original, { provider, model }) : bindPortableGraphProviders(original, config)
5269
+ : undefined;
4705
5270
  // The run's open record is also the crash-recovery source of its model identity. Persist
4706
5271
  // the accepted selection *before* publishing it to the turn-boundary resolver: a model B
4707
5272
  // checkpoint must never outlive a record that still claims the run used model A.
5273
+ let switched;
4708
5274
  await this.serializeRunRecordWrite(run, async () => {
4709
5275
  if (this.run !== run || run.controller.signal.aborted || run.steersClosed)
4710
5276
  throw new AppServerError('invalid-params', 'That run is no longer active.');
@@ -4714,47 +5280,72 @@ export class AppServer {
4714
5280
  const existing = JSON.parse(await readFile(path, 'utf8'));
4715
5281
  if (existing.status !== 'running')
4716
5282
  throw new AppServerError('invalid-params', 'That run is no longer active.');
4717
- existing.provider = provider;
4718
- existing.model = model;
4719
- existing.liveModelChanged = true;
4720
- if (params.overrideAllNodes)
4721
- existing.overrideAllNodes = true;
4722
- else
4723
- delete existing.overrideAllNodes;
4724
- // Effort from a previous provider is invalid on providers that do not support it.
4725
- // The open record must be as resumable as the terminal record.
4726
- if (!['openai-compatible', 'opencode-go'].includes(config.providers.find(item => item.id === provider)?.type ?? ''))
4727
- delete existing.reasoningEffort;
5283
+ if (scopedNode !== undefined) {
5284
+ // The run's own pair stands: only the named node's pair is recorded, so a resume re-applies
5285
+ // it on top of the bound graph and everything else runs as the graph names. The run-scoped
5286
+ // branch below rebuilds from the graph's own selections, which is why it clears the map.
5287
+ const node = run.modelGraph.nodes[scopedNode];
5288
+ // The node's effective pair is what a previous switch moved it to, not what the graph
5289
+ // originally pinned: `modelGraph` is left untouched by a node switch, so the map it wrote
5290
+ // is the only place the first switch's pair still lives.
5291
+ const existingOverride = existing.nodeModelOverrides?.[scopedNode];
5292
+ const previousProvider = existingOverride?.provider ?? (typeof node.provider === 'string' ? node.provider : String(existing.provider ?? ''));
5293
+ const previousModel = existingOverride?.model ?? (typeof node.model === 'string' ? node.model
5294
+ : node.provider === undefined ? existing.model
5295
+ : config.providers.find(item => item.id === node.provider)?.model);
5296
+ existing.nodeModelOverrides = { ...(existing.nodeModelOverrides ?? {}), [scopedNode]: { provider, model } };
5297
+ // The switch still moved a model under a checkpoint, so a resume owes that node the same
5298
+ // reconciliation a run-level switch gets; the record's own pair is what it stays.
5299
+ existing.liveModelChanged = true;
5300
+ switched = { scope: 'node', from: { provider: previousProvider, ...(previousModel === undefined ? {} : { model: String(previousModel) }) }, nodeName: node.name };
5301
+ }
5302
+ else {
5303
+ switched = { scope: 'run', from: { provider: String(existing.provider ?? ''), ...(existing.model === undefined ? {} : { model: String(existing.model) }) } };
5304
+ existing.provider = provider;
5305
+ existing.model = model;
5306
+ existing.liveModelChanged = true;
5307
+ if (params.overrideAllNodes)
5308
+ existing.overrideAllNodes = true;
5309
+ else
5310
+ delete existing.overrideAllNodes;
5311
+ delete existing.nodeModelOverrides;
5312
+ // Effort from a previous provider is invalid on providers that do not support it.
5313
+ // The open record must be as resumable as the terminal record.
5314
+ if (!['openai-compatible', 'opencode-go'].includes(config.providers.find(item => item.id === provider)?.type ?? ''))
5315
+ delete existing.reasoningEffort;
5316
+ }
4728
5317
  await writeOpenRunRecord(this.directory, existing);
4729
5318
  // No await after durability: a model call now either sees the previously persisted pair
4730
5319
  // or this one, including its override scope. An unsuccessful write never mutates the
4731
5320
  // graph, the live resolver, or the timer carry.
4732
- for (const [id, source] of Object.entries(replacement.nodes)) {
4733
- const target = run.modelGraph.nodes[id];
4734
- if (!target || target.type !== 'agent')
4735
- continue;
4736
- for (const key of ['provider', 'model']) {
4737
- if (source[key] === undefined)
4738
- delete target[key];
4739
- else
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];
5321
+ if (replacement !== undefined) {
5322
+ for (const [id, source] of Object.entries(replacement.nodes)) {
5323
+ const target = run.modelGraph.nodes[id];
5324
+ if (!target || target.type !== 'agent')
5325
+ continue;
5326
+ for (const key of ['provider', 'model']) {
5327
+ if (source[key] === undefined)
5328
+ delete target[key];
4748
5329
  else
4749
- Object.assign(target.subagents, { [key]: source.subagents[key] });
5330
+ target[key] = source[key];
4750
5331
  }
4751
- for (const role of target.subagents.roles ?? []) {
4752
- const originalRole = source.subagents.roles?.find(item => item.id === role.id);
4753
- for (const key of ['provider', 'model']) {
4754
- if (originalRole?.[key] === undefined)
4755
- delete role[key];
5332
+ if (target.retry && source.retry)
5333
+ target.retry.fallback = structuredClone(source.retry.fallback);
5334
+ if (target.subagents && source.subagents) {
5335
+ for (const key of ['provider', 'model', 'modelPolicy']) {
5336
+ if (source.subagents[key] === undefined)
5337
+ delete target.subagents[key];
4756
5338
  else
4757
- role[key] = originalRole[key];
5339
+ Object.assign(target.subagents, { [key]: source.subagents[key] });
5340
+ }
5341
+ for (const role of target.subagents.roles ?? []) {
5342
+ const originalRole = source.subagents.roles?.find(item => item.id === role.id);
5343
+ for (const key of ['provider', 'model']) {
5344
+ if (originalRole?.[key] === undefined)
5345
+ delete role[key];
5346
+ else
5347
+ role[key] = originalRole[key];
5348
+ }
4758
5349
  }
4759
5350
  }
4760
5351
  }
@@ -4763,12 +5354,37 @@ export class AppServer {
4763
5354
  // and later switches must not resurrect an effort already removed from that record.
4764
5355
  const liveEffort = typeof existing.reasoningEffort === 'string'
4765
5356
  ? reasoningEffort(existing.reasoningEffort) : undefined;
4766
- run.modelSelection = { provider, model, overrideAllNodes: params.overrideAllNodes, config,
4767
- ...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
4768
- revision: (run.modelSelection?.revision ?? 0) + 1 };
5357
+ if (scopedNode !== undefined) {
5358
+ // The scalar pair is the run's own (or its first selection when none exists): a per-node
5359
+ // pick must not read as the pair every other node resolves to.
5360
+ const previous = run.modelSelection;
5361
+ run.modelSelection = {
5362
+ provider: previous?.provider ?? String(existing.provider),
5363
+ model: previous?.model ?? String(existing.model),
5364
+ // The whole-run scope is what it was: a switch that names a node does not widen or clear
5365
+ // it — the resolver gives the node's own override precedence, and every other node keeps
5366
+ // answering from this scope, which is what a whole-run switch rebuilt the graph to.
5367
+ overrideAllNodes: previous?.overrideAllNodes ?? existing.overrideAllNodes === true,
5368
+ // Node-only only while no run-level selection exists: a previous run-scoped pick or
5369
+ // whole-run override already answers for the nodes this switch leaves alone.
5370
+ nodeOnly: previous === undefined ? true : previous.nodeOnly === true,
5371
+ config,
5372
+ ...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
5373
+ // The record's map is the union: it holds what a resume carried before this switch, so
5374
+ // the finalizer's copy — which prefers this map — cannot drop a carried node.
5375
+ nodeOverrides: { ...(existing.nodeModelOverrides ?? previous?.nodeOverrides ?? {}), [scopedNode]: { provider, model } },
5376
+ revision: (previous?.revision ?? 0) + 1,
5377
+ };
5378
+ }
5379
+ else {
5380
+ run.modelSelection = { provider, model, overrideAllNodes: params.overrideAllNodes, config,
5381
+ ...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
5382
+ revision: (run.modelSelection?.revision ?? 0) + 1 };
5383
+ }
4769
5384
  // 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
- if (run.wakeCarry) {
5385
+ // cloned carry. Effort is reconciled by the same provider eligibility as the record. A
5386
+ // per-node switch is not the run's pair, so a timer keeps the pair it would have run on.
5387
+ if (replacement !== undefined && run.wakeCarry) {
4772
5388
  if (liveEffort === undefined)
4773
5389
  delete run.wakeCarry.reasoningEffort;
4774
5390
  else
@@ -4781,8 +5397,173 @@ export class AppServer {
4781
5397
  delete run.wakeCarry.overrideAllNodes;
4782
5398
  }
4783
5399
  });
5400
+ // A marker outside the durability window: the record already guarantees the pair, and the row
5401
+ // only names the switch to the timeline. A run-scoped switch carries no node, so it splits no
5402
+ // card; a node-scoped one is attributed and the timeline starts a new card at it.
5403
+ if (switched !== undefined) {
5404
+ await this.recordRunEvent(run.runId, { type: 'run.model.switched', time: new Date().toISOString(), data: {
5405
+ runId: run.runId,
5406
+ scope: switched.scope,
5407
+ ...(switched.scope === 'node' && scopedNode !== undefined ? { nodeId: scopedNode, nodeName: switched.nodeName } : {}),
5408
+ from: switched.from,
5409
+ to: { provider, model },
5410
+ } });
5411
+ }
4784
5412
  return { ok: true };
4785
5413
  }
5414
+ /**
5415
+ * Change the permission mode a live attempt runs under, without interrupting it.
5416
+ *
5417
+ * The new mode reaches the attempt through its permission control (`ActiveRun.permissionControl`): a
5418
+ * tool call that has not decided yet decides under it, and every approval the attempt is waiting on
5419
+ * is handed back as `policy-changed`, so its tool decides again — a prompt the new mode answers goes
5420
+ * away, and one the new mode still requires is asked again. The mode is saved where the attempt read
5421
+ * it from, so the next task, a resume and a terminal on the same project agree with what is running.
5422
+ */
5423
+ async setRunPermissions(params) {
5424
+ const runId = text(params.runId, 'runId', 200);
5425
+ const next = permissionMode(params.permissions);
5426
+ const live = this.run;
5427
+ if (live === undefined || live.runId !== runId || live.controller.signal.aborted || live.steersClosed) {
5428
+ throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
5429
+ }
5430
+ const change = (live.permissionChanges ?? Promise.resolve()).then(() => this.applyRunPermissions(live, next));
5431
+ live.permissionChanges = change.then(() => undefined, () => undefined);
5432
+ return change;
5433
+ }
5434
+ async applyRunPermissions(live, next) {
5435
+ const stillLive = () => this.run === live && !live.controller.signal.aborted;
5436
+ if (!stillLive())
5437
+ throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
5438
+ const previous = live.permissionControl.permissions ?? 'ask-for-approval';
5439
+ try {
5440
+ // The index cache writes into the workspace, so it stops before Read Only is saved or reaches a
5441
+ // tool, and resumes only after a wider mode is in force — the order `/permissions` keeps too. The
5442
+ // target is set on the run before anything awaits, so a manager the run creates from here on
5443
+ // starts in it; one already being created started in the earlier mode, so the change waits for it
5444
+ // and suspends it before Read Only is acknowledged.
5445
+ if (next === 'read-only' || next === 'plan') {
5446
+ live.codeIntelPermissions = next;
5447
+ await live.codeIntelReady;
5448
+ await this.syncCodeIntelPermissions(live);
5449
+ }
5450
+ await this.saveRunPermissions(live, next, stillLive);
5451
+ }
5452
+ catch (error) {
5453
+ // Nothing was saved, or the index could not be suspended: the run keeps its mode, and the index
5454
+ // goes back to that mode, so a later pick of it, or a retry, starts from a manager in step.
5455
+ live.codeIntelPermissions = live.permissionControl.permissions ?? previous;
5456
+ await live.codeIntelReady;
5457
+ await this.syncCodeIntelPermissions(live).catch(syncError => this.log('warn', `Could not restore code intelligence after a refused mode change: ${message(syncError)}`));
5458
+ throw error;
5459
+ }
5460
+ // The run may have ended while the mode was being saved. The saved mode still governs the next
5461
+ // task, which is what the caller asked for once this attempt is gone.
5462
+ if (!stillLive())
5463
+ return { ok: true, permissions: next, settled: [] };
5464
+ // A pick of the mode the run already has changes nothing in it: re-asking its open prompts would
5465
+ // only make them flicker. The index is still brought in step below.
5466
+ const settled = await this.switchLiveRunPermissions(live, next, previous);
5467
+ live.codeIntelPermissions = next;
5468
+ await live.codeIntelReady;
5469
+ await this.syncCodeIntelPermissions(live).catch(error => this.log('warn', `Could not apply the new mode to code intelligence: ${message(error)}`));
5470
+ return { ok: true, permissions: next, settled };
5471
+ }
5472
+ /**
5473
+ * Move a live run's control to `next` and journal the change, settling any prompt that waited
5474
+ * across it. Shared by the saved switch (`run.setPermissions`) and the run-scoped plan-approval
5475
+ * flip: neither re-asks a mode the run already has.
5476
+ */
5477
+ async switchLiveRunPermissions(live, next, previous) {
5478
+ if (next === previous)
5479
+ return [];
5480
+ live.permissionControl.permissions = next;
5481
+ live.permissionControl.yolo = next === 'full-access';
5482
+ live.permissionRevision += 1;
5483
+ const settled = [...live.approvals];
5484
+ // Journaled before the prompts are handed back, so the record reads as the change and then the
5485
+ // decisions it led to. The same record emits `run.event`, which is how every window — including
5486
+ // one that did not make the change — drops the prompts it no longer has to show.
5487
+ await this.recordRunEvent(live.runId, {
5488
+ type: 'run.permissions.changed',
5489
+ time: new Date().toISOString(),
5490
+ data: { runId: live.runId, sessionId: live.sessionId, permissions: next, previous, settled },
5491
+ });
5492
+ for (const id of settled)
5493
+ this.pending.get(id)?.('policy-changed');
5494
+ return settled;
5495
+ }
5496
+ /**
5497
+ * The plan-approval flip. Unlike `run.setPermissions` it is run-scoped only: approving a plan
5498
+ * never rewrites the saved workspace default, so the next task plans again. The run continues in
5499
+ * the workspace's saved default when that is an editing mode, and in Ask for approval otherwise.
5500
+ */
5501
+ async approvePlan(live) {
5502
+ const change = (live.permissionChanges ?? Promise.resolve()).then(async () => {
5503
+ if (this.run !== live || live.controller.signal.aborted)
5504
+ throw new AppServerError('not-found', 'That task is not running on this engine. The plan applies to the next task.');
5505
+ const config = await loadConfig(this.directory);
5506
+ const saved = config.workspacePermissions?.[workspacePermissionKey(live.workspace)];
5507
+ const next = saved === 'ask-for-approval' || saved === 'approve-for-me' || saved === 'full-access' ? saved : 'ask-for-approval';
5508
+ await this.switchLiveRunPermissions(live, next, live.permissionControl.permissions ?? 'ask-for-approval');
5509
+ live.codeIntelPermissions = next;
5510
+ await live.codeIntelReady;
5511
+ await this.syncCodeIntelPermissions(live).catch(error => this.log('warn', `Could not apply the new mode to code intelligence: ${message(error)}`));
5512
+ return next;
5513
+ });
5514
+ live.permissionChanges = change.then(() => undefined, () => undefined);
5515
+ return change;
5516
+ }
5517
+ /** Save a live mode where the attempt reads it from: its own record when bound, the workspace default otherwise. */
5518
+ async saveRunPermissions(live, next, stillLive) {
5519
+ if (live.boundPermissions) {
5520
+ // The attempt's own record is where a resume reads a bound mode back from.
5521
+ await this.serializeRunRecordWrite(live, async () => {
5522
+ if (!stillLive())
5523
+ throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
5524
+ const existing = JSON.parse(await readFile(runRecordPath(this.directory, live.runId, 'json'), 'utf8'));
5525
+ if (existing.status !== 'running')
5526
+ throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
5527
+ existing.permissions = next;
5528
+ await writeOpenRunRecord(this.directory, existing);
5529
+ });
5530
+ }
5531
+ else {
5532
+ // Serialized with every other configuration write, exactly as `run.start` saves a picked mode.
5533
+ const saved = await this.serializeConfig(async () => {
5534
+ try {
5535
+ return await changeConfigFile(this.directory, current => ({ ...current, workspacePermissions: { ...current.workspacePermissions, [workspacePermissionKey(live.workspace)]: next } }));
5536
+ }
5537
+ catch (error) {
5538
+ if (error instanceof AppServerError)
5539
+ throw error;
5540
+ throw error instanceof ConfigConflictError ? new AppServerError('busy', message(error)) : new AppServerError('invalid-params', message(error));
5541
+ }
5542
+ });
5543
+ this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
5544
+ }
5545
+ }
5546
+ /**
5547
+ * Bring the workspace's code-intelligence manager, once it exists, to the mode the run holds for it.
5548
+ *
5549
+ * One change at a time, each reading the target when it runs, so the last one leaves the manager on
5550
+ * the latest target. A manager already on the target is left alone; one whose change failed is in an
5551
+ * unknown mode, so the next sync applies the target again rather than trusting it.
5552
+ */
5553
+ syncCodeIntelPermissions(live) {
5554
+ const apply = async () => {
5555
+ const manager = this.codeIntel?.workspace === live.workspace ? this.codeIntel.manager : undefined;
5556
+ const target = live.codeIntelPermissions;
5557
+ if (!manager || live.codeIntelApplied === target)
5558
+ return;
5559
+ live.codeIntelApplied = undefined;
5560
+ await manager.setPermissions(target);
5561
+ live.codeIntelApplied = target;
5562
+ };
5563
+ const step = (live.codeIntelSync ?? Promise.resolve()).then(apply);
5564
+ live.codeIntelSync = step.then(() => undefined, () => undefined);
5565
+ return step;
5566
+ }
4786
5567
  async resolveModel(config, id, model, signal, reasoningEffort) {
4787
5568
  const provider = config.providers.find(item => item.id === id);
4788
5569
  if (!provider)
@@ -4851,14 +5632,14 @@ export class AppServer {
4851
5632
  }
4852
5633
  // The manager takes its own read-only branch and its own disabled branch, so it is always
4853
5634
  // created; what matters is that both guards reach it rather than indexing by default.
4854
- const manager = await CodeIntelligenceManager.create({ workspace: root, config, permissions, onEvent: event => { this.runEvent(event); } });
5635
+ const manager = await this.createCodeIntelligence({ workspace: root, config, permissions, onEvent: event => { this.runEvent(event); } });
4855
5636
  this.codeIntel = { workspace: root, signature, manager };
4856
5637
  return manager;
4857
5638
  }
4858
5639
  /** Code-intelligence events belong to the active run's stream when one is running. */
4859
5640
  runEvent(event) {
4860
5641
  if (this.run) {
4861
- void this.recordRunEvent(this.run.runId, runRecordPath(this.directory, this.run.runId, 'jsonl'), event);
5642
+ void this.recordRunEvent(this.run.runId, event);
4862
5643
  // Code intelligence reports through this separate sink, not GraphRunOptions.onEvent.
4863
5644
  // Keep the session-wide debug account complete as well as the resumable run journal.
4864
5645
  void this.trajectory?.recordEvent(event);
@@ -4866,32 +5647,33 @@ export class AppServer {
4866
5647
  else
4867
5648
  this.emit('codeintel.event', { event });
4868
5649
  }
5650
+ /** The journal writer of one run, created on its first event. */
5651
+ journalFor(runId) {
5652
+ let writer = this.journals.get(runId);
5653
+ if (writer === undefined) {
5654
+ // The run keeps going when an append fails (a storage hiccup must not kill the user's work).
5655
+ // The writer holds the event and writes it once the file accepts appends again, so a disk
5656
+ // that filled for a minute leaves a complete journal rather than one no resume can trust.
5657
+ writer = createRunJournalWriter(this.directory, runId, { onFailure: error => this.log('warn', `Could not append to the run journal: ${message(error)}`) });
5658
+ this.journals.set(runId, writer);
5659
+ }
5660
+ return writer;
5661
+ }
4869
5662
  /**
4870
5663
  * Journal first, then the client: a client that missed an event can re-read the record.
4871
5664
  *
4872
- * `runs/` is created here rather than assumed: the terminal client creates it during startup,
4873
- * and this mode returns before that code runs, so a fresh configuration home would otherwise
4874
- * fail every append with ENOENT and silently produce no record at all.
5665
+ * The writer creates `runs/` when the first append finds it missing: the terminal client creates
5666
+ * it during startup, and this mode returns before that code runs, so a fresh configuration home
5667
+ * would otherwise fail every append with ENOENT. Appends are ordered: the filesystem does not
5668
+ * finish concurrent appends in the order they were started.
4875
5669
  */
4876
- async recordRunEvent(runId, journal, event) {
5670
+ async recordRunEvent(runId, event) {
4877
5671
  // The provider answered once, so a naming request queued behind this turn no longer competes
4878
5672
  // with the run's opening request: from here the run works through the turn's tools, and the
4879
5673
  // title can take the endpoint without delaying the work it names.
4880
5674
  if (event.type === 'agent.model.completed')
4881
5675
  this.releaseTitleWaiter(runId);
4882
- try {
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
- }
5676
+ await this.journalFor(runId).append(event);
4895
5677
  if (event.type === 'graph.started' || event.type === 'graph.node.started')
4896
5678
  bootMark(`run.event.${event.type}`, typeof event.data?.nodeId === 'string' ? `node=${event.data.nodeId}` : undefined);
4897
5679
  this.emit('run.event', { runId, event });
@@ -4917,18 +5699,34 @@ export class AppServer {
4917
5699
  async approve(runId, name, args, signal) {
4918
5700
  const id = randomUUID();
4919
5701
  const sessionId = this.run?.sessionId;
5702
+ // The tool decided to ask under the mode in force now. A live change that lands while the prompt
5703
+ // is still being recorded finds nothing pending to hand back, so the prompt checks for itself
5704
+ // before it is shown: asking under a mode the user has already left is the prompt they switched
5705
+ // modes to get rid of.
5706
+ const live = this.run?.runId === runId ? this.run : undefined;
5707
+ const revision = live?.permissionRevision;
4920
5708
  if (sessionId)
4921
5709
  await writePendingAgentInteraction(this.directory, {
4922
5710
  version: 1, id, runId, sessionId, kind: 'approval',
4923
5711
  prompt: 'Approval required for tool ' + name, createdAt: new Date().toISOString(),
4924
5712
  }).catch(error => this.log('warn', 'Could not record pending approval: ' + message(error)));
5713
+ if (live !== undefined && live.permissionRevision !== revision) {
5714
+ if (sessionId)
5715
+ await removePendingAgentInteraction(this.directory, runId, id)
5716
+ .catch(error => this.log('warn', 'Could not clear pending approval: ' + message(error)));
5717
+ return 'policy-changed';
5718
+ }
4925
5719
  this.emit('run.approval', { runId, id, name, arguments: args });
4926
5720
  this.emit('run.state', { runId, state: 'awaiting-approval' });
4927
5721
  let answer;
4928
5722
  try {
4929
- answer = await this.interaction(id, signal);
5723
+ // Registered in the same turn the prompt becomes pending, so no live change can fall between.
5724
+ const answered = this.interaction(id, signal);
5725
+ live?.approvals.add(id);
5726
+ answer = await answered;
4930
5727
  }
4931
5728
  finally {
5729
+ live?.approvals.delete(id);
4932
5730
  if (sessionId)
4933
5731
  await removePendingAgentInteraction(this.directory, runId, id)
4934
5732
  .catch(error => this.log('warn', 'Could not clear pending approval: ' + message(error)));
@@ -5100,7 +5898,7 @@ export class AppServer {
5100
5898
  // from that journal, so the user's own message stays where it was said even after the attempt
5101
5899
  // stops and its card is replaced by the work it did. The same record emits `run.event`, which
5102
5900
  // is what draws the row live.
5103
- await this.recordRunEvent(runId, runRecordPath(this.directory, runId, 'jsonl'), {
5901
+ await this.recordRunEvent(runId, {
5104
5902
  type: 'run.steered',
5105
5903
  time: entry.at,
5106
5904
  data: { runId, sessionId: live.sessionId, steerId: entry.id, text: entry.text, ...(refs.length ? { attachments: refs } : {}) },
@@ -5123,6 +5921,18 @@ export class AppServer {
5123
5921
  * them into B's account. `graphStorageAccess` claims an unclaimed directory for a confirmed account —
5124
5922
  * the account the builder claims it for — and reports the ones that are still shared.
5125
5923
  */
5924
+ /** Whether a stored graph selection names a graph whose latest revision is soft-deleted. */
5925
+ async selectionIsDeleted(selection) {
5926
+ if (selection === 'default' || selection.includes(':'))
5927
+ return false;
5928
+ try {
5929
+ const { directory } = await this.graphDirectory();
5930
+ return isDeletedGraph(await loadGraph(selection, undefined, directory));
5931
+ }
5932
+ catch {
5933
+ return false;
5934
+ }
5935
+ }
5126
5936
  async graphDirectory(canClaim = false) {
5127
5937
  const subject = await currentGraphSubject();
5128
5938
  // Signed-in graphs live under the account's storage; the local directory is the fallback and the
@@ -5171,7 +5981,8 @@ export class AppServer {
5171
5981
  const kept = confirmed ? (await readGraphQuota(directory, saved)).freeGraphId : undefined;
5172
5982
  if (status.signedIn && !free)
5173
5983
  graphs.push({ id: ANDORRA_GRAPH_SELECTION, name: 'Andorra', revision: getAndorraHarness().revision, preset: true });
5174
- for (const graph of saved) {
5984
+ // Deleted graphs leave the picker; the quota above still counts them.
5985
+ for (const graph of withoutDeletedGraphs(saved)) {
5175
5986
  // A kept graph over the allowance (one saved on a paid plan) stays editable but is not offered to run.
5176
5987
  if (graph.id === 'default' || (free && (graph.id !== kept || freeTierGraphViolation(graph) !== undefined)))
5177
5988
  continue;
@@ -5181,7 +5992,11 @@ export class AppServer {
5181
5992
  // The identity this listing belongs to travels with it: a client reads the listing and its own account
5182
5993
  // in one refresh, and an account that changed between the two requests would otherwise be hidden —
5183
5994
  // one account's plan published with the other account's graph names.
5184
- return { graphs, selected: configuredGraphSelection(await loadConfig(this.directory), subject), paid: membership.paid === true, ...(subject === undefined ? {} : { subject }) };
5995
+ // A saved selection that names a deleted graph reads as Default until the graph is restored; the
5996
+ // selection itself is kept, so restoring brings it back.
5997
+ const configured = configuredGraphSelection(await loadConfig(this.directory), subject);
5998
+ const selected = saved.some(graph => graph.id === configured && isDeletedGraph(graph)) ? 'default' : configured;
5999
+ return { graphs, selected, paid: membership.paid === true, ...(subject === undefined ? {} : { subject }) };
5185
6000
  }
5186
6001
  /**
5187
6002
  * The shareable file of one library Agent, for the desktop's Share action to write into the
@@ -6079,7 +6894,7 @@ export class AppServer {
6079
6894
  }
6080
6895
  /** Say what a session is waiting on. An empty list is a real answer: it is what ends a wait. */
6081
6896
  emitPullRequest(sessionId, pullRequest) {
6082
- this.emit('session.pullRequest.updated', { sessionId, pullRequest });
6897
+ this.emit('session.pullRequest.updated', { sessionId, pullRequest: pullRequestForClients(pullRequest) });
6083
6898
  }
6084
6899
  /**
6085
6900
  * Start tracking `ref` for the session. A PR already tracked under the same URL keeps its settings, so a
@@ -6089,17 +6904,24 @@ export class AppServer {
6089
6904
  const attached = await withPullRequest(this.directory, sessionId, async () => {
6090
6905
  const current = await readPullRequest(this.directory, sessionId);
6091
6906
  let next = current?.url === ref.url ? current : newPullRequest(ref);
6092
- // The title, state and auto-merge are read once on attach; a PR that cannot be read is still tracked, as open.
6907
+ // The title, state and auto-merge are read once on attach, as an account that can see the PR, and that account
6908
+ // is kept for every later call. A PR that cannot be read is still tracked, as open: when no signed-in account
6909
+ // can read it the row says so, and an outage is logged and left to the next read (the watcher's poll, or a
6910
+ // draft or auto-merge change).
6093
6911
  if (next !== current) {
6094
- const seen = await viewPullRequest(this.gh, ref.url).catch(() => undefined);
6095
- if (seen)
6096
- next = { ...next, title: seen.title, state: seen.state, mergeWhenReady: seen.autoMerge };
6912
+ const read = await readPullRequestAsAnyAccount(this.gh, ref.url);
6913
+ if (read.seen)
6914
+ next = { ...next, title: read.seen.title, state: read.seen.state, mergeWhenReady: read.seen.autoMerge, ...(read.ghUser === undefined ? {} : { ghUser: read.ghUser }) };
6915
+ else if (read.unreadable)
6916
+ next = { ...next, watchError: noAccountMessage(ref.url) };
6917
+ else if ('failed' in read)
6918
+ this.log('warn', `Could not read ${ref.url} while attaching it: ${message(read.failed)}`);
6097
6919
  }
6098
6920
  // The run that attached it names the graph, model and effort an Auto-fix run continues under.
6099
6921
  if (carry !== undefined)
6100
6922
  next = { ...next, carry: structuredClone(carry) };
6101
6923
  if (Object.keys(settings).length)
6102
- next = await applyPullRequestSettings(this.gh, next, settings);
6924
+ next = await applyPullRequestSettingsAsReadableAccount(this.gh, next, settings);
6103
6925
  await writePullRequest(this.directory, sessionId, next);
6104
6926
  return next;
6105
6927
  });
@@ -6115,7 +6937,7 @@ export class AppServer {
6115
6937
  throw new AppServerError('not-found', 'This session has no pull request.');
6116
6938
  let next;
6117
6939
  try {
6118
- next = await applyPullRequestSettings(this.gh, current, settings);
6940
+ next = await applyPullRequestSettingsAsReadableAccount(this.gh, current, settings);
6119
6941
  }
6120
6942
  catch (error) {
6121
6943
  throw new AppServerError('remote', message(error));
@@ -6193,8 +7015,6 @@ export class AppServer {
6193
7015
  settleSessionTimers(sessionId) {
6194
7016
  this.emitTimers(sessionId);
6195
7017
  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
7018
  }
6199
7019
  /** Arm the next deadline check, across every session this engine holds wakes for. */
6200
7020
  armTimerCheck(minimumDelayMs = 1) {
@@ -6240,6 +7060,134 @@ export class AppServer {
6240
7060
  .catch(error => this.log('error', `Self-wake delivery failed: ${message(error)}`))
6241
7061
  .finally(() => { this.timerDeliveryTask = undefined; });
6242
7062
  }
7063
+ /**
7064
+ * Say a wake will never be delivered: drop it, publish the shorter wait list, and tell the user why.
7065
+ *
7066
+ * A wake is the agent's own reminder about work that is over or was replaced, and starting it as a new task
7067
+ * would restart that work behind the user's back. Dropping it silently would hide a promise the agent made,
7068
+ * so the reason goes out with `timers.spent` - which a window shows as a notice - and into the log.
7069
+ */
7070
+ spendWake(timer, reason) {
7071
+ this.timers.settle(timer.id);
7072
+ this.autoFixWakes.delete(timer.id);
7073
+ this.log('info', `Self-wake ${timer.id} was not delivered: ${reason}`);
7074
+ const sessionId = timer.owner;
7075
+ if (sessionId === undefined)
7076
+ return;
7077
+ void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
7078
+ this.emit('timers.spent', { sessionId, timerId: timer.id, prompt: timer.prompt, reason });
7079
+ this.emitTimers(sessionId);
7080
+ }
7081
+ /**
7082
+ * Spend the session's node-armed wakes that belong to an attempt in `attempts` and satisfy `spent`.
7083
+ *
7084
+ * Wakes another surface is in the middle of delivering are left alone: that delivery decides what became of
7085
+ * them. Wakes no graph node armed are never touched here.
7086
+ */
7087
+ spendAttemptWakes(sessionId, attempts, reason, spent = () => true) {
7088
+ for (const timer of this.timers.list(sessionId)) {
7089
+ if (timer.origin === undefined || !attempts.has(timer.origin.runId) || this.timers.isHeld(timer.id))
7090
+ continue;
7091
+ if (spent(timer.origin))
7092
+ this.spendWake(timer, reason);
7093
+ }
7094
+ }
7095
+ /**
7096
+ * Hand every due wake the live run itself armed (or an attempt that run continues) to that run, as a
7097
+ * steering message its working node reads at the next turn boundary.
7098
+ *
7099
+ * The wake is settled once the message is queued: from there the run owns it. One the run ends before
7100
+ * reading is put back on the registry by the finalizer, where the rules for a finished run decide it.
7101
+ */
7102
+ steerDueWakes(live) {
7103
+ if (live.steersClosed || live.controller.signal.aborted)
7104
+ return;
7105
+ const own = new Set([live.runId, ...(live.lineage ?? [])]);
7106
+ for (;;) {
7107
+ const timer = this.timers.takeDueOne(Date.now(), live.sessionId, candidate => candidate.origin !== undefined && own.has(candidate.origin.runId));
7108
+ if (timer === undefined)
7109
+ return;
7110
+ const at = new Date().toISOString();
7111
+ const entry = { id: `${live.runId}#wake-${timer.id}`, text: timer.prompt,
7112
+ // The model reads it as its own reminder, not as the user speaking.
7113
+ content: timerReminderText(timer.prompt), images: [], at, wake: timer };
7114
+ live.steers.push(entry);
7115
+ this.timers.settle(timer.id);
7116
+ void clearWakeClaim(this.directory, live.sessionId, timer.id).catch(() => { });
7117
+ this.log('info', `Delivering self-wake ${timer.id} into the running attempt ${live.runId}`);
7118
+ // Journaled like a steer the user typed, so the transcript keeps the reminder where the node read it -
7119
+ // marked as a wake, so no window draws it as the user's message.
7120
+ void this.recordRunEvent(live.runId, { type: 'run.steered', time: at,
7121
+ data: { runId: live.runId, sessionId: live.sessionId, steerId: entry.id, text: entry.text, wake: 'timer' } });
7122
+ this.emitTimers(live.sessionId);
7123
+ }
7124
+ }
7125
+ /**
7126
+ * Where a node-armed wake goes once no run has the engine: the attempt to continue, a reason it is spent, or
7127
+ * a reason to wait.
7128
+ *
7129
+ * It continues only the session's newest attempt, and only when that attempt is the one that armed it or a
7130
+ * continuation of it, the attempt stopped without finishing, the user did not stop it, and the arming node
7131
+ * has not finished since the wake was armed. Anything else means the work the reminder was about is over or
7132
+ * was replaced by a newer turn, and it is spent.
7133
+ */
7134
+ async wakeContinuation(timer, origin, record) {
7135
+ const newest = record.history?.at(-1)?.runId;
7136
+ if (newest === undefined)
7137
+ return { spent: 'the session no longer has the attempt that set it' };
7138
+ // The newest attempt's lineage, newest first: the reminder belongs to it only when the attempt that armed
7139
+ // it is in that chain.
7140
+ const chain = [];
7141
+ let newestRecord;
7142
+ for (let cursor = newest; cursor !== undefined && chain.length < MAX_RESUME_LINEAGE && !chain.includes(cursor);) {
7143
+ chain.push(cursor);
7144
+ if (cursor === origin.runId)
7145
+ break;
7146
+ let value;
7147
+ try {
7148
+ value = JSON.parse(await readFile(runRecordPath(this.directory, cursor, 'json'), 'utf8'));
7149
+ }
7150
+ catch {
7151
+ break;
7152
+ }
7153
+ if (cursor === newest)
7154
+ newestRecord = value;
7155
+ cursor = typeof value.resumedFrom === 'string' ? value.resumedFrom : undefined;
7156
+ }
7157
+ if (!chain.includes(origin.runId))
7158
+ return { spent: 'a newer turn in this session replaced the attempt that set it' };
7159
+ newestRecord ??= JSON.parse(await readFile(runRecordPath(this.directory, newest, 'json'), 'utf8'));
7160
+ const status = typeof newestRecord.status === 'string' ? newestRecord.status : undefined;
7161
+ if (status === 'succeeded')
7162
+ return { spent: 'the attempt that set it has finished' };
7163
+ if (status === 'cancelled')
7164
+ return { spent: 'the attempt that set it was stopped' };
7165
+ if (status === 'running' && typeof newestRecord.pid === 'number' && isPidAlive(newestRecord.pid))
7166
+ return { wait: 'its attempt is still running in another engine' };
7167
+ // The node finished after the reminder was set: what it was waiting on is behind it, and continuing the
7168
+ // attempt from wherever it stopped would hand the reminder to work it was never about.
7169
+ const armedAt = timer.fireAt - timer.seconds * 1_000;
7170
+ for (const attempt of chain) {
7171
+ const journal = await readFile(runRecordPath(this.directory, attempt, 'jsonl'), 'utf8').catch(() => '');
7172
+ for (const line of journal.split('\n')) {
7173
+ if (!line.includes('"graph.node.completed"') || !line.includes(origin.nodeId))
7174
+ continue;
7175
+ let event;
7176
+ try {
7177
+ event = JSON.parse(line);
7178
+ }
7179
+ catch {
7180
+ continue;
7181
+ }
7182
+ if (event.type !== 'graph.node.completed' || event.data?.nodeId !== origin.nodeId)
7183
+ continue;
7184
+ const time = typeof event.time === 'string' ? Date.parse(event.time) : Number.NaN;
7185
+ if (Number.isNaN(time) || time >= armedAt)
7186
+ return { spent: 'the node that set it has finished its work' };
7187
+ }
7188
+ }
7189
+ return { resume: newest };
7190
+ }
6243
7191
  /**
6244
7192
  * Give every wake that has come due to the session that armed it, one run at a time.
6245
7193
  *
@@ -6263,6 +7211,11 @@ export class AppServer {
6263
7211
  // A wake waits out a run that is already going: a deadline says the earliest a prompt may be given,
6264
7212
  // not the moment it is. Look again when that run ends, or on the retry below if it never says so.
6265
7213
  if (this.run !== undefined || this.starting) {
7214
+ // ...unless the run that has the engine is the wake's own work: a reminder the arming node set while
7215
+ // it waits on something is read by that node at its next turn boundary, the way a message the user
7216
+ // types into the live run is. Every other wake waits for the run to end.
7217
+ if (this.run !== undefined && !this.starting)
7218
+ this.steerDueWakes(this.run);
6266
7219
  this.armTimerCheck();
6267
7220
  return;
6268
7221
  }
@@ -6305,41 +7258,93 @@ export class AppServer {
6305
7258
  this.emitTimers(sessionId);
6306
7259
  continue;
6307
7260
  }
6308
- // An Auto-fix wake is delivered only while the session still wants it: the PR may have been dismissed,
6309
- // replaced or had Auto-fix switched off — here or in another engine — while the wake waited out a run. A
6310
- // wake dropped here costs nothing it should keep: a still-wanted fix is re-armed from the record's pending
6311
- // mark on the next poll.
6312
- if (this.autoFixWakes.has(timer.id) && !await autoFixWakeWanted(this.directory, sessionId, timer.id).catch(() => false)) {
6313
- this.autoFixWakes.delete(timer.id);
6314
- this.timers.settle(timer.id);
6315
- void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
6316
- this.emitTimers(sessionId);
6317
- this.log('info', `Dropped Auto-fix wake ${timer.id}: session ${sessionId} no longer asks for it`);
6318
- continue;
7261
+ // An Auto-fix wake is delivered only while the session still wants it and GitHub, asked now, says the PR is
7262
+ // still open: the PR may have been dismissed, replaced or had Auto-fix switched off — here or in another
7263
+ // engine — or been merged or closed by hand while the wake waited out a run. A wake dropped here costs nothing
7264
+ // it should keep: a still-wanted fix is re-armed from the record's pending mark on the next poll.
7265
+ if (this.autoFixWakes.has(timer.id)) {
7266
+ let confirmed;
7267
+ try {
7268
+ confirmed = await confirmAutoFixWake(this.directory, this.gh, sessionId, timer.id);
7269
+ }
7270
+ catch (error) {
7271
+ // Not sent unconfirmed: the wake is kept and GitHub is asked again later. One withdrawn while GitHub was
7272
+ // being asked (Auto-fix switched off, the PR dismissed) is not brought back.
7273
+ if (this.timers.get(timer.id) !== undefined)
7274
+ this.timers.restore(timer, AUTO_FIX_CONFIRM_RETRY_MS);
7275
+ nextCheckIn = WAKE_RETRY_MS;
7276
+ this.log('warn', `Auto-fix wake ${timer.id} waits: GitHub could not confirm the pull request is still open (${message(error)})`);
7277
+ continue;
7278
+ }
7279
+ if (confirmed.pullRequest)
7280
+ this.emitPullRequest(sessionId, confirmed.pullRequest);
7281
+ if (!confirmed.deliver) {
7282
+ this.autoFixWakes.delete(timer.id);
7283
+ this.timers.settle(timer.id);
7284
+ void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
7285
+ this.emitTimers(sessionId);
7286
+ this.log('info', confirmed.pullRequest
7287
+ ? `Dropped Auto-fix wake ${timer.id}: ${confirmed.pullRequest.url} is ${confirmed.pullRequest.state}, so Auto-fix is off`
7288
+ : `Dropped Auto-fix wake ${timer.id}: session ${sessionId} no longer asks for it`);
7289
+ continue;
7290
+ }
7291
+ }
7292
+ // A wake a graph node armed goes back to that node's work: as a continuation of the attempt it armed, from
7293
+ // that node's checkpoint. One with nothing left to continue is spent, never started as a new task that
7294
+ // enters the graph at its entry node with the agent's reminder for a prompt.
7295
+ let resume;
7296
+ if (timer.origin !== undefined) {
7297
+ let plan;
7298
+ try {
7299
+ plan = await this.wakeContinuation(timer, timer.origin, record);
7300
+ }
7301
+ catch (error) {
7302
+ plan = { wait: `its attempt could not be read (${message(error)})` };
7303
+ }
7304
+ if ('wait' in plan) {
7305
+ this.timers.restore(timer);
7306
+ nextCheckIn = WAKE_RETRY_MS;
7307
+ this.log('info', `Self-wake ${timer.id} waits: ${plan.wait}`);
7308
+ continue;
7309
+ }
7310
+ if ('spent' in plan) {
7311
+ this.spendWake(timer, plan.spent);
7312
+ continue;
7313
+ }
7314
+ resume = plan.resume;
6319
7315
  }
6320
- this.log('info', `Delivering self-wake ${timer.id} to session ${sessionId}`);
7316
+ 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
7317
  // The row keeps saying the session is waiting until a run is really there to carry the prompt. The list
6322
7318
  // is republished after the attempt rather than before it, so there is no moment between the deadline and
6323
7319
  // `run.started` in which the session reads as done with the user while its prompt has gone nowhere.
6324
7320
  try {
6325
7321
  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
7322
  // The wake is settled below, once this call has returned: a run of this session then carries the
6331
7323
  // prompt, and only then is the wake no longer owed. Until that point it stays on the list, including
6332
7324
  // while this start is still preparing — which is what tells a window reattaching in that moment that the
6333
7325
  // wake is this engine's, and that its session is still waiting rather than free.
6334
- await this.startRun({ workspace: record.workspace, sessionId, task: timer.prompt,
6335
- ...(carry?.graph === undefined ? {} : { graph: carry.graph }),
6336
- ...(carry?.provider === undefined ? {} : { provider: carry.provider }),
6337
- ...(carry?.model === undefined ? {} : { model: carry.model }),
6338
- ...(carry?.reasoningEffort === undefined ? {} : { reasoningEffort: carry.reasoningEffort }),
6339
- ...(carry?.overrideAllNodes === undefined ? {} : { overrideAllNodes: carry.overrideAllNodes }),
6340
- ...(carry?.panelBrowserRelay === undefined ? {} : { panelBrowserRelay: carry.panelBrowserRelay }),
6341
- ...(carry?.input === undefined ? {} : { input: carry.input }),
6342
- ...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId });
7326
+ if (resume !== undefined) {
7327
+ // The continuation runs under the attempt's own recorded selections (`resumeRun` reads them from its
7328
+ // record), with the reminder as the direction the re-entered node reads at its first turn boundary.
7329
+ // Only the panel relay is this engine's own and not the record's, so it rides along.
7330
+ await this.resumeRun({ runId: resume, direction: timer.prompt,
7331
+ ...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake: 'timer', wakeNode: timer.origin.nodeId, freshAllowance: true });
7332
+ }
7333
+ else {
7334
+ // A wake no graph node armed - an Auto-fix wake, or one held from before wakes named their node -
7335
+ // starts a run the way it always did. It carries the selections of the run that armed it (see
7336
+ // `WakeCarry`): starting it with only the workspace, session and prompt would hand it whatever the
7337
+ // configuration says today.
7338
+ await this.startRun({ workspace: record.workspace, sessionId, task: timer.prompt,
7339
+ ...(carry?.graph === undefined ? {} : { graph: carry.graph }),
7340
+ ...(carry?.provider === undefined ? {} : { provider: carry.provider }),
7341
+ ...(carry?.model === undefined ? {} : { model: carry.model }),
7342
+ ...(carry?.reasoningEffort === undefined ? {} : { reasoningEffort: carry.reasoningEffort }),
7343
+ ...(carry?.overrideAllNodes === undefined ? {} : { overrideAllNodes: carry.overrideAllNodes }),
7344
+ ...(carry?.panelBrowserRelay === undefined ? {} : { panelBrowserRelay: carry.panelBrowserRelay }),
7345
+ ...(carry?.input === undefined ? {} : { input: carry.input }),
7346
+ ...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: this.autoFixWakes.has(timer.id) ? 'auto-fix' : 'timer' });
7347
+ }
6343
7348
  // Given: a run of this session carries the prompt, so the wake is no longer owed and the row stops waiting.
6344
7349
  this.timers.settle(timer.id);
6345
7350
  this.autoFixWakes.delete(timer.id);
@@ -6374,11 +7379,12 @@ export class AppServer {
6374
7379
  this.log('info', `Self-wake ${timer.id} waits: ${message(error)}`);
6375
7380
  break;
6376
7381
  }
6377
- // Any other refusal describes the task, not the moment. The wake is spent, and a row must not keep
7382
+ // Any other refusal describes the task, not the moment — for a continuation, that the attempt has
7383
+ // nothing left to continue. The wake is spent, said where the user sees it, and a row must not keep
6378
7384
  // waiting on one that will never be delivered.
6379
7385
  this.log('error', `Self-wake ${timer.id} could not start: ${message(error)}`);
6380
- this.timers.settle(timer.id);
6381
- void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
7386
+ this.spendWake(timer, message(error));
7387
+ continue;
6382
7388
  }
6383
7389
  // One fewer wake the row is waiting on — said once the attempt is over, whether it landed or was spent.
6384
7390
  this.emitTimers(sessionId);
@@ -6455,6 +7461,10 @@ export class AppServer {
6455
7461
  this.closed = true;
6456
7462
  await this.codexAuth.close().catch(() => { });
6457
7463
  await this.anthropicAuth.close().catch(() => { });
7464
+ await this.claudeSignIn.close().catch(() => { });
7465
+ await this.grokSignIn.close().catch(() => { });
7466
+ await this.openCodeSignIn.close().catch(() => { });
7467
+ await sharedOpenCodeServer().close().catch(() => { });
6458
7468
  if (this.automationCheck)
6459
7469
  clearInterval(this.automationCheck);
6460
7470
  await this.pullRequestWatcher.stop().catch(() => { });