@andorra-labs/code 0.1.17 → 0.1.19

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 (313) hide show
  1. package/dist/src/account-jev-savings.d.ts +4 -0
  2. package/dist/src/account-jev-savings.js +92 -0
  3. package/dist/src/acp-agent.js +2 -2
  4. package/dist/src/agent-execution.js +441 -53
  5. package/dist/src/agent-mcp.js +7 -1
  6. package/dist/src/agent-modifiers.js +5 -7
  7. package/dist/src/analytics.d.ts +19 -1
  8. package/dist/src/analytics.js +9 -1
  9. package/dist/src/andorra/entry.js +15 -6
  10. package/dist/src/andorra/errors.js +3 -0
  11. package/dist/src/andorra/hosted.d.ts +8 -0
  12. package/dist/src/andorra/hosted.js +22 -3
  13. package/dist/src/andorra/streams.d.ts +49 -0
  14. package/dist/src/andorra/streams.js +98 -0
  15. package/dist/src/antigravity-acp.d.ts +28 -0
  16. package/dist/src/antigravity-acp.js +150 -0
  17. package/dist/src/antigravity-terminal.d.ts +2 -0
  18. package/dist/src/antigravity-terminal.js +214 -0
  19. package/dist/src/app-server/adaptive-routing-settings.d.ts +37 -0
  20. package/dist/src/app-server/adaptive-routing-settings.js +69 -0
  21. package/dist/src/app-server/artifact.d.ts +14 -0
  22. package/dist/src/app-server/artifact.js +46 -0
  23. package/dist/src/app-server/legal-protocol.d.ts +33 -0
  24. package/dist/src/app-server/legal-protocol.js +16 -0
  25. package/dist/src/app-server/protocol.d.ts +34 -3
  26. package/dist/src/app-server/protocol.js +3 -1
  27. package/dist/src/app-server/telemetry-protocol.d.ts +53 -0
  28. package/dist/src/app-server/telemetry-protocol.js +2 -0
  29. package/dist/src/app-server/telemetry.d.ts +38 -0
  30. package/dist/src/app-server/telemetry.js +163 -0
  31. package/dist/src/app-server/workspace.d.ts +21 -0
  32. package/dist/src/app-server/workspace.js +192 -10
  33. package/dist/src/app-server.d.ts +82 -26
  34. package/dist/src/app-server.js +1573 -417
  35. package/dist/src/attachments.d.ts +10 -0
  36. package/dist/src/attachments.js +102 -7
  37. package/dist/src/auth/AuthManager.d.ts +11 -2
  38. package/dist/src/auth/AuthManager.js +56 -13
  39. package/dist/src/auth/index.d.ts +5 -1
  40. package/dist/src/auth/index.js +8 -1
  41. package/dist/src/auth/lifecycle.d.ts +13 -0
  42. package/dist/src/auth/lifecycle.js +109 -0
  43. package/dist/src/auth/store.d.ts +1 -0
  44. package/dist/src/auth/store.js +12 -0
  45. package/dist/src/auth/types.d.ts +12 -0
  46. package/dist/src/automation-runner.js +2 -0
  47. package/dist/src/automation-service.js +7 -2
  48. package/dist/src/automation-tool.js +2 -1
  49. package/dist/src/benchmark-scores.d.ts +88 -0
  50. package/dist/src/benchmark-scores.js +302 -0
  51. package/dist/src/bridge/command.js +16 -1
  52. package/dist/src/bridge/control.d.ts +3 -1
  53. package/dist/src/bridge/control.js +9 -3
  54. package/dist/src/bridge/engines.d.ts +2 -0
  55. package/dist/src/bridge/engines.js +9 -0
  56. package/dist/src/bridge/github.d.ts +108 -0
  57. package/dist/src/bridge/github.js +378 -0
  58. package/dist/src/bridge/host-ops.d.ts +3 -3
  59. package/dist/src/bridge/host-ops.js +14 -2
  60. package/dist/src/bridge/host.d.ts +2 -0
  61. package/dist/src/bridge/host.js +70 -16
  62. package/dist/src/bridge/protocol.d.ts +1 -0
  63. package/dist/src/bridge/protocol.js +1 -0
  64. package/dist/src/browser-panel-tool.d.ts +12 -0
  65. package/dist/src/browser-panel-tool.js +30 -3
  66. package/dist/src/browser-runner.js +53 -62
  67. package/dist/src/browser-server.js +10 -4
  68. package/dist/src/browser-session.d.ts +14 -0
  69. package/dist/src/browser-session.js +57 -12
  70. package/dist/src/browser-view.d.ts +40 -1
  71. package/dist/src/browser-view.js +163 -9
  72. package/dist/src/browser-window-style.d.ts +27 -0
  73. package/dist/src/browser-window-style.js +244 -0
  74. package/dist/src/bug-report-attachments.d.ts +48 -0
  75. package/dist/src/bug-report-attachments.js +327 -0
  76. package/dist/src/bug-report.d.ts +23 -3
  77. package/dist/src/bug-report.js +72 -9
  78. package/dist/src/claude-provider.d.ts +1 -0
  79. package/dist/src/claude-provider.js +77 -36
  80. package/dist/src/cli.d.ts +1 -3
  81. package/dist/src/cli.js +245 -62
  82. package/dist/src/codex-provider.d.ts +1 -0
  83. package/dist/src/codex-provider.js +44 -8
  84. package/dist/src/coding-tools.d.ts +1 -0
  85. package/dist/src/coding-tools.js +28 -7
  86. package/dist/src/command-screens.d.ts +1 -1
  87. package/dist/src/command-screens.js +2 -2
  88. package/dist/src/commands.d.ts +9 -2
  89. package/dist/src/commands.js +69 -64
  90. package/dist/src/completion.js +13 -7
  91. package/dist/src/config.d.ts +14 -3
  92. package/dist/src/config.js +57 -17
  93. package/dist/src/context-budget.d.ts +11 -2
  94. package/dist/src/context-budget.js +38 -4
  95. package/dist/src/context-compaction.d.ts +10 -8
  96. package/dist/src/context-compaction.js +23 -24
  97. package/dist/src/deadline.js +1 -1
  98. package/dist/src/decision/DecisionEngine.d.ts +2 -0
  99. package/dist/src/decision/DecisionManager.d.ts +16 -0
  100. package/dist/src/decision/DecisionManager.js +75 -2
  101. package/dist/src/decision/applyTaskKind.d.ts +8 -0
  102. package/dist/src/decision/applyTaskKind.js +53 -0
  103. package/dist/src/decision/applyToolMenu.js +6 -2
  104. package/dist/src/decision/hostedPolicy.js +6 -3
  105. package/dist/src/decision/optimizationPolicy.d.ts +10 -0
  106. package/dist/src/decision/optimizationPolicy.js +23 -3
  107. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +4 -1
  108. package/dist/src/decision/providers/AndorraDecisionProvider.js +29 -7
  109. package/dist/src/decision/providers/index.js +1 -1
  110. package/dist/src/decision/taskKind.d.ts +52 -0
  111. package/dist/src/decision/taskKind.js +76 -0
  112. package/dist/src/decision/toolFamilies.js +1 -1
  113. package/dist/src/decision/types.d.ts +3 -1
  114. package/dist/src/default-graph.js +1 -1
  115. package/dist/src/efficiency.d.ts +80 -1
  116. package/dist/src/efficiency.js +119 -4
  117. package/dist/src/effort-routing.d.ts +27 -0
  118. package/dist/src/effort-routing.js +34 -0
  119. package/dist/src/evidence.d.ts +110 -0
  120. package/dist/src/evidence.js +195 -0
  121. package/dist/src/extensions.d.ts +2 -0
  122. package/dist/src/extensions.js +30 -20
  123. package/dist/src/github-app/agent-writes.d.ts +1 -1
  124. package/dist/src/github-app/agent-writes.js +1 -1
  125. package/dist/src/github-app/client.d.ts +19 -0
  126. package/dist/src/github-app/client.js +21 -1
  127. package/dist/src/github-app/event-source.d.ts +0 -5
  128. package/dist/src/github-app/event-source.js +1 -31
  129. package/dist/src/github-app/metrics.d.ts +2 -5
  130. package/dist/src/github-app/metrics.js +2 -14
  131. package/dist/src/github-app/review-loop.d.ts +5 -5
  132. package/dist/src/github-app/review-loop.js +1 -1
  133. package/dist/src/github-app/review-node.d.ts +2 -2
  134. package/dist/src/github-app/triggers.d.ts +3 -3
  135. package/dist/src/github-names.d.ts +7 -0
  136. package/dist/src/github-names.js +7 -0
  137. package/dist/src/glob-search.d.ts +1 -0
  138. package/dist/src/glob-search.js +3 -0
  139. package/dist/src/google-provider.d.ts +5 -28
  140. package/dist/src/google-provider.js +6 -141
  141. package/dist/src/graph-editor-session.d.ts +1 -0
  142. package/dist/src/graph-editor-session.js +2 -0
  143. package/dist/src/graph-health.js +3 -1
  144. package/dist/src/graph-preview.d.ts +2 -0
  145. package/dist/src/graph-preview.js +1 -0
  146. package/dist/src/graph-runner.js +20 -14
  147. package/dist/src/graph-selection.d.ts +3 -1
  148. package/dist/src/graph-selection.js +2 -2
  149. package/dist/src/graph-server.d.ts +8 -1
  150. package/dist/src/graph-server.js +49 -12
  151. package/dist/src/graph-sync.d.ts +2 -1
  152. package/dist/src/graph-sync.js +13 -0
  153. package/dist/src/graph-ui/app.js +49 -8
  154. package/dist/src/graph-ui/index.html +1 -1
  155. package/dist/src/graphs.d.ts +23 -1
  156. package/dist/src/graphs.js +58 -7
  157. package/dist/src/grok-provider.js +17 -14
  158. package/dist/src/hardened-runtime.js +39 -25
  159. package/dist/src/jev-savings.d.ts +4 -0
  160. package/dist/src/jev-savings.js +13 -0
  161. package/dist/src/legal/client.d.ts +25 -0
  162. package/dist/src/legal/client.js +47 -0
  163. package/dist/src/legal/command.d.ts +13 -0
  164. package/dist/src/legal/command.js +98 -0
  165. package/dist/src/legal/documents.d.ts +2 -0
  166. package/dist/src/legal/documents.js +14 -0
  167. package/dist/src/legal/gate.d.ts +13 -0
  168. package/dist/src/legal/gate.js +96 -0
  169. package/dist/src/legal/manifest.d.ts +21 -0
  170. package/dist/src/legal/manifest.js +23 -0
  171. package/dist/src/legal/receipt.d.ts +13 -0
  172. package/dist/src/legal/receipt.js +137 -0
  173. package/dist/src/legal/release.d.ts +27 -0
  174. package/dist/src/legal/release.js +28 -0
  175. package/dist/src/managed-sign-in.d.ts +0 -1
  176. package/dist/src/managed-sign-in.js +0 -13
  177. package/dist/src/membership.d.ts +27 -1
  178. package/dist/src/membership.js +139 -7
  179. package/dist/src/model-health-cache.js +1 -1
  180. package/dist/src/model-metadata.js +3 -7
  181. package/dist/src/model-override.d.ts +2 -1
  182. package/dist/src/model-override.js +9 -0
  183. package/dist/src/model-pool.d.ts +99 -0
  184. package/dist/src/model-pool.js +136 -0
  185. package/dist/src/model-relay/local.js +5 -0
  186. package/dist/src/model-relay/remote.d.ts +2 -0
  187. package/dist/src/model-relay/remote.js +4 -0
  188. package/dist/src/model-tiers.d.ts +16 -1
  189. package/dist/src/model-tiers.js +31 -7
  190. package/dist/src/opencode-cli-provider.js +59 -56
  191. package/dist/src/opencode-provider.js +16 -13
  192. package/dist/src/permissions.d.ts +5 -0
  193. package/dist/src/permissions.js +7 -0
  194. package/dist/src/plan-pass.js +2 -1
  195. package/dist/src/pool-scores.d.ts +45 -0
  196. package/dist/src/pool-scores.js +40 -0
  197. package/dist/src/provider-connection.js +3 -17
  198. package/dist/src/provider-engine.d.ts +13 -1
  199. package/dist/src/provider-engine.js +116 -12
  200. package/dist/src/provider-request-error.d.ts +8 -0
  201. package/dist/src/provider-request-error.js +12 -0
  202. package/dist/src/provider-settings.d.ts +1 -1
  203. package/dist/src/provider-settings.js +36 -18
  204. package/dist/src/provider-turn-deadline.d.ts +39 -0
  205. package/dist/src/provider-turn-deadline.js +139 -0
  206. package/dist/src/providers.d.ts +8 -9
  207. package/dist/src/providers.js +211 -150
  208. package/dist/src/pull-request-merge.d.ts +1 -8
  209. package/dist/src/pull-request-merge.js +0 -4
  210. package/dist/src/pull-requests.d.ts +83 -57
  211. package/dist/src/pull-requests.js +266 -225
  212. package/dist/src/qa/runtime/ProcessManager.d.ts +5 -1
  213. package/dist/src/qa/runtime/ProcessManager.js +9 -3
  214. package/dist/src/react-runtime.js +245 -71
  215. package/dist/src/reasoning-probe-cloud.d.ts +10 -0
  216. package/dist/src/reasoning-probe-cloud.js +209 -0
  217. package/dist/src/remote/engine-pool.d.ts +3 -0
  218. package/dist/src/remote/engine-pool.js +88 -21
  219. package/dist/src/remote/recovery.d.ts +6 -0
  220. package/dist/src/remote/recovery.js +37 -0
  221. package/dist/src/run-records.d.ts +13 -3
  222. package/dist/src/run-records.js +59 -34
  223. package/dist/src/runtime.d.ts +47 -2
  224. package/dist/src/runtime.js +33 -7
  225. package/dist/src/session-summary.d.ts +8 -0
  226. package/dist/src/session-summary.js +34 -0
  227. package/dist/src/sessions.d.ts +32 -0
  228. package/dist/src/sessions.js +65 -3
  229. package/dist/src/shell.js +6 -0
  230. package/dist/src/side-panel.js +36 -2
  231. package/dist/src/sign-in-detection.d.ts +1 -1
  232. package/dist/src/sign-in-detection.js +4 -10
  233. package/dist/src/sign-in-offer.js +1 -1
  234. package/dist/src/skill-commands.js +1 -1
  235. package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
  236. package/dist/src/skills/bundled/graph-manager/SKILL.md +2 -2
  237. package/dist/src/skills/bundled/graph-manager/patterns.md +13 -19
  238. package/dist/src/skills/bundled/provenance.json +3 -3
  239. package/dist/src/subagent-run.js +50 -50
  240. package/dist/src/subscription-usage.d.ts +50 -0
  241. package/dist/src/subscription-usage.js +92 -0
  242. package/dist/src/task-checkout.d.ts +157 -0
  243. package/dist/src/task-checkout.js +628 -0
  244. package/dist/src/telemetry/access.d.ts +18 -0
  245. package/dist/src/telemetry/access.js +43 -0
  246. package/dist/src/telemetry/aggregate.d.ts +18 -2
  247. package/dist/src/telemetry/aggregate.js +22 -9
  248. package/dist/src/telemetry/capture-core.d.ts +33 -14
  249. package/dist/src/telemetry/capture-core.js +124 -25
  250. package/dist/src/telemetry/capture.d.ts +3 -2
  251. package/dist/src/telemetry/capture.js +21 -1
  252. package/dist/src/telemetry/decision-capture.js +4 -0
  253. package/dist/src/telemetry/emitter.d.ts +6 -7
  254. package/dist/src/telemetry/emitter.js +124 -29
  255. package/dist/src/telemetry/gate.d.ts +41 -2
  256. package/dist/src/telemetry/gate.js +89 -4
  257. package/dist/src/telemetry/home.d.ts +1 -0
  258. package/dist/src/telemetry/home.js +20 -0
  259. package/dist/src/telemetry/identity.d.ts +6 -3
  260. package/dist/src/telemetry/identity.js +19 -6
  261. package/dist/src/telemetry/lifecycle.d.ts +8 -0
  262. package/dist/src/telemetry/lifecycle.js +76 -0
  263. package/dist/src/telemetry/outbox.d.ts +13 -8
  264. package/dist/src/telemetry/outbox.js +68 -12
  265. package/dist/src/telemetry/permission-command.d.ts +38 -0
  266. package/dist/src/telemetry/permission-command.js +208 -0
  267. package/dist/src/telemetry/permission.d.ts +168 -0
  268. package/dist/src/telemetry/permission.js +662 -0
  269. package/dist/src/telemetry/record-installation.d.ts +1 -0
  270. package/dist/src/telemetry/record-installation.js +9 -0
  271. package/dist/src/telemetry/region-data.d.ts +12 -0
  272. package/dist/src/telemetry/region-data.js +1314 -0
  273. package/dist/src/telemetry/region.d.ts +34 -0
  274. package/dist/src/telemetry/region.js +87 -0
  275. package/dist/src/telemetry/run-privacy.d.ts +11 -0
  276. package/dist/src/telemetry/run-privacy.js +165 -0
  277. package/dist/src/telemetry/schema.d.ts +27 -6
  278. package/dist/src/telemetry/schema.js +109 -14
  279. package/dist/src/telemetry/state.d.ts +11 -7
  280. package/dist/src/telemetry/state.js +39 -6
  281. package/dist/src/telemetry/surface.d.ts +20 -3
  282. package/dist/src/telemetry/surface.js +71 -15
  283. package/dist/src/telemetry/uploader.d.ts +6 -11
  284. package/dist/src/telemetry/uploader.js +72 -46
  285. package/dist/src/telemetry/uploads.d.ts +5 -1
  286. package/dist/src/telemetry/uploads.js +25 -6
  287. package/dist/src/telemetry/version.d.ts +5 -0
  288. package/dist/src/telemetry/version.js +34 -0
  289. package/dist/src/telemetry/workspace.d.ts +4 -1
  290. package/dist/src/telemetry/workspace.js +18 -3
  291. package/dist/src/terminal-ui.d.ts +3 -0
  292. package/dist/src/terminal-ui.js +48 -6
  293. package/dist/src/test-edit-guard.d.ts +30 -0
  294. package/dist/src/test-edit-guard.js +167 -2
  295. package/dist/src/thinking-level-detect.d.ts +13 -0
  296. package/dist/src/thinking-level-detect.js +52 -0
  297. package/dist/src/thinking-levels.d.ts +30 -0
  298. package/dist/src/thinking-levels.js +131 -0
  299. package/dist/src/timers.d.ts +3 -0
  300. package/dist/src/todos.d.ts +2 -1
  301. package/dist/src/todos.js +24 -4
  302. package/dist/src/tool-argument-coercion.d.ts +7 -0
  303. package/dist/src/tool-argument-coercion.js +49 -0
  304. package/dist/src/tool-catalog.d.ts +2 -2
  305. package/dist/src/tool-catalog.js +1 -1
  306. package/dist/src/tools.js +67 -22
  307. package/dist/src/transcript.js +3 -2
  308. package/dist/src/types.d.ts +48 -1
  309. package/dist/src/update.js +4 -0
  310. package/dist/src/usage-analytics.d.ts +7 -0
  311. package/dist/src/usage-analytics.js +85 -13
  312. package/dist/telemetry-consent-v1 +1 -0
  313. package/package.json +97 -96
@@ -1,19 +1,26 @@
1
1
  import { createInterface } from 'node:readline';
2
2
  import { createRequire } from 'node:module';
3
3
  import { readFileSync } from 'node:fs';
4
+ import { acceptLegal, legalStatus, requireLegalAcceptance, legalMethodRequiresAcceptance, LegalAcceptanceRequired, LEGAL_ACCEPTANCE_REQUIRED } from './legal/gate.js';
5
+ import { legalDocument } from './legal/documents.js';
4
6
  import { randomBytes, randomUUID } from 'node:crypto';
5
7
  import { bootMark } from './boot-trace.js';
6
8
  import { ModelHealthCache } from './model-health-cache.js';
7
- import { mkdir, readFile, realpath, rm, stat, writeFile } from 'node:fs/promises';
9
+ import { mkdir, readFile, realpath, rm, stat } from 'node:fs/promises';
8
10
  import { homedir } from 'node:os';
9
11
  import { fileURLToPath } from 'node:url';
10
12
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
11
- import { changeConfigFile, configDirectory, ConfigConflictError, readGitHubAgentWrites, readGitHubAppEventsEnabled, readGitHubAppReviewNewPullRequests, readGitHubAppReviewsEnabled, readGitHubAppTriggersEnabled, GITHUB_AGENT_WRITES, modelRelayAllowedFor, withModelRelayEntry, isProjectExtensionOverride, loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer, checkSearxngUrl, validateWebSearchConfig, WEB_SEARCH_FIELDS, WEB_SEARCH_KEY_FIELDS, WEB_SEARCH_PROVIDERS } from './config.js';
13
+ import { changeFunctionalConfigFile as changeConfigFile, changeConfigFile as changeLegacyConfigFile, configDirectory, ConfigConflictError, readGitHubAgentWrites, readGitHubAppEventsEnabled, readGitHubAppReviewNewPullRequests, readGitHubAppReviewsEnabled, readGitHubAppTriggersEnabled, GITHUB_AGENT_WRITES, modelRelayAllowedFor, withModelRelayEntry, isProjectExtensionOverride, loadFunctionalConfig as loadConfig, reconcileSubagentPair, resolveCodeIntelConfig, resolveConfiguredLimits, validateMcpServer, checkSearxngUrl, validateWebSearchConfig, WEB_SEARCH_FIELDS, WEB_SEARCH_KEY_FIELDS, WEB_SEARCH_PROVIDERS } from './config.js';
14
+ import { AppServerTelemetry, readTelemetryRunRecord } from './app-server/telemetry.js';
15
+ import { TELEMETRY_CONSENT_CAPABILITY } from './app-server/telemetry-protocol.js';
16
+ import { LEGAL_ACCEPTANCE_CAPABILITY, legalRequestRequiresAcceptance } from './app-server/legal-protocol.js';
17
+ import { TelemetryPrivacyError, telemetryLeaseSnapshot, sameTelemetryLease, withTelemetryAdmission } from './telemetry/permission.js';
12
18
  import { isUnlimitedAlias } from './limits.js';
13
- import { isPermissionMode, permissionMode as livePermissionMode, workspacePermissionKey } from './permissions.js';
19
+ import { cloudPermissionMode, isPermissionMode, permissionMode as livePermissionMode, workspacePermissionKey } from './permissions.js';
14
20
  import { RunControl } from './run-control.js';
15
21
  import { allocateCodexAccountSlots, createAdapter, findProviderById, isSignInProviderType, providerLabel, providerSecrets, resolveProviderApiKey, REASONING_EFFORTS, supportsReasoningEffort } from './providers.js';
16
22
  import { ModelRelayBroker, RELAY_FAILURE_CODE } from './model-relay/remote.js';
23
+ import { readProviderTurnTiming } from './provider-turn-deadline.js';
17
24
  import { LocalModelRelay, relayedModelIds } from './model-relay/local.js';
18
25
  import { ModelRelayRunStore } from './model-relay/runs.js';
19
26
  import { MODEL_RELAY_CONNECTION_PREFIX } from './model-relay/wire.js';
@@ -21,22 +28,27 @@ import { droppedCodexSlots, removeCodexAccount } from './codex-auth.js';
21
28
  import { testProviderConnection } from './provider-connection.js';
22
29
  import { CodexAccountAuth } from './codex-browser-auth.js';
23
30
  import { AnthropicConsoleAuth, droppedAnthropicAccounts } from './anthropic-console-auth.js';
24
- import { claudeSignIn, googleSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
31
+ import { claudeSignIn, grokSignIn, OpenCodeSignIn } from './managed-sign-in.js';
25
32
  import { applySignInImports, detectSignIns, isDetectableSignInType } from './sign-in-detection.js';
26
33
  import { OPENCODE_BASE_URL, sharedOpenCodeServer } from './opencode-cli-provider.js';
27
- import { GOOGLE_BASE_URL } from './google-provider.js';
34
+ import { GOOGLE_BASE_URL, GOOGLE_LEGACY_MESSAGE } from './google-provider.js';
35
+ import { AntigravitySession } from './antigravity-acp.js';
28
36
  import { GROK_BASE_URL } from './grok-provider.js';
29
37
  import { anthropicAccountHome } from './anthropic-credentials.js';
30
38
  import { codexAccountHome } from './codex-rpc.js';
31
39
  import { configuredModelSnapshot, discoverModelMetadata, resolveModelContext, resolveModelContextWindows } from './model-metadata.js';
32
40
  import { liveModelTarget } from './live-model.js';
33
- import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, isReservedGraphId, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
41
+ import { decideEffort } from './effort-routing.js';
42
+ import { graphLeavesNodesToSession, graphMcpServers, isDeletedGraph, isNodeReasoningEffort, isReservedGraphId, listGraphs, loadGraph, maxNodeVisitsOf, withoutDeletedGraphs } from './graphs.js';
34
43
  import { exportAgentDefinition, readAgentDefinition } from './agent-definitions.js';
35
44
  import { blockingHealthFailures, checkGraphModelHealth, formatGraphHealthFailure, resumeModelNodes } from './graph-health.js';
36
45
  import { bindPortableGraphProviders, GraphProviderUnavailableError } from './graph-provider-portability.js';
37
46
  import { applyModelOverride, applyNodeModelOverrides } from './model-override.js';
47
+ import { autoLevels, enabledLevels, nearestEnabled, withDetectedLevels, withDisabledLevels, validateThinkingLevels } from './thinking-levels.js';
48
+ import { detectProviderLevels } from './thinking-level-detect.js';
49
+ import { currentReasoningProbeSubject, flushReasoningProbes, queueReasoningProbe, readReasoningProbe } from './reasoning-probe-cloud.js';
38
50
  import { freeTierGraphViolation, notePremiumGraphAccount, readGraphQuota } from './graph-quota.js';
39
- import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, createMembershipClient, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph, membershipPlanLabel, relayedGraph } from './membership.js';
51
+ import { RETIRED_ANDORRA_SELECTION, SOFTWARE_ENGINEER_HARNESS, createMembershipClient, currentGraphSelection, getGraphMembership, getMembership, loadAccessibleGraph, membershipPlanLabel, relayedGraph, withAnonymousJev } from './membership.js';
40
52
  import { loadProfile, saveProfile, ProfileAccountError, ProfileTextError } from './profile.js';
41
53
  import { hostedDecisionPolicy } from './decision/hostedPolicy.js';
42
54
  import { createAccountPresentationReader, publishableMembership } from './account-presentation.js';
@@ -45,14 +57,16 @@ import { configuredGraphSelection, currentGraphSubject, identityStillHolds } fro
45
57
  import { announceGraphVisibilityChange, graphVisibilityFor, importGraphVisibility, onGraphVisibilityChange, relinkGraphVisibility, setGraphVisibility } from './graph-visibility.js';
46
58
  import { graphStorageAccess } from './graph-account.js';
47
59
  import { GraphAccessSync } from './graph-sync.js';
