@andorra-labs/code 0.1.12 → 0.1.14

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