48
- import { canExtendLineage, displayHistory, hiddenSession, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
60
+ import { checkoutState, discardPreparedWorktree, forgetPrepared, inPlaceCheckout, inspectWorktreeRemoval, isAutoTaskBranch, locateTaskWorktree, prepareTaskWorktree, recreateTaskWorktree, removeTaskWorktree, renameTaskBranch, revertTaskBranchRename, takePrepared, taskStartPoints, TaskCheckoutError, worktreeInstructions } from './task-checkout.js';
61
+ import { cleanRecorded, COMMAND_LIMIT, outputTail, readRevision, resolveEvidence } from './evidence.js';
62
+ import { reviewAfterTurn, canExtendLineage, displayHistory, hiddenSession, lineagePoints, lineageThrough, SessionStore, projectIdentity, removeSessionSnapshot, savedSessionFields, sessionName, validSavedSession } from './sessions.js';
49
63
  import { folderChangeBusy, folderChangeHeld, reserveFolderChange } from './project-reservation.js';
50
64
  import { writePendingAgentInteraction, removePendingAgentInteraction } from './session-monitor.js';
51
- import { summarizeSessionPrompt, titleRequestSupported } from './session-summary.js';
65
+ import { summarizeSessionPrompt, summarizeTaskBranch, titleRequestSupported } from './session-summary.js';
52
66
  import { createTools } from './tools.js';
53
67
  import { TimerRegistry, WAKE_RETRY_MS } from './timers.js';
54
68
  import { checksRollup, classifyGhError, classifyWriteError, PullRequestReader, runAsAccount, sameChecksRollup, PullRequestRefusal } from './pull-request-details.js';
55
- import { commitBody, commitTitle, deleteBranch, dequeue, enableAutoMerge, enqueue, headCommit, mergeMethod, mergePullRequest, setReadyForReview, updateBranch, updateMethod } from './pull-request-merge.js';
69
+ import { commitBody, commitTitle, deleteBranch, dequeue, enqueue, headCommit, mergeMethod, mergePullRequest, setReadyForReview, updateBranch, updateMethod } from './pull-request-merge.js';
56
70
  import { accountToken, branchName, createFromFolder, githubHttpsUrl, githubRepositoryOf, gitIn, PullRequestCreateBlocked, pullRequestTitle, readCreateDraft, repositoryName, tokenCredentials } from './pull-request-create.js';
57
71
  import { addComment, applySuggestionText, commitFile, coAuthorTrailer, deleteComment, editComment, reactionContent, readFileAt, setReaction, suggestionOf, uniformLineEndings } from './pull-request-conversation.js';
58
72
  import { changeAssignees, changeLabels, currentText, editBody, editTitle, nodeIds, setOpen, updateText } from './pull-request-edit.js';
@@ -60,32 +74,35 @@ import { actionsJobOf, fixChecksPrompt, jobId } from './pull-request-logs.js';
60
74
  import { issueNamedIn, readRepositoryIssues, readReviewRequests } from './github-inbox.js';
61
75
  import { changeReviewers, commentBody, draftComments, failedRunIds, githubLogin, nodeId, replyToThread, rerunFailedJobs, reviewerEntries, reviewerLogins, reviewEvent, reviewPath, runIds, setFileViewed, setThreadResolved, submitReview, teamSlugs, } from './pull-request-review.js';
62
76
  import { chatReviewLoopActive, parseReviewModel, reviewLoopActive, reviewLoopSettings, REVIEW_SETTING_KEYS } from './pull-requests.js';
63
- import { confirmAutoFixWake, handedOver, isFinishedPullRequest, settleFinishedPullRequest, withChecks, markAutoFixDelivered, withoutPendingFix, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, listPullRequests, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, codexReviewsRepository, ghFor, newReviewComments, noAccountMessage, readReviewSignals, REVIEW_BUMP_COMMENT, REVIEW_BUMP_DELAY_MS, REVIEW_SIGNAL_INTERVAL_MS, readPullRequestAsAnyAccount, withPullRequest, writePullRequest } from './pull-requests.js';
77
+ import { isFinishedPullRequest, withChecks, newPullRequest, parsePullRequestUrl, PullRequestCreateDetector, pullRequestNeedsWatch, pullRequestSettings, PullRequestWatcher, listPullRequests, readPullRequest, removePullRequest, runGh, applyPullRequestSettingsAsReadableAccount, codexReviewsRepository, ghFor, newReviewComments, noAccountMessage, readReviewSignals, REVIEW_BUMP_COMMENT, REVIEW_BUMP_DELAY_MS, REVIEW_SIGNAL_INTERVAL_MS, readPullRequestAsAnyAccount, withPullRequest, withSupersededPullRequest, writePullRequest } from './pull-requests.js';
64
78
  import { AutomationStore } from './automations.js';
65
79
  import { executeAutomation } from './automation-runner.js';
66
80
  import { automationService, automationServiceRunning, reconcileAutomationService } from './automation-service.js';
67
81
  import { runGraph, stopReasonPhrase, timerReminderText, wakeMessageText } from './runtime.js';
68
- import { configuredSurface, createRunHandle, drainTelemetry, graphShape, reportGitHubWatch, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
82
+ import { configuredSurface, beginTelemetryRun, runTelemetryMetadata, drainTelemetry, graphShape, reportGitHubWatch, reportInstallationObserved, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
83
+ import { desktopInstallationReceipt } from './telemetry/version.js';
69
84
  import { telemetryGate } from './telemetry/gate.js';
70
85
  import { accountApiTarget, defaultGitHubAppClient, GitHubAppError } from './github-app/client.js';
86
+ import { GITHUB_ACCOUNT, GITHUB_REPO } from './github-names.js';
71
87
  import { GitHubEventSource } from './github-app/event-source.js';
72
88
  import { MentionTriggers } from './github-app/triggers.js';
73
89
  import { applyReviewSettings, coverageAllowsReview, coverageRefusal, ReviewLoopController } from './github-app/review-loop.js';
74
90
  import { newRequestId as newReviewLoopId } from './github-app/agent-writes.js';
75
91
  import { asksBot, performAgentWrite } from './github-app/agent-writes.js';
76
92
  import { createReviewNodeService, endGraphLoops } from './github-app/review-node.js';
77
- import { analyticsGenerationFor, resolveAnalyticsConfig } from './analytics.js';
93
+ import { analyticsGenerationFor, resolveAnalyticsConfig, validateAnalyticsConfig } from './analytics.js';
78
94
  import { telemetryDirectory } from './telemetry/identity.js';
79
95
  import { recordPreference } from './telemetry/state.js';
80
- import { createRunTelemetry, recordModelUse } from './telemetry/capture.js';
96
+ import { createRunTelemetry, hasRunTelemetry, mergeRunTelemetry, recordModelUse } from './telemetry/capture.js';
81
97
  import { pricingFor } from './model-tiers.js';
82
98
  import { purgeOutbox } from './telemetry/outbox.js';
83
- import { acquireSessionMutationLock, checkpointFailure, claimProcessWorkspace, createCheckpointFailureTracker, createRunJournalWriter, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runIsOpen, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
99
+ import { acquireSessionMutationLock, checkpointFailure, claimProcessWorkspace, createCheckpointFailureTracker, createRunJournalWriter, claimRunResume, clearOpenRunClaim, clearWakeClaim, clearWakeClaims, isPidAlive, journalWriteFailed, readRunCheckpoints, releaseProcessWorkspace, releaseRunResumeClaim, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runIsOpen, runRecordPath, runRecordsDirectory, sessionHasArmedWake, sessionHasOpenRun, sessionsWithOpenRunClaims, SessionMutationLockHeldError, writeFinalRunRecord, functionalRunRecord, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary, writeWakeClaim } from './run-records.js';
84
100
  import { ArtifactStore } from './artifacts.js';
101
+ import { artifactUnavailable, parseArtifactReference, readArtifactPreview } from './app-server/artifact.js';
85
102
  import { coverUnsavedToolCalls, mergeRunProgress, replayRunJournal, toolBoundaryOpen } from './run-progress.js';
86
103
  import { compactHistory, compactedContextEstimate } from './commands.js';
87
104
  import { readFavicon } from './favicons.js';
88
- import { attachmentReferenceBlock, loadResolvedImages, parsePendingAttachments, pruneAttachments, readSpooledImage, readSpooledText, relinkAttachmentPath, resolveAttachments, attachmentReadRoots } from './attachments.js';
105
+ import { attachmentReferenceBlock, cloudAttachments, loadResolvedImages, parsePendingAttachments, pruneAttachments, readSpooledImage, readSpooledText, relinkAttachmentPath, resolveAttachments, attachmentReadRoots } from './attachments.js';
89
106
  import { extensionSnapshot, effectiveExtensionConfig, listBundles, installBundle, removeBundle, removeBundleTransactional, setBundleEnabled, listSkillResources, readSkillResource, writeSkillResource, resolveSkillInvocations } from './extensions.js';
90
107
  import { isBuiltinSlashCommand } from './skill-commands.js';
91
108
  import { applyGoalCommand, isGoalCommand, metSessionGoal } from './session-goal.js';
@@ -101,7 +118,7 @@ import { TodoStore } from './todos.js';
101
118
  import { LocalToolMemory } from './memory/LocalToolMemory.js';
102
119
  import { ProjectMemory } from './memory/ProjectMemory.js';
103
120
  import { CodeIntelligenceManager } from './code-intelligence/CodeIntelligenceManager.js';
104
- import { startGraphServer } from './graph-server.js';
121
+ import { graphEditorParentOrigins, startGraphServer } from './graph-server.js';
105
122
  import { createSessionTrajectory } from './trajectory.js';
106
123
  import { readUsageAnalytics } from './usage-analytics.js';
107
124
  import { TerminalFlow, TerminalManager } from './app-server/terminal.js';
@@ -112,7 +129,7 @@ import { createBrowserIncognitoTool, createBrowserPanelTool, createPanelBrowserH
112
129
  import { createBrowserExtensionsTool, EXTENSIONS_OPERATION, relayExtensionSteps, validateExtensionStep } from './browser-extensions-tool.js';
113
130
  import { resolveCapsolverKey } from './capsolver.js';
114
131
  import { resolveWebSearchProvider } from './web-search.js';
115
- import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, gitLinkBase, listWorkspaceFiles, readTree, readWorkspaceFile, searchOptions, searchWorkspace, summarizeMcpServer, workspaceRoot, writeTarget } from './app-server/workspace.js';
132
+ import { checkoutBranch, gitDiff, gitStatus, listBranches, listExtensions, listRuns, readRun, readSessionTrajectory, runRecordFile, sessionTrajectoryFile, gitLinkBase, listWorkspaceFiles, readTree, readWorkspaceFile, readWorkspaceImage, searchOptions, searchWorkspace, summarizeMcpServer, workspaceRoot, writeTarget } from './app-server/workspace.js';
116
133
  import { andorraGetToolPath } from '../vendor/engine/runtime/coding-agent/utils/tools-manager.js';
117
134
  /** Where ripgrep is, looked up once a minute: the lookup can run `rg --version`, which should not happen per keystroke. */
118
135
  let ripgrepLookup;
@@ -127,8 +144,9 @@ import { AppServerError } from './app-server/error.js';
127
144
  import { AUTH_DEPLOYMENT } from './auth/deployment.js';
128
145
  import { AuthError } from './auth/types.js';
129
146
  import { claimEnvironment, cloudDelete, cloudGet, cloudStart, cloudStop, ControlError, listEnvironments, removeEnvironment, renameEnvironment } from './bridge/control.js';
130
- import { relayUrlFromEnvironment } from './bridge/host.js';
147
+ import { RESTARTING_MESSAGE, relayUrlFromEnvironment } from './bridge/host.js';
131
148
  import { RelayClosedError, RelayLink } from './bridge/link.js';
149
+ import { CLOUD_BRIDGE_AUTO_UPDATE } from './bridge/protocol.js';
132
150
  import { bothBridgeCommands, bridgeCommand } from './bridge/wording.js';
133
151
  import { fallbackProviderId, hasAndorraEntry, virtualAndorraEntry } from './andorra/entry.js';
134
152
  import { ANDORRA_CHANGED_MESSAGE, ANDORRA_UNAVAILABLE_MESSAGE } from './andorra/endpoint.js';
@@ -136,8 +154,16 @@ import { andorraAnnouncement } from './andorra/notices.js';
136
154
  import { ANDORRA_REMOVE_FAILED, recordAndorraRemoved, removingAndorraEntry } from './andorra/state.js';
137
155
  import { addAndorraEntry, saveAndorraAnswer } from './andorra/opt-in.js';
138
156
  import { HostedMonitor } from './andorra/monitor.js';
157
+ import { createUsageReader, poolUsageReader } from './subscription-usage.js';
158
+ import { refreshPoolScores, scoreSubjects } from './pool-scores.js';
159
+ import { MAX_POOL_SCORES, validateEfficiencyConfig } from './efficiency.js';
160
+ import { adaptiveRoutingView, mergeAdaptiveRoutingSettings } from './app-server/adaptive-routing-settings.js';
139
161
  import { watchRequests } from './andorra/request-watch.js';
140
162
  const SELECTION_HEALTH_TIMEOUT_MS = 60_000;
163
+ /** Only this explicit capability refusal permanently closes a link as consent-unsupported. */
164
+ class RemoteConsentUnsupportedError extends AppServerError {
165
+ constructor() { super('remote', 'Telemetry permission unavailable: update the paired host and deliberately restart its older engines. Existing engines have not been stopped.'); }
166
+ }
141
167
  const SESSION_HISTORY_TURNS = 6;
142
168
  const MAX_TASK_CHARS = 100_000;
143
169
  /** A note the desktop sends with a message for the agent only (`run.note`), such as the person's hand edits. */
@@ -220,8 +246,10 @@ const RELAY_ERROR_CODES = new Set(['invalid-request', 'unknown-method', 'invalid
220
246
  const RELAY_DEADLINE_MS = 290_000;
221
247
  const RELAY_LONG_METHODS = new Set(['browser.runtime.install']);
222
248
  const RELAY_LONG_DEADLINE_MS = 1_260_000;
249
+ const CLOUD_BRIDGE_RETRY_MS = 1_000;
250
+ const CLOUD_BRIDGE_RETRY_LIMIT_MS = 60_000;
223
251
  const MAX_RESUME_LINEAGE = 32;
224
- const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'projectMemory', 'limits', 'workspacePermissions', 'projectExtensions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays', 'browser', 'webSearch'];
252
+ const EDITABLE_CONFIG_KEYS = ['provider', 'providers', 'graph', 'graphSelections', 'jevEnabled', 'decisions', 'commandMemory', 'projectMemory', 'limits', 'workspacePermissions', 'projectExtensions', 'mcpServers', 'extensions', 'memory', 'codeIntel', 'externalSubagent', 'analytics', 'systemPromptOverride', 'autoArchiveDays', 'browser', 'webSearch', 'adaptiveRouting'];
225
253
  function message(error) { return error instanceof Error ? error.message : String(error); }
226
254
  const MERGE_METHOD_WORD = { merge: 'A merge commit', squash: 'Squash and merge', rebase: 'Rebase and merge' };
227
255
  const NEW_COMMITS = 'This pull request has new commits since you read it. Look at them before merging or updating it.';
@@ -281,7 +309,7 @@ function providerAuthView(view, includeUrl) {
281
309
  return result;
282
310
  }
283
311
  const MANAGED_SIGN_IN_HOSTS = {
284
- claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], google: ['accounts.google.com'], opencode: undefined,
312
+ claude: ['claude.com', 'claude.ai', 'anthropic.com'], grok: ['x.ai', 'grok.com'], opencode: undefined,
285
313
  };
286
314
  function managedAuthView(type, view, includeUrl) {
287
315
  if (!['signedOut', 'starting', 'waiting', 'signedIn', 'cancelled', 'error'].includes(view.state))
@@ -344,6 +372,13 @@ function managedAuthView(type, view, includeUrl) {
344
372
  }
345
373
  return result;
346
374
  }
375
+ /** When a first automatic title never lands (refused run, failed or cut-short request), each retry waits this long; the last one is the last try. */
376
+ const TITLE_RETRY_DELAYS_MS = [60_000, 180_000];
377
+ /** How often a retry may find its session busy and step back without spending one of the attempts above. */
378
+ const MAX_TITLE_RETRY_DEFERRALS = 10;
379
+ /** A sibling session whose lock is busy while its branch is renamed: retry this often at this spacing. */
380
+ const MAX_SIBLING_LOCK_TRIES = 10;
381
+ const SIBLING_LOCK_RETRY_MS = 1_000;
347
382
  function profileSubject(params) {
348
383
  const subject = params.subject;
349
384
  if (subject === undefined)
@@ -440,7 +475,11 @@ function viewUrl(value) {
440
475
  function permissionMode(value) {
441
476
  if (!isPermissionMode(value))
442
477
  throw new AppServerError('invalid-params', 'permissions must be read-only, plan, ask-for-approval, approve-for-me, or full-access');
443
- return value;
478
+ return cloudPermissionMode() ?? value;
479
+ }
480
+ /** The mode a request names, if any. On a Cloud instance that is always full access, named or not. */
481
+ function requestedPermissionMode(value) {
482
+ return value === undefined ? cloudPermissionMode() : permissionMode(value);
444
483
  }
445
484
  function reasoningEffort(value) {
446
485
  if (typeof value !== 'string' || !REASONING_EFFORTS.includes(value)) {
@@ -493,6 +532,7 @@ function providerView(provider, providers) {
493
532
  ...(provider.textOnlyModels === undefined ? {} : { textOnlyModels: [...provider.textOnlyModels] }),
494
533
  ...(provider.contextWindow === undefined ? {} : { contextWindow: provider.contextWindow }),
495
534
  ...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
535
+ ...(provider.thinkingLevels === undefined ? {} : { thinkingLevels: structuredClone(provider.thinkingLevels) }),
496
536
  ...(provider.requestTimeoutMs === undefined ? {} : { requestTimeoutMs: provider.requestTimeoutMs }),
497
537
  ...(provider.streamIdleTimeoutMs === undefined ? {} : { streamIdleTimeoutMs: provider.streamIdleTimeoutMs }),
498
538
  ...(providers === undefined ? {} : { label: providerLabel(provider, providers) }),
@@ -521,6 +561,7 @@ function configView(config, analytics) {
521
561
  ...(config.autoArchiveDays === undefined ? {} : { autoArchiveDays: config.autoArchiveDays }),
522
562
  ...(resolveCapsolverKey(config) ? { browser: browserConfigView(config) } : {}),
523
563
  ...webSearchConfigView(config),
564
+ adaptiveRouting: adaptiveRoutingView(config.efficiency?.adaptiveRouting),
524
565
  };
525
566
  }
526
567
  function browserConfigView(config) {
@@ -651,6 +692,9 @@ export function mergeProviderSecrets(stored, incoming) {
651
692
  if (previousEntry?.modelContextWindows !== undefined)
652
693
  provider.modelContextWindows = previousEntry.modelContextWindows;
653
694
  }
695
+ // Thinking levels are set through their own requests, so a provider list saved by a client never drops them.
696
+ if (previousEntry?.thinkingLevels !== undefined && provider.type === previousEntry.type && provider.baseUrl === previousEntry.baseUrl)
697
+ provider.thinkingLevels = structuredClone(previousEntry.thinkingLevels);
654
698
  // The engine keeps an Andorra entry's display names from the router; a client never sets them.
655
699
  if (provider.type === 'andorra' && previousEntry?.type === 'andorra' && previousEntry.modelNames !== undefined)
656
700
  provider.modelNames = { ...previousEntry.modelNames };
@@ -726,9 +770,44 @@ function foldUsage(target, delta) {
726
770
  target.cacheWrite = (target.cacheWrite ?? 0) + delta.cacheWrite;
727
771
  }
728
772
  const TIMER_DELIVERY_RETRY_MS = 1_000;
729
- const AUTO_FIX_CONFIRM_RETRY_MS = 60_000;
730
- function pullRequestForClients(pullRequest) {
731
- return pullRequest ? { ...pullRequest, autoArchive: false } : null;
773
+ const REVIEW_CONFIRM_RETRY_MS = 60_000;
774
+ /** How many commands a turn's evidence keeps a record of: the newest are the ones outcomes cite. */
775
+ const MAX_TURN_OBSERVATIONS = 200;
776
+ /** Notes when the agent edits files, so evidence can say a check was followed by edits. */
777
+ function notingEdits(recorder, edits) {
778
+ // Only writes the recorder takes (inside the workspace) count, and only once they land.
779
+ return {
780
+ beforeWrite: async (targets) => {
781
+ const recording = await recorder.beforeWrite(targets);
782
+ if (recording === undefined)
783
+ return recording;
784
+ return { begin: () => recording.begin(), abort: () => recording.abort(), commit: async () => { edits.push(new Date().toISOString()); await recording.commit(); } };
785
+ },
786
+ };
787
+ }
788
+ /** The prepared worktree a run.start names (`checkout: { prepared }`), or undefined for a task in its project folder. */
789
+ function preparedCheckoutKey(value) {
790
+ if (value === undefined || value === null)
791
+ return undefined;
792
+ if (typeof value !== 'object' || Array.isArray(value))
793
+ throw new AppServerError('invalid-params', 'checkout must be an object');
794
+ const entry = value;
795
+ if (entry.inPlace === true && entry.prepared === undefined)
796
+ return undefined;
797
+ if (typeof entry.prepared !== 'string' || !/^[A-Za-z0-9_-]{8,64}$/.test(entry.prepared))
798
+ throw new AppServerError('invalid-params', 'checkout.prepared must be the key of a prepared worktree');
799
+ return entry.prepared;
800
+ }
801
+ /** The folder a task's Git work happens in; refused when its worktree was removed, rather than using the lead's checkout. */
802
+ function sessionGitRoot(record) {
803
+ if (record.checkout?.kind === 'worktree' && record.checkout.removedAt !== undefined) {
804
+ throw new AppServerError('checkout-missing', 'This task’s worktree was removed. Recreate it from the task, then try again.');
805
+ }
806
+ return sessionWorkRoot(record);
807
+ }
808
+ /** The folder a task works in: its own worktree while it stands, else its project folder. */
809
+ function sessionWorkRoot(record) {
810
+ return record.checkout?.kind === 'worktree' && record.checkout.removedAt === undefined ? record.checkout.path : record.workspace;
732
811
  }
733
812
  function sessionSummary(record) {
734
813
  const finished = record.history?.length
@@ -736,11 +815,15 @@ function sessionSummary(record) {
736
815
  : undefined;
737
816
  return {
738
817
  id: record.id, name: record.name, workspace: record.workspace, updatedAt: record.updatedAt, turns: (record.history ?? []).length,
818
+ ...(record.placeholder === undefined ? {} : { placeholder: record.placeholder }),
739
819
  ...(record.parentId === undefined ? {} : { parentId: record.parentId }),
820
+ ...(record.handoffParentId === undefined ? {} : { handoffParentId: record.handoffParentId }),
740
821
  ...(record.projectId === undefined ? {} : { projectId: record.projectId }),
741
822
  ...(record.archived === undefined ? {} : { archived: record.archived }),
742
823
  ...(record.pinned === true ? { pinned: true } : {}),
743
824
  ...(record.jevEnabled === undefined ? {} : { jevEnabled: record.jevEnabled }),
825
+ ...(record.checkout === undefined ? {} : { checkout: record.checkout }),
826
+ ...(record.review === undefined ? {} : { review: record.review }),
744
827
  ...(record.history?.length ? { lastTask: record.history[record.history.length - 1].direction ?? record.history[record.history.length - 1].task } : {}),
745
828
  ...(finished === undefined ? {} : { lastTurnStatus: finished }),
746
829
  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 }),
@@ -765,11 +848,8 @@ function requestCompaction(state) {
765
848
  }
766
849
  /** The gh-backed PR settings and the Andorra review loop's, apart: the first change the PR on GitHub, the second never. */
767
850
  function splitPullRequestSettings(settings) {
768
- const gh = {};
851
+ const gh = settings.draft === undefined ? {} : { draft: settings.draft };
769
852
  const review = {};
770
- for (const key of ['autoFix', 'mergeWhenReady', 'draft'])
771
- if (settings[key] !== undefined)
772
- gh[key] = settings[key];
773
853
  for (const key of REVIEW_SETTING_KEYS)
774
854
  if (settings[key] !== undefined)
775
855
  Object.assign(review, { [key]: settings[key] });
@@ -784,7 +864,9 @@ const REVIEW_WAIT_RECORD_TICKS = 5;
784
864
  export function isFinalWakeRefusal(error) {
785
865
  return error instanceof AppServerError
786
866
  && (error.code === 'invalid-params' || error.code === 'not-found' || error.code === 'remote'
787
- || error.code === 'unknown-method' || error.code === 'auth' || error.code === 'nothing-to-continue');
867
+ || error.code === 'unknown-method' || error.code === 'auth' || error.code === 'nothing-to-continue'
868
+ // A task whose worktree is gone cannot wake until the lead recovers it; retrying every few seconds helps nothing.
869
+ || error.code === 'checkout-missing');
788
870
  }
789
871
  const keptPullRequestMessage = (pullRequest) => `${pullRequest.url} is ${pullRequest.state}, so it stays on this task: it is how the user sees what became of the work. Nothing was changed, and there is nothing to clean up here. Only the user removes a ${pullRequest.state} pull request, with Dismiss in its menu.`;
790
872
  function outcomeCompletion(status, reason, limits) {
@@ -846,12 +928,13 @@ function readNodeModelOverrides(value) {
846
928
  const model = entry.model;
847
929
  if (typeof provider !== 'string' || !provider || typeof model !== 'string' || !model)
848
930
  continue;
931
+ const level = entry.reasoningEffort;
849
932
  read ??= {};
850
- read[id] = { provider, model };
933
+ read[id] = { provider, model, ...(isNodeReasoningEffort(level) ? { reasoningEffort: level } : {}) };
851
934
  }
852
935
  return read;
853
936
  }
854
- const RELAYED_PROVIDER_FIELDS = new Set(['id', 'model', 'models', 'modelContextWindows', 'reasoningEffort']);
937
+ const RELAYED_PROVIDER_FIELDS = new Set(['id', 'model', 'models', 'modelContextWindows', 'reasoningEffort', 'thinkingLevels']);
855
938
  const MAX_RELAYED_PROVIDERS = 64;
856
939
  const RELAYED_RESUME_NEEDS_DESKTOP = 'This task uses your computer\'s models. Resume it from Andorra Code on your computer.';
857
940
  const RELAYED_GRAPH_NEEDS_DESKTOP = 'This task uses a graph from your computer. Resume it from Andorra Code on your computer.';
@@ -894,7 +977,7 @@ function readRelay(value, options = {}) {
894
977
  throw new AppServerError('invalid-params', 'Each relayed provider must be an object.');
895
978
  const source = entry;
896
979
  if (Object.keys(source).some(key => !RELAYED_PROVIDER_FIELDS.has(key))) {
897
- throw new AppServerError('invalid-params', 'A relayed provider carries only id, model, models, modelContextWindows and reasoningEffort.');
980
+ throw new AppServerError('invalid-params', 'A relayed provider carries only id, model, models, modelContextWindows, reasoningEffort and thinkingLevels.');
898
981
  }
899
982
  if (typeof source.id !== 'string' || !/^[\w-]{1,128}$/.test(source.id))
900
983
  throw new AppServerError('invalid-params', 'A relayed provider id must be up to 128 word characters and dashes.');
@@ -918,6 +1001,18 @@ function readRelay(value, options = {}) {
918
1001
  }
919
1002
  provider.modelContextWindows = Object.fromEntries(Object.entries(windows));
920
1003
  }
1004
+ if (source.thinkingLevels !== undefined) {
1005
+ try {
1006
+ validateThinkingLevels(source.thinkingLevels, 'relayed');
1007
+ if (Object.keys(source.thinkingLevels).some(key => key !== provider.model && !provider.models?.includes(key))) {
1008
+ throw new Error('reasoning levels must belong to a declared model');
1009
+ }
1010
+ provider.thinkingLevels = source.thinkingLevels;
1011
+ }
1012
+ catch (error) {
1013
+ throw new AppServerError('invalid-params', `Invalid relay thinking levels: ${message(error)}`);
1014
+ }
1015
+ }
921
1016
  if (source.reasoningEffort !== undefined)
922
1017
  provider.reasoningEffort = reasoningEffort(source.reasoningEffort);
923
1018
  return provider;
@@ -942,7 +1037,9 @@ function readRelayFailure(value) {
942
1037
  return undefined;
943
1038
  const source = value;
944
1039
  const kind = RELAY_ERROR_KINDS.includes(source.kind) ? source.kind : 'other';
1040
+ const timeout = kind === 'provider-request' && source.code === 'provider_timeout' ? readProviderTurnTiming(source.timeout) : undefined;
945
1041
  return {
1042
+ ...(timeout ? { timeout } : {}),
946
1043
  message: typeof source.message === 'string' ? source.message.slice(0, 4_000) : '', kind,
947
1044
  ...(source.contextOverflow === true ? { contextOverflow: true } : {}),
948
1045
  ...(typeof source.code === 'string' && RELAY_FAILURE_CODE.test(source.code) ? { code: source.code } : {}),
@@ -957,6 +1054,7 @@ export class AppServer {
957
1054
  manualAutomationTasks = new Set();
958
1055
  automationController = new AbortController();
959
1056
  directory;
1057
+ telemetry;
960
1058
  output;
961
1059
  error;
962
1060
  checkGraphHealth;
@@ -967,7 +1065,6 @@ export class AppServer {
967
1065
  anthropicAuth;
968
1066
  claudeSignIn;
969
1067
  grokSignIn;
970
- googleSignIn;
971
1068
  openCodeSignIn;
972
1069
  signInProbes;
973
1070
  detectedSignIns = new Map();
@@ -982,18 +1079,17 @@ export class AppServer {
982
1079
  githubEvents;
983
1080
  /** "@andorra-code" mentions on a task's PR (phase 3): the access check, the 👀 and the wake. */
984
1081
  mentions;
985
- /** The App's bot login (`bot` from `GET /v1/github`, or `as` from a bot write), for the Auto-fix prompt. */
1082
+ /** The App's bot login (`bot` from `GET /v1/github`, or `as` from a bot write), for review findings. */
986
1083
  githubBot;
987
1084
  pullRequestReader;
988
1085
  sessionChanges;
989
- autoFixWakes = new Set();
990
1086
  /** Wakes the PR tab's Fix with Agent armed: delivered as the person's request, not as a timer. */
991
1087
  fixWakes = new Set();
992
1088
  /** Wakes a mention of the App's bot on the task's PR armed: delivered as "Mentioned on GitHub", not as a timer. */
993
1089
  mentionWakes = new Set();
994
1090
  reviewWaiters = new Map();
995
1091
  reviewWaitsStarting = new Set();
996
- /** The Andorra review loop's fixer wakes, beside Auto-fix's: delivered as "Andorra review", routed like Auto-fix's. */
1092
+ /** The Andorra review loop's fixer wakes, routed to the node that took the pull request. */
997
1093
  reviewWakes = new Set();
998
1094
  /** Each review wait's run, when it started, and the review loop it watches (the one running when it started, or after). */
999
1095
  reviewWaitRuns = new Map();
@@ -1071,7 +1167,9 @@ export class AppServer {
1071
1167
  titleReleases = new Map();
1072
1168
  titleAnswered = new Set(); // runs whose model has answered at least once
1073
1169
  sessionTitles = new Map();
1074
- workGeneration = 0;
1170
+ /** Automatic titles waiting to be asked again, by session, after an attempt was refused, failed, or cut short. */
1171
+ titleRetries = new Map();
1172
+ draftGraphProbes = new Map();
1075
1173
  operations = new Set();
1076
1174
  prepareTask;
1077
1175
  foreignEngineWatch;
@@ -1080,6 +1178,8 @@ export class AppServer {
1080
1178
  codeIntel;
1081
1179
  codeIntelOpening = Promise.resolve();
1082
1180
  engineLinks = new Map();
1181
+ /** The telemetry lease in force when the current GitHub watch window began; its counts are reported only under that lease. */
1182
+ githubWatchLease;
1083
1183
  environmentOptions;
1084
1184
  relay;
1085
1185
  environmentIds;
@@ -1091,6 +1191,8 @@ export class AppServer {
1091
1191
  /** Bumped when the account changes, so an answer fetched for the previous account is never cached. */
1092
1192
  accountGeneration = 0;
1093
1193
  closed = false;
1194
+ antigravityStartups = new Set();
1195
+ antigravitySessions = new Map();
1094
1196
  emitsStopped = false;
1095
1197
  hosted;
1096
1198
  hostedStarted = false;
@@ -1098,6 +1200,7 @@ export class AppServer {
1098
1200
  onStop;
1099
1201
  constructor(options) {
1100
1202
  this.directory = options.directory ?? configDirectory();
1203
+ this.telemetry = new AppServerTelemetry(this.directory, result => this.emit('telemetry.changed', { ...result }), () => this.emit('config.changed', {})); // invalidate outside display data without polling auth
1101
1204
  this.sessionChanges = new SessionChangeStore(this.directory);
1102
1205
  this.output = options.output;
1103
1206
  this.error = options.error;
@@ -1128,7 +1231,6 @@ export class AppServer {
1128
1231
  this.environmentOptions = options.environments ?? {};
1129
1232
  this.claudeSignIn = options.managedSignIn?.claude ?? claudeSignIn();
1130
1233
  this.grokSignIn = options.managedSignIn?.grok ?? grokSignIn();
1131
- this.googleSignIn = options.managedSignIn?.google ?? googleSignIn();
1132
1234
  this.openCodeSignIn = options.managedSignIn?.opencode ?? new OpenCodeSignIn();
1133
1235
  this.signInProbes = options.signInProbes;
1134
1236
  this.retireCodexAccount = options.removeCodexAccount ?? removeCodexAccount;
@@ -1142,16 +1244,9 @@ export class AppServer {
1142
1244
  this.pullRequestWatcher = new PullRequestWatcher({
1143
1245
  home: this.directory, gh: this.gh, intervalMs: options.pullRequestPollMs,
1144
1246
  onUpdated: (sessionId, pullRequest) => this.emitPullRequest(sessionId, pullRequest),
1145
- wake: (sessionId, prompt, carry, origin) => {
1146
- const wakeId = this.wakeForPullRequest(sessionId, prompt, carry, origin);
1147
- this.githubEvents.woke(sessionId);
1148
- return wakeId;
1149
- },
1150
- wakePending: id => this.timers.list().some(timer => timer.id === id),
1151
1247
  log: (level, detail) => this.log(level, detail),
1152
1248
  covered: sessionId => this.githubEvents.covers(sessionId),
1153
1249
  onGhCall: sessionId => this.githubEvents.countGhCall(sessionId),
1154
- agentWrites: sessionId => this.autoFixWrites(sessionId),
1155
1250
  onRead: (sessionId, pullRequest) => this.reviewLoop.pullRequestRead(sessionId, pullRequest),
1156
1251
  ...(options.githubApp?.now === undefined ? {} : { now: options.githubApp.now }),
1157
1252
  ...(options.githubApp?.checkNowDelayMs === undefined ? {} : { checkNowDelayMs: options.githubApp.checkNowDelayMs }),
@@ -1187,8 +1282,11 @@ export class AppServer {
1187
1282
  onSummary: summary => {
1188
1283
  // The window is gated like a run's events, on the signed-in account's plan and opt-out. Without a readable
1189
1284
  // subject that cannot be checked, so the window is not sent at all.
1285
+ // The window's counts carry the lease latched when it began; the next window latches the one current now.
1286
+ const lease = this.githubWatchLease;
1287
+ this.githubWatchLease = telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals });
1190
1288
  const work = this.githubAccount().catch(() => undefined).then(subject => subject === undefined ? undefined
1191
- : reportGitHubWatch({ home: this.directory, surface: configuredSurface('desktop'), subject }, summary));
1289
+ : reportGitHubWatch({ home: this.directory, signals: this.telemetry.signals, surface: configuredSurface('desktop'), subject, ...(lease ? { lease } : {}) }, summary));
1192
1290
  this.telemetrySettle = this.telemetrySettle.then(() => work).catch(() => { });
1193
1291
  return work;
1194
1292
  },
@@ -1216,13 +1314,13 @@ export class AppServer {
1216
1314
  const status = await readFile(runRecordPath(this.directory, runId, 'json'), 'utf8').then(text => JSON.parse(text).status, () => undefined);
1217
1315
  return status === 'interrupted' || status === 'running';
1218
1316
  },
1219
- workspace: async (sessionId) => (await this.readSession(sessionId).catch(() => undefined))?.workspace,
1317
+ workspace: async (sessionId) => { const record = await this.readSession(sessionId).catch(() => undefined); return record === undefined ? undefined : sessionWorkRoot(record); },
1220
1318
  defaultModel: async () => {
1221
1319
  const config = await loadConfig(this.directory);
1222
1320
  const provider = config.providers.find(entry => entry.id === config.provider);
1223
1321
  return provider?.model ? { provider: provider.id, model: provider.model } : undefined;
1224
1322
  },
1225
- writes: sessionId => this.autoFixWrites(sessionId),
1323
+ writes: sessionId => this.reviewCommentWrites(sessionId),
1226
1324
  wake: (sessionId, prompt, pullRequest) => this.wakeForReview(sessionId, prompt, pullRequest),
1227
1325
  wakeArmed: wakeId => this.timers.get(wakeId) !== undefined,
1228
1326
  cancelWake: (sessionId, wakeId) => this.cancelReviewWake(sessionId, wakeId),
@@ -1360,8 +1458,20 @@ export class AppServer {
1360
1458
  }
1361
1459
  async ready() {
1362
1460
  setAuthSignOutReporter(error => this.accountSignedOut(error.message));
1461
+ this.telemetry.watch();
1363
1462
  this.emit('ready', await this.hostInfo());
1364
1463
  bootMark('ready.emitted');
1464
+ if (process.env.ANDORRA_AUTOMATION_WORKER !== '1')
1465
+ this.flushReasoningProbeQueue();
1466
+ if (process.env.ANDORRA_DESKTOP_RELEASE_VERSION && process.env.ANDORRA_AUTOMATION_WORKER !== '1' &&
1467
+ configuredSurface('desktop') === 'desktop') {
1468
+ // The observation is made now, so it carries the lease current now; a later Yes does not authorize it.
1469
+ const observedLease = telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals });
1470
+ const input = { home: this.directory, surface: 'desktop', signals: this.telemetry.signals, ...(observedLease ? { lease: observedLease } : {}) };
1471
+ this.telemetrySettle = this.telemetrySettle
1472
+ .then(() => reportInstallationObserved(input, desktopInstallationReceipt()))
1473
+ .then(() => drainTelemetry(input, AbortSignal.timeout(2_000)));
1474
+ }
1365
1475
  if (process.env.ANDORRA_AUTOMATION_WORKER !== '1' && !this.closed && !this.automationCheck) {
1366
1476
  const reconcile = reconcileAutomationService(this.directory)
1367
1477
  .catch(error => this.log('warn', `Automation sign-in registration: ${message(error)}`))
@@ -1520,7 +1630,7 @@ export class AppServer {
1520
1630
  return { run: {
1521
1631
  runId: live.runId, sessionId: live.sessionId, workspace: live.workspace,
1522
1632
  questions: waiting.flatMap(item => item.kind === 'question'
1523
- ? [{ id: item.id, question: item.question, ...(item.choices === undefined ? {} : { choices: [...item.choices] }) }] : []),
1633
+ ? [{ id: item.id, question: item.question, ...(item.choices === undefined ? {} : { choices: [...item.choices] }), ...(item.handoff ? { handoff: item.handoff } : {}) }] : []),
1524
1634
  approvals: waiting.flatMap(item => item.kind === 'approval'
1525
1635
  ? [{ id: item.id, name: item.name, arguments: item.arguments }] : []),
1526
1636
  ...(this.modelRelay.awaiting(live.runId) ? { state: 'awaiting-desktop' } : {}),
@@ -1577,7 +1687,7 @@ export class AppServer {
1577
1687
  this.write({ id: request.id, result: result ?? null });
1578
1688
  }
1579
1689
  catch (error) {
1580
- this.write({ id: request.id, error: { code: error instanceof AppServerError ? error.code : 'internal', message: message(error) } });
1690
+ this.write({ id: request.id, error: { code: error instanceof AppServerError || error instanceof TelemetryPrivacyError || error instanceof LegalAcceptanceRequired ? error.code : 'internal', message: message(error) } });
1581
1691
  }
1582
1692
  }
1583
1693
  write(response) {
@@ -1586,10 +1696,130 @@ export class AppServer {
1586
1696
  }
1587
1697
  catch { }
1588
1698
  }
1699
+ async antigravityRequest(method, params) {
1700
+ if (this.closed)
1701
+ throw new AppServerError('cancelled', 'Engine is shutting down');
1702
+ if (method === 'antigravity.start') {
1703
+ if (typeof params.cwd !== 'string' || !isAbsolute(params.cwd)) {
1704
+ throw new AppServerError('invalid-params', 'Choose a local project directory for Antigravity.');
1705
+ }
1706
+ const sessionId = randomUUID();
1707
+ const startup = new AbortController();
1708
+ const permissions = new Map();
1709
+ const clearPermissions = () => {
1710
+ for (const answer of permissions.values())
1711
+ answer();
1712
+ permissions.clear();
1713
+ };
1714
+ this.antigravityStartups.add(startup);
1715
+ try {
1716
+ const session = await AntigravitySession.start({
1717
+ cwd: params.cwd,
1718
+ signal: startup.signal,
1719
+ version: await this.version(),
1720
+ onUpdate: update => this.emit('antigravity.update', { sessionId, update }),
1721
+ requestPermission: request => new Promise(resolve => {
1722
+ const requestId = randomUUID();
1723
+ permissions.set(requestId, resolve);
1724
+ this.emit('antigravity.permissionRequested', {
1725
+ sessionId, requestId, toolCall: request.toolCall, options: request.options,
1726
+ });
1727
+ }),
1728
+ onClosed: message => {
1729
+ clearPermissions();
1730
+ this.antigravitySessions.delete(sessionId);
1731
+ this.emit('antigravity.closed', { sessionId, message });
1732
+ },
1733
+ });
1734
+ if (this.closed) {
1735
+ await session.close();
1736
+ throw new AppServerError('cancelled', 'Engine is shutting down');
1737
+ }
1738
+ if (!session.isOpen) {
1739
+ await session.close();
1740
+ throw new AppServerError('not-found', 'Antigravity closed during startup. Start a new session to try again.');
1741
+ }
1742
+ this.antigravitySessions.set(sessionId, { session, permissions, clearPermissions, prompting: false });
1743
+ return { sessionId, options: session.options };
1744
+ }
1745
+ finally {
1746
+ this.antigravityStartups.delete(startup);
1747
+ }
1748
+ }
1749
+ const sessionId = identifier(params.sessionId, 'sessionId');
1750
+ const entry = this.antigravitySessions.get(sessionId);
1751
+ if (!entry) {
1752
+ if (method === 'antigravity.close')
1753
+ return {};
1754
+ throw new AppServerError('invalid-params', 'This Antigravity session has closed. Start a new session to continue.');
1755
+ }
1756
+ switch (method) {
1757
+ case 'antigravity.prompt': {
1758
+ if (typeof params.text !== 'string' || !params.text.trim() || params.text.length > 100_000) {
1759
+ throw new AppServerError('invalid-params', 'Enter an Antigravity prompt of up to 100,000 characters.');
1760
+ }
1761
+ if (entry.prompting)
1762
+ throw new AppServerError('busy', 'Antigravity is already processing a prompt.');
1763
+ entry.prompting = true;
1764
+ try {
1765
+ return await entry.session.prompt(params.text);
1766
+ }
1767
+ finally {
1768
+ entry.clearPermissions();
1769
+ entry.prompting = false;
1770
+ }
1771
+ }
1772
+ case 'antigravity.permission': {
1773
+ const requestId = identifier(params.requestId, 'requestId');
1774
+ if (params.optionId !== undefined && typeof params.optionId !== 'string') {
1775
+ throw new AppServerError('invalid-params', 'Choose an Antigravity permission option.');
1776
+ }
1777
+ const answer = entry.permissions.get(requestId);
1778
+ entry.permissions.delete(requestId);
1779
+ answer?.(params.optionId);
1780
+ return {};
1781
+ }
1782
+ case 'antigravity.cancel':
1783
+ entry.clearPermissions();
1784
+ await entry.session.cancel();
1785
+ return {};
1786
+ case 'antigravity.close':
1787
+ this.antigravitySessions.delete(sessionId);
1788
+ entry.clearPermissions();
1789
+ await entry.session.close();
1790
+ return {};
1791
+ case 'antigravity.option': {
1792
+ if (typeof params.configId !== 'string' || typeof params.value !== 'string') {
1793
+ throw new AppServerError('invalid-params', 'Choose an Antigravity option and value.');
1794
+ }
1795
+ return { options: await entry.session.setOption(params.configId, params.value) };
1796
+ }
1797
+ default: throw new AppServerError('unknown-method', `Unknown method: ${method}`);
1798
+ }
1799
+ }
1589
1800
  async dispatch(method, params) {
1801
+ if (method.startsWith('antigravity.')) {
1802
+ // Starting a session and sending a prompt are coding work; cancelling, closing and answering stay available.
1803
+ if (legalMethodRequiresAcceptance(method))
1804
+ await requireLegalAcceptance(this.directory);
1805
+ return this.antigravityRequest(method, params);
1806
+ }
1590
1807
  if (this.closed && method.startsWith('automations.'))
1591
1808
  throw new AppServerError('cancelled', 'Engine is shutting down');
1809
+ if (legalRequestRequiresAcceptance(method, params))
1810
+ await requireLegalAcceptance(this.directory);
1592
1811
  switch (method) {
1812
+ case 'legal.status': return legalStatus(this.directory, {}, params.refresh === true);
1813
+ case 'legal.documents': {
1814
+ if (params.kind !== 'terms' && params.kind !== 'privacy')
1815
+ throw new AppServerError('invalid-params', 'Choose terms or privacy');
1816
+ return { html: await legalDocument(params.kind) };
1817
+ }
1818
+ case 'legal.accept': {
1819
+ if (params.confirmed !== true || typeof params.releaseId !== 'string' || (params.expectedSubject !== null && typeof params.expectedSubject !== 'string'))
1820
+ throw new AppServerError('invalid-params', 'Review the policies and confirm explicitly.');
1821
+ return acceptLegal({ releaseId: params.releaseId, expectedSubject: params.expectedSubject, confirmed: true }, this.directory, {}, 'desktop');
1822
+ }
1593
1823
  case 'automations.list': return { automations: await new AutomationStore(this.directory).list(), service: await automationService('status', this.directory) };
1594
1824
  case 'automations.create': return { automation: await new AutomationStore(this.directory).create(params) };
1595
1825
  case 'automations.update': {
@@ -1612,9 +1842,12 @@ export class AppServer {
1612
1842
  }
1613
1843
  case 'host.info': return { ...(await this.hostInfo()), running: this.run !== undefined || this.starting };
1614
1844
  case 'run.current': return this.currentRun();
1845
+ case 'telemetry.status': return this.telemetry.status(params);
1846
+ case 'telemetry.setConsent': return this.telemetry.setConsent(params);
1615
1847
  case 'config.get': return { config: await this.analyticsConfigView(await loadConfig(this.directory)) };
1616
1848
  case 'config.set': return this.setConfig(params);
1617
1849
  case 'project.extensions': return this.projectExtensionEntry(params);
1850
+ case 'workspace.permission': return this.workspacePermissionEntry(params);
1618
1851
  case 'project.extensions.set': return this.setProjectExtensionEntry(params);
1619
1852
  case 'providers.list': {
1620
1853
  const config = await loadConfig(this.directory);
@@ -1641,6 +1874,11 @@ export class AppServer {
1641
1874
  case 'andorra.remove': return this.hideListedEntry();
1642
1875
  case 'providers.discover': return this.discoverModels(params);
1643
1876
  case 'providers.test': return this.testProviderEndpoint(params);
1877
+ case 'providers.getThinkingLevels': return this.getThinkingLevels(params);
1878
+ case 'providers.detectThinkingLevels': return this.detectThinkingLevels(params);
1879
+ case 'providers.setThinkingLevels': return this.setThinkingLevels(params);
1880
+ case 'providers.usage': return this.providerUsage();
1881
+ case 'routing.refreshScores': return this.refreshRoutingScores();
1644
1882
  case 'providers.detectSignIns': return this.detectProviderSignIns(params);
1645
1883
  case 'providers.importSignIns': return this.importProviderSignIns(params);
1646
1884
  case 'providers.auth.status': return this.providerAuth('status', params);
@@ -1678,9 +1916,10 @@ export class AppServer {
1678
1916
  case 'sessions.setJev': return { session: this.summary(await this.setSessionJev(params)) };
1679
1917
  case 'sessions.setArchived': return { session: this.summary(await this.setSessionArchived(params)) };
1680
1918
  case 'sessions.setPinned': return { session: this.summary(await this.setSessionPinned(params)) };
1919
+ case 'sessions.setWorkspace': return { session: this.summary(await this.setSessionWorkspace(params)) };
1681
1920
  case 'sessions.delete': return this.deleteSession(params);
1682
- case 'sessions.pullRequest.get': return { pullRequest: pullRequestForClients(await readPullRequest(this.directory, identifier(params.id, 'id'))) };
1683
- case 'sessions.pullRequest.list': return { pullRequests: (await listPullRequests(this.directory)).map(entry => ({ sessionId: entry.sessionId, pullRequest: pullRequestForClients(entry.pullRequest) })) };
1921
+ case 'sessions.pullRequest.get': return { pullRequest: this.pullRequestForClient(await readPullRequest(this.directory, identifier(params.id, 'id'))) };
1922
+ case 'sessions.pullRequest.list': return { pullRequests: (await listPullRequests(this.directory)).map(entry => ({ sessionId: entry.sessionId, pullRequest: this.pullRequestForClient(entry.pullRequest) })) };
1684
1923
  case 'sessions.pullRequest.update': {
1685
1924
  let settings;
1686
1925
  try {
@@ -1689,7 +1928,7 @@ export class AppServer {
1689
1928
  catch (error) {
1690
1929
  throw new AppServerError('invalid-params', message(error));
1691
1930
  }
1692
- return { pullRequest: pullRequestForClients(await this.updatePullRequest(identifier(params.id, 'id'), settings)) };
1931
+ return { pullRequest: this.pullRequestForClient(await this.updatePullRequest(identifier(params.id, 'id'), settings)) };
1693
1932
  }
1694
1933
  case 'sessions.pullRequest.dismiss':
1695
1934
  await this.dismissPullRequest(identifier(params.id, 'id'));
@@ -1722,6 +1961,7 @@ export class AppServer {
1722
1961
  case 'github.status': return this.githubStatus();
1723
1962
  case 'github.connect': return this.githubConnect(params);
1724
1963
  case 'github.disconnect': return this.githubDisconnect();
1964
+ case 'github.repositories': return this.githubRepositories();
1725
1965
  case 'github.setAgentWrites': return this.githubSetAgentWrites(params);
1726
1966
  case 'issues.list': return this.listWorkspaceIssues(params);
1727
1967
  case 'sessions.changes.list': return this.sessionChanges.list(changesSessionId(params.id), diffLines(params.maxLines, LIST_DIFF_LINES));
@@ -1758,10 +1998,11 @@ export class AppServer {
1758
1998
  case 'graphs.list': return this.listGraphs(params);
1759
1999
  case 'graphs.get': return this.getGraph(params);
1760
2000
  case 'graphs.select': return this.selectGraph(params);
2001
+ case 'graphs.checkModels': return this.checkDraftGraphModels(params);
1761
2002
  case 'graphs.visibility.set': return this.setGraphVisibilityMethod(params);
1762
2003
  case 'graphs.visibility.import': return this.importGraphVisibilityMethod(params);
1763
2004
  case 'agents.export': return this.exportAgent(params);
1764
- case 'editor.open': return this.openEditor();
2005
+ case 'editor.open': return this.openEditor(params);
1765
2006
  case 'editor.close': return this.closeEditor();
1766
2007
  case 'terminal.open': {
1767
2008
  const root = await workspaceRoot(params.cwd);
@@ -2019,6 +2260,15 @@ export class AppServer {
2019
2260
  const root = await workspaceRoot(params.workspace);
2020
2261
  return readWorkspaceFile(root, params.path);
2021
2262
  }
2263
+ case 'workspace.image': {
2264
+ const root = await workspaceRoot(params.workspace);
2265
+ try {
2266
+ return await readWorkspaceImage(root, params.path, { outside: params.outside === true });
2267
+ }
2268
+ catch (error) {
2269
+ throw new AppServerError('invalid-params', message(error));
2270
+ }
2271
+ }
2022
2272
  case 'workspace.write': {
2023
2273
  const root = await workspaceRoot(params.workspace);
2024
2274
  if (params.sessionId !== undefined && (typeof params.sessionId !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(params.sessionId)))
@@ -2085,6 +2335,20 @@ export class AppServer {
2085
2335
  return listBranches(root);
2086
2336
  }
2087
2337
  case 'workspace.checkout': return this.switchBranch(params);
2338
+ case 'workspace.startPoints': {
2339
+ const root = await workspaceRoot(params.workspace);
2340
+ return taskStartPoints(root);
2341
+ }
2342
+ case 'workspace.prepareTask': return this.prepareTaskCheckout(params);
2343
+ case 'workspace.discardPrepared': {
2344
+ const root = await workspaceRoot(params.workspace);
2345
+ return { removed: await discardPreparedWorktree(this.directory, root, text(params.key, 'key', 64)) };
2346
+ }
2347
+ case 'sessions.setReviewed': return { session: this.summary(await this.setSessionReviewed(params)) };
2348
+ case 'sessions.checkout.state': return this.sessionCheckoutState(params);
2349
+ case 'sessions.checkout.recover': return { session: this.summary(await this.recoverSessionCheckout(params)) };
2350
+ case 'sessions.checkout.inspect': return this.inspectSessionCheckout(params);
2351
+ case 'sessions.checkout.remove': return this.removeSessionCheckout(params);
2088
2352
  case 'workspace.diff': {
2089
2353
  const root = await workspaceRoot(params.workspace);
2090
2354
  return gitDiff(root, { path: params.path, staged: params.staged, base: params.base });
@@ -2099,6 +2363,14 @@ export class AppServer {
2099
2363
  }
2100
2364
  return sessionTrajectoryFile(this.directory, await this.trajectoryIdOf(id));
2101
2365
  }
2366
+ case 'sessions.artifact.read': {
2367
+ const id = identifier(params.id, 'id');
2368
+ const reference = parseArtifactReference(params.ref);
2369
+ const session = await this.readSession(id);
2370
+ if (!session.history.some(turn => turn.runId === reference.runId))
2371
+ throw artifactUnavailable();
2372
+ return readArtifactPreview(this.directory, reference);
2373
+ }
2102
2374
  case 'sessions.trajectory': {
2103
2375
  const id = params.id;
2104
2376
  if (typeof id !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(id)) {
@@ -2135,6 +2407,7 @@ export class AppServer {
2135
2407
  case 'remote.owner.roots': return this.remoteOwnerRoots(params);
2136
2408
  case 'remote.owner.browse': return this.remoteOwnerBrowse(params);
2137
2409
  case 'remote.owner.projects.add': return this.remoteOwnerAddProject(params);
2410
+ case 'remote.owner.github.clone': return this.remoteOwnerGitHubClone(params);
2138
2411
  case 'remote.engine.connect': return this.remoteEngineConnect(params);
2139
2412
  case 'remote.engine.request': return this.remoteEngineRequest(params);
2140
2413
  case 'remote.engine.disconnect': return this.remoteEngineDisconnect(params);
@@ -2195,7 +2468,7 @@ export class AppServer {
2195
2468
  this.slotWrites.delete(slot); });
2196
2469
  return next;
2197
2470
  }
2198
- async setConfig(params) {
2471
+ async setConfig(params, admittedLegacy = false) {
2199
2472
  const patch = params.config;
2200
2473
  if (!patch || typeof patch !== 'object' || Array.isArray(patch))
2201
2474
  throw new AppServerError('invalid-params', 'config must be an object');
@@ -2206,13 +2479,48 @@ export class AppServer {
2206
2479
  const unknown = entries.map(([key]) => key).filter(key => !EDITABLE_CONFIG_KEYS.includes(key));
2207
2480
  if (unknown.length)
2208
2481
  throw new AppServerError('invalid-params', `Unknown configuration field: ${unknown.join(', ')}`);
2482
+ const analytics = patch.analytics;
2483
+ if (analytics !== undefined && !admittedLegacy) {
2484
+ try {
2485
+ validateAnalyticsConfig(analytics);
2486
+ }
2487
+ catch (error) {
2488
+ throw new AppServerError('invalid-params', message(error));
2489
+ }
2490
+ const permission = await this.telemetry.permission();
2491
+ if (!permission.permissionRequired) {
2492
+ const saved = await withTelemetryAdmission({ home: this.directory, signals: this.telemetry.signals }, async (admission) => {
2493
+ if (admission.lease.mode !== 'out')
2494
+ throw new AppServerError('busy', 'Privacy settings changed. Reload and try again.');
2495
+ return this.setConfig(params, true);
2496
+ });
2497
+ if (saved === undefined)
2498
+ throw new AppServerError('busy', 'Privacy settings changed. Reload and try again.');
2499
+ return saved;
2500
+ }
2501
+ // An old on is never permission, a migration, or an analytics config write. Old off
2502
+ // is a safe explicit refusal on every plan, before taking any configuration lock.
2503
+ if (analytics.enabled === false) {
2504
+ const result = await this.telemetry.setConsent({ answer: 'no', expectedRevision: permission.revision, noticeVersion: permission.noticeVersion });
2505
+ if (result.conflict)
2506
+ throw new AppServerError('busy', 'Privacy settings changed. Reload and try again.');
2507
+ if (result.cleanupError)
2508
+ throw new AppServerError('storage', 'Reports are off; privacy cleanup needs to finish. Retry the setting.');
2509
+ }
2510
+ const functional = Object.fromEntries(entries.filter(([key]) => key !== 'analytics'));
2511
+ if (Object.keys(functional).length)
2512
+ return this.setConfig({ ...params, config: functional, ...(expects ? { expects: Object.fromEntries(Object.entries(expects).filter(([key]) => key !== 'analytics')) } : {}) });
2513
+ const view = await this.analyticsConfigView(await loadConfig(this.directory));
2514
+ this.emit('config.changed', { config: view });
2515
+ return { config: view };
2516
+ }
2209
2517
  if (patch.analytics?.enabled === false) {
2210
2518
  const current = await loadConfig(this.directory);
2211
2519
  const status = await getAuthStatus().catch(() => undefined);
2212
- const gate = await telemetryGate({ home: this.directory, config: current, subject: status?.signedIn ? status.subject : undefined });
2520
+ const gate = await telemetryGate({ home: this.directory, signals: this.telemetry.signals, config: current, subject: status?.signedIn ? status.subject : undefined });
2213
2521
  if (!gate.canOptOut) {
2214
2522
  const named = gate.plan === 'free' ? 'Free' : gate.plan === 'legacy' ? 'Legacy' : 'current';
2215
- throw new AppServerError('invalid-params', `Anonymous feedback is included with the ${named} plan; upgrade to Paid to turn it off.`);
2523
+ throw new AppServerError('invalid-params', `Product usage reports stay on: collection is included with the ${named} plan outside the EEA, UK and Switzerland. Upgrade to Plus to turn it off.`);
2216
2524
  }
2217
2525
  }
2218
2526
  let turnedOff = false;
@@ -2220,7 +2528,7 @@ export class AppServer {
2220
2528
  const removedAnthropic = [];
2221
2529
  const saved = await this.serializeConfig(async () => {
2222
2530
  try {
2223
- return await changeConfigFile(this.directory, current => {
2531
+ return await (admittedLegacy ? changeLegacyConfigFile : changeConfigFile)(this.directory, current => {
2224
2532
  for (const [key, value] of Object.entries((expects ?? {}))) {
2225
2533
  const stored = current[key];
2226
2534
  const expected = value === null && ['decisions', 'jevEnabled', 'systemPromptOverride', 'autoArchiveDays'].includes(key) ? undefined : value;
@@ -2228,6 +2536,18 @@ export class AppServer {
2228
2536
  throw new AppServerError('busy', `That setting changed elsewhere: ${key}. Reload it and try again.`);
2229
2537
  }
2230
2538
  const merged = { ...current, ...Object.fromEntries(entries) };
2539
+ if (Object.hasOwn(patch, 'adaptiveRouting')) {
2540
+ // The settings key is a view of efficiency.adaptiveRouting: it is merged there and never stored at the top level.
2541
+ delete merged.adaptiveRouting;
2542
+ const { adaptiveRouting: _savedRouting, ...otherEfficiency } = current.efficiency ?? {};
2543
+ const routing = mergeAdaptiveRoutingSettings(_savedRouting, patch.adaptiveRouting);
2544
+ const efficiency = { ...otherEfficiency, ...(routing === undefined ? {} : { adaptiveRouting: routing }) };
2545
+ validateEfficiencyConfig(efficiency);
2546
+ if (Object.keys(efficiency).length)
2547
+ merged.efficiency = efficiency;
2548
+ else
2549
+ delete merged.efficiency;
2550
+ }
2231
2551
  if (patch.analytics !== undefined) {
2232
2552
  turnedOff = resolveAnalyticsConfig(current).enabled && merged.analytics?.enabled === false;
2233
2553
  merged.analytics = { ...merged.analytics, generation: analyticsGenerationFor(current.analytics, merged.analytics?.enabled !== false) };
@@ -2271,14 +2591,14 @@ export class AppServer {
2271
2591
  }
2272
2592
  });
2273
2593
  if (turnedOff)
2274
- await purgeOutbox(telemetryDirectory(this.directory));
2594
+ await purgeOutbox(telemetryDirectory(this.directory), { signals: this.telemetry.signals });
2275
2595
  if (patch.analytics !== undefined) {
2276
2596
  const status = await getAuthStatus().catch(() => undefined);
2277
2597
  let failure;
2278
2598
  for (let attempt = 0; attempt < 3; attempt++) {
2279
2599
  try {
2280
2600
  await recordPreference({
2281
- directory: telemetryDirectory(this.directory),
2601
+ directory: telemetryDirectory(this.directory), signals: this.telemetry.signals,
2282
2602
  subject: status?.signedIn ? status.subject : undefined,
2283
2603
  preference: saved.analytics?.enabled === false ? 'off' : 'on',
2284
2604
  });
@@ -2314,6 +2634,14 @@ export class AppServer {
2314
2634
  const entry = config.projectExtensions?.[workspacePermissionKey(path)];
2315
2635
  return { entry: entry ? structuredClone(entry) : { override: false } };
2316
2636
  }
2637
+ // Mirrors projectExtensionEntry: the desktop sends the project path and the engine resolves the stored entry
2638
+ // with the same workspacePermissionKey and workspaceRoot every run applies, so the desktop's permission picker
2639
+ // shows the mode a task would actually start in instead of guessing the CLI's fallback.
2640
+ async workspacePermissionEntry(params) {
2641
+ const root = await workspaceRoot(params.workspace);
2642
+ const config = await loadConfig(this.directory);
2643
+ return { mode: config.workspacePermissions?.[workspacePermissionKey(root)] ?? 'ask-for-approval' };
2644
+ }
2317
2645
  async setProjectExtensionEntry(params) {
2318
2646
  const path = text(params.path, 'path', 4096);
2319
2647
  if (!isProjectExtensionOverride(params.entry))
@@ -2717,10 +3045,12 @@ export class AppServer {
2717
3045
  return { config: view, added };
2718
3046
  }
2719
3047
  async providerAuth(action, params) {
2720
- if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'google' || params.providerType === 'opencode')
3048
+ if (params.providerType === 'google')
3049
+ throw new AppServerError('invalid-params', GOOGLE_LEGACY_MESSAGE);
3050
+ if (params.providerType === 'claude' || params.providerType === 'grok' || params.providerType === 'opencode')
2721
3051
  return this.managedProviderAuth(action, params);
2722
3052
  if (action === 'submit')
2723
- throw new AppServerError('invalid-params', 'Only Claude, Grok, Google and OpenCode sign-ins accept a pasted code.');
3053
+ throw new AppServerError('invalid-params', 'Only Claude, Grok and OpenCode sign-ins accept a pasted code.');
2724
3054
  if (params.providerType === 'anthropic')
2725
3055
  return this.anthropicProviderAuth(action, params);
2726
3056
  if (params.providerType !== 'codex' || Object.keys(params).some(key => !['providerType', 'attemptId', 'providerId'].includes(key))) {
@@ -2753,7 +3083,7 @@ export class AppServer {
2753
3083
  }
2754
3084
  async managedProviderAuth(action, params) {
2755
3085
  const type = params.providerType;
2756
- const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : type === 'google' ? 'Google' : 'OpenCode';
3086
+ const product = type === 'claude' ? 'Claude' : type === 'grok' ? 'Grok' : 'OpenCode';
2757
3087
  const allowed = ['providerType', 'attemptId', 'providerId', 'code', ...(type === 'opencode' ? ['signInProvider', 'signInMethod'] : [])];
2758
3088
  if (Object.keys(params).some(key => !allowed.includes(key))) {
2759
3089
  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.`);
@@ -2785,7 +3115,7 @@ export class AppServer {
2785
3115
  : await service.status(id);
2786
3116
  }
2787
3117
  else {
2788
- const service = type === 'claude' ? this.claudeSignIn : type === 'google' ? this.googleSignIn : this.grokSignIn;
3118
+ const service = type === 'claude' ? this.claudeSignIn : this.grokSignIn;
2789
3119
  view = action === 'start' ? await service.start(id)
2790
3120
  : action === 'cancel' ? await service.cancel(id)
2791
3121
  : action === 'submit' ? await service.submitCode(id, code)
@@ -2854,6 +3184,142 @@ export class AppServer {
2854
3184
  throw new AppServerError('network', message(error));
2855
3185
  }
2856
3186
  }
3187
+ thinkingLevelTarget(config, params) {
3188
+ const id = identifier(params.providerId, 'providerId');
3189
+ const provider = config.providers.find(item => item.id === id);
3190
+ if (!provider)
3191
+ throw new AppServerError('not-found', `Unknown provider: ${id}`);
3192
+ if (!supportsReasoningEffort(provider.type) || provider.type === 'relayed')
3193
+ throw new AppServerError('invalid-params', `The ${provider.type} provider does not take a thinking level`);
3194
+ const model = params.model === undefined ? provider.model : params.model;
3195
+ if (typeof model !== 'string' || !model.trim() || model.length > 500)
3196
+ throw new AppServerError('invalid-params', 'model must be a non-empty model id');
3197
+ return { provider, model: model.trim() };
3198
+ }
3199
+ thinkingLevelsView(provider, model, detected) {
3200
+ const entry = provider.thinkingLevels?.[model];
3201
+ return { providerId: provider.id, model, detected, supported: entry?.supported ?? [...REASONING_EFFORTS], disabled: entry?.disabled ?? [], enabled: enabledLevels(provider, model) };
3202
+ }
3203
+ async getThinkingLevels(params) {
3204
+ const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
3205
+ if (provider.thinkingLevels?.[model]?.supported !== undefined)
3206
+ return this.thinkingLevelsView(provider, model, true);
3207
+ if (provider.type === 'andorra')
3208
+ return this.thinkingLevelsView(provider, model, false);
3209
+ this.flushReasoningProbeQueue();
3210
+ const generation = this.accountGeneration;
3211
+ const supported = await this.operation(6000, signal => readReasoningProbe(provider, model, signal));
3212
+ if (supported === undefined || generation !== this.accountGeneration)
3213
+ return this.thinkingLevelsView(provider, model, false);
3214
+ const saved = await this.saveThinkingLevels(provider.id, current => {
3215
+ if (generation !== this.accountGeneration)
3216
+ return current;
3217
+ if (current.type !== provider.type || current.baseUrl !== provider.baseUrl)
3218
+ throw new AppServerError('busy', 'The provider changed. Reopen the model picker.');
3219
+ if (Object.hasOwn(current.thinkingLevels ?? {}, model) && current.thinkingLevels?.[model]?.supported !== undefined)
3220
+ return current;
3221
+ return withDetectedLevels(current, model, supported);
3222
+ });
3223
+ this.emit('config.changed', { config: await this.analyticsConfigView(await loadConfig(this.directory)) });
3224
+ return this.thinkingLevelsView(saved, model, saved.thinkingLevels?.[model]?.supported !== undefined);
3225
+ }
3226
+ /** Finds out which thinking levels a model accepts and saves them. An inconclusive answer saves nothing. */
3227
+ async detectThinkingLevels(params) {
3228
+ const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
3229
+ if (provider.type === 'andorra')
3230
+ return this.thinkingLevelsView(provider, model, provider.thinkingLevels?.[model]?.supported !== undefined);
3231
+ const subject = await currentReasoningProbeSubject(AbortSignal.timeout(1500));
3232
+ const probeId = typeof params.probeId === 'string' && /^[a-zA-Z0-9-]{1,64}$/.test(params.probeId) ? params.probeId : undefined;
3233
+ const onAccepted = probeId === undefined ? undefined : (level) => {
3234
+ this.emit('providers.thinkingLevelAccepted', { probeId, providerId: provider.id, model, level });
3235
+ };
3236
+ let supported;
3237
+ try {
3238
+ supported = await this.operation(90_000, signal => detectProviderLevels(provider, model, signal, undefined, onAccepted));
3239
+ }
3240
+ catch (error) {
3241
+ throw new AppServerError('network', message(error));
3242
+ }
3243
+ if (supported === undefined)
3244
+ return this.thinkingLevelsView(provider, model, false);
3245
+ const saved = await this.saveThinkingLevels(provider.id, current => {
3246
+ if (current.type !== provider.type || current.baseUrl !== provider.baseUrl)
3247
+ throw new AppServerError('busy', 'The provider changed. Reopen the model picker.');
3248
+ return withDetectedLevels(current, model, supported);
3249
+ });
3250
+ if (subject !== undefined) {
3251
+ try {
3252
+ await queueReasoningProbe(this.directory, subject, provider, model, supported);
3253
+ }
3254
+ catch {
3255
+ this.log('warn', 'Could not queue reasoning levels for account sync. They were saved locally.');
3256
+ }
3257
+ this.flushReasoningProbeQueue();
3258
+ }
3259
+ this.emit('config.changed', { config: await this.analyticsConfigView(await loadConfig(this.directory)) });
3260
+ return this.thinkingLevelsView(saved, model, true);
3261
+ }
3262
+ flushReasoningProbeQueue() {
3263
+ void this.operation(30_000, signal => flushReasoningProbes(this.directory, signal)).catch(() => { });
3264
+ }
3265
+ async setThinkingLevels(params) {
3266
+ const { provider, model } = this.thinkingLevelTarget(await loadConfig(this.directory), params);
3267
+ const disabled = params.disabled;
3268
+ if (!Array.isArray(disabled) || disabled.some(level => typeof level !== 'string' || !REASONING_EFFORTS.includes(level))) {
3269
+ throw new AppServerError('invalid-params', `disabled must list thinking levels: ${REASONING_EFFORTS.join(', ')}`);
3270
+ }
3271
+ let saved;
3272
+ try {
3273
+ saved = await this.saveThinkingLevels(provider.id, current => withDisabledLevels(current, model, disabled));
3274
+ }
3275
+ catch (error) {
3276
+ if (error instanceof AppServerError)
3277
+ throw error;
3278
+ throw new AppServerError('invalid-params', message(error));
3279
+ }
3280
+ return this.thinkingLevelsView(saved, model, saved.thinkingLevels?.[model]?.supported !== undefined);
3281
+ }
3282
+ /** The subscription usage windows of every provider whose client reports them, by provider id. */
3283
+ async providerUsage() {
3284
+ const config = await loadConfig(this.directory);
3285
+ const read = createUsageReader(() => config.providers, { hosted: () => this.hosted.usage() });
3286
+ const readings = await this.operation(20_000, signal => read(signal));
3287
+ return { usage: Object.entries(readings).flatMap(([providerId, windows]) => windows?.length ? [{ providerId, windows: [...windows] }] : []) };
3288
+ }
3289
+ /**
3290
+ * Scores every configured model from published benchmarks (the average of three providers' general-purpose scores,
3291
+ * at each thinking level they list) and saves the scores that routing chooses by
3292
+ * (`efficiency.adaptiveRouting.scores`). A refresh that scores no model saves nothing.
3293
+ */
3294
+ async refreshRoutingScores() {
3295
+ const config = await loadConfig(this.directory);
3296
+ const subjects = scoreSubjects(config.providers, (providerId, name) => enabledLevels(config.providers.find(item => item.id === providerId), name)).slice(0, MAX_POOL_SCORES);
3297
+ if (!subjects.length)
3298
+ throw new AppServerError('invalid-params', 'No models are configured to score');
3299
+ const previous = config.efficiency?.adaptiveRouting?.scores;
3300
+ let result;
3301
+ try {
3302
+ result = await this.operation(240_000, signal => refreshPoolScores({ subjects, signal, ...(previous ? { previous } : {}) }));
3303
+ }
3304
+ catch (error) {
3305
+ throw new AppServerError('network', message(error));
3306
+ }
3307
+ const scoresUpdatedAt = new Date().toISOString();
3308
+ const saved = await changeConfigFile(this.directory, current => ({ ...current, efficiency: { ...current.efficiency, adaptiveRouting: { ...current.efficiency?.adaptiveRouting, scores: result.scores, scoresUpdatedAt } } }));
3309
+ this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
3310
+ return { scoresUpdatedAt, models: subjects.length, rated: result.rated.length, kept: result.kept.length, unrated: result.unrated, benchmarks: result.benchmarks };
3311
+ }
3312
+ async saveThinkingLevels(id, change) {
3313
+ let next;
3314
+ await changeConfigFile(this.directory, current => {
3315
+ const at = current.providers.findIndex(item => item.id === id);
3316
+ if (at < 0)
3317
+ throw new AppServerError('not-found', `Unknown provider: ${id}`);
3318
+ next = change(current.providers[at]);
3319
+ return { ...current, providers: current.providers.map((item, index) => index === at ? next : item) };
3320
+ });
3321
+ return next;
3322
+ }
2857
3323
  operation(deadlineMs, run) {
2858
3324
  const controller = new AbortController();
2859
3325
  const timer = deadlineMs === undefined ? undefined : setTimeout(() => controller.abort(), deadlineMs);
@@ -2949,6 +3415,7 @@ export class AppServer {
2949
3415
  // The new account's machines that are allowed here get their links.
2950
3416
  this.syncModelRelayLinks();
2951
3417
  this.githubEvents.refresh();
3418
+ this.flushReasoningProbeQueue();
2952
3419
  return { signedIn: status.signedIn, subject: status.subject };
2953
3420
  }
2954
3421
  catch (error) {
@@ -3211,11 +3678,15 @@ export class AppServer {
3211
3678
  widgets: record.widgets,
3212
3679
  context: record.context,
3213
3680
  };
3214
- await new SessionStore(this.directory).save(savedSessionFields(merged));
3215
- publish(merged);
3216
- if (merged.goal?.status === 'met' && metGoal !== undefined && merged.goal.setAt === metGoal.setAt)
3217
- this.emitSessionGoal(merged.id, merged.goal);
3218
- return merged;
3681
+ // A completed turn waits for the lead's review in Needs you; any other ending takes the task off that list.
3682
+ const review = reviewAfterTurn(merged.history, fresh?.review, record.updatedAt);
3683
+ const { review: _was, ...rest } = merged;
3684
+ const reviewed = review === undefined ? rest : { ...rest, review };
3685
+ await new SessionStore(this.directory).save(savedSessionFields(reviewed));
3686
+ publish(reviewed);
3687
+ if (reviewed.goal?.status === 'met' && metGoal !== undefined && reviewed.goal.setAt === metGoal.setAt)
3688
+ this.emitSessionGoal(reviewed.id, reviewed.goal);
3689
+ return reviewed;
3219
3690
  });
3220
3691
  }
3221
3692
  catch (error) {
@@ -3244,6 +3715,24 @@ export class AppServer {
3244
3715
  return updated;
3245
3716
  });
3246
3717
  }
3718
+ /** Marks a task's completed turn reviewed, as Needs you's Mark Reviewed does: only the turn the lead was shown. */
3719
+ async setSessionReviewed(params) {
3720
+ const id = identifier(params.id, 'id');
3721
+ const runId = identifier(params.runId, 'runId');
3722
+ return this.withSessionMutation(id, async () => {
3723
+ const record = await this.readSession(id);
3724
+ if (record.review === undefined)
3725
+ throw new AppServerError('not-found', 'That task has no finished turn waiting for review.');
3726
+ if (record.review.runId !== runId)
3727
+ throw new AppServerError('invalid-params', 'A newer turn of that task finished since you read it. Look at it before marking it reviewed.');
3728
+ if (record.review.reviewedAt !== undefined)
3729
+ return record;
3730
+ const updated = { ...record, review: { ...record.review, reviewedAt: new Date().toISOString() } };
3731
+ await this.store().save(savedSessionFields(updated));
3732
+ this.emit('session.updated', { session: this.summary(updated) });
3733
+ return updated;
3734
+ });
3735
+ }
3247
3736
  /** Pins or unpins a task in the rail. The pin is rail-owned like a rename, so this window's own run may be pinned too: the run carries it forward when it saves. */
3248
3737
  async setSessionPinned(params) {
3249
3738
  const id = identifier(params.id, 'id');
@@ -3267,6 +3756,40 @@ export class AppServer {
3267
3756
  return updated;
3268
3757
  });
3269
3758
  }
3759
+ /** Moves a task into another project folder: the rail lists it there, and its next run works there. */
3760
+ async setSessionWorkspace(params) {
3761
+ const id = identifier(params.id, 'id');
3762
+ const root = await workspaceRoot(params.workspace);
3763
+ if (this.run?.sessionId === id || this.startingSession === id || this.starting)
3764
+ throw new AppServerError('busy', 'That task is running. Stop the run or wait for it to finish, then move it.');
3765
+ if (await folderChangeHeld(this.directory, root))
3766
+ throw new AppServerError('busy', folderChangeBusy);
3767
+ let rekey = false;
3768
+ const result = await this.withSessionMutation(id, async () => {
3769
+ if (await sessionHasOpenRun(this.directory, id))
3770
+ throw new AppServerError('busy', 'That task is running in another window. Stop the run or wait for it to finish, then move it.');
3771
+ const record = await this.readSession(id);
3772
+ if (resolve(record.workspace) === resolve(root))
3773
+ return record;
3774
+ if (this.timers.list(id).length > 0 || await sessionHasArmedWake(this.directory, id))
3775
+ throw new AppServerError('busy', 'That task has a timer set. Wait for it or cancel it, then move it.');
3776
+ // A worktree belongs to the repository of the project the task left; the task would go on editing that one.
3777
+ if (record.checkout?.kind === 'worktree' && record.checkout.removedAt === undefined) {
3778
+ throw new AppServerError('invalid-params', 'That task works in its own worktree of its project. Remove the worktree first, then move it.');
3779
+ }
3780
+ const { checkout: _checkout, ...rest } = record;
3781
+ const moved = { ...rest, workspace: root, projectId: await this.projectIdFor(root) };
3782
+ await this.store().save(savedSessionFields(moved));
3783
+ rekey = AppServer.panelProfileKey(record) !== AppServer.panelProfileKey(moved);
3784
+ this.emit('session.updated', { session: this.summary(moved) });
3785
+ return moved;
3786
+ });
3787
+ // The panel browser picks its profile once, when it opens: a moved task must lose the one it holds, or it would go
3788
+ // on browsing with the cookies and logins of the project it left.
3789
+ if (rekey)
3790
+ await this.browserViews.rekeyProfiles([id]).catch(() => { });
3791
+ return result;
3792
+ }
3270
3793
  async deleteSession(params) {
3271
3794
  const id = identifier(params.id, 'id');
3272
3795
  if (this.run?.sessionId === id || this.startingSession === id || this.starting)
@@ -3291,7 +3814,18 @@ export class AppServer {
3291
3814
  return { removed: true };
3292
3815
  });
3293
3816
  }
3817
+ beginRunTelemetry(params) {
3818
+ const startedAt = new Date().toISOString();
3819
+ // Snapshot before the first await: a pending start can never be upgraded by a later Yes.
3820
+ const lease = telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals });
3821
+ if (!lease)
3822
+ return Promise.resolve({ startedAt });
3823
+ return beginTelemetryRun({ home: this.directory, signals: this.telemetry.signals, lease, surface: configuredSurface('desktop') }, startedAt, {
3824
+ graphId: typeof params.graph === 'string' ? params.graph : 'default', nodes: 0, subagents: false,
3825
+ }).then(handle => ({ startedAt, handle }), () => ({ startedAt }));
3826
+ }
3294
3827
  async startRun(params, internal) {
3828
+ await requireLegalAcceptance(this.directory);
3295
3829
  bootMark('run.start.received');
3296
3830
  if (this.run || this.starting)
3297
3831
  throw new AppServerError('engine-busy', 'This engine is already running a task. Cancel it before starting another.');
@@ -3327,10 +3861,12 @@ export class AppServer {
3327
3861
  }
3328
3862
  }
3329
3863
  async resumeRun(params, internal) {
3864
+ await requireLegalAcceptance(this.directory);
3330
3865
  if (this.run || this.starting)
3331
3866
  throw new AppServerError('engine-busy', 'This engine is already running a task. Cancel it before starting another.');
3332
3867
  if (this.checkout)
3333
3868
  throw new AppServerError('busy', 'The working tree is being switched to another branch. Try again when it finishes.');
3869
+ const telemetryStart = this.beginRunTelemetry(params);
3334
3870
  const originalRunId = identifier(params.runId, 'runId');
3335
3871
  let direction = params.direction === undefined ? undefined : text(params.direction, 'direction', MAX_TASK_CHARS);
3336
3872
  // A note rides on a direction the person sent; a resume without one has nothing to carry it.
@@ -3340,7 +3876,7 @@ export class AppServer {
3340
3876
  this.assertRunning();
3341
3877
  let source;
3342
3878
  try {
3343
- source = JSON.parse(await readFile(runRecordPath(this.directory, originalRunId, 'json'), 'utf8'));
3879
+ source = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, originalRunId, 'json'), { signals: this.telemetry.signals });
3344
3880
  }
3345
3881
  catch {
3346
3882
  throw new AppServerError('invalid-params', 'There is no saved record for that run, so it cannot be resumed.');
@@ -3405,10 +3941,14 @@ export class AppServer {
3405
3941
  }
3406
3942
  const rawSelection = typeof source.graphSelection === 'string' ? source.graphSelection : source.graph?.id;
3407
3943
  const graphId = rawSelection === 'software-engineer' ? 'default' : rawSelection === 'andorra' ? RETIRED_ANDORRA_SELECTION : rawSelection;
3944
+ if (params.runPermissions !== undefined && params.permissions !== undefined) {
3945
+ throw new AppServerError('invalid-params', 'Choose either runPermissions for this run or permissions for the workspace default.');
3946
+ }
3947
+ const resumeRunPermissions = params.runPermissions === undefined ? undefined : permissionMode(params.runPermissions);
3408
3948
  if (!await claimRunResume(this.directory, originalRunId))
3409
3949
  throw new AppServerError('busy', 'That run is already being resumed by another engine.');
3410
- const inheritedPermissions = params.permissions === undefined && isPermissionMode(source.permissions)
3411
- ? source.permissions : undefined;
3950
+ const inheritedPermissions = resumeRunPermissions ?? (params.permissions === undefined && isPermissionMode(source.permissions)
3951
+ ? source.permissions : undefined);
3412
3952
  const carriedModel = typeof source.model === 'string' && source.model ? source.model : undefined;
3413
3953
  const carriedNodeModelOverrides = readNodeModelOverrides(source.nodeModelOverrides);
3414
3954
  this.startingSession = sessionId;
@@ -3421,16 +3961,19 @@ export class AppServer {
3421
3961
  ...(params.model === undefined ? {} : { model: params.model }),
3422
3962
  ...(source.runInput !== undefined && typeof source.runInput === 'object' && source.runInput !== null ? { input: source.runInput } : {}),
3423
3963
  ...(source.runState !== undefined && typeof source.runState === 'object' && source.runState !== null ? { state: source.runState } : {}),
3424
- ...(typeof source.reasoningEffort === 'string' && (params.provider === undefined || params.provider === source.provider) ? { reasoningEffort: source.reasoningEffort } : {}),
3964
+ ...(params.reasoningEffort !== undefined ? { reasoningEffort: params.reasoningEffort } : typeof source.reasoningEffort === 'string' && (params.provider === undefined || params.provider === source.provider) && (params.model === undefined || params.model === source.model) ? { reasoningEffort: source.reasoningEffort } : {}),
3425
3965
  ...(params.overrideAllNodes === undefined ? (source.overrideAllNodes === true ? { overrideAllNodes: true } : {}) : { overrideAllNodes: params.overrideAllNodes }),
3966
+ // A resume keeps Auto unless it names its own choice: a pair without autoModel is an explicit pick.
3967
+ ...(params.autoModel === true || (params.autoModel === undefined && params.provider === undefined && params.model === undefined && source.autoModel === true) ? { autoModel: true } : {}),
3426
3968
  ...(params.overrideAllNodes === true || carriedNodeModelOverrides === undefined ? {} : { nodeModelOverrides: carriedNodeModelOverrides }),
3427
3969
  ...(source.entryHistory === true ? { entryHistory: true } : {}),
3428
3970
  ...(params.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}),
3971
+ ...(params.chatHandoffs === true ? { chatHandoffs: true } : {}),
3429
3972
  ...(params.relay === undefined ? {} : { relay: params.relay }),
3430
3973
  ...(params.permissions === undefined ? {} : { permissions: params.permissions }),
3431
3974
  ...(sentAttachments === undefined ? {} : { attachments: sentAttachments }),
3432
3975
  ...(note === undefined ? {} : { note }),
3433
- }, { sameSession: sessionId, resumedFrom: originalRunId, ...(turn?.note ? { priorNote: turn.note } : {}), ...(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 } : {}), ...(params.compact === true ? { compact: true } : {}) });
3976
+ }, { telemetryStart, sameSession: sessionId, resumedFrom: originalRunId, ...(turn?.note ? { priorNote: turn.note } : {}), ...(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 } : {}), ...(params.compact === true ? { compact: true } : {}) });
3434
3977
  }
3435
3978
  catch (error) {
3436
3979
  await releaseRunResumeClaim(this.directory, originalRunId);
@@ -3472,13 +4015,124 @@ export class AppServer {
3472
4015
  this.checkout = undefined;
3473
4016
  }
3474
4017
  }
4018
+ /** Makes a writing task's worktree before its run starts; the same key returns the same worktree on a retry. */
4019
+ async prepareTaskCheckout(params) {
4020
+ const root = await workspaceRoot(params.workspace);
4021
+ const base = text(params.base, 'base', 200);
4022
+ const slug = text(params.slug, 'slug', MAX_TASK_CHARS);
4023
+ const key = text(params.key, 'key', 64);
4024
+ if (await folderChangeHeld(this.directory, root))
4025
+ throw new AppServerError('busy', folderChangeBusy);
4026
+ try {
4027
+ return await prepareTaskWorktree({ home: this.directory, root, base, slug, key });
4028
+ }
4029
+ catch (error) {
4030
+ if (error instanceof TaskCheckoutError)
4031
+ throw new AppServerError('invalid-params', error.message);
4032
+ throw error;
4033
+ }
4034
+ }
4035
+ async sessionCheckoutState(params) {
4036
+ const record = await this.readSession(identifier(params.id, 'id'));
4037
+ if (record.checkout === undefined)
4038
+ return { state: 'ok' };
4039
+ return { ...await checkoutState(record.checkout, resolve(record.workspace)), checkout: record.checkout };
4040
+ }
4041
+ refuseCheckoutChange(id, doing) {
4042
+ if (this.run?.sessionId === id || this.startingSession === id || this.starting || this.finishingSessionId === id)
4043
+ throw new AppServerError('busy', `That task is running. Stop the run or wait for it to finish, then ${doing}.`);
4044
+ }
4045
+ /** Recreates a task's missing worktree from its branch, or takes the folder it moved to. */
4046
+ async recoverSessionCheckout(params) {
4047
+ const id = identifier(params.id, 'id');
4048
+ if (params.mode !== 'recreate' && params.mode !== 'locate')
4049
+ throw new AppServerError('invalid-params', 'mode must be recreate or locate');
4050
+ const mode = params.mode;
4051
+ const picked = mode === 'locate' ? text(params.path, 'path', 4096) : undefined;
4052
+ this.refuseCheckoutChange(id, 'recover its worktree');
4053
+ return this.withSessionMutation(id, async () => {
4054
+ this.refuseCheckoutChange(id, 'recover its worktree');
4055
+ if (await sessionHasOpenRun(this.directory, id))
4056
+ throw new AppServerError('busy', 'That task is running in another window. Wait for it to finish, then recover its worktree.');
4057
+ const record = await this.readSession(id);
4058
+ if (record.checkout?.kind !== 'worktree')
4059
+ throw new AppServerError('invalid-params', 'That task does not work in a worktree of its own.');
4060
+ const root = resolve(record.workspace);
4061
+ let checkout;
4062
+ try {
4063
+ checkout = mode === 'recreate' ? await recreateTaskWorktree(record.checkout, root) : await locateTaskWorktree(record.checkout, root, picked);
4064
+ }
4065
+ catch (error) {
4066
+ if (error instanceof TaskCheckoutError)
4067
+ throw new AppServerError('invalid-params', error.message);
4068
+ throw error;
4069
+ }
4070
+ const updated = { ...record, checkout };
4071
+ await this.store().save(savedSessionFields(updated));
4072
+ this.emit('session.updated', { session: this.summary(updated) });
4073
+ return updated;
4074
+ });
4075
+ }
4076
+ async inspectSessionCheckout(params) {
4077
+ const id = identifier(params.id, 'id');
4078
+ const record = await this.readSession(id);
4079
+ if (record.checkout?.kind !== 'worktree' || record.checkout.removedAt !== undefined)
4080
+ throw new AppServerError('invalid-params', 'That task has no worktree of its own to remove.');
4081
+ const running = this.run?.sessionId === id || this.startingSession === id || await sessionHasOpenRun(this.directory, id);
4082
+ // A continuation shares its task's worktree: removing it leaves the other without one.
4083
+ const path = record.checkout.path;
4084
+ const sharedWith = (await this.store().list(record.workspace)).filter(other => other.id !== id && other.checkout?.kind === 'worktree' && other.checkout.removedAt === undefined && resolve(other.checkout.path) === resolve(path)).map(other => other.name);
4085
+ try {
4086
+ return { check: await inspectWorktreeRemoval(record.checkout, resolve(record.workspace)), running, checkout: record.checkout, sharedWith };
4087
+ }
4088
+ catch (error) {
4089
+ if (error instanceof TaskCheckoutError)
4090
+ throw new AppServerError('invalid-params', error.message);
4091
+ throw error;
4092
+ }
4093
+ }
4094
+ /** Removes a task's worktree after the lead saw what it holds; the branch stays when it has commits nothing else has. */
4095
+ async removeSessionCheckout(params) {
4096
+ const id = identifier(params.id, 'id');
4097
+ const expectDirty = params.expectDirty;
4098
+ if (typeof expectDirty !== 'number' || !Number.isSafeInteger(expectDirty) || expectDirty < 0)
4099
+ throw new AppServerError('invalid-params', 'expectDirty must be the number of files the check found');
4100
+ this.refuseCheckoutChange(id, 'remove its worktree');
4101
+ return this.withSessionMutation(id, async () => {
4102
+ this.refuseCheckoutChange(id, 'remove its worktree');
4103
+ if (await sessionHasOpenRun(this.directory, id))
4104
+ throw new AppServerError('busy', 'That task is running in another window. Wait for it to finish, then remove its worktree.');
4105
+ const record = await this.readSession(id);
4106
+ if (record.checkout?.kind !== 'worktree' || record.checkout.removedAt !== undefined)
4107
+ throw new AppServerError('invalid-params', 'That task has no worktree of its own to remove.');
4108
+ let removal;
4109
+ try {
4110
+ removal = await removeTaskWorktree(record.checkout, resolve(record.workspace), { expectDirty });
4111
+ }
4112
+ catch (error) {
4113
+ if (error instanceof TaskCheckoutError)
4114
+ throw new AppServerError('invalid-params', error.message);
4115
+ throw error;
4116
+ }
4117
+ const updated = { ...record, checkout: removal.checkout };
4118
+ await this.store().save(savedSessionFields(updated));
4119
+ const summary = this.summary(updated);
4120
+ this.emit('session.updated', { session: summary });
4121
+ return { session: summary, branchDeleted: removal.branchDeleted };
4122
+ });
4123
+ }
3475
4124
  assertRunning() {
3476
4125
  if (this.closed)
3477
4126
  throw new AppServerError('cancelled', 'The engine is shutting down.');
3478
4127
  }
3479
4128
  async prepareRun(params, internal) {
3480
- this.cancelSessionTitles();
3481
- this.workGeneration++;
4129
+ const start = await (internal?.telemetryStart ?? this.beginRunTelemetry(params));
4130
+ // New work owns the provider from here: abort the title work of the session it is about to use. A
4131
+ // brand-new session has no title of its own pending, so nothing is cancelled for it, and other
4132
+ // sessions' titles are left alone — a task started elsewhere never costs them their name.
4133
+ const titleSession = internal?.sameSession ?? (typeof params.sessionId === 'string' && params.sessionId ? params.sessionId : undefined);
4134
+ if (titleSession !== undefined)
4135
+ this.cancelSessionTitles(titleSession);
3482
4136
  const createdSpools = [];
3483
4137
  let releaseStartLock;
3484
4138
  if (internal?.sameSession !== undefined) {
@@ -3492,7 +4146,7 @@ export class AppServer {
3492
4146
  }
3493
4147
  }
3494
4148
  try {
3495
- return await this.prepareRunValidated(params, internal, createdSpools);
4149
+ return await this.prepareRunValidated(start, params, internal, createdSpools);
3496
4150
  }
3497
4151
  catch (error) {
3498
4152
  await Promise.all(createdSpools.map(dir => rm(dir, { recursive: true, force: true }).catch(() => { })));
@@ -3526,7 +4180,7 @@ export class AppServer {
3526
4180
  }
3527
4181
  return applyNodeModelOverrides(bindPortableGraphProviders(prebound, config), nodeModelOverrides);
3528
4182
  }
3529
- async prepareRunValidated(params, internal, createdSpools) {
4183
+ async prepareRunValidated(start, params, internal, createdSpools) {
3530
4184
  const root = await workspaceRoot(params.workspace);
3531
4185
  this.assertRunning();
3532
4186
  const submitted = text(params.task, 'task', MAX_TASK_CHARS);
@@ -3571,12 +4225,16 @@ export class AppServer {
3571
4225
  const modelId = carriedModel !== undefined
3572
4226
  ? (carriedModelConfigured ? carriedModel : provider.model)
3573
4227
  : (params.model === undefined ? provider.model : text(params.model, 'model', 200));
3574
- const effort = params.reasoningEffort === undefined || params.reasoningEffort === '' ? undefined : reasoningEffort(params.reasoningEffort);
4228
+ const autoEffort = params.reasoningEffort === 'auto';
4229
+ const effort = autoEffort || params.reasoningEffort === undefined || params.reasoningEffort === '' ? undefined : reasoningEffort(params.reasoningEffort);
3575
4230
  if (effort !== undefined && !supportsReasoningEffort(provider.type))
3576
4231
  throw new AppServerError('invalid-params', `The ${provider.type} provider does not support a thinking effort`);
3577
4232
  const overrideAllNodes = params.overrideAllNodes === true;
3578
4233
  const nodeModelOverrides = readNodeModelOverrides(params.nodeModelOverrides);
3579
- const modelPinned = overrideAllNodes || params.model !== undefined || params.provider !== undefined;
4234
+ // Auto: the provider and model name the starting pair only, so adaptive routing may still choose the run's model.
4235
+ // An override of every node is an explicit choice and wins over it.
4236
+ const autoModel = params.autoModel === true && !overrideAllNodes;
4237
+ const modelPinned = !autoModel && (overrideAllNodes || params.model !== undefined || params.provider !== undefined);
3580
4238
  const panelRelay = params.panelBrowserRelay === true;
3581
4239
  const entryHistory = params.entryHistory === true;
3582
4240
  const runInput = params.input !== undefined && typeof params.input === 'object' && params.input !== null && !Array.isArray(params.input)
@@ -3591,7 +4249,7 @@ export class AppServer {
3591
4249
  : internal?.resumedFrom !== undefined ? identifier(params.graph, 'graph') : currentGraphSelection(identifier(params.graph, 'graph'));
3592
4250
  if (relay?.graph === undefined && implicit && await this.selectionIsDeleted(selection))
3593
4251
  selection = 'default';
3594
- const requested = params.permissions === undefined ? undefined : permissionMode(params.permissions);
4252
+ const requested = requestedPermissionMode(params.permissions);
3595
4253
  if (requested) {
3596
4254
  const next = await this.serializeConfig(async () => {
3597
4255
  try {
@@ -3612,8 +4270,22 @@ export class AppServer {
3612
4270
  throw new AppServerError('busy', folderChangeBusy);
3613
4271
  const store = this.store();
3614
4272
  let record;
4273
+ let handoffParentId;
4274
+ if (params.handoffParentId !== undefined) {
4275
+ if (params.sessionId !== undefined || params.continueSession === true || params.entryHistory === true || internal?.resumedFrom !== undefined) {
4276
+ throw new AppServerError('invalid-params', 'A chat handoff must start a fresh session');
4277
+ }
4278
+ const origin = await this.readSession(identifier(params.handoffParentId, 'handoffParentId'));
4279
+ if (resolve(origin.workspace) !== root)
4280
+ throw new AppServerError('invalid-params', 'The originating chat belongs to a different project');
4281
+ handoffParentId = origin.id;
4282
+ }
3615
4283
  if (params.sessionId === undefined) {
3616
- record = { version: 1, id: randomUUID(), name: sessionName(task), workspace: root, updatedAt: new Date().toISOString(), history: [], usage: { inputTokens: 0, outputTokens: 0, requests: 0 } };
4284
+ // The name the session shows at once is the first few words of its first prompt, never the worktree's
4285
+ // temporary id. The same string is kept as the `placeholder`, so a model title (first attempt or a later
4286
+ // retry) can still replace it, while a name the user chose is never overwritten.
4287
+ const name = sessionName(task);
4288
+ record = { version: 1, id: randomUUID(), name, placeholder: name, workspace: root, updatedAt: new Date().toISOString(), history: [], usage: { inputTokens: 0, outputTokens: 0, requests: 0 }, ...(handoffParentId === undefined ? {} : { handoffParentId }) };
3617
4289
  }
3618
4290
  else if (internal?.sameSession !== undefined) {
3619
4291
  const continuedId = identifier(params.sessionId, 'sessionId');
@@ -3632,7 +4304,8 @@ export class AppServer {
3632
4304
  throw new AppServerError('invalid-params', 'That session belongs to a different project');
3633
4305
  // The pin belongs to the task the user pinned; its continuation is listed under it and shares its place.
3634
4306
  const { archived: _archived, autoArchived: _autoArchived, pinned: _pinned, ...continued } = existing;
3635
- const { trajectoryId: _parentTrajectory, ...forked } = continued;
4307
+ // A continuation is its own task in Needs you: it waits for review once its own turn completes.
4308
+ const { trajectoryId: _parentTrajectory, review: _parentReview, handoffParentId: _originalHandoff, ...forked } = continued;
3636
4309
  if (!canExtendLineage(existing.ancestors)) {
3637
4310
  throw new AppServerError('invalid-params', 'This session has been continued too many times to keep its lineage, so it cannot be continued again. Start a new session instead.');
3638
4311
  }
@@ -3644,10 +4317,38 @@ export class AppServer {
3644
4317
  if (params.jevEnabled !== undefined && typeof params.jevEnabled !== 'boolean')
3645
4318
  throw new AppServerError('invalid-params', 'jevEnabled must be a boolean');
3646
4319
  record = { ...record, workspace: root, projectId: record.projectId ?? await this.projectIdFor(root), updatedAt: new Date().toISOString(), ...(params.jevEnabled === undefined ? {} : { jevEnabled: params.jevEnabled }) };
4320
+ // A new task records where it works; a follow-up goes on in that same place, which must still be there.
4321
+ const preparedKey = params.sessionId === undefined ? preparedCheckoutKey(params.checkout) : undefined;
4322
+ if (params.sessionId === undefined) {
4323
+ let checkout;
4324
+ try {
4325
+ checkout = preparedKey !== undefined ? await takePrepared(this.directory, root, preparedKey) : await inPlaceCheckout(root);
4326
+ }
4327
+ catch (error) {
4328
+ if (error instanceof TaskCheckoutError)
4329
+ throw new AppServerError('invalid-params', error.message);
4330
+ throw error;
4331
+ }
4332
+ record = { ...record, checkout };
4333
+ // The worktree and its branch keep the `task/<id>` name the start drew them under (renamed to a model
4334
+ // summary later, in nameWorktreeBranch); the session's name stays the prompt's first words set above, so
4335
+ // the rail never shows the temporary worktree id — also when a collision made the start draw a fresh id.
4336
+ }
4337
+ else if (record.checkout !== undefined) {
4338
+ const state = await checkoutState(record.checkout, root);
4339
+ if (state.state !== 'ok')
4340
+ throw new AppServerError('checkout-missing', state.reason);
4341
+ }
4342
+ const workRoot = sessionWorkRoot(record);
3647
4343
  const controller = new AbortController();
3648
4344
  const runId = randomUUID();
3649
- const telemetryRunId = randomUUID();
3650
- const startedAt = new Date().toISOString();
4345
+ const { startedAt, handle: telemetryHandle } = start;
4346
+ const telemetryAccess = { home: this.directory, signals: this.telemetry.signals, lease: telemetryHandle?.lease };
4347
+ const telemetrySurface = { ...telemetryAccess, surface: configuredSurface('desktop'), config };
4348
+ if (telemetryHandle?.lease && sameTelemetryLease(telemetryHandle.lease, telemetryLeaseSnapshot(telemetryAccess))) {
4349
+ telemetryHandle.workspace = root;
4350
+ telemetryHandle.dimensions = { graphId: selection, nodes: 0, subagents: false, jevEnabled: config.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off', permissionMode: internal?.inheritedPermissions ?? effective };
4351
+ }
3651
4352
  const accountSubject = await currentGraphSubject();
3652
4353
  const resumedFrom = internal?.resumedFrom;
3653
4354
  // A relayed run's graph is bound to the desktop's providers here, before it starts, so a node naming a provider the
@@ -3693,7 +4394,7 @@ export class AppServer {
3693
4394
  const attempt = cursor;
3694
4395
  cursor = undefined;
3695
4396
  try {
3696
- const value = JSON.parse(await readFile(runRecordPath(this.directory, attempt, 'json'), 'utf8'));
4397
+ const value = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, attempt, 'json'), { signals: this.telemetry.signals });
3697
4398
  if (typeof value.resumedFrom === 'string' && value.resumedFrom !== attempt)
3698
4399
  cursor = value.resumedFrom;
3699
4400
  if (typeof value.toolCalls === 'number' && Number.isFinite(value.toolCalls))
@@ -3967,7 +4668,7 @@ export class AppServer {
3967
4668
  openingAttachments = { refs: stoppedRefs, images: await loadResolvedImages(this.directory, root, stoppedRefs) };
3968
4669
  }
3969
4670
  }
3970
- lineageArtifacts = new ArtifactStore(runId);
4671
+ lineageArtifacts = new ArtifactStore(runId, this.directory);
3971
4672
  for (const attempt of chain)
3972
4673
  await lineageArtifacts.importFrom(attempt).catch(() => { });
3973
4674
  resumeWarnings = warnings;
@@ -3995,11 +4696,12 @@ export class AppServer {
3995
4696
  const openRecord = { id: runId, status: 'running', sessionId: record.id, startedAt, pid: process.pid, graphSelection: selection, graph: { id: selection }, provider: provider.id, model: modelId,
3996
4697
  surface: configuredSurface('desktop'),
3997
4698
  ...(accountSubject ? { accountSubject } : {}),
3998
- telemetry: { runId: telemetryRunId, nodes: 0, subagents: false, jevEnabled: config.jevEnabled !== false && record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off', permissionMode: internal?.inheritedPermissions ?? effective, startSent: false },
3999
- ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? {} : { reasoningEffort: effort }),
4699
+ telemetry: runTelemetryMetadata(telemetrySurface, telemetryHandle),
4700
+ ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(effort === undefined ? autoEffort ? { reasoningEffort: 'auto' } : {} : { reasoningEffort: effort }),
4000
4701
  ...(automationContext === undefined ? {} : { automationContext }),
4001
4702
  ...(internal?.inheritedPermissions === undefined ? {} : { permissions: internal.inheritedPermissions }),
4002
4703
  ...(overrideAllNodes ? { overrideAllNodes: true } : {}),
4704
+ ...(autoModel ? { autoModel: true } : {}),
4003
4705
  ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }),
4004
4706
  ...(entryHistory ? { entryHistory: true } : {}),
4005
4707
  // Only the fact is kept: the desktop's provider list never reaches this machine's disk.
@@ -4011,7 +4713,7 @@ export class AppServer {
4011
4713
  ...(directionNode === undefined ? {} : { directionNode }),
4012
4714
  ...(armedCarried.length === 0 ? {} : { pendingDirections: armedCarried.map(entry => ({ runId: entry.runId, direction: entry.direction, ...(entry.id === undefined ? {} : { id: entry.id }), ...wakeProvenance(entry.wake, entry.node) })) }) };
4013
4715
  bootMark('run.prepare.record-write.start');
4014
- await writeOpenRunRecord(this.directory, openRecord)
4716
+ await writeOpenRunRecord(this.directory, openRecord, telemetryAccess)
4015
4717
  .catch(async (error) => {
4016
4718
  this.log('warn', `Could not write the open run record: ${message(error)}`);
4017
4719
  await rm(runRecordPath(this.directory, runId, 'json'), { force: true }).catch(() => { });
@@ -4042,16 +4744,16 @@ export class AppServer {
4042
4744
  throw error;
4043
4745
  }
4044
4746
  this.runAbort = undefined;
4045
- if (!claimProcessWorkspace(root, runId)) {
4747
+ if (!claimProcessWorkspace(workRoot, runId)) {
4046
4748
  throw new AppServerError('busy', 'This project is being worked in by another engine in this process.');
4047
4749
  }
4048
4750
  const liveSteers = [];
4049
4751
  const permissionControl = new RunControl();
4050
4752
  permissionControl.permissions = effective;
4051
4753
  permissionControl.yolo = effective === 'full-access';
4052
- this.run = { runId, sessionId: record.id, controller, workspace: root, steers: liveSteers, subagents: new Set(), steersClosed: false,
4754
+ this.run = { runId, sessionId: record.id, controller, workspace: root, workRoot, steers: liveSteers, subagents: new Set(), steersClosed: false,
4053
4755
  permissionControl, permissionRevision: 0, approvals: new Set(), boundPermissions: internal?.inheritedPermissions !== undefined,
4054
- codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }), ...(relay === undefined ? {} : { relayProviders: relay.providers }) };
4756
+ telemetryAccess, codeIntelPermissions: effective, ...(lineage.length === 0 ? {} : { lineage: [...lineage] }), ...(relay === undefined ? {} : { relayProviders: relay.providers }) };
4055
4757
  {
4056
4758
  const continues = new Set([runId, ...lineage]);
4057
4759
  for (const timer of this.timers.list(record.id)) {
@@ -4062,6 +4764,8 @@ export class AppServer {
4062
4764
  }
4063
4765
  this.emit('session.updated', { session: sessionSummary(record) });
4064
4766
  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 }) });
4767
+ if (preparedKey !== undefined)
4768
+ void forgetPrepared(this.directory, preparedKey);
4065
4769
  bootMark('run.started.emitted');
4066
4770
  for (const text of resumeWarnings) {
4067
4771
  void this.recordRunEvent(runId, { type: 'run.resume.warning', time: new Date().toISOString(), data: { runId, sessionId: record.id, text } });
@@ -4071,7 +4775,7 @@ export class AppServer {
4071
4775
  const preparedGraph = resumedGraph ?? relayPrepared;
4072
4776
  const invocationText = internal?.resumedFrom === undefined ? task
4073
4777
  : internal.recoveredDirection === true || internal.wake !== undefined ? undefined : internal.direction;
4074
- const runTask = this.executeRun({ runId, startedAt, telemetryRunId, ...(accountSubject ? { accountSubject } : {}), ...(invocationText === undefined ? {} : { invocationText }), task, ...(note === undefined ? {} : { note }), ...(turnNote === undefined ? {} : { turnNote }), 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 }), ...(internal?.startNode === undefined ? {} : { startNode: internal.startNode }), ...(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 }), ...(preparedGraph === undefined ? {} : { prepared: preparedGraph }), ...(relay === undefined ? {} : { relayProviders: relay.providers }), ...(relay?.graph === undefined ? {} : { relayedGraph: true }) })
4778
+ const runTask = this.executeRun({ runId, startedAt, telemetryHandle, ...(accountSubject ? { accountSubject } : {}), ...(invocationText === undefined ? {} : { invocationText }), task, ...(note === undefined ? {} : { note }), ...(turnNote === undefined ? {} : { turnNote }), selection, providerId: provider.id, modelId, root: workRoot, project: root, permissions: effective, liveSteers, ...(internal?.inheritedPermissions === undefined ? {} : { boundPermissions: internal.inheritedPermissions }), ...(effort === undefined ? {} : { reasoningEffort: effort }), ...(autoEffort ? { autoEffort: true } : {}), ...(overrideAllNodes ? { overrideAllNodes: true } : {}), ...(autoModel ? { autoModel: true } : {}), ...(modelPinned ? { modelPinned: true } : {}), ...(nodeModelOverrides === undefined ? {} : { nodeModelOverrides }), ...(panelRelay ? { panelBrowserRelay: true } : {}), chatHandoffs: params.chatHandoffs === true, ...(entryHistory ? { entryHistory: true } : {}), ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }), ...(automationContext === undefined ? {} : { automationContext }), ...(resumedDirection === undefined ? {} : { direction: resumedDirection }), ...(wake === undefined ? {} : { wake }), ...(directionNode === undefined ? {} : { directionNode }), ...(internal?.startNode === undefined ? {} : { startNode: internal.startNode }), ...(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 }), ...(preparedGraph === undefined ? {} : { prepared: preparedGraph }), ...(relay === undefined ? {} : { relayProviders: relay.providers }), ...(relay?.graph === undefined ? {} : { relayedGraph: true }) })
4075
4779
  .catch(error => this.log('error', `Run ${runId} failed: ${message(error)}`));
4076
4780
  this.runTask = runTask;
4077
4781
  runTask.finally(() => {
@@ -4086,7 +4790,6 @@ export class AppServer {
4086
4790
  return Promise.resolve();
4087
4791
  const controller = new AbortController();
4088
4792
  this.operations.add(controller);
4089
- const generation = this.workGeneration;
4090
4793
  this.sessionTitles.set(record.id, controller);
4091
4794
  const firstAnswer = new Promise(resolve => { this.titleReleases.set(runId, resolve); });
4092
4795
  const released = controller.signal.aborted ? Promise.resolve() : Promise.race([firstAnswer, new Promise(resolve => {
@@ -4094,25 +4797,25 @@ export class AppServer {
4094
4797
  })]);
4095
4798
  const settled = released
4096
4799
  // A run Andorra refused (unavailable, sign in, allowance, busy) ended without an answer: no second request follows the refusal.
4097
- .then(() => controller.signal.aborted || this.workGeneration !== generation || (provider.type === 'andorra' && !this.titleAnswered.has(runId)) ? '' : summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal))
4800
+ .then(() => controller.signal.aborted || (provider.type === 'andorra' && !this.titleAnswered.has(runId)) ? '' : summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal))
4098
4801
  .then(async (summary) => {
4099
- if (!summary || controller.signal.aborted || record.renamed === true)
4802
+ // No name landed: the run was refused, the request was cut short by new work, it failed, or the save
4803
+ // had to step aside. The retry asks again later instead of keeping the prompt's first words forever.
4804
+ if (!summary || controller.signal.aborted) {
4805
+ this.scheduleTitleRetry(record.id, task, provider, modelId, 0);
4100
4806
  return;
4101
- await this.withSessionMutation(record.id, async () => {
4102
- const ownRunId = this.run?.runId === runId ? runId
4103
- : this.finishingRunId === runId && this.finishingSessionId === record.id ? runId : undefined;
4104
- if (ownRunId === undefined && (this.run?.sessionId === record.id || await sessionHasOpenRun(this.directory, record.id)))
4105
- return;
4106
- const fresh = await this.readSession(record.id).catch(() => undefined);
4107
- if (!fresh || fresh.renamed === true || fresh.name === summary)
4108
- return;
4109
- if (ownRunId === undefined && (fresh.history ?? []).some(turn => turn.runId === runId && turn.completion?.status === 'running'))
4110
- return;
4111
- const titled = { ...fresh, name: summary };
4112
- await this.store().save(savedSessionFields(titled));
4113
- this.emit('session.updated', { session: this.summary(titled) });
4114
- });
4807
+ }
4808
+ this.nameWorktreeBranchTracked(record.id, task, provider, modelId);
4809
+ if (record.renamed === true) {
4810
+ this.scheduleTitleRetry(record.id, task, provider, modelId, 0);
4811
+ return;
4812
+ }
4813
+ if (await this.saveSessionTitle(record.id, runId, summary) === 'busy') {
4814
+ // The name was made but the session is claimed: stand back without spending an attempt.
4815
+ this.scheduleTitleRetry(record.id, task, provider, modelId, 0, 1);
4816
+ }
4115
4817
  })
4818
+ .catch(() => { this.scheduleTitleRetry(record.id, task, provider, modelId, 0); })
4116
4819
  .finally(() => {
4117
4820
  this.titleReleases.delete(runId);
4118
4821
  this.titleAnswered.delete(runId);
@@ -4125,6 +4828,175 @@ export class AppServer {
4125
4828
  tracked.finally(() => { this.requests.delete(tracked); });
4126
4829
  return settled;
4127
4830
  }
4831
+ /** Saves an automatic title under the same lock and guards a user rename takes. */
4832
+ /** `saved`: the name landed. `busy`: a run owns the session — the title can land once it settles. `stale`: the record is gone, renamed, already carrying the name, or waiting on a failed final save that recovery owns. */
4833
+ async saveSessionTitle(recordId, runId, summary) {
4834
+ return await this.withSessionMutation(recordId, async () => {
4835
+ // A retry names a session with no run of its own: its guards must stay active, so an undefined
4836
+ // run id stays undefined here (a `&&` chain would yield false and skip every check below).
4837
+ const ownRunId = runId === undefined ? undefined : this.run?.runId === runId ? runId
4838
+ : this.finishingRunId === runId && this.finishingSessionId === recordId ? runId : undefined;
4839
+ if (ownRunId === undefined && (this.run?.sessionId === recordId || await sessionHasOpenRun(this.directory, recordId)))
4840
+ return 'busy';
4841
+ const fresh = await this.readSession(recordId).catch(() => undefined);
4842
+ if (!fresh || fresh.renamed === true || fresh.name === summary)
4843
+ return 'stale';
4844
+ // A history turn still marked running is an attempt whose final save failed (or is in flight in
4845
+ // another window): the title must not publish that snapshot back as running. A retry with no run
4846
+ // of its own defers on any such marker.
4847
+ if (ownRunId === undefined && (fresh.history ?? []).some(turn => turn.completion?.status === 'running'
4848
+ && (runId === undefined || turn.runId === runId)))
4849
+ return 'stale';
4850
+ const titled = { ...fresh, name: summary };
4851
+ await this.store().save(savedSessionFields(titled));
4852
+ this.emit('session.updated', { session: this.summary(titled) });
4853
+ return 'saved';
4854
+ });
4855
+ }
4856
+ /**
4857
+ * Names a new task's branch from a model summary of the task (`task/fix-login-redirect-loop`), replacing the random
4858
+ * id the start gave it. Runs once the run has answered once, beside the title work. Any failure keeps the random
4859
+ * id: the branch name is a nicety, never worth a retry of its own.
4860
+ */
4861
+ async nameWorktreeBranch(recordId, task, provider, modelId) {
4862
+ const controller = new AbortController();
4863
+ this.operations.add(controller);
4864
+ try {
4865
+ if (!titleRequestSupported(provider))
4866
+ return;
4867
+ // A retry path can land here after the branch was named: skip the request when it no longer carries the start's name.
4868
+ const prior = await this.readSession(recordId).catch(() => undefined);
4869
+ if (!prior?.checkout || !isAutoTaskBranch(prior.checkout.branch))
4870
+ return;
4871
+ const name = await summarizeTaskBranch(task, createAdapter(provider), modelId, controller.signal);
4872
+ if (!name || this.closed)
4873
+ return;
4874
+ await this.withSessionMutation(recordId, async () => {
4875
+ const fresh = await this.readSession(recordId).catch(() => undefined);
4876
+ if (!fresh?.checkout)
4877
+ return;
4878
+ const branch = await renameTaskBranch(fresh.checkout, name);
4879
+ if (!branch || branch === fresh.checkout.branch)
4880
+ return;
4881
+ try {
4882
+ const updated = { ...fresh, checkout: { ...fresh.checkout, branch } };
4883
+ await this.store().save(savedSessionFields(updated));
4884
+ this.emit('session.updated', { session: this.summary(updated) });
4885
+ }
4886
+ catch (error) {
4887
+ // Git already moved the branch; with the record left behind the two would disagree for good, and a
4888
+ // later naming attempt could no longer repair it (the recorded branch no longer matches HEAD). Put the
4889
+ // branch back under its recorded name, so record and repository agree and the rename can be retried.
4890
+ await revertTaskBranchRename(fresh.checkout, branch, fresh.checkout.branch).catch(() => { });
4891
+ throw error;
4892
+ }
4893
+ // A continuation started while this request was pending copied the automatic branch over. Every record
4894
+ // still sharing that worktree under the old name moves with it, so its commands and worktree recovery
4895
+ // point at the branch that holds the task's work. Each sibling is locked, reread and revalidated under
4896
+ // its own lock, so a turn that completes meanwhile is never overwritten with this stale snapshot.
4897
+ const worktree = resolve(fresh.checkout.path);
4898
+ const oldBranch = fresh.checkout.branch;
4899
+ const siblings = (await this.store().list(fresh.workspace)).filter(other => other.id !== fresh.id
4900
+ && other.checkout?.kind === 'worktree' && other.checkout.removedAt === undefined
4901
+ && other.checkout.branch === oldBranch && resolve(other.checkout.path) === worktree);
4902
+ for (const sibling of siblings) {
4903
+ // A sibling's lock is only held briefly by ordinary saves. Retry a busy lock instead of skipping it:
4904
+ // a skipped sibling would keep pointing at a ref the rename just removed (checkoutState never refreshes
4905
+ // the branch), which breaks its commands and its worktree recovery.
4906
+ for (let attempt = 0; attempt < MAX_SIBLING_LOCK_TRIES && !this.closed; attempt++) {
4907
+ try {
4908
+ await this.withSessionMutation(sibling.id, async () => {
4909
+ const shared = await this.readSession(sibling.id).catch(() => undefined);
4910
+ if (!shared || shared.checkout?.kind !== 'worktree' || shared.checkout.removedAt !== undefined
4911
+ || shared.checkout.branch !== oldBranch || resolve(shared.checkout.path) !== worktree)
4912
+ return;
4913
+ const update = { ...shared, checkout: { ...shared.checkout, branch } };
4914
+ await this.store().save(savedSessionFields(update));
4915
+ this.emit('session.updated', { session: this.summary(update) });
4916
+ });
4917
+ break;
4918
+ }
4919
+ catch {
4920
+ await new Promise(resolve => { const timer = setTimeout(resolve, SIBLING_LOCK_RETRY_MS); timer.unref?.(); });
4921
+ }
4922
+ }
4923
+ }
4924
+ });
4925
+ }
4926
+ catch { /* A failed or refused name keeps the random id the task started under. */ }
4927
+ finally {
4928
+ this.operations.delete(controller);
4929
+ }
4930
+ }
4931
+ nameWorktreeBranchTracked(recordId, task, provider, modelId) {
4932
+ const pending = this.nameWorktreeBranch(recordId, task, provider, modelId).catch(() => { });
4933
+ this.requests.add(pending);
4934
+ pending.finally(() => { this.requests.delete(pending); });
4935
+ }
4936
+ /** A title that never landed waits and asks again, so one busy moment does not leave the session with its prompt's first words. */
4937
+ scheduleTitleRetry(sessionId, task, provider, modelId, attempt, deferrals = 0) {
4938
+ if (this.closed || !titleRequestSupported(provider))
4939
+ return;
4940
+ if (attempt >= TITLE_RETRY_DELAYS_MS.length)
4941
+ return;
4942
+ if (this.titleRetries.has(sessionId))
4943
+ return;
4944
+ const controller = new AbortController();
4945
+ const timer = setTimeout(() => { void this.retrySessionTitle(sessionId, task, provider, modelId, attempt); }, TITLE_RETRY_DELAYS_MS[attempt]);
4946
+ timer.unref();
4947
+ controller.signal.addEventListener('abort', () => { clearTimeout(timer); this.titleRetries.delete(sessionId); }, { once: true });
4948
+ this.titleRetries.set(sessionId, { timer, controller, task, provider, modelId, attempt, deferrals });
4949
+ }
4950
+ async retrySessionTitle(sessionId, task, provider, modelId, attempt) {
4951
+ // A storage failure anywhere below must never surface as an unhandled rejection from the retry
4952
+ // timer: the bounded attempt budget covers it instead.
4953
+ try {
4954
+ await this.runTitleRetry(sessionId, task, provider, modelId, attempt);
4955
+ }
4956
+ catch {
4957
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt + 1);
4958
+ }
4959
+ }
4960
+ async runTitleRetry(sessionId, task, provider, modelId, attempt) {
4961
+ const pending = this.titleRetries.get(sessionId);
4962
+ this.titleRetries.delete(sessionId);
4963
+ if (!pending || pending.controller.signal.aborted || this.closed)
4964
+ return;
4965
+ const fresh = await this.readSession(sessionId).catch(() => undefined);
4966
+ // Deleted, renamed by the user, or already carrying a real name: nothing left to do.
4967
+ if (!fresh || fresh.renamed === true || fresh.name !== (fresh.placeholder ?? sessionName(task)))
4968
+ return;
4969
+ // A run is working on the session, so the save would step aside anyway. Step back without
4970
+ // spending one of the bounded attempts: the title is not lost, it is just not this minute's.
4971
+ if (this.run?.sessionId === sessionId || await sessionHasOpenRun(this.directory, sessionId)) {
4972
+ if (pending.deferrals >= MAX_TITLE_RETRY_DEFERRALS)
4973
+ return;
4974
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt, pending.deferrals + 1);
4975
+ return;
4976
+ }
4977
+ const controller = new AbortController();
4978
+ this.operations.add(controller);
4979
+ this.sessionTitles.set(sessionId, controller);
4980
+ try {
4981
+ const summary = await summarizeSessionPrompt(task, createAdapter(provider), modelId, controller.signal);
4982
+ if (!summary) {
4983
+ // The model answered nothing usable: spend the attempt the way an empty first title does.
4984
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt + 1);
4985
+ return;
4986
+ }
4987
+ this.nameWorktreeBranchTracked(sessionId, task, provider, modelId);
4988
+ const outcome = await this.saveSessionTitle(sessionId, undefined, summary);
4989
+ if (outcome === 'busy' && pending.deferrals < MAX_TITLE_RETRY_DEFERRALS) {
4990
+ // The name was made but the session was claimed meanwhile: stand back, spend nothing.
4991
+ this.scheduleTitleRetry(sessionId, task, provider, modelId, attempt, pending.deferrals + 1);
4992
+ }
4993
+ }
4994
+ finally {
4995
+ if (this.sessionTitles.get(sessionId) === controller)
4996
+ this.sessionTitles.delete(sessionId);
4997
+ this.operations.delete(controller);
4998
+ }
4999
+ }
4128
5000
  releaseTitleWaiter(runId) {
4129
5001
  const release = this.titleReleases.get(runId);
4130
5002
  if (release !== undefined) {
@@ -4132,14 +5004,41 @@ export class AppServer {
4132
5004
  release();
4133
5005
  }
4134
5006
  }
4135
- cancelSessionTitles() {
4136
- for (const controller of this.sessionTitles.values())
5007
+ /** Abort title work for the session given, or for all: the request on the wire, and a retry that is still waiting is moved back, not dropped. */
5008
+ cancelSessionTitles(onlySessionId) {
5009
+ const postpone = (sessionId) => {
5010
+ const pending = this.titleRetries.get(sessionId);
5011
+ if (pending === undefined)
5012
+ return;
5013
+ this.titleRetries.delete(sessionId);
5014
+ pending.controller.abort();
5015
+ // New work on the session does not ask for a title itself, so killing a waiting retry here would
5016
+ // leave the session unnamed for good. Push the attempt back instead of discarding it.
5017
+ this.scheduleTitleRetry(sessionId, pending.task, pending.provider, pending.modelId, pending.attempt + 1);
5018
+ };
5019
+ if (onlySessionId !== undefined) {
5020
+ const controller = this.sessionTitles.get(onlySessionId);
5021
+ if (controller !== undefined) {
5022
+ this.sessionTitles.delete(onlySessionId);
5023
+ controller.abort();
5024
+ }
5025
+ postpone(onlySessionId);
5026
+ return;
5027
+ }
5028
+ for (const [id, controller] of this.sessionTitles) {
5029
+ this.sessionTitles.delete(id);
4137
5030
  controller.abort();
4138
- this.sessionTitles.clear();
5031
+ }
5032
+ for (const pending of this.titleRetries.values())
5033
+ pending.controller.abort();
5034
+ this.titleRetries.clear();
4139
5035
  }
4140
5036
  async executeRun(input) {
4141
- const { runId, startedAt, telemetryRunId, accountSubject, task, note, turnNote, 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, startNode, controller, attachments, openingAttachments, resumedFrom, resumeFrom, lineage, lineageArtifacts, prepared, nodeModelOverrides } = input;
5037
+ const { runId, startedAt, telemetryHandle, accountSubject, task, note, turnNote, selection, providerId, modelId, root, project, permissions, liveSteers, boundPermissions, reasoningEffort, autoEffort = false, overrideAllNodes = false, autoModel = false, modelPinned = overrideAllNodes, panelBrowserRelay = false, entryHistory = false, runInput, runState, automationContext, direction, wake, carriedDirections, ownDirectionId, armedRunIds, pendingDirections, directionNode, startNode, controller, attachments, openingAttachments, resumedFrom, resumeFrom, lineage, lineageArtifacts, prepared, nodeModelOverrides } = input;
4142
5038
  const signal = controller.signal;
5039
+ const telemetryAccess = { home: this.directory, signals: this.telemetry.signals, lease: telemetryHandle?.lease };
5040
+ const turnObservations = [];
5041
+ const turnEdits = [];
4143
5042
  const panelHold = createPanelBrowserHold(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined);
4144
5043
  const liveRun = this.run?.runId === runId ? this.run : undefined;
4145
5044
  if (liveRun)
@@ -4152,7 +5051,7 @@ export class AppServer {
4152
5051
  ...(meta?.generation === undefined ? {} : { generation: meta.generation }),
4153
5052
  ...(meta?.provider === undefined ? {} : { provider: meta.provider }), ...(meta?.model === undefined ? {} : { model: meta.model }),
4154
5053
  ...(meta?.routedFrom === undefined ? {} : { routedFrom: meta.routedFrom }),
4155
- ...(deliveredIds.size === 0 ? {} : { steeringDelivered: [...deliveredIds] }) }))
5054
+ ...(deliveredIds.size === 0 ? {} : { steeringDelivered: [...deliveredIds] }) }, telemetryAccess))
4156
5055
  .then(() => checkpointHealth.succeeded({ nodeId, generation: meta?.generation }), async (error) => {
4157
5056
  await checkpointHealth.failed({ nodeId, generation: meta?.generation }, error);
4158
5057
  this.log('warn', `Could not write the run checkpoint: ${message(error)}`);
@@ -4170,7 +5069,7 @@ export class AppServer {
4170
5069
  let localCacheInputTokens = 0;
4171
5070
  let localCacheReadTokens = 0;
4172
5071
  const probeUsage = { requests: 0, inputTokens: 0, outputTokens: 0 };
4173
- const probeModels = new Map();
5072
+ const probeCapture = createRunTelemetry(telemetryAccess);
4174
5073
  // Set by the first model request this run sends to an Andorra provider (the health probe's included): the
4175
5074
  // hosted usage is asked for again when such a run ends.
4176
5075
  let askedAndorra = false;
@@ -4193,7 +5092,7 @@ export class AppServer {
4193
5092
  };
4194
5093
  for (const entry of carriedDirections ?? []) {
4195
5094
  const refs = entry.attachments ?? [];
4196
- const images = refs.length ? await loadResolvedImages(this.directory, root, refs) : [];
5095
+ const images = refs.length ? await loadResolvedImages(this.directory, project, refs) : [];
4197
5096
  const said = wakeMessageText(entry.wake, entry.direction);
4198
5097
  arm(entry.wake === undefined ? undefined : entry.node, { ...(entry.id === undefined ? {} : { id: entry.id }), content: refs.length ? `${said}\n\n${attachmentReferenceBlock(refs, { imagesIncluded: images.length > 0 })}` : said, images });
4199
5098
  }
@@ -4217,7 +5116,6 @@ export class AppServer {
4217
5116
  let result;
4218
5117
  let failure;
4219
5118
  let runConfig;
4220
- let telemetryHandle;
4221
5119
  let telemetryFinished = false;
4222
5120
  let telemetryStart = Promise.resolve();
4223
5121
  let healthProviderFailed = false;
@@ -4226,38 +5124,27 @@ export class AppServer {
4226
5124
  let codeIntelSettled = Promise.resolve();
4227
5125
  let mcpTeardown = Promise.resolve();
4228
5126
  const telemetrySurfaceFor = (config) => ({
4229
- home: this.directory, ...(config === undefined ? {} : { config }),
5127
+ ...telemetryAccess, ...(config === undefined ? {} : { config }),
4230
5128
  ...(accountSubject === undefined ? {} : { subject: accountSubject }), surface: configuredSurface('desktop'),
4231
5129
  });
4232
5130
  const trackTelemetry = (work) => {
4233
5131
  this.telemetrySettle = this.telemetrySettle.then(() => work).catch(() => { });
4234
5132
  };
4235
5133
  const settleTelemetry = (status, reason) => {
4236
- if (telemetryFinished)
5134
+ if (telemetryFinished || !telemetryHandle)
4237
5135
  return;
4238
- if (telemetryHandle === undefined) {
4239
- telemetryHandle = createRunHandle(telemetryRunId, startedAt, {
4240
- graphId: selection, nodes: 0, subagents: false, permissionMode: boundPermissions ?? permissions,
4241
- }, root);
4242
- const placeholder = telemetryHandle;
4243
- telemetryStart = reportRunStarted(telemetrySurfaceFor(runConfig), placeholder).catch(() => { });
4244
- }
5136
+ // Setup failure still uses the original admitted handle, never a new finish-time lease.
5137
+ if (telemetryHandle.started === undefined)
5138
+ telemetryStart = reportRunStarted(telemetrySurfaceFor(runConfig), telemetryHandle).catch(() => { });
4245
5139
  telemetryFinished = true;
4246
- const finishedTelemetry = result?.telemetry ?? createRunTelemetry();
4247
- for (const probe of probeModels.values()) {
4248
- const provider = runConfig?.providers.find(item => item.id === probe.provider);
4249
- recordModelUse(finishedTelemetry, {
4250
- ...(provider === undefined ? {} : { providerType: provider.type, baseUrl: provider.baseUrl }),
4251
- model: probe.model, role: 'other', usage: probe.usage,
4252
- ...(provider === undefined ? {} : { pricing: pricingFor(runConfig?.efficiency?.adaptiveRouting, probe.provider, probe.model) }),
4253
- });
4254
- }
5140
+ const finishedTelemetry = result?.telemetry ?? createRunTelemetry(telemetryAccess);
5141
+ mergeRunTelemetry(finishedTelemetry, probeCapture);
4255
5142
  trackTelemetry(telemetryStart.then(() => reportRunFinished(telemetrySurfaceFor(runConfig), telemetryHandle, {
4256
5143
  status, reason,
4257
5144
  ...(result?.providerRequestFailed || healthProviderFailed ? { providerRequestFailed: true } : {}),
4258
5145
  ...(result?.providerOverflow ? { providerOverflow: true } : {}),
4259
5146
  ...(result?.failureCode === undefined ? {} : { errorCode: result.failureCode }),
4260
- ...(result?.telemetry !== undefined || probeModels.size > 0 ? { telemetry: finishedTelemetry } : {}),
5147
+ ...(hasRunTelemetry(finishedTelemetry) ? { telemetry: finishedTelemetry } : {}),
4261
5148
  ...(result?.toolCalls === undefined ? {} : { toolCalls: result.toolCalls }),
4262
5149
  })));
4263
5150
  };
@@ -4267,8 +5154,8 @@ export class AppServer {
4267
5154
  const config = input.relayProviders === undefined ? saved : withRelayedProviders(saved, input.relayProviders);
4268
5155
  bootMark('run.exec.config-loaded');
4269
5156
  runConfig = config;
4270
- if (archive.length === 0)
4271
- trackTelemetry(reportSessionStarted({ ...telemetrySurfaceFor(config), workspace: root }));
5157
+ if (archive.length === 0 && telemetryHandle?.lease)
5158
+ trackTelemetry(reportSessionStarted({ ...telemetrySurfaceFor(config), workspace: project }));
4272
5159
  const provider = config.providers.find(item => item.id === providerId);
4273
5160
  if (!provider)
4274
5161
  throw new Error(`Unknown provider: ${providerId}`);
@@ -4288,22 +5175,20 @@ export class AppServer {
4288
5175
  liveRun.modelGraph = graph;
4289
5176
  liveRun.originalModelGraph = this.originalModelGraphs.get(graph) ?? structuredClone(graph);
4290
5177
  }
4291
- const startedHandle = createRunHandle(telemetryRunId, startedAt, {
4292
- graphId: selection, ...graphShape(graph), permissionMode: boundPermissions ?? permissions,
4293
- jevEnabled: config.jevEnabled !== false && input.record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off',
4294
- }, root);
4295
- telemetryHandle = startedHandle;
4296
- telemetryStart = reportRunStarted(telemetrySurfaceFor(config), startedHandle).catch(() => { });
5178
+ if (telemetryHandle?.lease && sameTelemetryLease(telemetryHandle.lease, telemetryLeaseSnapshot(telemetryAccess))) {
5179
+ telemetryHandle.dimensions = { graphId: selection, ...graphShape(graph), permissionMode: boundPermissions ?? permissions,
5180
+ jevEnabled: config.jevEnabled !== false && input.record.jevEnabled !== false, decisionRouting: config.decisions?.mode ?? 'off' };
5181
+ telemetryStart = reportRunStarted(telemetrySurfaceFor(config), telemetryHandle).catch(() => { });
5182
+ }
4297
5183
  await telemetryStart;
4298
5184
  bootMark('run.exec.telemetry-start.queued');
4299
5185
  try {
4300
5186
  const stamp = async () => {
4301
5187
  const path = runRecordPath(this.directory, runId, 'json');
4302
- const existing = JSON.parse(await readFile(path, 'utf8'));
4303
- const telemetry = existing.telemetry;
4304
- if (existing.status === 'running' && telemetry && typeof telemetry === 'object') {
4305
- existing.telemetry = { ...telemetry, ...graphShape(graph), startSent: startedHandle.started !== false };
4306
- await writeOpenRunRecord(this.directory, existing);
5188
+ const existing = await readTelemetryRunRecord(this.directory, path, this.run?.telemetryAccess);
5189
+ if (existing.status === 'running') {
5190
+ existing.telemetry = runTelemetryMetadata(telemetrySurfaceFor(config), telemetryHandle);
5191
+ await writeOpenRunRecord(this.directory, existing, telemetryAccess);
4307
5192
  }
4308
5193
  };
4309
5194
  if (liveRun)
@@ -4327,14 +5212,10 @@ export class AppServer {
4327
5212
  onUsage: (delta, reference) => {
4328
5213
  foldUsage(probeUsage, delta);
4329
5214
  foldUsage(runUsage, delta);
4330
- const key = `${reference.provider}\0${reference.model}`;
4331
- const entry = probeModels.get(key) ?? { provider: reference.provider, model: reference.model, usage: {} };
4332
- for (const field of ['requests', 'inputTokens', 'outputTokens', 'cacheRead', 'cacheWrite']) {
4333
- const value = delta[field];
4334
- if (typeof value === 'number')
4335
- entry.usage[field] = (entry.usage[field] ?? 0) + value;
4336
- }
4337
- probeModels.set(key, entry);
5215
+ const provider = config.providers.find(item => item.id === reference.provider);
5216
+ recordModelUse(probeCapture, { ...(provider ? { providerType: provider.type, baseUrl: provider.baseUrl } : {}),
5217
+ model: reference.model, role: 'other', usage: delta,
5218
+ pricing: pricingFor(config.efficiency?.adaptiveRouting, reference.provider, reference.model) });
4338
5219
  },
4339
5220
  createAdapter: provider => watchAndorra(provider.type, this.tracedAdapter(createAdapter(provider), provider.id)),
4340
5221
  andorra: () => this.hosted.gate(),
@@ -4378,7 +5259,7 @@ export class AppServer {
4378
5259
  contextWindow = snapshot.contextWindow;
4379
5260
  this.emit('run.context', { runId, provider: provider.id, model: snapshot.model, ...(snapshot.contextWindow === undefined ? {} : { contextWindow: snapshot.contextWindow }), ...(snapshot.reasoningEffort === undefined ? {} : { reasoningEffort: snapshot.reasoningEffort }) });
4380
5261
  const invocationInput = input.invocationText;
4381
- const runExtensions = effectiveExtensionConfig(config, root);
5262
+ const runExtensions = effectiveExtensionConfig(config, project);
4382
5263
  bootMark('run.exec.model-context.resolved');
4383
5264
  const invocations = invocationInput === undefined || isBuiltinSlashCommand(invocationInput) ? []
4384
5265
  : await resolveSkillInvocations(invocationInput, runExtensions, signal, this.directory);
@@ -4393,9 +5274,9 @@ export class AppServer {
4393
5274
  this.emit('log', { level: 'info', message: notice });
4394
5275
  bootMark('run.exec.extensions.loaded');
4395
5276
  if (config.commandMemory !== false)
4396
- commandMemory = await LocalToolMemory.open({ directory: this.directory, workspace: root });
5277
+ commandMemory = await LocalToolMemory.open({ directory: this.directory, workspace: project });
4397
5278
  if (config.projectMemory !== false)
4398
- projectMemory = await ProjectMemory.open({ home: this.directory, workspace: root });
5279
+ projectMemory = await ProjectMemory.open({ home: this.directory, workspace: project });
4399
5280
  bootMark('run.exec.command-memory.opened');
4400
5281
  const attachmentRoots = await attachmentReadRoots(this.directory, [
4401
5282
  ...(attachments?.refs ?? []),
@@ -4403,8 +5284,10 @@ export class AppServer {
4403
5284
  ...(history ?? []).flatMap(turn => [...(turn.attachments ?? []), ...(turn.steers ?? []).flatMap(steer => steer.attachments ?? [])]),
4404
5285
  ]);
4405
5286
  const wakeCarry = { graph: selection, provider: providerId, model: modelId,
4406
- ...(reasoningEffort === undefined ? {} : { reasoningEffort }),
5287
+ // A run on Auto thinking hands Auto to the runs its wakes start, as it hands a fixed level.
5288
+ ...(reasoningEffort === undefined ? autoEffort ? { reasoningEffort: 'auto' } : {} : { reasoningEffort }),
4407
5289
  ...(overrideAllNodes ? { overrideAllNodes: true } : {}),
5290
+ ...(autoModel ? { autoModel: true } : {}),
4408
5291
  ...(panelBrowserRelay ? { panelBrowserRelay: true } : {}),
4409
5292
  ...(input.relayProviders === undefined ? {} : { relayed: true }),
4410
5293
  ...(runInput === undefined ? {} : { input: runInput }),
@@ -4412,12 +5295,31 @@ export class AppServer {
4412
5295
  if (liveRun)
4413
5296
  liveRun.wakeCarry = wakeCarry;
4414
5297
  const pullRequestDetector = new PullRequestCreateDetector();
5298
+ // What this turn's commands ran against, and when files were edited: the turn's evidence is resolved from them.
5299
+ const observeCommand = async (start) => {
5300
+ // Kept as the transcript keeps tool text: terminal escapes stripped, known secret shapes redacted.
5301
+ const observation = { id: randomUUID(), command: cleanRecorded(start.command).slice(0, COMMAND_LIMIT), directory: start.directory, startedAt: new Date().toISOString() };
5302
+ const revision = await readRevision(start.directory, start.signal).catch(() => undefined);
5303
+ if (revision !== undefined)
5304
+ observation.revision = revision;
5305
+ turnObservations.push(observation);
5306
+ if (turnObservations.length > MAX_TURN_OBSERVATIONS)
5307
+ turnObservations.shift();
5308
+ return end => {
5309
+ observation.endedAt = new Date().toISOString();
5310
+ if (end.exitCode !== undefined)
5311
+ observation.exitCode = end.exitCode;
5312
+ if (end.output)
5313
+ observation.output = outputTail(cleanRecorded(end.output));
5314
+ };
5315
+ };
4415
5316
  const toolContext = {
4416
- workspace: root, signal, userSignal: signal, yolo: permissions === 'full-access', permissions, approvalMode: 'interactive',
5317
+ workspace: root, ...(project !== root ? { project } : {}), signal, userSignal: signal, yolo: permissions === 'full-access', permissions, approvalMode: 'interactive',
4417
5318
  ...(liveRun ? { runControl: liveRun.permissionControl } : {}),
4418
5319
  attachmentRoots,
4419
5320
  approve: (name, args, toolSignal) => this.approve(runId, name, args, toolSignal),
4420
- askUser: (question, toolSignal, choices) => this.ask(runId, question, choices, toolSignal),
5321
+ chatHandoffs: input.chatHandoffs === true,
5322
+ askUser: (question, toolSignal, choices, handoff) => this.ask(runId, question, choices, toolSignal, handoff),
4421
5323
  ...(liveRun ? { approvePlan: () => this.approvePlan(liveRun) } : {}),
4422
5324
  onApprovalEvent: (type, data) => {
4423
5325
  const event = { type, time: new Date().toISOString(), data };
@@ -4431,10 +5333,10 @@ export class AppServer {
4431
5333
  this.trajectory?.recordEvent(event),
4432
5334
  ]);
4433
5335
  },
4434
- timers: this.timers, sessionScope: input.record.id, wakesArmed, automationDirectory: this.directory,
5336
+ timers: this.timers, sessionScope: input.record.id, sessionId: input.record.id, wakesArmed, automationDirectory: this.directory,
4435
5337
  wakeCarry,
4436
- pullRequests: this.pullRequestControl(input.record.id, wakeCarry),
4437
- fileChanges: this.sessionChanges.recorder(input.record.id, root, changes => this.emitSessionChanges(changes), error => this.log('warn', `Could not record a file change for review: ${message(error)}`), () => livePermissionMode(toolContext) !== 'full-access'),
5338
+ fileChanges: notingEdits(this.sessionChanges.recorder(input.record.id, root, changes => this.emitSessionChanges(changes), error => this.log('warn', `Could not record a file change for review: ${message(error)}`), () => livePermissionMode(toolContext) !== 'full-access'), turnEdits),
5339
+ observeCommand,
4438
5340
  };
4439
5341
  bootMark('run.exec.mcp.connect.start');
4440
5342
  const healthGate = judgeHealth();
@@ -4457,11 +5359,18 @@ export class AppServer {
4457
5359
  if (codeIntel && liveRun)
4458
5360
  await this.syncCodeIntelPermissions(liveRun).catch(error => this.log('warn', `Could not bring code intelligence to the run's mode: ${message(error)}`));
4459
5361
  bootMark('run.exec.code-intel.ready');
4460
- const membership = await membershipRead;
5362
+ const jevWanted = config.jevEnabled !== false && input.record.jevEnabled !== false;
5363
+ // Only a run with JEV on asks the signed-out switch; a disabled run stays network-free.
5364
+ const membership = jevWanted ? await withAnonymousJev(await membershipRead, signal, this.directory) : await membershipRead;
4461
5365
  bootMark('run.exec.membership.read');
5366
+ const decisionPolicy = hostedDecisionPolicy(membership, jevWanted, config.decisions);
5367
+ toolContext.pullRequests = this.pullRequestControl(input.record.id, wakeCarry, (body, origin, invocationId, classifySignal) => origin !== undefined && graph.nodes[origin.nodeId]?.jevEnabled === true
5368
+ ? decisionPolicy.decisionManager.classifyPullRequestComment(body, { ...origin, invocationId }, classifySignal, event => this.recordRunEvent(runId, event))
5369
+ : Promise.resolve(undefined));
4462
5370
  await healthGate;
4463
5371
  runGoal = input.record.goal?.status === 'active' ? input.record.goal : undefined;
4464
5372
  const options = {
5373
+ telemetry: telemetryHandle?.lease ? telemetryAccess : false,
4465
5374
  task: note && direction === undefined ? `${task}\n\n${note}` : task, runId, provider: provider.id, model: snapshot.model, adapter: watchAndorra(provider.type, this.tracedAdapter(this.reasoningAdapter(this.adapterFor(snapshot, { sessionId: input.record.id, runId })), provider.id)),
4466
5375
  ...(openingAttachments === undefined ? {} : { attachments: openingAttachments }),
4467
5376
  ...(snapshot.contextWindow === undefined ? {} : { contextWindow: snapshot.contextWindow }),
@@ -4469,19 +5378,22 @@ export class AppServer {
4469
5378
  createBrowserIncognitoTool(this.browserViews, input.record.id, panelBrowserRelay ? this.panelBrowserRelayFor(input.record.id) : undefined, panelHold),
4470
5379
  createBrowserExtensionsTool(panelBrowserRelay ? relayExtensionSteps(this.panelBrowserRelayFor(input.record.id)) : step => this.runExtensionStep(input.record.id, step)), ...extension.tools, ...(mcp?.tools ?? [])], installedSkillClaims: extension.claimsSkillName, history: contextSeed,
4471
5380
  ...(runSkill.skills?.length ? { inheritedSkills: runSkill.skills.map(skill => skill.id), skillInvocationInstruction: runSkill.instruction } : {}),
4472
- instructions: `${await loadWorkspaceInstructions(root, signal, systemPromptOverrideFor(graph, config.systemPromptOverride))}${extension.instructions}`,
5381
+ instructions: `${await loadWorkspaceInstructions(root, signal, systemPromptOverrideFor(graph, config.systemPromptOverride))}${extension.instructions}${worktreeInstructions(input.record.checkout)}`,
4473
5382
  codeIntel, todoStore: new TodoStore(), ...(commandMemory ? { commandMemory } : {}), ...(projectMemory ? { projectMemory } : {}),
4474
5383
  limits: resolveConfiguredLimits(config),
4475
- ...hostedDecisionPolicy(membership, config.jevEnabled !== false && input.record.jevEnabled !== false, config.decisions),
5384
+ ...decisionPolicy,
4476
5385
  ...(config.efficiency ? { efficiency: config.efficiency } : {}),
4477
5386
  ...(runGoal ? { goalCompletionVerification: { goal: runGoal.text } } : {}),
4478
5387
  modelPinned: modelPinned || overrideAllNodes,
4479
5388
  ...(entryHistory ? { entryHistory: true } : {}),
4480
5389
  ...(startNode === undefined ? {} : { startNode }),
4481
- configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
4482
- resolveModel: (id, model, modelSignal) => this.resolveModel(config, id, model, modelSignal, id === provider.id && (model === undefined || model === modelId) ? reasoningEffort : undefined, input.record.id).then(watchResolved),
5390
+ configuredModels: config.providers.map(item => ({ id: item.id, type: item.type, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
5391
+ ...(config.efficiency?.adaptiveRouting?.strategy === 'pool' ? { quotaReadings: poolUsageReader(config, () => this.hosted.usage()) } : {}),
5392
+ resolveModel: (id, model, modelSignal, levelled) => this.resolveModel(config, id, model, modelSignal, levelled ?? (id === provider.id && (model === undefined || model === modelId) ? reasoningEffort : undefined), input.record.id).then(watchResolved),
5393
+ ...(autoEffort ? { sessionEffortAuto: true } : {}),
5394
+ thinkingLevels: (id, model, forAuto) => (forAuto ? autoLevels : enabledLevels)(config.providers.find(item => item.id === id), model),
4483
5395
  resolveProvider: id => watchResolved(this.resolveProvider(config, id, input.record.id)),
4484
- getLiveModel: async (nodeId, fallbackProvider, fallbackModel, modelSignal) => {
5396
+ getLiveModel: async (nodeId, fallbackProvider, fallbackModel, modelSignal, appliedRevision, hints) => {
4485
5397
  while (true) {
4486
5398
  const current = liveRun?.modelSelection;
4487
5399
  if (!current)
@@ -4491,14 +5403,27 @@ export class AppServer {
4491
5403
  return undefined;
4492
5404
  const targetProvider = target.provider, targetModel = target.model;
4493
5405
  const effectiveModel = targetModel ?? current.config.providers.find(item => item.id === targetProvider)?.model;
4494
- if (targetProvider === fallbackProvider && effectiveModel === fallbackModel)
5406
+ const scope = nodeId?.split('/')[0]?.replace(/#fallback$/, '');
5407
+ const nodeOverride = scope === undefined ? undefined : current.nodeOverrides?.[scope];
5408
+ const onSessionModel = targetProvider === current.provider && effectiveModel === current.model;
5409
+ const onNodeModel = nodeOverride?.provider === targetProvider && nodeOverride.model === effectiveModel;
5410
+ const appliesSelection = onNodeModel || (!current.nodeOnly && onSessionModel);
5411
+ if (targetProvider === fallbackProvider && effectiveModel === fallbackModel && (!appliesSelection || appliedRevision === current.revision))
4495
5412
  return undefined;
4496
- const selectedEffort = targetProvider === current.provider && effectiveModel === current.model
4497
- ? current.reasoningEffort : undefined;
4498
- const resolved = watchResolved(await this.resolveModel(current.config, targetProvider, targetModel, modelSignal, selectedEffort, input.record.id));
5413
+ const selectedEffort = onNodeModel ? nodeOverride.reasoningEffort : onSessionModel
5414
+ ? current.autoEffort ? 'auto' : current.reasoningEffort : undefined;
5415
+ // A level switched off for the replacement model is never sent, whether it is the run's or the provider's
5416
+ // saved one. The runtime installs this adapter mid-attempt, past the attempt-start check.
5417
+ const liveProvider = current.config.providers.find(item => item.id === targetProvider);
5418
+ const saved = selectedEffort ?? (effectiveModel === liveProvider?.model ? liveProvider?.reasoningEffort : undefined);
5419
+ const allowed = effectiveModel === undefined ? [] : enabledLevels(liveProvider, effectiveModel);
5420
+ const liveEffort = saved === 'auto'
5421
+ ? effectiveModel === undefined ? undefined : decideEffort({ task, levels: autoLevels(liveProvider, effectiveModel), hints, fallback: effectiveModel === liveProvider?.model ? liveProvider?.reasoningEffort : undefined }).level
5422
+ : saved === undefined || allowed.length === 0 ? (selectedEffort === 'auto' ? undefined : selectedEffort) : nearestEnabled(allowed, saved);
5423
+ const resolved = watchResolved(await this.resolveModel(current.config, targetProvider, targetModel, modelSignal, liveEffort, input.record.id));
4499
5424
  if (liveRun?.modelSelection !== current)
4500
5425
  continue;
4501
- return { ...resolved, provider: targetProvider };
5426
+ return { ...resolved, provider: targetProvider, selectionRevision: current.revision, ...(onSessionModel ? { sessionModel: true } : {}) };
4502
5427
  }
4503
5428
  },
4504
5429
  context: toolContext,
@@ -4602,7 +5527,7 @@ export class AppServer {
4602
5527
  return [...directed, ...own].map(entry => ({ role: 'user', content: entry.content, ...(entry.images.length ? { images: entry.images } : {}) }));
4603
5528
  },
4604
5529
  ...(resumeFrom === undefined ? {} : { resumeFrom }),
4605
- ...(lineageArtifacts === undefined ? {} : { artifactStore: lineageArtifacts }),
5530
+ artifactStore: lineageArtifacts ?? new ArtifactStore(runId, this.directory),
4606
5531
  reviewNode: this.reviewNodeService(input.record.id, runId, input.resumedFrom, () => liveSteers.filter(entry => entry.wake === undefined && entry.subagentId === undefined).map(entry => entry.id)),
4607
5532
  };
4608
5533
  bootMark('run.exec.options-built');
@@ -4662,7 +5587,16 @@ export class AppServer {
4662
5587
  await releaseRunResumeClaim(this.directory, resumedFrom);
4663
5588
  await checkpointWrites;
4664
5589
  const closedWithRun = controller.signal.aborted && this.runAbort === 'shutdown';
4665
- const completion = finalCompletion(result, controller.signal.aborted, failure, closedWithRun);
5590
+ const finished = finalCompletion(result, controller.signal.aborted, failure, closedWithRun);
5591
+ // The outcomes the agent listed, each tied to the runtime's record of the command that shows it.
5592
+ // The folders as the turn left them: a check followed by a shell edit is noticed even when nothing ran after it.
5593
+ const finalRevisions = new Map();
5594
+ if (finished.outcomes?.length) {
5595
+ for (const directory of [...new Set(turnObservations.map(item => item.directory))].slice(-5)) {
5596
+ finalRevisions.set(directory, await readRevision(directory).catch(() => undefined));
5597
+ }
5598
+ }
5599
+ const completion = finished.outcomes?.length ? { ...finished, evidence: resolveEvidence(finished.outcomes, turnObservations, turnEdits, finalRevisions) } : finished;
4666
5600
  if (result)
4667
5601
  foldUsage(result.usage, probeUsage);
4668
5602
  foldUsage(usage, result?.usage ?? runUsage);
@@ -4707,8 +5641,11 @@ export class AppServer {
4707
5641
  ...(automationContext === undefined ? {} : { automationContext }),
4708
5642
  ...(liveRun?.modelSelection ? { liveModelChanged: true } : {}),
4709
5643
  ...((liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort) === undefined
4710
- ? {} : { reasoningEffort: liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort }),
5644
+ ? ((liveRun?.modelSelection ? liveRun.modelSelection.autoEffort === true : autoEffort) ? { reasoningEffort: 'auto' } : {}) : { reasoningEffort: liveRun?.modelSelection ? liveRun.modelSelection.reasoningEffort : reasoningEffort }),
4711
5645
  ...((liveRun?.modelSelection?.overrideAllNodes ?? overrideAllNodes) ? { overrideAllNodes: true } : {}),
5646
+ // A model picked for the whole run while it was live is an explicit choice, so the run is no longer on Auto.
5647
+ // A pick for one node leaves the rest of the run on Auto.
5648
+ ...(autoModel && (!liveRun?.modelSelection || liveRun?.modelSelection?.nodeOnly === true) ? { autoModel: true } : {}),
4712
5649
  ...((liveNodeOverrides !== undefined && Object.keys(liveNodeOverrides).length > 0)
4713
5650
  ? { nodeModelOverrides: liveNodeOverrides } : {}),
4714
5651
  ...(entryHistory ? { entryHistory: true } : {}),
@@ -4721,8 +5658,8 @@ export class AppServer {
4721
5658
  ...(resumedFrom === undefined ? {} : { resumedFrom }),
4722
5659
  ...(journalIntact ? {} : { journalIntegrity: 'failed' }),
4723
5660
  ...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
4724
- ...(boundPermissions === undefined ? {} : { permissions: liveRun?.permissionControl.permissions ?? boundPermissions }) };
4725
- const writeFinal = () => writeFile(runRecordPath(this.directory, runId, 'json'), `${JSON.stringify(finalRecord, null, 2)}\n`, { mode: 0o600 });
5661
+ ...(boundPermissions === undefined && liveRun?.boundPermissions !== true ? {} : { permissions: liveRun?.permissionControl.permissions ?? boundPermissions }) };
5662
+ const writeFinal = () => writeFinalRunRecord(this.directory, finalRecord, telemetryAccess);
4726
5663
  if (liveRun)
4727
5664
  await this.serializeRunRecordWrite(liveRun, writeFinal);
4728
5665
  else
@@ -4762,9 +5699,11 @@ export class AppServer {
4762
5699
  this.spendAttemptWakes(record.id, new Set([runId, ...lineage]), finishedOwn);
4763
5700
  this.settleSessionTimers(record.id);
4764
5701
  this.emit('session.updated', { session: this.terminalSummary(snapshot) });
4765
- const eventResult = closedWithRun && result !== undefined && result.status === 'cancelled'
4766
- ? { ...result, status: 'interrupted', reason: APP_CLOSED_REASON }
4767
- : result;
5702
+ const visibleResult = result === undefined || (telemetryHandle?.lease && sameTelemetryLease(telemetryHandle.lease, telemetryLeaseSnapshot({ home: this.directory, signals: this.telemetry.signals })))
5703
+ ? result : functionalRunRecord(result);
5704
+ const eventResult = closedWithRun && visibleResult !== undefined && visibleResult.status === 'cancelled'
5705
+ ? { ...visibleResult, status: 'interrupted', reason: APP_CLOSED_REASON }
5706
+ : visibleResult;
4768
5707
  const undelivered = undeliveredSteers.length
4769
5708
  ? { undeliveredSteers: undeliveredSteers.map(entry => ({ id: entry.id, text: entry.text, ...(entry.note ? { note: entry.note } : {}), ...(entry.refs?.length ? { attachments: entry.refs } : {}) })) }
4770
5709
  : {};
@@ -4830,6 +5769,9 @@ export class AppServer {
4830
5769
  throw new AppServerError('invalid-params', 'That run is no longer active.');
4831
5770
  const provider = identifier(params.provider, 'provider');
4832
5771
  const model = text(params.model, 'model', 200);
5772
+ const requestedEffort = params.reasoningEffort === undefined || params.reasoningEffort === null ? undefined
5773
+ : params.reasoningEffort === 'auto' ? 'auto' : reasoningEffort(params.reasoningEffort);
5774
+ const selection = { provider, model, ...(requestedEffort === undefined ? {} : { reasoningEffort: requestedEffort }) };
4833
5775
  const scopedNode = params.nodeId === undefined ? undefined : identifier(params.nodeId, 'nodeId');
4834
5776
  if (scopedNode === undefined && typeof params.overrideAllNodes !== 'boolean')
4835
5777
  throw new AppServerError('invalid-params', 'overrideAllNodes must be a boolean');
@@ -4845,7 +5787,7 @@ export class AppServer {
4845
5787
  if (scopedNode !== undefined && run.modelGraph.nodes[scopedNode]?.type !== 'agent')
4846
5788
  throw new AppServerError('invalid-params', `Unknown agent node: ${scopedNode}`);
4847
5789
  const replacement = scopedNode === undefined
4848
- ? params.overrideAllNodes ? applyModelOverride(original, { provider, model }) : bindPortableGraphProviders(original, config)
5790
+ ? params.overrideAllNodes ? applyModelOverride(original, selection) : bindPortableGraphProviders(original, config)
4849
5791
  : undefined;
4850
5792
  let switched;
4851
5793
  await this.serializeRunRecordWrite(run, async () => {
@@ -4854,7 +5796,7 @@ export class AppServer {
4854
5796
  if (run.modelChangeGeneration !== generation)
4855
5797
  throw new AppServerError('busy', 'A newer model selection superseded this one.');
4856
5798
  const path = runRecordPath(this.directory, run.runId, 'json');
4857
- const existing = JSON.parse(await readFile(path, 'utf8'));
5799
+ const existing = await readTelemetryRunRecord(this.directory, path, this.run?.telemetryAccess);
4858
5800
  if (existing.status !== 'running')
4859
5801
  throw new AppServerError('invalid-params', 'That run is no longer active.');
4860
5802
  if (scopedNode !== undefined) {
@@ -4864,8 +5806,14 @@ export class AppServer {
4864
5806
  const previousModel = existingOverride?.model ?? (typeof node.model === 'string' ? node.model
4865
5807
  : node.provider === undefined ? existing.model
4866
5808
  : config.providers.find(item => item.id === node.provider)?.model);
4867
- existing.nodeModelOverrides = { ...(existing.nodeModelOverrides ?? {}), [scopedNode]: { provider, model } };
5809
+ existing.nodeModelOverrides = { ...(existing.nodeModelOverrides ?? {}), [scopedNode]: selection };
4868
5810
  existing.liveModelChanged = true;
5811
+ // A model override replaces the node's whole model choice, its own thinking level included, as one given at
5812
+ // run start does (applyNodeModelOverrides).
5813
+ if (requestedEffort === undefined)
5814
+ delete node.reasoningEffort;
5815
+ else
5816
+ node.reasoningEffort = requestedEffort;
4869
5817
  switched = { scope: 'node', from: { provider: previousProvider, ...(previousModel === undefined ? {} : { model: String(previousModel) }) }, nodeName: node.name };
4870
5818
  }
4871
5819
  else {
@@ -4877,11 +5825,15 @@ export class AppServer {
4877
5825
  existing.overrideAllNodes = true;
4878
5826
  else
4879
5827
  delete existing.overrideAllNodes;
5828
+ // A model picked for the whole run is an explicit choice: a resume after a crash must not restore Auto.
5829
+ delete existing.autoModel;
4880
5830
  delete existing.nodeModelOverrides;
4881
- if (!supportsReasoningEffort(config.providers.find(item => item.id === provider)?.type ?? ''))
5831
+ if (requestedEffort !== undefined)
5832
+ existing.reasoningEffort = requestedEffort;
5833
+ else if (params.reasoningEffort === null || !supportsReasoningEffort(config.providers.find(item => item.id === provider)?.type ?? ''))
4882
5834
  delete existing.reasoningEffort;
4883
5835
  }
4884
- await writeOpenRunRecord(this.directory, existing);
5836
+ await writeOpenRunRecord(this.directory, existing, this.run?.telemetryAccess);
4885
5837
  if (replacement !== undefined) {
4886
5838
  for (const [id, source] of Object.entries(replacement.nodes)) {
4887
5839
  const target = run.modelGraph.nodes[id];
@@ -4893,6 +5845,11 @@ export class AppServer {
4893
5845
  else
4894
5846
  target[key] = source[key];
4895
5847
  }
5848
+ // The thinking level goes with the model choice: an override removes the node's own, and lifting it restores it.
5849
+ if (source.reasoningEffort === undefined)
5850
+ delete target.reasoningEffort;
5851
+ else
5852
+ target.reasoningEffort = source.reasoningEffort;
4896
5853
  if (target.retry && source.retry)
4897
5854
  target.retry.fallback = structuredClone(source.retry.fallback);
4898
5855
  if (target.subagents && source.subagents) {
@@ -4914,8 +5871,9 @@ export class AppServer {
4914
5871
  }
4915
5872
  }
4916
5873
  }
4917
- const liveEffort = typeof existing.reasoningEffort === 'string'
5874
+ const liveEffort = typeof existing.reasoningEffort === 'string' && existing.reasoningEffort !== 'auto'
4918
5875
  ? reasoningEffort(existing.reasoningEffort) : undefined;
5876
+ const liveAuto = existing.reasoningEffort === 'auto';
4919
5877
  if (scopedNode !== undefined) {
4920
5878
  const previous = run.modelSelection;
4921
5879
  run.modelSelection = {
@@ -4925,26 +5883,32 @@ export class AppServer {
4925
5883
  nodeOnly: previous === undefined ? true : previous.nodeOnly === true,
4926
5884
  config,
4927
5885
  ...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
4928
- nodeOverrides: { ...(existing.nodeModelOverrides ?? previous?.nodeOverrides ?? {}), [scopedNode]: { provider, model } },
5886
+ ...(liveAuto ? { autoEffort: true } : {}),
5887
+ nodeOverrides: { ...(existing.nodeModelOverrides ?? previous?.nodeOverrides ?? {}), [scopedNode]: selection },
4929
5888
  revision: (previous?.revision ?? 0) + 1,
4930
5889
  };
4931
5890
  }
4932
5891
  else {
4933
5892
  run.modelSelection = { provider, model, overrideAllNodes: params.overrideAllNodes, config,
4934
5893
  ...(liveEffort === undefined ? {} : { reasoningEffort: liveEffort }),
5894
+ ...(liveAuto ? { autoEffort: true } : {}),
4935
5895
  revision: (run.modelSelection?.revision ?? 0) + 1 };
4936
5896
  }
4937
5897
  if (replacement !== undefined && run.wakeCarry) {
4938
- if (liveEffort === undefined)
4939
- delete run.wakeCarry.reasoningEffort;
4940
- else
5898
+ if (liveEffort !== undefined)
4941
5899
  run.wakeCarry.reasoningEffort = liveEffort;
5900
+ else if (liveAuto)
5901
+ run.wakeCarry.reasoningEffort = 'auto';
5902
+ else
5903
+ delete run.wakeCarry.reasoningEffort;
4942
5904
  run.wakeCarry.provider = provider;
4943
5905
  run.wakeCarry.model = model;
4944
5906
  if (params.overrideAllNodes)
4945
5907
  run.wakeCarry.overrideAllNodes = true;
4946
5908
  else
4947
5909
  delete run.wakeCarry.overrideAllNodes;
5910
+ if (scopedNode === undefined)
5911
+ delete run.wakeCarry.autoModel;
4948
5912
  }
4949
5913
  });
4950
5914
  if (switched !== undefined) {
@@ -4965,11 +5929,15 @@ export class AppServer {
4965
5929
  if (live === undefined || live.runId !== runId || live.controller.signal.aborted || live.steersClosed) {
4966
5930
  throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
4967
5931
  }
4968
- const change = (live.permissionChanges ?? Promise.resolve()).then(() => this.applyRunPermissions(live, next));
5932
+ // `scope: "run"` keeps the change with this run: its record carries the mode, and the workspace default is left alone.
5933
+ if (params.scope !== undefined && params.scope !== 'run')
5934
+ throw new AppServerError('invalid-params', 'scope must be "run" when it is given.');
5935
+ const bind = params.scope === 'run';
5936
+ const change = (live.permissionChanges ?? Promise.resolve()).then(() => this.applyRunPermissions(live, next, bind));
4969
5937
  live.permissionChanges = change.then(() => undefined, () => undefined);
4970
5938
  return change;
4971
5939
  }
4972
- async applyRunPermissions(live, next) {
5940
+ async applyRunPermissions(live, next, bind = false) {
4973
5941
  const stillLive = () => this.run === live && !live.controller.signal.aborted;
4974
5942
  if (!stillLive())
4975
5943
  throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
@@ -4980,7 +5948,10 @@ export class AppServer {
4980
5948
  await live.codeIntelReady;
4981
5949
  await this.syncCodeIntelPermissions(live);
4982
5950
  }
4983
- await this.saveRunPermissions(live, next, stillLive);
5951
+ await this.saveRunPermissions(live, next, stillLive, bind);
5952
+ // From here on the run owns its mode: later changes stay with it too, and its final record carries the mode.
5953
+ if (bind)
5954
+ live.boundPermissions = true;
4984
5955
  }
4985
5956
  catch (error) {
4986
5957
  live.codeIntelPermissions = live.permissionControl.permissions ?? previous;
@@ -5028,16 +5999,16 @@ export class AppServer {
5028
5999
  live.permissionChanges = change.then(() => undefined, () => undefined);
5029
6000
  return change;
5030
6001
  }
5031
- async saveRunPermissions(live, next, stillLive) {
5032
- if (live.boundPermissions) {
6002
+ async saveRunPermissions(live, next, stillLive, bind = false) {
6003
+ if (live.boundPermissions || bind) {
5033
6004
  await this.serializeRunRecordWrite(live, async () => {
5034
6005
  if (!stillLive())
5035
6006
  throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
5036
- const existing = JSON.parse(await readFile(runRecordPath(this.directory, live.runId, 'json'), 'utf8'));
6007
+ const existing = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, live.runId, 'json'), live.telemetryAccess);
5037
6008
  if (existing.status !== 'running')
5038
6009
  throw new AppServerError('not-found', 'That task is not running on this engine. The new mode applies to the next task.');
5039
6010
  existing.permissions = next;
5040
- await writeOpenRunRecord(this.directory, existing);
6011
+ await writeOpenRunRecord(this.directory, existing, this.run?.telemetryAccess);
5041
6012
  });
5042
6013
  }
5043
6014
  else {
@@ -5056,7 +6027,7 @@ export class AppServer {
5056
6027
  }
5057
6028
  syncCodeIntelPermissions(live) {
5058
6029
  const apply = async () => {
5059
- const manager = this.codeIntel?.workspace === live.workspace ? this.codeIntel.manager : undefined;
6030
+ const manager = this.codeIntel?.workspace === live.workRoot ? this.codeIntel.manager : undefined;
5060
6031
  const target = live.codeIntelPermissions;
5061
6032
  if (!manager || live.codeIntelApplied === target)
5062
6033
  return;
@@ -5079,14 +6050,10 @@ export class AppServer {
5079
6050
  return { model: resolved.model, adapter: this.tracedAdapter(this.reasoningAdapter(this.adapterFor(resolved, { sessionId })), id), ...(resolved.contextWindow === undefined ? {} : { contextWindow: resolved.contextWindow }), ...(resolved.reasoningEffort === undefined ? {} : { reasoningEffort: resolved.reasoningEffort }), providerType: provider.type, baseUrl: provider.baseUrl };
5080
6051
  }
5081
6052
  async analyticsConfigView(config) {
5082
- try {
5083
- const status = await getAuthStatus();
5084
- const gate = await telemetryGate({ home: this.directory, config, subject: status.signedIn ? status.subject : undefined });
5085
- return configView(config, { plan: gate.plan, canOptOut: gate.canOptOut });
5086
- }
5087
- catch {
5088
- return configView(config);
5089
- }
6053
+ const { status, analytics } = await this.telemetry.snapshot();
6054
+ const functional = { ...config };
6055
+ delete functional.analytics;
6056
+ return { ...configView(functional), ...(analytics === undefined ? {} : { analytics }), telemetryConsent: status };
5090
6057
  }
5091
6058
  resolveProvider(config, id, sessionId = this.run?.sessionId) {
5092
6059
  const provider = config.providers.find(item => item.id === id);
@@ -5126,7 +6093,7 @@ export class AppServer {
5126
6093
  if (busy())
5127
6094
  throw new AppServerError('engine-busy', 'This engine is already running a task.');
5128
6095
  const root = await workspaceRoot(params.workspace);
5129
- const requested = params.permissions === undefined ? undefined : permissionMode(params.permissions);
6096
+ const requested = requestedPermissionMode(params.permissions);
5130
6097
  const config = await loadConfig(this.directory);
5131
6098
  const effective = requested ?? config.workspacePermissions?.[workspacePermissionKey(root)] ?? 'ask-for-approval';
5132
6099
  const manager = await this.operation(undefined, signal => this.codeIntelligence(root, effective, signal, { onlyWhileIdle: true }));
@@ -5220,7 +6187,7 @@ export class AppServer {
5220
6187
  return 'policy-changed';
5221
6188
  return answer === 'approve';
5222
6189
  }
5223
- async ask(runId, question, choices, signal) {
6190
+ async ask(runId, question, choices, signal, handoff) {
5224
6191
  const id = randomUUID();
5225
6192
  const sessionId = this.run?.sessionId;
5226
6193
  if (sessionId)
@@ -5228,8 +6195,8 @@ export class AppServer {
5228
6195
  version: 1, id, runId, sessionId, kind: 'question',
5229
6196
  prompt: question.slice(0, 2048), createdAt: new Date().toISOString(),
5230
6197
  }).catch(error => this.log('warn', 'Could not record pending question: ' + message(error)));
5231
- this.emit('run.question', { runId, id, question, ...(choices === undefined ? {} : { choices }) });
5232
- this.waiting.set(id, { kind: 'question', runId, id, question, ...(choices === undefined ? {} : { choices: [...choices] }) });
6198
+ this.emit('run.question', { runId, id, question, ...(choices === undefined ? {} : { choices }), ...(handoff ? { handoff } : {}) });
6199
+ this.waiting.set(id, { kind: 'question', runId, id, question, ...(choices === undefined ? {} : { choices: [...choices] }), ...(handoff ? { handoff } : {}) });
5233
6200
  this.emit('run.state', { runId, state: 'awaiting-input' });
5234
6201
  try {
5235
6202
  return await this.interaction(id, signal);
@@ -5411,17 +6378,23 @@ export class AppServer {
5411
6378
  }
5412
6379
  async graphDirectory(canClaim = false) {
5413
6380
  const subject = await currentGraphSubject();
5414
- if (subject === undefined)
6381
+ if (subject === undefined) {
6382
+ await this.graphSync.close();
5415
6383
  return { directory: this.directory };
6384
+ }
5416
6385
  let access;
6386
+ const legal = LEGAL_ACCEPTANCE_REQUIRED ? await legalStatus(this.directory) : undefined;
6387
+ const accepted = legal === undefined || (legal.accepted && legal.scope === 'account' && legal.subject === subject);
5417
6388
  try {
5418
- access = await graphStorageAccess(this.directory, subject, { claim: canClaim, paid: who => this.currentAccountIsConfirmed(who) });
6389
+ access = await graphStorageAccess(this.directory, subject, { claim: canClaim && accepted, paid: who => this.currentAccountIsConfirmed(who) });
5419
6390
  }
5420
6391
  catch {
5421
6392
  return { directory: this.directory };
5422
6393
  }
5423
- if (!access.shared)
6394
+ if (!access.shared && accepted)
5424
6395
  await this.graphSync.ensure(access.directory, subject);
6396
+ else
6397
+ await this.graphSync.close(); // Local metadata is harmless, but must not start autosync.
5425
6398
  return { directory: access.directory, subject };
5426
6399
  }
5427
6400
  async currentAccountIsConfirmed(subject) {
@@ -5538,6 +6511,57 @@ export class AppServer {
5538
6511
  }
5539
6512
  return { graph, ...(execution !== undefined ? { execution } : {}), ...(subject === undefined ? {} : { subject }) };
5540
6513
  }
6514
+ async checkDraftGraphModels(params) {
6515
+ const id = currentGraphSelection(identifier(params.id, 'id'));
6516
+ const scope = identifier(params.scope, 'scope');
6517
+ const provider = params.provider === undefined ? undefined : identifier(params.provider, 'provider');
6518
+ const model = params.model === undefined ? undefined : text(params.model, 'model', 200);
6519
+ const override = params.overrideAllNodes === true && provider !== undefined && model !== undefined
6520
+ ? { provider, model } : undefined;
6521
+ this.draftGraphProbes.get(scope)?.abort();
6522
+ const controller = new AbortController();
6523
+ this.draftGraphProbes.set(scope, controller);
6524
+ try {
6525
+ return await this.operation(undefined, async (tracked) => {
6526
+ const signal = AbortSignal.any([tracked, controller.signal]);
6527
+ const config = await loadConfig(this.directory);
6528
+ if (config.providers.length === 0)
6529
+ return {};
6530
+ try {
6531
+ const graph = await this.loadGraph(id, signal, undefined, { bindProviders: override === undefined });
6532
+ signal.throwIfAborted();
6533
+ const warning = await this.graphModelWarning(override === undefined ? graph : applyModelOverride(graph, override), config, signal, { ...(provider === undefined ? {} : { provider }), ...(model === undefined ? {} : { model }) }, override === undefined
6534
+ ? 'Open the graph in Studio, correct the model selections, then select it again.'
6535
+ : 'Choose another model to check its availability.');
6536
+ return warning === undefined ? {} : { modelWarning: warning };
6537
+ }
6538
+ catch (error) {
6539
+ if (!(error instanceof GraphProviderUnavailableError))
6540
+ throw error;
6541
+ return { modelWarning: this.graphProviderWarning(error) };
6542
+ }
6543
+ });
6544
+ }
6545
+ catch (error) {
6546
+ if (!controller.signal.aborted)
6547
+ throw error;
6548
+ return {};
6549
+ }
6550
+ finally {
6551
+ if (this.draftGraphProbes.get(scope) === controller)
6552
+ this.draftGraphProbes.delete(scope);
6553
+ }
6554
+ }
6555
+ async graphModelWarning(graph, config, signal, session, advice) {
6556
+ const health = await this.checkGraphHealth(graph, config, signal, {
6557
+ ...(session === undefined ? {} : { session }), overallTimeoutMs: SELECTION_HEALTH_TIMEOUT_MS,
6558
+ verified: { has: () => false, add: (provider, model) => this.modelHealth.add(provider, model) },
6559
+ });
6560
+ return health.healthy ? undefined : formatGraphHealthFailure(health, advice);
6561
+ }
6562
+ graphProviderWarning(error) {
6563
+ return `${error.message}\nThe selection stands. A task on this graph starts only once it can run on this machine, or with a model override that runs every node on one provider.`;
6564
+ }
5541
6565
  async selectGraph(params) {
5542
6566
  const id = currentGraphSelection(identifier(params.id, 'id'));
5543
6567
  const madeFor = params.subject === undefined || params.subject === '' ? undefined : identifier(params.subject, 'subject');
@@ -5555,25 +6579,23 @@ export class AppServer {
5555
6579
  ...(sessionProvider === undefined ? {} : { provider: sessionProvider }),
5556
6580
  ...(sessionModel === undefined ? {} : { model: sessionModel }),
5557
6581
  };
5558
- const config = await loadConfig(this.directory);
6582
+ const checkModels = params.skipModelHealth !== true;
5559
6583
  let modelWarning;
5560
6584
  let boundGraph;
5561
6585
  try {
5562
- boundGraph = await this.loadGraph(id);
6586
+ boundGraph = await this.loadGraph(id, undefined, undefined, { bindProviders: checkModels });
5563
6587
  }
5564
6588
  catch (error) {
5565
6589
  if (!(error instanceof GraphProviderUnavailableError))
5566
6590
  throw error;
5567
- modelWarning = `${error.message}\nThe selection stands. A task on this graph starts only once it can run on this machine, or with a model override that runs every node on one provider.`;
6591
+ if (checkModels)
6592
+ modelWarning = this.graphProviderWarning(error);
5568
6593
  }
5569
6594
  const probed = boundGraph;
5570
- if (probed !== undefined && config.providers.length !== 0) {
5571
- const health = await this.operation(undefined, tracked => this.checkGraphHealth(probed, config, tracked, {
5572
- ...(session === undefined ? {} : { session }), overallTimeoutMs: SELECTION_HEALTH_TIMEOUT_MS,
5573
- verified: { has: () => false, add: (provider, model) => this.modelHealth.add(provider, model) },
5574
- }));
5575
- if (!health.healthy)
5576
- modelWarning = formatGraphHealthFailure(health, 'Open the graph in Studio, correct the model selections, then select it again.');
6595
+ if (checkModels && probed !== undefined) {
6596
+ const config = await loadConfig(this.directory);
6597
+ if (config.providers.length !== 0)
6598
+ modelWarning = await this.operation(undefined, tracked => this.graphModelWarning(probed, config, tracked, session, 'Open the graph in Studio, correct the model selections, then select it again.'));
5577
6599
  }
5578
6600
  const withWarning = (answer) => modelWarning === undefined ? answer : { ...answer, modelWarning };
5579
6601
  const subject = await currentGraphSubject();
@@ -5598,10 +6620,13 @@ export class AppServer {
5598
6620
  this.emit('config.changed', { config: await this.analyticsConfigView(saved) });
5599
6621
  return withWarning({ config: await this.analyticsConfigView(saved), selected: id, persisted: true });
5600
6622
  }
5601
- async openEditor() {
6623
+ async openEditor(params) {
6624
+ // Validate before reusing a listener as well as before creating one.
6625
+ graphEditorParentOrigins(params.parentOrigin);
6626
+ const parentOrigin = params.parentOrigin;
5602
6627
  if (this.editor)
5603
6628
  return { url: this.editor.url, reused: true, embeddable: true };
5604
- this.editorTask ??= startGraphServer(this.directory).then(app => ({ url: app.url, close: app.close }));
6629
+ this.editorTask ??= startGraphServer(this.directory, undefined, { parentOrigin }).then(app => ({ url: app.url, close: app.close }));
5605
6630
  try {
5606
6631
  const editor = await this.editorTask;
5607
6632
  this.editor = editor;
@@ -5665,6 +6690,7 @@ export class AppServer {
5665
6690
  case 'invalid_name': return new AppServerError('invalid-params', MACHINE_NAME_RULE);
5666
6691
  case 'not_found': return new AppServerError('not-found', 'That machine is not linked to your account.');
5667
6692
  case 'cloud_not_enabled': return new AppServerError('forbidden', 'Cloud is not available for your account yet.');
6693
+ case 'cloud_plan': return new AppServerError('forbidden', 'Cloud is not included in the Free plan. Upgrade to use it.');
5668
6694
  case 'cloud_environment': return new AppServerError('invalid-params', 'Delete Cloud from Settings → Environments.');
5669
6695
  case 'invalid_version': return new AppServerError('invalid-params', 'This version of Andorra Code cannot start Cloud. Update Andorra Code and try again.');
5670
6696
  case 'stopping': return new AppServerError('busy', 'Cloud is still stopping. Try again in a moment.');
@@ -5749,7 +6775,9 @@ export class AppServer {
5749
6775
  if (remember)
5750
6776
  this.cloudEnvironmentId = status.state === 'none' ? undefined : status.environmentId ?? this.cloudEnvironmentId;
5751
6777
  const { version, ...rest } = status;
5752
- return { ...rest, outdated: (status.state === 'starting' || status.state === 'running') && version !== undefined && version !== engineVersion };
6778
+ const link = status.environmentId === undefined ? undefined : this.engineLinks.get(status.environmentId);
6779
+ const autoUpdates = remember && link?.capabilities?.includes(CLOUD_BRIDGE_AUTO_UPDATE) === true;
6780
+ return { ...rest, outdated: !autoUpdates && (status.state === 'starting' || status.state === 'running') && version !== undefined && version !== engineVersion };
5753
6781
  }
5754
6782
  async environmentRemove(params) {
5755
6783
  const id = environmentId(params.id);
@@ -5860,10 +6888,13 @@ export class AppServer {
5860
6888
  this.environmentIdsLoading = undefined; });
5861
6889
  return loading;
5862
6890
  }
6891
+ offlineEnvironmentLine(env) {
6892
+ return env === this.cloudEnvironmentId ? 'Connecting to Cloud…' : MACHINE_OFFLINE;
6893
+ }
5863
6894
  /** A call for a machine whose link is waiting for it to come back fails now instead of at its deadline. */
5864
6895
  refuseWhileReconnecting(env) {
5865
6896
  if (this.engineLinks.get(env)?.reconnecting)
5866
- throw new AppServerError('network', MACHINE_OFFLINE);
6897
+ throw new AppServerError('network', this.offlineEnvironmentLine(env));
5867
6898
  }
5868
6899
  hostOperation(params, op, operationParams = {}) {
5869
6900
  const env = environmentId(params.workspaceId);
@@ -5915,8 +6946,46 @@ export class AppServer {
5915
6946
  const identity = await this.machineIdentity(env);
5916
6947
  if (identity?.capabilities !== undefined && this.engineLinks.get(env) === link)
5917
6948
  link.capabilities = identity.capabilities;
6949
+ // A machine that says it cannot ask before product telemetry gets no link. One that could not be asked keeps a
6950
+ // retryable link: no relayed method runs on it until the capability has been proved (assertRemotePolicy).
6951
+ if (identity?.capabilities !== undefined && !identity.capabilities.includes(TELEMETRY_CONSENT_CAPABILITY)) {
6952
+ this.dropEngineLink(env, link);
6953
+ throw new RemoteConsentUnsupportedError();
6954
+ }
5918
6955
  return { ok: true, engine: REMOTE_LINK_ENGINE, host: { ...opened.host, ...(identity ?? {}) } };
5919
6956
  }
6957
+ /**
6958
+ * Relayed work reaches only a machine that proved it asks before product telemetry and, for coding or policy
6959
+ * calls, that it records policy acceptance. The proof is the capabilities its `whoami` named for this link; a
6960
+ * machine that could not be asked is refused, never assumed capable.
6961
+ */
6962
+ async assertRemotePolicy(env, method) {
6963
+ const link = this.engineLinks.get(env);
6964
+ let capabilities = link?.capabilities;
6965
+ if (capabilities === undefined) {
6966
+ try {
6967
+ const whoami = await this.relayLink().host(env, 'whoami', {}, Date.now() + REMOTE_HOST_DEADLINE_MS);
6968
+ const named = whoami && typeof whoami === 'object' ? whoami.capabilities : undefined;
6969
+ if (Array.isArray(named)) {
6970
+ capabilities = named.filter((entry) => typeof entry === 'string');
6971
+ if (link !== undefined && this.engineLinks.get(env) === link)
6972
+ link.capabilities = capabilities;
6973
+ }
6974
+ }
6975
+ catch (error) {
6976
+ // A machine the relay does not know is not found, as before; any other failure leaves the capability unproved.
6977
+ if (error instanceof AppServerError && error.code === 'not-found')
6978
+ throw error;
6979
+ }
6980
+ }
6981
+ if (capabilities === undefined)
6982
+ throw new AppServerError('remote', 'Telemetry permission unavailable: that machine could not be asked what it supports. Try again in a moment.');
6983
+ if (!capabilities.includes(TELEMETRY_CONSENT_CAPABILITY))
6984
+ throw new RemoteConsentUnsupportedError();
6985
+ if ((legalMethodRequiresAcceptance(method) || method.startsWith('legal.')) && !capabilities.includes(LEGAL_ACCEPTANCE_CAPABILITY)) {
6986
+ throw new AppServerError('remote', 'Update the paired machine for policy acceptance before coding work.');
6987
+ }
6988
+ }
5920
6989
  /** What the machine's `whoami` adds to its host description (grant, capabilities); undefined when it could not be read. */
5921
6990
  async machineIdentity(env) {
5922
6991
  try {
@@ -6332,21 +7401,40 @@ export class AppServer {
6332
7401
  this.modelRelaySaveRetries.add(timer);
6333
7402
  }
6334
7403
  async remoteEngineRequest(params) {
7404
+ const requestedAt = Date.now();
6335
7405
  const workspaceId = typeof params.workspaceId === 'string' ? params.workspaceId : '';
6336
7406
  const connectionId = typeof params.connectionId === 'string' ? params.connectionId : '';
6337
7407
  const engine = typeof params.engine === 'string' ? params.engine : '';
6338
7408
  const method = typeof params.method === 'string' ? params.method : '';
6339
7409
  if (!workspaceId || !connectionId || !engine || !method)
6340
7410
  throw new AppServerError('invalid-params', 'workspaceId, connectionId, engine, and method are required.');
7411
+ if (method === 'telemetry.setConsent')
7412
+ throw new AppServerError('unknown-method', 'Permission must be changed locally on the execution host.');
6341
7413
  const env = environmentId(workspaceId);
6342
7414
  this.refuseWhileReconnecting(env);
7415
+ await this.assertRemotePolicy(env, method);
7416
+ const startsTask = method === 'run.start' || method === 'run.resume';
7417
+ const cloudTaskLink = startsTask && env === this.cloudEnvironmentId ? this.engineLinks.get(env) : undefined;
7418
+ const generation = this.accountGeneration;
6343
7419
  let inner = params.params !== undefined && typeof params.params === 'object' && !Array.isArray(params.params)
6344
7420
  ? params.params : undefined;
6345
- const relayMachine = this.engineLinks.get(env)?.capabilities?.includes(MODEL_RELAY_CAPABILITY) === true;
7421
+ if (inner?.attachments !== undefined && env === this.cloudEnvironmentId && ['run.start', 'run.resume', 'run.steer'].includes(method)) {
7422
+ try {
7423
+ inner = { ...inner, attachments: await cloudAttachments(inner.attachments) };
7424
+ }
7425
+ catch (error) {
7426
+ throw new AppServerError('invalid-params', message(error));
7427
+ }
7428
+ if (generation !== this.accountGeneration)
7429
+ throw new AppServerError('cancelled', 'The Andorra account changed.');
7430
+ this.refuseWhileReconnecting(env);
7431
+ }
7432
+ const capabilities = this.engineLinks.get(env)?.capabilities;
7433
+ const relayMachine = capabilities?.includes(MODEL_RELAY_CAPABILITY) === true;
6346
7434
  // A machine whose engine takes relayed providers runs this computer's models: its start carries them by id only.
6347
7435
  let relayed = false;
6348
- if ((method === 'run.start' || method === 'run.resume') && relayMachine) {
6349
- const enriched = await this.withModelRelay(method, inner ?? {});
7436
+ if (startsTask && relayMachine) {
7437
+ const enriched = await this.withModelRelay(method, inner ?? {}, capabilities?.includes('providers.reasoningProbe') === true);
6350
7438
  if (enriched !== undefined) {
6351
7439
  relayed = true;
6352
7440
  inner = enriched;
@@ -6356,24 +7444,49 @@ export class AppServer {
6356
7444
  await this.checkRelayedModel(inner);
6357
7445
  const ceiling = RELAY_LONG_METHODS.has(method) ? RELAY_LONG_DEADLINE_MS : RELAY_DEADLINE_MS;
6358
7446
  const deadlineMs = typeof params.deadlineMs === 'number' && params.deadlineMs > 0 ? Math.min(Math.round(params.deadlineMs), ceiling) : undefined;
6359
- const send = (sent) => {
7447
+ const send = (sent, budget = deadlineMs) => {
6360
7448
  // The machine bounds the call by deadlineMs and answers with its own error; the slack lets that answer arrive.
6361
- const deadlineAt = Date.now() + (deadlineMs ?? ceiling) + RELAY_TRANSPORT_SLACK_MS;
7449
+ const deadlineAt = Date.now() + (budget ?? ceiling) + RELAY_TRANSPORT_SLACK_MS;
6362
7450
  return this.relayLink().request(env, {
6363
7451
  connectionId,
6364
7452
  viewerWorkspaceId: env,
6365
7453
  engine,
6366
7454
  method,
6367
7455
  ...(sent !== undefined ? { params: sent } : {}),
6368
- ...(deadlineMs !== undefined ? { deadlineMs } : {}),
7456
+ ...(budget !== undefined ? { deadlineMs: budget } : {}),
6369
7457
  }, deadlineAt);
6370
7458
  };
6371
- let answer = await send(inner);
7459
+ const sendTask = async (sent) => {
7460
+ if (cloudTaskLink?.connectionId !== connectionId)
7461
+ return send(sent);
7462
+ const checkLink = () => {
7463
+ if (generation !== this.accountGeneration)
7464
+ throw new AppServerError('cancelled', 'The Andorra account changed.');
7465
+ if (this.closed || !this.linkIsCurrent(env, cloudTaskLink))
7466
+ throw new AppServerError('cancelled', 'The connection to that machine was closed.');
7467
+ };
7468
+ checkLink();
7469
+ this.refuseWhileReconnecting(env);
7470
+ let result = await send(sent);
7471
+ const callerDeadline = requestedAt + (deadlineMs ?? ceiling);
7472
+ const retryUntil = Math.min(Date.now() + CLOUD_BRIDGE_RETRY_LIMIT_MS, callerDeadline - RELAY_TRANSPORT_SLACK_MS);
7473
+ // Only this answer proves the task was refused before dispatch. An unanswered request could have started work.
7474
+ while (result.error?.code === 'busy' && result.error.message === RESTARTING_MESSAGE && Date.now() < retryUntil) {
7475
+ await new Promise(resolve => setTimeout(resolve, Math.min(CLOUD_BRIDGE_RETRY_MS, Math.max(0, retryUntil - Date.now()))));
7476
+ checkLink();
7477
+ const now = Date.now();
7478
+ if (now >= retryUntil || cloudTaskLink.reconnecting)
7479
+ continue;
7480
+ result = await send(sent, callerDeadline - now - RELAY_TRANSPORT_SLACK_MS);
7481
+ }
7482
+ return result;
7483
+ };
7484
+ let answer = await sendTask(inner);
6372
7485
  // A resumed run that ran a graph from this computer needs it again; the machine's record names it.
6373
7486
  if (relayed && method === 'run.resume' && answer.error?.message === RELAYED_GRAPH_NEEDS_DESKTOP && inner !== undefined) {
6374
7487
  const graph = await this.relayedResumeGraph(env, connectionId, inner.runId, relayOfferedProviders(await loadConfig(this.directory)));
6375
7488
  if (graph !== undefined)
6376
- answer = await send({ ...inner, relay: { ...inner.relay, graph } });
7489
+ answer = await sendTask({ ...inner, relay: { ...inner.relay, graph } });
6377
7490
  }
6378
7491
  // The machine took a run on this computer's models: from now on that run's model requests are answered here.
6379
7492
  if (relayed && !answer.error)
@@ -6417,7 +7530,7 @@ export class AppServer {
6417
7530
  * falls back to one of its own. Undefined when this computer has no provider to offer: the request then goes as it
6418
7531
  * was, and the machine runs it on its own providers if it has any.
6419
7532
  */
6420
- async withModelRelay(method, params) {
7533
+ async withModelRelay(method, params, relayReasoning) {
6421
7534
  const config = await loadConfig(this.directory);
6422
7535
  const providers = relayOfferedProviders(config);
6423
7536
  if (!providers.length)
@@ -6453,7 +7566,7 @@ export class AppServer {
6453
7566
  // sign-in names the one compatible profile here), so every node names an entry of `relay.providers`. A start that runs
6454
7567
  // every node on one model is not bound, as locally: the override replaces the nodes' providers on the machine.
6455
7568
  const graph = loaded === undefined || (method === 'run.start' && params.overrideAllNodes === true) ? loaded : this.relayBoundGraph(loaded, providers);
6456
- next.relay = { providers: await this.relayedProviders(providers), ...(graph === undefined ? {} : { graph }) };
7569
+ next.relay = { providers: await this.relayedProviders(providers, relayReasoning), ...(graph === undefined ? {} : { graph }) };
6457
7570
  return next;
6458
7571
  }
6459
7572
  /**
@@ -6473,7 +7586,7 @@ export class AppServer {
6473
7586
  * Each provider as a relay entry, with the effective window of each listed model resolved here within 5 s in all.
6474
7587
  * A provider's windows are reused for 5 minutes while its address and models stay the same.
6475
7588
  */
6476
- async relayedProviders(providers) {
7589
+ async relayedProviders(providers, relayReasoning) {
6477
7590
  const controller = new AbortController();
6478
7591
  const windows = new Map();
6479
7592
  const keyOf = (provider) => JSON.stringify([provider.id, provider.type, provider.baseUrl, relayedModelIds(provider), provider.modelContextWindows ?? null]);
@@ -6500,11 +7613,15 @@ export class AppServer {
6500
7613
  controller.abort();
6501
7614
  return providers.map(provider => {
6502
7615
  const models = provider.models === undefined ? undefined : relayedModelIds(provider).filter(model => provider.models.includes(model));
7616
+ const thinkingLevels = relayReasoning
7617
+ ? Object.fromEntries(Object.entries(provider.thinkingLevels ?? {}).filter(([model]) => model === provider.model || models?.includes(model)))
7618
+ : undefined;
6503
7619
  const known = Object.fromEntries(Object.entries(windows.get(provider.id) ?? {}).filter(([, window]) => Number.isSafeInteger(window) && window > 0));
6504
7620
  return {
6505
7621
  id: provider.id, model: provider.model,
6506
7622
  ...(models === undefined || models.length === 0 ? {} : { models }),
6507
7623
  ...(Object.keys(known).length === 0 ? {} : { modelContextWindows: known }),
7624
+ ...(thinkingLevels && Object.keys(thinkingLevels).length ? { thinkingLevels } : {}),
6508
7625
  ...(provider.reasoningEffort === undefined ? {} : { reasoningEffort: provider.reasoningEffort }),
6509
7626
  };
6510
7627
  });
@@ -6634,7 +7751,7 @@ export class AppServer {
6634
7751
  if (!link)
6635
7752
  return { error: { code: 'cancelled', message: 'The connection to that machine was closed.' } };
6636
7753
  if (link.reconnecting || this.closed)
6637
- return { error: { code: 'network', message: MACHINE_OFFLINE } };
7754
+ return { error: { code: 'network', message: this.offlineEnvironmentLine(env) } };
6638
7755
  try {
6639
7756
  const answer = await this.relayLink().request(env, { connectionId: link.connectionId, viewerWorkspaceId: env, engine, method, params, deadlineMs: MODEL_RELAY_CALL_MS }, Date.now() + MODEL_RELAY_CALL_MS + RELAY_TRANSPORT_SLACK_MS);
6640
7757
  return { ...answer, via: link.connectionId };
@@ -6677,6 +7794,30 @@ export class AppServer {
6677
7794
  throw new AppServerError('invalid-params', 'Host path required');
6678
7795
  return this.hostOperation(params, 'owner.projects.add', { path: params.path, ...(typeof params.name === 'string' ? { name: params.name } : {}) });
6679
7796
  }
7797
+ /** Asks a Cloud machine to clone a GitHub repository and register it; answered at once, and asked again while it clones. */
7798
+ async remoteOwnerGitHubClone(params) {
7799
+ const { owner, repo } = params;
7800
+ if (typeof owner !== 'string' || !GITHUB_ACCOUNT.test(owner) || typeof repo !== 'string' || !GITHUB_REPO.test(repo))
7801
+ throw new AppServerError('invalid-params', 'A GitHub owner and repository name are required.');
7802
+ let answer;
7803
+ try {
7804
+ answer = await this.hostOperation(params, 'owner.github.clone', { owner, repo });
7805
+ }
7806
+ catch (error) {
7807
+ // A machine running an engine from before this operation: Cloud installs the desktop's version when it starts.
7808
+ if (error instanceof Error && /Unknown host operation/.test(error.message))
7809
+ throw new AppServerError('remote', 'This Cloud engine cannot clone from GitHub. Update Andorra Code to a release that supports Cloud repository cloning, then restart Cloud.');
7810
+ throw error;
7811
+ }
7812
+ const found = (answer ?? {});
7813
+ if (found.state === 'cloning')
7814
+ return { state: 'cloning' };
7815
+ if (found.state === 'ready' && typeof found.rootId === 'string' && typeof found.name === 'string')
7816
+ return { state: 'ready', rootId: found.rootId, name: found.name };
7817
+ if (found.state === 'failed' && typeof found.message === 'string')
7818
+ return { state: 'failed', message: found.message.slice(0, 600) };
7819
+ throw new AppServerError('remote', 'The machine sent a malformed answer about the clone.');
7820
+ }
6680
7821
  async listProjects() {
6681
7822
  const config = await loadConfig(this.directory);
6682
7823
  return config.projects ?? [];
@@ -6685,6 +7826,16 @@ export class AppServer {
6685
7826
  const path = typeof params.path === 'string' ? params.path.trim() : '';
6686
7827
  if (!path || path.includes('\0'))
6687
7828
  throw new AppServerError('invalid-params', 'projects.add requires a folder path.');
7829
+ if (params.create === true) {
7830
+ // A new project: the folder is made first, then registered like any other.
7831
+ if (!isAbsolute(path))
7832
+ throw new AppServerError('invalid-params', 'A new project folder needs an absolute path.');
7833
+ const existing = await stat(path).catch(() => undefined);
7834
+ if (existing !== undefined && !existing.isDirectory())
7835
+ throw new AppServerError('invalid-params', `${path} is a file, not a folder.`);
7836
+ if (existing === undefined)
7837
+ await mkdir(path, { recursive: true }).catch((error) => { throw new AppServerError('storage', `Couldn't create ${path}: ${message(error)}`); });
7838
+ }
6688
7839
  const realPath = await realpath(path).catch(() => undefined);
6689
7840
  if (!realPath || !(await stat(realPath).catch(() => undefined))?.isDirectory())
6690
7841
  throw new AppServerError('not-found', `No folder exists at ${path}.`);
@@ -6898,8 +8049,11 @@ export class AppServer {
6898
8049
  this.emitSessionSkills(sessionId, skills);
6899
8050
  return skills;
6900
8051
  }
8052
+ pullRequestForClient(pullRequest) {
8053
+ return pullRequest ? { ...pullRequest, autoArchive: false } : null;
8054
+ }
6901
8055
  emitPullRequest(sessionId, pullRequest) {
6902
- this.emit('session.pullRequest.updated', { sessionId, pullRequest: pullRequestForClients(pullRequest) });
8056
+ this.emit('session.pullRequest.updated', { sessionId, pullRequest: this.pullRequestForClient(pullRequest) });
6903
8057
  // An attach, a finish or a dismiss changes the watched set: the GitHub App subscriptions follow it.
6904
8058
  this.githubEvents.nudge();
6905
8059
  const waiter = this.reviewWaiters.get(sessionId);
@@ -6913,9 +8067,6 @@ export class AppServer {
6913
8067
  const ended = this.watchedLoopEnded(sessionId, pullRequest);
6914
8068
  if (ended)
6915
8069
  waiter(ended);
6916
- // A wait goes on while Auto-fix or a review loop is on: it answers off only when neither is.
6917
- else if (!pullRequest.autoFix && !chatReviewLoopActive(pullRequest))
6918
- waiter({ kind: 'off', pullRequest });
6919
8070
  }
6920
8071
  }
6921
8072
  /**
@@ -6972,12 +8123,14 @@ export class AppServer {
6972
8123
  return await new Promise(resolve => {
6973
8124
  let settled = false;
6974
8125
  let signalTimer;
8126
+ const classify = new AbortController();
6975
8127
  // The run that waits: the review loop's round counts it as held while it waits (`review.waiting`).
6976
8128
  const wait = { ...(this.run?.sessionId === sessionId ? { runId: this.run.runId } : {}), since: new Date().toISOString() };
6977
8129
  const finish = (ended) => {
6978
8130
  if (settled)
6979
8131
  return false;
6980
8132
  settled = true;
8133
+ classify.abort();
6981
8134
  clearTimeout(timeout);
6982
8135
  clearTimeout(signalTimer);
6983
8136
  clearInterval(ticks);
@@ -6999,7 +8152,7 @@ export class AppServer {
6999
8152
  // then as often as each read asks (sooner while a quiet head waits out the delay before a bump).
7000
8153
  const watch = {};
7001
8154
  const fromSignals = () => {
7002
- void this.reviewWaitFromSignals(sessionId, finish, watch, () => settled, options.approveBump)
8155
+ void this.reviewWaitFromSignals(sessionId, finish, watch, classify.signal, options)
7003
8156
  .catch(error => { this.log('warn', `Could not read Codex's review signals for session ${sessionId}: ${message(error)}`); return this.reviewSignalMs; })
7004
8157
  .then(delay => {
7005
8158
  if (settled)
@@ -7030,40 +8183,102 @@ export class AppServer {
7030
8183
  fromSignals();
7031
8184
  });
7032
8185
  }
7033
- /**
7034
- * One read of Codex's signals on a waiting session's PR; answers how long until the next read.
7035
- *
7036
- * A sign-off on the head commit ends the wait as approved, unless a review comment is still to be handed
7037
- * over: comments come first. Where Codex shows nothing at all for the head (no eyes, no review, no comment,
7038
- * nobody asked yet), the next read comes after the bump delay, and if that one is as quiet the wait posts
7039
- * "@codex review", once per head and only in a repository Codex is known to review.
7040
- */
7041
- async reviewWaitFromSignals(sessionId, deliver, watch, settled, approveBump) {
8186
+ /** Polls GitHub only while the agent has an explicit wait. The record stores activity already reported. */
8187
+ async reviewWaitFromSignals(sessionId, deliver, watch, signal, options) {
7042
8188
  const every = this.reviewSignalMs;
7043
8189
  const current = await readPullRequest(this.directory, sessionId);
7044
- // The record's own states (gone, finished, Auto-fix off) end the wait through the record.
7045
- if (!current || isFinishedPullRequest(current.state) || !current.autoFix)
8190
+ if (!current || isFinishedPullRequest(current.state) || signal.aborted)
7046
8191
  return every;
7047
8192
  const gh = ghFor(this.gh, current);
7048
- const seen = await readReviewSignals(gh, current);
7049
- if (settled())
8193
+ const [found, seen] = await Promise.all([
8194
+ newReviewComments(gh, current, { includeDetails: true }).catch(error => {
8195
+ this.log('warn', 'Could not read review comments for ' + current.url + ': ' + message(error));
8196
+ return undefined;
8197
+ }),
8198
+ readReviewSignals(gh, current).catch(error => {
8199
+ this.log('warn', 'Could not read reactions and review signals for ' + current.url + ': ' + message(error));
8200
+ return undefined;
8201
+ }),
8202
+ ]);
8203
+ if (signal.aborted)
7050
8204
  return every;
7051
- const head = seen.headSha;
7052
- if (seen.approved) {
7053
- delete watch.quiet;
7054
- if (current.pendingFix !== undefined)
7055
- return every;
7056
- // An Andorra review loop in progress decides when this task's review is done: Codex's sign-off does not end the wait.
7057
- if (chatReviewLoopActive(current))
7058
- return every;
7059
- const found = await newReviewComments(gh, current);
7060
- if (found.threads > 0 || found.comments > 0) {
7061
- void this.pullRequestWatcher.readNow(sessionId);
7062
- return every;
7063
- }
7064
- deliver({ kind: 'approved', pullRequest: current, ...(head === undefined ? {} : { headSha: head }) });
8205
+ if (seen?.state === 'closed' || seen?.state === 'merged') {
8206
+ await this.recordPullRequestChange(sessionId, current.url, { state: seen.state, mergeWhenReady: false });
7065
8207
  return every;
7066
8208
  }
8209
+ const candidates = found?.candidates ?? [];
8210
+ // Bound Jev traffic when a batch contains many inline comments. The remaining comments are reported unclassified.
8211
+ const labels = await Promise.all(candidates.slice(0, 4).map(async (comment) => {
8212
+ if (!comment.body.trim())
8213
+ return undefined;
8214
+ return options.classifyComment?.(comment.body, signal).catch(() => undefined);
8215
+ }));
8216
+ if (signal.aborted)
8217
+ return every;
8218
+ const ended = await withPullRequest(this.directory, sessionId, async () => {
8219
+ const live = await readPullRequest(this.directory, sessionId);
8220
+ if (!live || live.url !== current.url || isFinishedPullRequest(live.state) || signal.aborted)
8221
+ return true;
8222
+ const reportedAt = Date.parse(live.handledThrough ?? '');
8223
+ const reportedIds = new Set(live.handledCommentIds);
8224
+ const comments = [];
8225
+ for (const [index, comment] of candidates.entries()) {
8226
+ const at = Date.parse(comment.createdAt);
8227
+ if (at < reportedAt || (at === reportedAt && (live.handledCommentIds === undefined || reportedIds.has(comment.id))))
8228
+ continue;
8229
+ const kind = labels[index] ?? 'unclassified';
8230
+ if (kind !== 'noise')
8231
+ comments.push({
8232
+ kind, author: comment.author, source: comment.source,
8233
+ ...(comment.url === undefined ? {} : { url: comment.url }),
8234
+ ...(comment.threadId === undefined ? {} : { threadId: comment.threadId }),
8235
+ });
8236
+ }
8237
+ const reactions = [];
8238
+ if (seen?.reactions !== undefined) {
8239
+ const before = new Set(live.reviewReactions?.map(reaction => reaction.id));
8240
+ const after = new Set(seen.reactions.map(reaction => reaction.id));
8241
+ for (const reaction of seen.reactions) {
8242
+ if (!before.has(reaction.id) && (live.reviewReactions !== undefined || Date.parse(reaction.createdAt) > Date.parse(live.attachedAt)))
8243
+ reactions.push({ ...reaction, kind: 'added' });
8244
+ }
8245
+ for (const reaction of live.reviewReactions ?? []) {
8246
+ if (!after.has(reaction.id))
8247
+ reactions.push({ ...reaction, kind: 'removed' });
8248
+ }
8249
+ }
8250
+ const head = seen?.headSha;
8251
+ const approved = found !== undefined && seen?.approved === true && head !== undefined && live.approvalHandled !== head && !chatReviewLoopActive(live);
8252
+ const activity = comments.length > 0
8253
+ ? { kind: 'activity', pullRequest: live, comments, reactions }
8254
+ : approved
8255
+ ? { kind: 'approved', pullRequest: live, headSha: head, reactions }
8256
+ : reactions.length > 0 ? { kind: 'activity', pullRequest: live, comments, reactions } : undefined;
8257
+ if (activity && !deliver(activity))
8258
+ return true;
8259
+ const next = { ...live };
8260
+ if (found?.newest !== undefined && (!Number.isFinite(reportedAt) || Date.parse(found.newest) >= reportedAt)) {
8261
+ if (Date.parse(found.newest) !== reportedAt)
8262
+ reportedIds.clear();
8263
+ for (const id of found.newestIds ?? [])
8264
+ reportedIds.add(id);
8265
+ next.handledThrough = found.newest;
8266
+ next.handledCommentIds = [...reportedIds];
8267
+ }
8268
+ if (seen?.reactions !== undefined && (live.reviewReactions === undefined || reactions.length > 0))
8269
+ next.reviewReactions = seen.reactions;
8270
+ if (activity?.kind === 'approved')
8271
+ next.approvalHandled = head;
8272
+ if (next.handledThrough !== live.handledThrough || next.handledCommentIds?.length !== live.handledCommentIds?.length
8273
+ || next.reviewReactions !== live.reviewReactions || next.approvalHandled !== live.approvalHandled) {
8274
+ await writePullRequest(this.directory, sessionId, { ...next, updatedAt: new Date().toISOString() });
8275
+ }
8276
+ return activity !== undefined;
8277
+ });
8278
+ if (ended || signal.aborted || !seen || seen.approved)
8279
+ return every;
8280
+ const head = seen.headSha;
8281
+ const { approveBump } = options;
7067
8282
  if (!approveBump || head === undefined || !seen.open || seen.reviewing || seen.reviewed || seen.asked || current.reviewBumped === head || watch.skipped === head) {
7068
8283
  delete watch.quiet;
7069
8284
  return every;
@@ -7088,12 +8303,12 @@ export class AppServer {
7088
8303
  watch.skipped = head;
7089
8304
  return every;
7090
8305
  }
7091
- if (settled())
8306
+ if (signal.aborted)
7092
8307
  return every;
7093
8308
  // Recorded before it is posted: a head is asked for once, even when the post's outcome is unknown.
7094
8309
  const claimed = await withPullRequest(this.directory, sessionId, async () => {
7095
8310
  const latest = await readPullRequest(this.directory, sessionId);
7096
- if (!latest || latest.url !== current.url || isFinishedPullRequest(latest.state) || !latest.autoFix || latest.reviewBumped === head)
8311
+ if (signal.aborted || !latest || latest.url !== current.url || isFinishedPullRequest(latest.state) || latest.reviewBumped === head)
7097
8312
  return false;
7098
8313
  await writePullRequest(this.directory, sessionId, { ...latest, reviewBumped: head, updatedAt: new Date().toISOString() });
7099
8314
  return true;
@@ -7111,8 +8326,7 @@ export class AppServer {
7111
8326
  }
7112
8327
  /**
7113
8328
  * One look at the record for a wait, in whichever engine process it runs: how the PR or the review loop ended, the
7114
- * review loop's next round (taken from the record, so a round another process posted reaches this wait), Auto-fix's
7115
- * comments, and the marker that tells the lease holder this run waits.
8329
+ * review loop's next round (including one posted by another engine), and the marker that this run is waiting.
7116
8330
  */
7117
8331
  async reviewWaitFromRecord(sessionId, deliver) {
7118
8332
  const wait = this.reviewWaitRuns.get(sessionId);
@@ -7133,10 +8347,6 @@ export class AppServer {
7133
8347
  return undefined;
7134
8348
  }
7135
8349
  const looping = chatReviewLoopActive(current);
7136
- if (!current.autoFix && !looping) {
7137
- deliver({ kind: 'off', pullRequest: current });
7138
- return undefined;
7139
- }
7140
8350
  const at = new Date().toISOString();
7141
8351
  let next = current;
7142
8352
  if (looping && wait?.runId !== undefined) {
@@ -7155,14 +8365,6 @@ export class AppServer {
7155
8365
  marked = true;
7156
8366
  }
7157
8367
  }
7158
- const pending = current.pendingFix;
7159
- const prompt = !current.autoFix || pending === undefined || this.timers.isHeld(pending.wakeId) ? undefined : pending.prompt ?? this.timers.get(pending.wakeId)?.prompt;
7160
- if (pending !== undefined && prompt !== undefined && deliver({ kind: 'comments', prompt })) {
7161
- if (this.autoFixWakes.has(pending.wakeId))
7162
- this.cancelAutoFixWake(sessionId, pending.wakeId);
7163
- next = { ...handedOver(next, pending), updatedAt: at };
7164
- marked = false;
7165
- }
7166
8368
  if (next === current)
7167
8369
  return undefined;
7168
8370
  await writePullRequest(this.directory, sessionId, next);
@@ -7173,16 +8375,6 @@ export class AppServer {
7173
8375
  if (marked)
7174
8376
  this.reviewLoop.waitStarted(sessionId);
7175
8377
  }
7176
- async recordAutoFixDelivered(sessionId, wakeId) {
7177
- try {
7178
- const pullRequest = await markAutoFixDelivered(this.directory, sessionId, wakeId);
7179
- if (pullRequest)
7180
- this.emitPullRequest(sessionId, pullRequest);
7181
- }
7182
- catch (error) {
7183
- this.log('warn', `Could not record the Auto-fix delivery for session ${sessionId}: ${message(error)}`);
7184
- }
7185
- }
7186
8378
  emitSessionChanges(changes) {
7187
8379
  this.emit('session.changes.updated', { sessionId: changes.sessionId, revision: changes.revision, changes: changes.changes });
7188
8380
  }
@@ -7200,10 +8392,10 @@ export class AppServer {
7200
8392
  let reviewed;
7201
8393
  const attached = await withPullRequest(this.directory, sessionId, async () => {
7202
8394
  const current = await readPullRequest(this.directory, sessionId);
7203
- // Another PR replaces this task's: a loop running on the old one goes with it.
8395
+ // Another PR replaces this task's: a loop running on the old one goes with it, and the old one is remembered.
7204
8396
  if (current && current.url !== ref.url && reviewLoopActive(current))
7205
8397
  replaced = current.review;
7206
- let next = current?.url === ref.url ? current : newPullRequest(ref);
8398
+ let next = withSupersededPullRequest(current?.url === ref.url ? current : newPullRequest(ref), current);
7207
8399
  if (next !== current) {
7208
8400
  const read = await readPullRequestAsAnyAccount(this.gh, ref.url);
7209
8401
  if (read.seen)
@@ -7215,8 +8407,8 @@ export class AppServer {
7215
8407
  }
7216
8408
  if (carry !== undefined)
7217
8409
  next = { ...next, carry: structuredClone(carry) };
7218
- // The node that switched Auto-fix or Andorra review on is where their wakes go.
7219
- if (origin !== undefined && (settings.autoFix === true || settings.review === true || next.origin === undefined))
8410
+ // Andorra review wakes the node that switched it on.
8411
+ if (origin !== undefined && (settings.review === true || next.origin === undefined))
7220
8412
  next = { ...next, origin: { runId: origin.runId, nodeId: origin.nodeId } };
7221
8413
  // A refused switch-on changes nothing: its checks, and the settings' own, run before any gh write.
7222
8414
  if (Object.keys(reviewSettings).length) {
@@ -7283,7 +8475,7 @@ export class AppServer {
7283
8475
  coverage: pullRequest => this.reviewCoverage(sessionId, pullRequest),
7284
8476
  readNow: () => this.pullRequestWatcher.readNow(sessionId),
7285
8477
  head: async () => { await this.pullRequestWatcher.readNow(sessionId).catch(() => { }); return this.pullRequestWatcher.headSha(sessionId); },
7286
- writes: () => this.autoFixWrites(sessionId),
8478
+ writes: () => this.reviewCommentWrites(sessionId),
7287
8479
  steers,
7288
8480
  });
7289
8481
  }
@@ -7388,13 +8580,9 @@ export class AppServer {
7388
8580
  }
7389
8581
  if (carry !== undefined)
7390
8582
  next = { ...next, carry: structuredClone(carry) };
7391
- // The node that switched Auto-fix or Andorra review on is where their wakes go.
7392
- if (origin !== undefined && (settings.autoFix === true || settings.review === true))
8583
+ // Andorra review wakes the node that switched it on.
8584
+ if (origin !== undefined && (settings.review === true))
7393
8585
  next = { ...next, origin: { runId: origin.runId, nodeId: origin.nodeId } };
7394
- if (!next.autoFix && next.pendingFix) {
7395
- this.cancelAutoFixWake(sessionId, next.pendingFix.wakeId);
7396
- next = withoutPendingFix(next);
7397
- }
7398
8586
  await writePullRequest(this.directory, sessionId, next);
7399
8587
  return next;
7400
8588
  });
@@ -7414,8 +8602,6 @@ export class AppServer {
7414
8602
  if (current.url !== agentChecked)
7415
8603
  throw new Error(`This task's pull request changed to ${current.url} while the dismiss was being checked. Nothing was changed.`);
7416
8604
  }
7417
- if (current?.pendingFix)
7418
- this.cancelAutoFixWake(sessionId, current.pendingFix.wakeId);
7419
8605
  await removePullRequest(this.directory, sessionId);
7420
8606
  return current;
7421
8607
  });
@@ -7521,7 +8707,7 @@ export class AppServer {
7521
8707
  pullRequests,
7522
8708
  };
7523
8709
  }
7524
- /** Settings → GitHub → "Agent replies on pull requests": `bot` (as the App's bot) or `me` (through gh as the person). Per engine. */
8710
+ /** Settings → GitHub → Agent replies on pull requests. */
7525
8711
  async githubSetAgentWrites(params) {
7526
8712
  const value = params.value;
7527
8713
  if (typeof value !== 'string' || !GITHUB_AGENT_WRITES.includes(value))
@@ -7533,7 +8719,7 @@ export class AppServer {
7533
8719
  return { agentWrites };
7534
8720
  }
7535
8721
  /**
7536
- * Who an agent write on this session's PR goes to first, decided one way for the tool and the Auto-fix prompt:
8722
+ * Who an agent write on this session's PR goes to first, decided one way for the tool and review findings:
7537
8723
  * the setting, and the PR's coverage as the event source (or, in another process, the lease holder) last
7538
8724
  * learned it. Events switched off here, or a PR the source has not looked at yet, are not covered.
7539
8725
  */
@@ -7590,8 +8776,8 @@ export class AppServer {
7590
8776
  }
7591
8777
  return this.githubBot;
7592
8778
  }
7593
- /** For the Auto-fix prompt: whether this session's replies post as the bot (the tool's own rule), and the bot's name. */
7594
- async autoFixWrites(sessionId) {
8779
+ /** For review findings: whether this session's replies post as the bot (the tool's own rule), and the bot's name. */
8780
+ async reviewCommentWrites(sessionId) {
7595
8781
  const pullRequest = await readPullRequest(this.directory, sessionId);
7596
8782
  // The gh form names the bot only for its sentence on mentions: the name already known, never a read for it.
7597
8783
  const known = this.githubBot === undefined ? {} : { bot: this.githubBot };
@@ -7646,6 +8832,20 @@ export class AppServer {
7646
8832
  throw new AppServerError('forbidden', 'The GitHub App is turned off on the Andorra service for now.');
7647
8833
  return { url: answer.url };
7648
8834
  }
8835
+ /** The repositories the GitHub App can reach for this account's linked GitHub user: what a Cloud machine may clone. */
8836
+ async githubRepositories() {
8837
+ if (!await this.githubSignedIn().catch(() => false))
8838
+ throw this.githubError(new GitHubAppError('signed-out', 'Sign in to Andorra first.'));
8839
+ try {
8840
+ return await this.githubClient.repositories();
8841
+ }
8842
+ catch (error) {
8843
+ // An account API from before this route reads as the App being off here, not as an error.
8844
+ if (error instanceof GitHubAppError && error.code === 'not-found')
8845
+ return { enabled: false, connected: false, repositories: [], more: false };
8846
+ throw this.githubError(error);
8847
+ }
8848
+ }
7649
8849
  async githubDisconnect() {
7650
8850
  if (!await this.githubSignedIn().catch(() => false))
7651
8851
  throw this.githubError(new GitHubAppError('signed-out', 'Sign in to Andorra first.'));
@@ -7831,9 +9031,7 @@ export class AppServer {
7831
9031
  const current = await readPullRequest(this.directory, sessionId);
7832
9032
  if (current?.url !== url)
7833
9033
  return undefined;
7834
- const next = settleFinishedPullRequest({ ...current, ...change, updatedAt: new Date().toISOString() });
7835
- if (next.pendingFix === undefined && current.pendingFix !== undefined)
7836
- this.cancelAutoFixWake(sessionId, current.pendingFix.wakeId);
9034
+ const next = { ...current, ...change, updatedAt: new Date().toISOString() };
7837
9035
  await writePullRequest(this.directory, sessionId, next);
7838
9036
  return next;
7839
9037
  }).catch(error => { this.log('warn', `Could not record the change to ${url}: ${message(error)}`); return undefined; });
@@ -7849,10 +9047,10 @@ export class AppServer {
7849
9047
  return { ok: false, error: answer.error };
7850
9048
  const read = await this.pullRequestReader.readMerge(sessionId, pullRequest, { force: true });
7851
9049
  const stored = await readPullRequest(this.directory, sessionId);
7852
- return { ok: true, ...answer.value, ...read, ...(stored?.url === pullRequest.url ? { pullRequest: pullRequestForClients(stored) } : {}) };
9050
+ return { ok: true, ...answer.value, ...read, ...(stored?.url === pullRequest.url ? { pullRequest: this.pullRequestForClient(stored) } : {}) };
7853
9051
  }
7854
9052
  /**
7855
- * Merges the task's PR now, or sets it to merge when ready (GitHub's auto-merge), with the method and
9053
+ * Merges the task's PR or adds it to the merge queue. A direct merge uses the method and
7856
9054
  * commit message the person chose, at the head commit they read. Deleting the head branch afterwards
7857
9055
  * is said separately: the merge has happened even when that fails.
7858
9056
  */
@@ -7860,8 +9058,8 @@ export class AppServer {
7860
9058
  const sessionId = identifier(params.id, 'id');
7861
9059
  const input = writeParams(() => {
7862
9060
  const when = params.when ?? 'now';
7863
- if (when !== 'now' && when !== 'ready' && when !== 'queue')
7864
- throw new Error('when must be now, ready or queue');
9061
+ if (when !== 'now' && when !== 'queue')
9062
+ throw new Error('when must be now or queue');
7865
9063
  if (params.deleteBranch !== undefined && typeof params.deleteBranch !== 'boolean')
7866
9064
  throw new Error('deleteBranch must be true or false');
7867
9065
  if (params.bypass !== undefined && typeof params.bypass !== 'boolean')
@@ -7909,12 +9107,6 @@ export class AppServer {
7909
9107
  throw new PullRequestRefusal(`GitHub holds this pull request back (${state.mergeState}). Read what holds it in the panel.`);
7910
9108
  }
7911
9109
  const commit = { method: input.method, headSha: input.headSha, ...(input.title === undefined ? {} : { title: input.title }), ...(input.body === undefined ? {} : { body: input.body }) };
7912
- if (input.when === 'ready') {
7913
- if (!state.autoMergeAllowed)
7914
- throw new PullRequestRefusal('This repository does not allow auto-merge, so the pull request cannot merge itself when ready.');
7915
- await enableAutoMerge(gh, state.pullRequestId, commit);
7916
- return { autoMerge: true };
7917
- }
7918
9110
  const merged = await mergePullRequest(gh, state.pullRequestId, commit);
7919
9111
  if (!input.deleteBranch || state.deletesBranch)
7920
9112
  return { merged: true, ...merged };
@@ -7928,8 +9120,8 @@ export class AppServer {
7928
9120
  return { merged: true, ...merged, branchError: classifyWriteError(error).message };
7929
9121
  }
7930
9122
  });
7931
- if (answer.ok && answer.value.queued !== true)
7932
- await this.recordPullRequestChange(sessionId, pullRequest.url, answer.value.merged === true ? { state: 'merged', mergeWhenReady: false } : { mergeWhenReady: true });
9123
+ if (answer.ok && answer.value.merged === true)
9124
+ await this.recordPullRequestChange(sessionId, pullRequest.url, { state: 'merged', mergeWhenReady: false });
7933
9125
  return this.afterMergeWrite(sessionId, pullRequest, answer);
7934
9126
  }
7935
9127
  /** Brings the PR's branch up to date with its base on GitHub (GitHub's "Update branch"), by a merge commit or a rebase. */
@@ -7987,9 +9179,10 @@ export class AppServer {
7987
9179
  const record = await this.readSession(sessionId);
7988
9180
  if (await readPullRequest(this.directory, sessionId))
7989
9181
  return { draft: null, blocked: { kind: 'has-pull-request', message: 'This task already has a pull request.' } };
9182
+ const gitRoot = sessionGitRoot(record);
7990
9183
  try {
7991
9184
  const prompt = record.history[0]?.task;
7992
- return { draft: await readCreateDraft(this.gh, this.git(record.workspace), record.workspace, { taskName: record.name, ...(base === undefined ? {} : { base }), closesIssue: (owner, repo) => issueNamedIn(prompt, owner, repo) }) };
9185
+ return { draft: await readCreateDraft(this.gh, this.git(gitRoot), gitRoot, { taskName: record.name, ...(base === undefined ? {} : { base }), closesIssue: (owner, repo) => issueNamedIn(prompt, owner, repo) }) };
7993
9186
  }
7994
9187
  catch (error) {
7995
9188
  if (error instanceof PullRequestCreateBlocked)
@@ -8021,9 +9214,10 @@ export class AppServer {
8021
9214
  const record = await this.readSession(sessionId);
8022
9215
  if (await readPullRequest(this.directory, sessionId))
8023
9216
  return { ok: false, error: { kind: 'refused', message: 'This task already has a pull request.' } };
9217
+ const gitRoot = sessionGitRoot(record);
8024
9218
  let opened;
8025
9219
  try {
8026
- opened = await runAsAccount(this.gh, input.as, gh => createFromFolder(gh, this.git(record.workspace), input));
9220
+ opened = await runAsAccount(this.gh, input.as, gh => createFromFolder(gh, this.git(gitRoot), input));
8027
9221
  }
8028
9222
  catch (error) {
8029
9223
  const failure = classifyWriteError(error);
@@ -8036,9 +9230,9 @@ export class AppServer {
8036
9230
  // A pull request the task picked up meanwhile (its agent opened one) is kept, not replaced.
8037
9231
  const meanwhile = await readPullRequest(this.directory, sessionId);
8038
9232
  if (meanwhile !== undefined && meanwhile.url !== ref.url)
8039
- return { ok: true, url: opened.url, pushed: opened.pushed, pullRequest: pullRequestForClients(meanwhile) };
9233
+ return { ok: true, url: opened.url, pushed: opened.pushed, pullRequest: this.pullRequestForClient(meanwhile) };
8040
9234
  const attached = await this.attachPullRequest(sessionId, ref);
8041
- return { ok: true, url: opened.url, pushed: opened.pushed, ...(opened.attached ? { attached: true } : {}), pullRequest: pullRequestForClients(attached) };
9235
+ return { ok: true, url: opened.url, pushed: opened.pushed, ...(opened.attached ? { attached: true } : {}), pullRequest: this.pullRequestForClient(attached) };
8042
9236
  }
8043
9237
  /** Where a comment the tab may change sits in the review read: a timeline comment, a review's text, or a comment in a thread. */
8044
9238
  static commentIn(state, commentId) {
@@ -8172,7 +9366,7 @@ export class AppServer {
8172
9366
  throw error;
8173
9367
  }
8174
9368
  const folder = record === undefined || committed.commit === undefined ? undefined
8175
- : await this.catchUpFolder(record.workspace, { repository, branch: meta.headRefName, from: input.headSha, to: committed.commit }, () => accountToken(gh, input.as));
9369
+ : await this.catchUpFolder(sessionWorkRoot(record), { repository, branch: meta.headRefName, from: input.headSha, to: committed.commit }, () => accountToken(gh, input.as));
8176
9370
  return { ...committed, ...(folder === undefined ? {} : { folder }) };
8177
9371
  }, { details: true });
8178
9372
  return this.afterReviewWrite(sessionId, pullRequest, answer);
@@ -8344,7 +9538,7 @@ export class AppServer {
8344
9538
  await this.recordPullRequestChange(sessionId, pullRequest.url, { state: input.open ? (pullRequest.state === 'draft' ? 'draft' : 'open') : 'closed' });
8345
9539
  const after = await this.afterReviewWrite(sessionId, pullRequest, answer);
8346
9540
  const stored = await readPullRequest(this.directory, sessionId);
8347
- return stored?.url === pullRequest.url ? { ...after, pullRequest: pullRequestForClients(stored) } : after;
9541
+ return stored?.url === pullRequest.url ? { ...after, pullRequest: this.pullRequestForClient(stored) } : after;
8348
9542
  }
8349
9543
  /** Takes the PR out of its base's merge queue. */
8350
9544
  async dequeueSessionPullRequest(params) {
@@ -8372,7 +9566,7 @@ export class AppServer {
8372
9566
  const current = await readPullRequest(this.directory, sessionId);
8373
9567
  if (current !== undefined && current.url !== ref.url)
8374
9568
  return { ok: false, error: { kind: 'refused', message: 'This task already has a pull request.' } };
8375
- return { ok: true, pullRequest: pullRequestForClients(await this.attachPullRequest(sessionId, ref)) };
9569
+ return { ok: true, pullRequest: this.pullRequestForClient(await this.attachPullRequest(sessionId, ref)) };
8376
9570
  }
8377
9571
  reviewRequestsRead = { failures: 0 };
8378
9572
  /**
@@ -8453,16 +9647,9 @@ export class AppServer {
8453
9647
  if (written)
8454
9648
  this.emitPullRequest(sessionId, written);
8455
9649
  }
8456
- cancelAutoFixWake(sessionId, wakeId) {
8457
- this.autoFixWakes.delete(wakeId);
8458
- if (!this.timers.cancel(wakeId))
8459
- return;
8460
- void clearWakeClaim(this.directory, sessionId, wakeId).catch(() => { });
8461
- this.emitTimers(sessionId);
8462
- }
8463
- pullRequestControl(sessionId, carry) {
9650
+ pullRequestControl(sessionId, carry, classifyComment) {
8464
9651
  return {
8465
- status: () => readPullRequest(this.directory, sessionId),
9652
+ status: async () => this.pullRequestForClient(await readPullRequest(this.directory, sessionId)) ?? undefined,
8466
9653
  attach: (url, settings, origin) => {
8467
9654
  const ref = parsePullRequestUrl(url);
8468
9655
  if (!ref)
@@ -8470,14 +9657,21 @@ export class AppServer {
8470
9657
  return this.attachPullRequest(sessionId, ref, settings, carry, origin);
8471
9658
  },
8472
9659
  update: (settings, origin) => this.updatePullRequest(sessionId, settings, carry, origin),
8473
- awaitReview: (signal, timeoutMs, origin, options) => this.awaitReview(sessionId, signal, timeoutMs, origin, options),
9660
+ awaitReview: (signal, timeoutMs, origin, options) => {
9661
+ const invocationId = options?.invocationId ?? randomUUID();
9662
+ return this.awaitReview(sessionId, signal, timeoutMs, origin, {
9663
+ ...options, ...(classifyComment === undefined ? {} : {
9664
+ classifyComment: (body, classifySignal) => classifyComment(body, origin, invocationId, classifySignal),
9665
+ }),
9666
+ });
9667
+ },
8474
9668
  dismiss: () => this.dismissPullRequestForAgent(sessionId),
8475
9669
  write: (write, options) => this.agentPullRequestWrite(sessionId, write, options),
8476
9670
  };
8477
9671
  }
8478
9672
  /**
8479
9673
  * The Andorra review loop's fixer wake: straight into a run of the session waiting in await_review here (which then holds
8480
- * the round), or as the next turn, routed like Auto-fix's to the node that took the PR.
9674
+ * the round), or as the next turn at the node that took the PR.
8481
9675
  */
8482
9676
  wakeForReview(sessionId, prompt, pullRequest) {
8483
9677
  const waiter = this.reviewWaiters.get(sessionId);
@@ -8497,20 +9691,6 @@ export class AppServer {
8497
9691
  void clearWakeClaim(this.directory, sessionId, wakeId).catch(() => { });
8498
9692
  this.emitTimers(sessionId);
8499
9693
  }
8500
- wakeForPullRequest(sessionId, prompt, carry, origin) {
8501
- const waiter = this.reviewWaiters.get(sessionId);
8502
- if (waiter) {
8503
- const id = `review-${randomUUID()}`;
8504
- waiter({ kind: 'comments', prompt });
8505
- void this.recordAutoFixDelivered(sessionId, id);
8506
- return id;
8507
- }
8508
- const timer = this.timers.arm(1, prompt, sessionId, carry, origin);
8509
- this.autoFixWakes.add(timer.id);
8510
- this.emitTimers(sessionId);
8511
- this.armTimerCheck();
8512
- return timer.id;
8513
- }
8514
9694
  emitTimers(sessionId) {
8515
9695
  this.emit('timers.updated', { sessionId, timers: this.timersFor(sessionId) });
8516
9696
  }
@@ -8553,7 +9733,6 @@ export class AppServer {
8553
9733
  if (this.reviewWakes.delete(timer.id) && timer.owner !== undefined) {
8554
9734
  void this.reviewLoop.wakeSpent(timer.owner, timer.id, reason).catch(error => this.log('warn', `Could not end the Andorra review loop of session ${timer.owner}: ${message(error)}`));
8555
9735
  }
8556
- this.autoFixWakes.delete(timer.id);
8557
9736
  this.fixWakes.delete(timer.id);
8558
9737
  this.mentionWakes.delete(timer.id);
8559
9738
  this.log('info', `Self-wake ${timer.id} was not delivered: ${reason}`);
@@ -8565,7 +9744,7 @@ export class AppServer {
8565
9744
  this.emitTimers(sessionId);
8566
9745
  }
8567
9746
  nodeReminder(timer) {
8568
- return timer.origin !== undefined && !this.autoFixWakes.has(timer.id) && !this.reviewWakes.has(timer.id);
9747
+ return timer.origin !== undefined && !this.reviewWakes.has(timer.id);
8569
9748
  }
8570
9749
  spendAttemptWakes(sessionId, attempts, reason, spent = () => true) {
8571
9750
  for (const timer of this.timers.list(sessionId)) {
@@ -8607,7 +9786,7 @@ export class AppServer {
8607
9786
  break;
8608
9787
  let value;
8609
9788
  try {
8610
- value = JSON.parse(await readFile(runRecordPath(this.directory, cursor, 'json'), 'utf8'));
9789
+ value = await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, cursor, 'json'), { signals: this.telemetry.signals });
8611
9790
  }
8612
9791
  catch {
8613
9792
  break;
@@ -8618,7 +9797,7 @@ export class AppServer {
8618
9797
  }
8619
9798
  if (!chain.includes(origin.runId))
8620
9799
  return { spent: 'a newer turn in this session replaced the attempt that set it' };
8621
- newestRecord ??= JSON.parse(await readFile(runRecordPath(this.directory, newest, 'json'), 'utf8'));
9800
+ newestRecord ??= await readTelemetryRunRecord(this.directory, runRecordPath(this.directory, newest, 'json'), { signals: this.telemetry.signals });
8622
9801
  const status = typeof newestRecord.status === 'string' ? newestRecord.status : undefined;
8623
9802
  if (status === 'succeeded')
8624
9803
  return { spent: 'the attempt that set it has finished' };
@@ -8626,7 +9805,7 @@ export class AppServer {
8626
9805
  return { spent: 'the attempt that set it was stopped' };
8627
9806
  if (status === 'running' && typeof newestRecord.pid === 'number' && isPidAlive(newestRecord.pid))
8628
9807
  return { wait: 'its attempt is still running in another engine' };
8629
- const armedAt = this.autoFixWakes.has(timer.id) || this.reviewWakes.has(timer.id) ? Number.NEGATIVE_INFINITY : timer.fireAt - timer.seconds * 1_000;
9808
+ const armedAt = this.reviewWakes.has(timer.id) ? Number.NEGATIVE_INFINITY : timer.fireAt - timer.seconds * 1_000;
8630
9809
  for (const attempt of chain) {
8631
9810
  const journal = await readFile(runRecordPath(this.directory, attempt, 'jsonl'), 'utf8').catch(() => '');
8632
9811
  for (const line of journal.split('\n')) {
@@ -8682,31 +9861,6 @@ export class AppServer {
8682
9861
  this.emitTimers(sessionId);
8683
9862
  continue;
8684
9863
  }
8685
- if (this.autoFixWakes.has(timer.id)) {
8686
- let confirmed;
8687
- try {
8688
- confirmed = await confirmAutoFixWake(this.directory, this.gh, sessionId, timer.id);
8689
- }
8690
- catch (error) {
8691
- if (this.timers.get(timer.id) !== undefined)
8692
- this.timers.restore(timer, AUTO_FIX_CONFIRM_RETRY_MS);
8693
- nextCheckIn = WAKE_RETRY_MS;
8694
- this.log('warn', `Auto-fix wake ${timer.id} waits: GitHub could not confirm the pull request is still open (${message(error)})`);
8695
- continue;
8696
- }
8697
- if (confirmed.pullRequest)
8698
- this.emitPullRequest(sessionId, confirmed.pullRequest);
8699
- if (!confirmed.deliver) {
8700
- this.autoFixWakes.delete(timer.id);
8701
- this.timers.settle(timer.id);
8702
- void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
8703
- this.emitTimers(sessionId);
8704
- this.log('info', confirmed.pullRequest
8705
- ? `Dropped Auto-fix wake ${timer.id}: ${confirmed.pullRequest.url} is ${confirmed.pullRequest.state}, so Auto-fix is off`
8706
- : `Dropped Auto-fix wake ${timer.id}: session ${sessionId} no longer asks for it`);
8707
- continue;
8708
- }
8709
- }
8710
9864
  const reviewWake = this.reviewWakes.has(timer.id);
8711
9865
  if (reviewWake) {
8712
9866
  let deliver;
@@ -8715,7 +9869,7 @@ export class AppServer {
8715
9869
  }
8716
9870
  catch (error) {
8717
9871
  if (this.timers.get(timer.id) !== undefined)
8718
- this.timers.restore(timer, AUTO_FIX_CONFIRM_RETRY_MS);
9872
+ this.timers.restore(timer, REVIEW_CONFIRM_RETRY_MS);
8719
9873
  nextCheckIn = WAKE_RETRY_MS;
8720
9874
  this.log('warn', `Andorra review wake ${timer.id} waits: GitHub could not confirm the pull request is still open (${message(error)})`);
8721
9875
  continue;
@@ -8729,10 +9883,7 @@ export class AppServer {
8729
9883
  continue;
8730
9884
  }
8731
9885
  }
8732
- const autoFix = this.autoFixWakes.has(timer.id);
8733
- // The review loop's wake is routed like Auto-fix's: to the node that took the PR, and kept when that node is done.
8734
- const routed = autoFix || reviewWake;
8735
- const wakeKind = autoFix ? 'auto-fix' : reviewWake ? 'andorra-review' : this.fixWakes.has(timer.id) ? 'fix-checks' : this.mentionWakes.has(timer.id) ? 'mention' : 'timer';
9886
+ const wakeKind = reviewWake ? 'andorra-review' : this.fixWakes.has(timer.id) ? 'fix-checks' : this.mentionWakes.has(timer.id) ? 'mention' : 'timer';
8736
9887
  let resume;
8737
9888
  let startNode;
8738
9889
  if (timer.origin !== undefined) {
@@ -8749,7 +9900,7 @@ export class AppServer {
8749
9900
  this.log('info', `Self-wake ${timer.id} waits: ${plan.wait}`);
8750
9901
  continue;
8751
9902
  }
8752
- if ('spent' in plan && !routed) {
9903
+ if ('spent' in plan && !reviewWake) {
8753
9904
  this.spendWake(timer, plan.spent);
8754
9905
  continue;
8755
9906
  }
@@ -8767,12 +9918,12 @@ export class AppServer {
8767
9918
  if (resume !== undefined) {
8768
9919
  try {
8769
9920
  started = await this.resumeRun({ runId: resume, direction: timer.prompt,
8770
- ...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake: routed ? wakeKind : 'timer', wakeNode: timer.origin.nodeId, freshAllowance: true });
9921
+ ...(carry?.panelBrowserRelay === true ? { panelBrowserRelay: true } : {}) }, { wake: reviewWake ? wakeKind : 'timer', wakeNode: timer.origin.nodeId, freshAllowance: true });
8771
9922
  }
8772
9923
  catch (error) {
8773
- if (!routed || !isFinalWakeRefusal(error))
9924
+ if (!reviewWake || !isFinalWakeRefusal(error))
8774
9925
  throw error;
8775
- this.log('info', `${reviewWake ? 'Andorra review' : 'Auto-fix'} wake ${timer.id} starts at node ${timer.origin.nodeId}: ${resume} could not be continued (${message(error)})`);
9926
+ this.log('info', `Andorra review wake ${timer.id} starts at node ${timer.origin.nodeId}: ${resume} could not be continued (${message(error)})`);
8776
9927
  resume = undefined;
8777
9928
  startNode = timer.origin.nodeId;
8778
9929
  }
@@ -8788,6 +9939,7 @@ export class AppServer {
8788
9939
  ...(carry?.model === undefined ? {} : { model: carry.model }),
8789
9940
  ...(carry?.reasoningEffort === undefined ? {} : { reasoningEffort: carry.reasoningEffort }),
8790
9941
  ...(carry?.overrideAllNodes === undefined ? {} : { overrideAllNodes: carry.overrideAllNodes }),
9942
+ ...(carry?.autoModel === true ? { autoModel: true } : {}),
8791
9943
  ...(carry?.panelBrowserRelay === undefined ? {} : { panelBrowserRelay: carry.panelBrowserRelay }),
8792
9944
  ...(carry?.input === undefined ? {} : { input: carry.input }),
8793
9945
  ...(carry?.state === undefined ? {} : { state: carry.state }) }, { sameSession: sessionId, wake: wakeKind, ...(startNode === undefined ? {} : { startNode }) });
@@ -8800,13 +9952,8 @@ export class AppServer {
8800
9952
  }
8801
9953
  this.timers.settle(timer.id);
8802
9954
  this.reviewWakes.delete(timer.id);
8803
- this.autoFixWakes.delete(timer.id);
8804
9955
  this.fixWakes.delete(timer.id);
8805
9956
  this.mentionWakes.delete(timer.id);
8806
- void markAutoFixDelivered(this.directory, sessionId, timer.id)
8807
- .then(pullRequest => { if (pullRequest)
8808
- this.emitPullRequest(sessionId, pullRequest); })
8809
- .catch(error => this.log('warn', `Could not record the Auto-fix delivery for session ${sessionId}: ${message(error)}`));
8810
9957
  void clearWakeClaim(this.directory, sessionId, timer.id).catch(() => { });
8811
9958
  }
8812
9959
  catch (error) {
@@ -8845,7 +9992,7 @@ export class AppServer {
8845
9992
  void (async () => {
8846
9993
  try {
8847
9994
  const settled = await reconcileInterruptedRuns(this.directory, new Set(dead.map(owner => owner.runId)), { includePending: true });
8848
- await reportInterruptedRuns({ home: this.directory, surface: configuredSurface('desktop') }, settled.interrupted);
9995
+ await reportInterruptedRuns({ home: this.directory, signals: this.telemetry.signals, surface: configuredSurface('desktop') }, settled.interrupted);
8849
9996
  }
8850
9997
  catch (recovery) {
8851
9998
  this.log('warn', `Could not reconcile runs from a stopped engine: ${message(recovery)}`);
@@ -8873,11 +10020,19 @@ export class AppServer {
8873
10020
  if (this.closed)
8874
10021
  return;
8875
10022
  this.closed = true;
10023
+ this.telemetry.close();
10024
+ for (const startup of this.antigravityStartups)
10025
+ startup.abort();
10026
+ const antigravitySessions = [...this.antigravitySessions.values()];
10027
+ this.antigravitySessions.clear();
10028
+ await Promise.allSettled(antigravitySessions.map(entry => {
10029
+ entry.clearPermissions();
10030
+ return entry.session.close();
10031
+ }));
8876
10032
  await this.codexAuth.close().catch(() => { });
8877
10033
  await this.anthropicAuth.close().catch(() => { });
8878
10034
  await this.claudeSignIn.close().catch(() => { });
8879
10035
  await this.grokSignIn.close().catch(() => { });
8880
- await this.googleSignIn.close().catch(() => { });
8881
10036
  await this.openCodeSignIn.close().catch(() => { });
8882
10037
  await sharedOpenCodeServer().close().catch(() => { });
8883
10038
  if (this.automationCheck)
@@ -8913,6 +10068,7 @@ export class AppServer {
8913
10068
  new Promise(resolve => { choresTimer = setTimeout(resolve, 5_000); choresTimer.unref?.(); }),
8914
10069
  ]);
8915
10070
  clearTimeout(choresTimer);
10071
+ this.cancelSessionTitles();
8916
10072
  for (const controller of this.operations)
8917
10073
  controller.abort();
8918
10074
  for (const settle of [...this.pending.values()])
@@ -8925,7 +10081,7 @@ export class AppServer {
8925
10081
  this.stopBackgroundWatch();
8926
10082
  await Promise.allSettled([disposePooledPowerShell(), disposeAllQaProcesses(), disposeAllQaPtys()]);
8927
10083
  await this.telemetrySettle;
8928
- await drainTelemetry({ home: this.directory, surface: configuredSurface('desktop') });
10084
+ await drainTelemetry({ home: this.directory, signals: this.telemetry.signals, surface: configuredSurface('desktop') });
8929
10085
  this.emitsStopped = true;
8930
10086
  this.stopGraphVisibilityWatch();
8931
10087
  this.terminals.shutdown();
@@ -8967,7 +10123,7 @@ export async function runAppServer(options = {}) {
8967
10123
  const error = options.error ?? process.stderr;
8968
10124
  try {
8969
10125
  const recovered = await reconcileInterruptedRuns(options.directory ?? configDirectory(), undefined, { includePending: true });
8970
- await reportInterruptedRuns({ home: options.directory ?? configDirectory(), surface: configuredSurface('desktop') }, recovered.interrupted);
10126
+ await reportInterruptedRuns({ home: options.directory ?? configDirectory(), signals: server.telemetry.signals, surface: configuredSurface('desktop') }, recovered.interrupted);
8971
10127
  if (recovered.runs.length || recovered.markers)
8972
10128
  error.write(`[app-server] marked ${recovered.runs.length} interrupted run(s) and ${recovered.markers} session marker(s) from a stopped engine\n`);
8973
10129
  server.watchForeignEngineShutdown(recovered.live);