@andorra-labs/code 0.1.12 → 0.1.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (592) hide show
  1. package/dist/src/account-presentation.d.ts +1 -37
  2. package/dist/src/account-presentation.js +2 -42
  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 +49 -416
  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 +9 -153
  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/anthropic-console-auth.d.ts +0 -24
  18. package/dist/src/anthropic-console-auth.js +0 -37
  19. package/dist/src/anthropic-credentials.d.ts +0 -25
  20. package/dist/src/anthropic-credentials.js +0 -28
  21. package/dist/src/app-server/protocol.d.ts +13 -245
  22. package/dist/src/app-server/protocol.js +1 -132
  23. package/dist/src/app-server/reasoning.d.ts +0 -31
  24. package/dist/src/app-server/reasoning.js +0 -54
  25. package/dist/src/app-server/terminal.d.ts +0 -36
  26. package/dist/src/app-server/terminal.js +3 -39
  27. package/dist/src/app-server/workspace.d.ts +0 -167
  28. package/dist/src/app-server/workspace.js +4 -406
  29. package/dist/src/app-server.d.ts +27 -927
  30. package/dist/src/app-server.js +537 -2992
  31. package/dist/src/artifacts.d.ts +0 -10
  32. package/dist/src/artifacts.js +1 -11
  33. package/dist/src/attachments.d.ts +4 -98
  34. package/dist/src/attachments.js +10 -130
  35. package/dist/src/auth/AuthManager.d.ts +0 -93
  36. package/dist/src/auth/AuthManager.js +3 -165
  37. package/dist/src/auth/callback-page.d.ts +0 -1
  38. package/dist/src/auth/callback-page.js +0 -4
  39. package/dist/src/auth/callback.d.ts +0 -25
  40. package/dist/src/auth/callback.js +1 -29
  41. package/dist/src/auth/deployment.d.ts +0 -16
  42. package/dist/src/auth/deployment.js +0 -16
  43. package/dist/src/auth/index.d.ts +0 -11
  44. package/dist/src/auth/index.js +0 -11
  45. package/dist/src/auth/lock.d.ts +0 -1
  46. package/dist/src/auth/lock.js +0 -1
  47. package/dist/src/auth/store.d.ts +7 -108
  48. package/dist/src/auth/store.js +21 -129
  49. package/dist/src/auth/types.d.ts +0 -8
  50. package/dist/src/auth-commands.d.ts +0 -5
  51. package/dist/src/auth-commands.js +0 -1
  52. package/dist/src/automation-runner.d.ts +0 -9
  53. package/dist/src/automation-runner.js +0 -11
  54. package/dist/src/automation-service.d.ts +0 -10
  55. package/dist/src/automation-service.js +3 -17
  56. package/dist/src/automation-tool.js +0 -5
  57. package/dist/src/automation-worker-shutdown.d.ts +0 -1
  58. package/dist/src/automation-worker-shutdown.js +0 -3
  59. package/dist/src/automations.d.ts +23 -2
  60. package/dist/src/automations.js +91 -12
  61. package/dist/src/background-tasks.d.ts +0 -23
  62. package/dist/src/background-tasks.js +0 -11
  63. package/dist/src/boot-trace.d.ts +0 -13
  64. package/dist/src/boot-trace.js +1 -14
  65. package/dist/src/browser-activity.js +0 -2
  66. package/dist/src/browser-bridge.d.ts +0 -2
  67. package/dist/src/browser-bridge.js +0 -27
  68. package/dist/src/browser-captcha-tool.d.ts +0 -13
  69. package/dist/src/browser-captcha-tool.js +3 -35
  70. package/dist/src/browser-extensions-tool.d.ts +24 -0
  71. package/dist/src/browser-extensions-tool.js +137 -0
  72. package/dist/src/browser-extensions.d.ts +127 -0
  73. package/dist/src/browser-extensions.js +729 -0
  74. package/dist/src/browser-observation.d.ts +0 -15
  75. package/dist/src/browser-observation.js +1 -22
  76. package/dist/src/browser-panel-tool.d.ts +1 -37
  77. package/dist/src/browser-panel-tool.js +3 -73
  78. package/dist/src/browser-runner.d.ts +0 -1
  79. package/dist/src/browser-runner.js +4 -45
  80. package/dist/src/browser-server.d.ts +0 -6
  81. package/dist/src/browser-server.js +6 -229
  82. package/dist/src/browser-session.d.ts +0 -25
  83. package/dist/src/browser-session.js +1 -71
  84. package/dist/src/browser-stealth.d.ts +0 -12
  85. package/dist/src/browser-stealth.js +0 -36
  86. package/dist/src/browser-ui/app.js +7 -174
  87. package/dist/src/browser-ui/style.css +0 -68
  88. package/dist/src/browser-ui/tokens.css +11 -93
  89. package/dist/src/browser-view.d.ts +47 -301
  90. package/dist/src/browser-view.js +333 -582
  91. package/dist/src/capabilities.d.ts +0 -8
  92. package/dist/src/capabilities.js +0 -29
  93. package/dist/src/capsolver.d.ts +0 -13
  94. package/dist/src/capsolver.js +0 -15
  95. package/dist/src/clarification-ui.d.ts +0 -7
  96. package/dist/src/clarification-ui.js +0 -8
  97. package/dist/src/claude-executable.d.ts +0 -1
  98. package/dist/src/claude-executable.js +1 -2
  99. package/dist/src/claude-provider.d.ts +6 -19
  100. package/dist/src/claude-provider.js +155 -63
  101. package/dist/src/cli-executable.d.ts +0 -16
  102. package/dist/src/cli-executable.js +0 -7
  103. package/dist/src/cli-process.d.ts +0 -26
  104. package/dist/src/cli-process.js +0 -18
  105. package/dist/src/cli-sign-in.d.ts +0 -20
  106. package/dist/src/cli-sign-in.js +1 -17
  107. package/dist/src/cli.d.ts +1 -55
  108. package/dist/src/cli.js +80 -721
  109. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +4 -59
  110. package/dist/src/code-intelligence/CodeIntelligenceManager.js +26 -99
  111. package/dist/src/code-intelligence/ContextLedger.d.ts +0 -4
  112. package/dist/src/code-intelligence/ContextLedger.js +0 -10
  113. package/dist/src/code-intelligence/ContextRouter.d.ts +0 -6
  114. package/dist/src/code-intelligence/ContextRouter.js +0 -8
  115. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.d.ts +0 -2
  116. package/dist/src/code-intelligence/codegraph/CodeGraphProjectSession.js +5 -12
  117. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.d.ts +0 -6
  118. package/dist/src/code-intelligence/codegraph/CodeGraphProvider.js +0 -6
  119. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.d.ts +0 -5
  120. package/dist/src/code-intelligence/codegraph/CodeGraphSyncBarrier.js +1 -17
  121. package/dist/src/code-intelligence/codegraph/repoExploreTool.d.ts +0 -5
  122. package/dist/src/code-intelligence/codegraph/repoExploreTool.js +0 -5
  123. package/dist/src/code-intelligence/repository.d.ts +0 -9
  124. package/dist/src/code-intelligence/repository.js +1 -11
  125. package/dist/src/code-intelligence/types.d.ts +0 -8
  126. package/dist/src/codex-auth.d.ts +0 -44
  127. package/dist/src/codex-auth.js +0 -45
  128. package/dist/src/codex-browser-auth.d.ts +0 -13
  129. package/dist/src/codex-browser-auth.js +3 -20
  130. package/dist/src/codex-errors.js +0 -2
  131. package/dist/src/codex-executable.d.ts +0 -2
  132. package/dist/src/codex-executable.js +1 -7
  133. package/dist/src/codex-provider.d.ts +0 -13
  134. package/dist/src/codex-provider.js +0 -28
  135. package/dist/src/codex-rpc.d.ts +0 -10
  136. package/dist/src/codex-rpc.js +0 -12
  137. package/dist/src/coding-tools.d.ts +4 -26
  138. package/dist/src/coding-tools.js +161 -181
  139. package/dist/src/command-metrics.d.ts +0 -4
  140. package/dist/src/command-output-tap.d.ts +0 -11
  141. package/dist/src/command-output-tap.js +0 -3
  142. package/dist/src/command-screens.d.ts +24 -0
  143. package/dist/src/command-screens.js +132 -100
  144. package/dist/src/commands.d.ts +6 -63
  145. package/dist/src/commands.js +20 -100
  146. package/dist/src/completion-gates.d.ts +0 -47
  147. package/dist/src/completion-gates.js +0 -14
  148. package/dist/src/completion.d.ts +0 -98
  149. package/dist/src/completion.js +2 -239
  150. package/dist/src/config.d.ts +11 -116
  151. package/dist/src/config.js +39 -171
  152. package/dist/src/context-budget.d.ts +0 -22
  153. package/dist/src/context-budget.js +0 -44
  154. package/dist/src/context-compaction.d.ts +29 -6
  155. package/dist/src/context-compaction.js +94 -25
  156. package/dist/src/context-selection.d.ts +0 -24
  157. package/dist/src/context-selection.js +0 -34
  158. package/dist/src/dashboard-view.d.ts +0 -2
  159. package/dist/src/dashboard-view.js +0 -35
  160. package/dist/src/dashboard.d.ts +0 -2
  161. package/dist/src/dashboard.js +0 -9
  162. package/dist/src/deadline.d.ts +0 -45
  163. package/dist/src/deadline.js +0 -54
  164. package/dist/src/decision/ContinuationAdapter.d.ts +0 -5
  165. package/dist/src/decision/ContinuationAdapter.js +0 -5
  166. package/dist/src/decision/DecisionEngine.d.ts +0 -4
  167. package/dist/src/decision/DecisionManager.d.ts +0 -1
  168. package/dist/src/decision/DecisionManager.js +2 -7
  169. package/dist/src/decision/DecisionPolicy.d.ts +0 -1
  170. package/dist/src/decision/DecisionPolicy.js +0 -1
  171. package/dist/src/decision/FactContinuations.d.ts +11 -43
  172. package/dist/src/decision/FactContinuations.js +126 -95
  173. package/dist/src/decision/FactServiceGate.d.ts +0 -1
  174. package/dist/src/decision/FactServiceGate.js +0 -4
  175. package/dist/src/decision/PreparedSteps.d.ts +0 -15
  176. package/dist/src/decision/PreparedSteps.js +0 -10
  177. package/dist/src/decision/applyToolMenu.d.ts +0 -1
  178. package/dist/src/decision/applyToolMenu.js +1 -5
  179. package/dist/src/decision/checks.d.ts +15 -28
  180. package/dist/src/decision/checks.js +118 -49
  181. package/dist/src/decision/facts.d.ts +0 -16
  182. package/dist/src/decision/facts.js +0 -30
  183. package/dist/src/decision/guidancePolicy.js +0 -1
  184. package/dist/src/decision/hostedPolicy.d.ts +0 -6
  185. package/dist/src/decision/hostedPolicy.js +0 -7
  186. package/dist/src/decision/hostedSkills.d.ts +0 -19
  187. package/dist/src/decision/hostedSkills.js +0 -19
  188. package/dist/src/decision/optimizationPolicy.d.ts +0 -3
  189. package/dist/src/decision/optimizationPolicy.js +1 -4
  190. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +0 -7
  191. package/dist/src/decision/providers/AndorraDecisionProvider.js +4 -27
  192. package/dist/src/decision/providers/HttpDecisionProvider.d.ts +0 -2
  193. package/dist/src/decision/providers/HttpDecisionProvider.js +0 -6
  194. package/dist/src/decision/routeTools.d.ts +0 -8
  195. package/dist/src/decision/routeTools.js +1 -8
  196. package/dist/src/decision/toolFamilies.d.ts +0 -1
  197. package/dist/src/decision/toolFamilies.js +0 -1
  198. package/dist/src/decision/toolMenu.d.ts +0 -3
  199. package/dist/src/decision/toolMenu.js +0 -4
  200. package/dist/src/decision/types.d.ts +0 -6
  201. package/dist/src/default-graph.d.ts +0 -9
  202. package/dist/src/default-graph.js +0 -9
  203. package/dist/src/delegation-changes.d.ts +0 -56
  204. package/dist/src/delegation-changes.js +4 -130
  205. package/dist/src/diff-preview.d.ts +0 -1
  206. package/dist/src/diff-preview.js +0 -17
  207. package/dist/src/duration.d.ts +0 -50
  208. package/dist/src/duration.js +0 -50
  209. package/dist/src/efficiency.d.ts +0 -39
  210. package/dist/src/efficiency.js +0 -16
  211. package/dist/src/engine/protocol.d.ts +0 -2
  212. package/dist/src/engine/protocol.js +0 -2
  213. package/dist/src/engine-streams.d.ts +0 -9
  214. package/dist/src/extensions.d.ts +3 -2
  215. package/dist/src/extensions.js +63 -35
  216. package/dist/src/favicons.d.ts +0 -26
  217. package/dist/src/favicons.js +0 -34
  218. package/dist/src/file-diff.d.ts +2 -58
  219. package/dist/src/file-diff.js +0 -32
  220. package/dist/src/file-read-key.d.ts +0 -7
  221. package/dist/src/file-read-key.js +0 -7
  222. package/dist/src/file-read-state.d.ts +0 -1
  223. package/dist/src/file-read-state.js +0 -4
  224. package/dist/src/firefox-cookies.d.ts +0 -34
  225. package/dist/src/firefox-cookies.js +1 -55
  226. package/dist/src/git-identity-audit.d.ts +27 -0
  227. package/dist/src/git-identity-audit.js +286 -0
  228. package/dist/src/git-identity-guard.d.ts +4 -0
  229. package/dist/src/git-identity-guard.js +998 -0
  230. package/dist/src/git-identity-hold.d.ts +12 -0
  231. package/dist/src/git-identity-hold.js +81 -0
  232. package/dist/src/git-summary.d.ts +0 -58
  233. package/dist/src/git-summary.js +2 -212
  234. package/dist/src/goal-completion-verification.d.ts +2 -2
  235. package/dist/src/goal-completion-verification.js +3 -6
  236. package/dist/src/graph-account.d.ts +0 -21
  237. package/dist/src/graph-account.js +0 -17
  238. package/dist/src/graph-editor-session.d.ts +0 -1
  239. package/dist/src/graph-editor-session.js +0 -3
  240. package/dist/src/graph-health.d.ts +0 -63
  241. package/dist/src/graph-health.js +0 -57
  242. package/dist/src/graph-manager-chat.d.ts +5 -155
  243. package/dist/src/graph-manager-chat.js +2 -177
  244. package/dist/src/graph-provider-portability.d.ts +1 -21
  245. package/dist/src/graph-provider-portability.js +6 -45
  246. package/dist/src/graph-quota.d.ts +0 -33
  247. package/dist/src/graph-quota.js +1 -44
  248. package/dist/src/graph-runner.d.ts +0 -1
  249. package/dist/src/graph-runner.js +31 -391
  250. package/dist/src/graph-selection.d.ts +0 -14
  251. package/dist/src/graph-selection.js +0 -14
  252. package/dist/src/graph-server.d.ts +2 -10
  253. package/dist/src/graph-server.js +39 -101
  254. package/dist/src/graph-studio-features.d.ts +0 -5
  255. package/dist/src/graph-studio-features.js +2 -42
  256. package/dist/src/graph-sync.d.ts +0 -78
  257. package/dist/src/graph-sync.js +5 -201
  258. package/dist/src/graph-tool.d.ts +0 -18
  259. package/dist/src/graph-tool.js +0 -27
  260. package/dist/src/graph-ui/app.js +152 -491
  261. package/dist/src/graph-ui/compat.js +0 -7
  262. package/dist/src/graph-ui/controls.css +0 -48
  263. package/dist/src/graph-ui/controls.js +0 -88
  264. package/dist/src/graph-ui/drafts.js +0 -12
  265. package/dist/src/graph-ui/edge-router.js +0 -62
  266. package/dist/src/graph-ui/embed.js +0 -59
  267. package/dist/src/graph-ui/icons.js +0 -8
  268. package/dist/src/graph-ui/library.css +0 -5
  269. package/dist/src/graph-ui/manager-markdown.js +0 -11
  270. package/dist/src/graph-ui/manager-state.js +1 -78
  271. package/dist/src/graph-ui/manager.css +0 -18
  272. package/dist/src/graph-ui/manager.js +3 -180
  273. package/dist/src/graph-ui/model-picker.js +0 -29
  274. package/dist/src/graph-ui/sidebar.js +2 -3
  275. package/dist/src/graph-ui/skill-picker.js +373 -39
  276. package/dist/src/graph-ui/studio-canvas.js +3 -38
  277. package/dist/src/graph-ui/studio.css +0 -18
  278. package/dist/src/graph-ui/studio.js +3 -71
  279. package/dist/src/graph-ui/style.css +11 -134
  280. package/dist/src/graph-ui/theme.js +1 -26
  281. package/dist/src/graph-ui/tokens.css +15 -114
  282. package/dist/src/graphs.d.ts +6 -157
  283. package/dist/src/graphs.js +65 -266
  284. package/dist/src/grep-regex-worker.js +0 -2
  285. package/dist/src/grep-regex.d.ts +1 -5
  286. package/dist/src/grep-regex.js +6 -8
  287. package/dist/src/grok-provider.d.ts +0 -17
  288. package/dist/src/grok-provider.js +1 -26
  289. package/dist/src/handoffs.d.ts +0 -11
  290. package/dist/src/handoffs.js +0 -13
  291. package/dist/src/hardened-runtime.d.ts +0 -10
  292. package/dist/src/hardened-runtime.js +8 -46
  293. package/dist/src/harness-home.d.ts +21 -0
  294. package/dist/src/harness-home.js +87 -0
  295. package/dist/src/host-process-guard.d.ts +0 -50
  296. package/dist/src/host-process-guard.js +0 -641
  297. package/dist/src/limits.d.ts +0 -64
  298. package/dist/src/limits.js +0 -62
  299. package/dist/src/managed-sign-in.d.ts +0 -12
  300. package/dist/src/managed-sign-in.js +0 -16
  301. package/dist/src/markdown.d.ts +0 -28
  302. package/dist/src/markdown.js +1 -175
  303. package/dist/src/mcp.d.ts +0 -99
  304. package/dist/src/mcp.js +4 -170
  305. package/dist/src/membership-errors.d.ts +0 -14
  306. package/dist/src/membership-errors.js +0 -13
  307. package/dist/src/membership.d.ts +2 -60
  308. package/dist/src/membership.js +0 -85
  309. package/dist/src/memory/LocalToolMemory.d.ts +0 -1
  310. package/dist/src/memory/LocalToolMemory.js +2 -7
  311. package/dist/src/memory/MemoryDistiller.js +0 -15
  312. package/dist/src/memory/MemoryManager.d.ts +0 -3
  313. package/dist/src/memory/MemoryManager.js +6 -18
  314. package/dist/src/memory/MemoryPolicy.d.ts +0 -2
  315. package/dist/src/memory/MemoryPolicy.js +0 -2
  316. package/dist/src/memory/MemoryProvider.d.ts +0 -6
  317. package/dist/src/memory/MemoryRetriever.js +0 -7
  318. package/dist/src/memory/PermissionMemoryProvider.d.ts +0 -1
  319. package/dist/src/memory/PermissionMemoryProvider.js +0 -1
  320. package/dist/src/memory/ProjectMemory.d.ts +5 -40
  321. package/dist/src/memory/ProjectMemory.js +22 -47
  322. package/dist/src/memory/ToolFailureLessons.d.ts +0 -3
  323. package/dist/src/memory/ToolFailureLessons.js +0 -6
  324. package/dist/src/memory/providers/NoOpMemoryProvider.d.ts +0 -1
  325. package/dist/src/memory/providers/NoOpMemoryProvider.js +0 -1
  326. package/dist/src/memory/redaction.d.ts +0 -5
  327. package/dist/src/memory/redaction.js +0 -11
  328. package/dist/src/memory/repository.d.ts +0 -6
  329. package/dist/src/memory/repository.js +2 -12
  330. package/dist/src/memory/types.d.ts +0 -1
  331. package/dist/src/model-health-cache.d.ts +0 -38
  332. package/dist/src/model-health-cache.js +1 -49
  333. package/dist/src/model-metadata.d.ts +0 -18
  334. package/dist/src/model-metadata.js +2 -42
  335. package/dist/src/model-override.d.ts +0 -36
  336. package/dist/src/model-override.js +0 -43
  337. package/dist/src/model-tiers.d.ts +0 -13
  338. package/dist/src/model-tiers.js +0 -23
  339. package/dist/src/opencode-catalog.d.ts +0 -2
  340. package/dist/src/opencode-catalog.js +0 -11
  341. package/dist/src/opencode-cli-provider.d.ts +0 -35
  342. package/dist/src/opencode-cli-provider.js +1 -44
  343. package/dist/src/opencode-provider.d.ts +0 -2
  344. package/dist/src/opencode-provider.js +1 -16
  345. package/dist/src/package-name.d.ts +0 -2
  346. package/dist/src/package-name.js +0 -2
  347. package/dist/src/paged-transcript.d.ts +0 -11
  348. package/dist/src/paged-transcript.js +2 -20
  349. package/dist/src/palette.d.ts +0 -63
  350. package/dist/src/palette.js +0 -63
  351. package/dist/src/permissions.d.ts +0 -15
  352. package/dist/src/permissions.js +0 -17
  353. package/dist/src/powershell-pool.d.ts +0 -9
  354. package/dist/src/powershell-pool.js +3 -26
  355. package/dist/src/process-warnings.d.ts +4 -0
  356. package/dist/src/process-warnings.js +103 -0
  357. package/dist/src/profile.d.ts +0 -43
  358. package/dist/src/profile.js +0 -43
  359. package/dist/src/project-reservation.d.ts +11 -0
  360. package/dist/src/project-reservation.js +143 -0
  361. package/dist/src/provider-connection.d.ts +0 -18
  362. package/dist/src/provider-connection.js +0 -39
  363. package/dist/src/provider-engine.d.ts +0 -21
  364. package/dist/src/provider-engine.js +1 -96
  365. package/dist/src/provider-import.d.ts +0 -49
  366. package/dist/src/provider-import.js +0 -60
  367. package/dist/src/provider-keys.d.ts +1 -36
  368. package/dist/src/provider-keys.js +5 -48
  369. package/dist/src/provider-settings.d.ts +0 -2
  370. package/dist/src/provider-settings.js +0 -32
  371. package/dist/src/providers.d.ts +0 -217
  372. package/dist/src/providers.js +0 -315
  373. package/dist/src/pull-requests.d.ts +0 -173
  374. package/dist/src/pull-requests.js +5 -195
  375. package/dist/src/qa/browser/PlaywrightRunner.d.ts +0 -7
  376. package/dist/src/qa/browser/PlaywrightRunner.js +2 -16
  377. package/dist/src/qa/command-policy.d.ts +0 -23
  378. package/dist/src/qa/command-policy.js +0 -30
  379. package/dist/src/qa/guidance.d.ts +0 -21
  380. package/dist/src/qa/guidance.js +0 -20
  381. package/dist/src/qa/profile/ProjectInspector.d.ts +0 -4
  382. package/dist/src/qa/profile/ProjectInspector.js +0 -6
  383. package/dist/src/qa/profile/QaConfigLoader.d.ts +0 -7
  384. package/dist/src/qa/profile/QaConfigLoader.js +0 -6
  385. package/dist/src/qa/profile/QaProfile.d.ts +0 -7
  386. package/dist/src/qa/profile/QaProfile.js +0 -7
  387. package/dist/src/qa/profile/yaml.d.ts +0 -9
  388. package/dist/src/qa/profile/yaml.js +0 -13
  389. package/dist/src/qa/qa-authorize.d.ts +0 -19
  390. package/dist/src/qa/qa-authorize.js +4 -11
  391. package/dist/src/qa/runtime/ProcessManager.d.ts +0 -31
  392. package/dist/src/qa/runtime/ProcessManager.js +4 -41
  393. package/dist/src/qa/runtime/PtyManager.d.ts +0 -4
  394. package/dist/src/qa/runtime/PtyManager.js +1 -7
  395. package/dist/src/qa/runtime/changes.d.ts +0 -11
  396. package/dist/src/qa/runtime/changes.js +1 -3
  397. package/dist/src/qa/tools.d.ts +0 -10
  398. package/dist/src/qa/tools.js +0 -12
  399. package/dist/src/qa/types.d.ts +0 -13
  400. package/dist/src/react-runtime.d.ts +2 -21
  401. package/dist/src/react-runtime.js +95 -415
  402. package/dist/src/read-document-doc.d.ts +0 -6
  403. package/dist/src/read-document-doc.js +0 -55
  404. package/dist/src/read-document-docx.d.ts +0 -16
  405. package/dist/src/read-document-docx.js +2 -69
  406. package/dist/src/read-document-text.d.ts +0 -17
  407. package/dist/src/read-document-text.js +0 -22
  408. package/dist/src/read-document-tool.d.ts +0 -31
  409. package/dist/src/read-document-tool.js +0 -30
  410. package/dist/src/read-document.d.ts +0 -49
  411. package/dist/src/read-document.js +1 -67
  412. package/dist/src/read-image.d.ts +0 -32
  413. package/dist/src/read-image.js +0 -33
  414. package/dist/src/remote/cert.d.ts +0 -18
  415. package/dist/src/remote/cert.js +0 -44
  416. package/dist/src/remote/client.d.ts +0 -70
  417. package/dist/src/remote/client.js +1 -116
  418. package/dist/src/remote/command.js +0 -17
  419. package/dist/src/remote/engine-pool.d.ts +0 -152
  420. package/dist/src/remote/engine-pool.js +17 -335
  421. package/dist/src/remote/errors.d.ts +0 -15
  422. package/dist/src/remote/errors.js +0 -7
  423. package/dist/src/remote/network.d.ts +0 -26
  424. package/dist/src/remote/network.js +1 -34
  425. package/dist/src/remote/pairing.d.ts +16 -51
  426. package/dist/src/remote/pairing.js +50 -57
  427. package/dist/src/remote/pem.d.ts +0 -4
  428. package/dist/src/remote/pem.js +0 -4
  429. package/dist/src/remote/roots.d.ts +0 -20
  430. package/dist/src/remote/roots.js +0 -8
  431. package/dist/src/remote/serve.d.ts +0 -47
  432. package/dist/src/remote/serve.js +0 -30
  433. package/dist/src/remote/server.d.ts +0 -14
  434. package/dist/src/remote/server.js +1 -79
  435. package/dist/src/remote/types.d.ts +1 -32
  436. package/dist/src/remote/types.js +0 -10
  437. package/dist/src/run-control.d.ts +0 -7
  438. package/dist/src/run-control.js +0 -7
  439. package/dist/src/run-progress.d.ts +0 -170
  440. package/dist/src/run-progress.js +0 -285
  441. package/dist/src/run-records.d.ts +0 -443
  442. package/dist/src/run-records.js +14 -687
  443. package/dist/src/run-temp.d.ts +12 -0
  444. package/dist/src/run-temp.js +50 -0
  445. package/dist/src/runtime.d.ts +10 -228
  446. package/dist/src/runtime.js +0 -127
  447. package/dist/src/sandbox-child.js +0 -1
  448. package/dist/src/save-lock.d.ts +0 -12
  449. package/dist/src/save-lock.js +0 -28
  450. package/dist/src/screen-selection.d.ts +0 -23
  451. package/dist/src/screen-selection.js +0 -22
  452. package/dist/src/secret-redaction.d.ts +0 -12
  453. package/dist/src/secret-redaction.js +0 -45
  454. package/dist/src/session-changes.d.ts +4 -80
  455. package/dist/src/session-changes.js +25 -130
  456. package/dist/src/session-goal.d.ts +129 -0
  457. package/dist/src/session-goal.js +230 -0
  458. package/dist/src/session-monitor.d.ts +1 -10
  459. package/dist/src/session-monitor.js +2 -39
  460. package/dist/src/session-reaper.d.ts +0 -15
  461. package/dist/src/session-reaper.js +0 -14
  462. package/dist/src/session-skills.d.ts +15 -44
  463. package/dist/src/session-skills.js +75 -60
  464. package/dist/src/session-summary.d.ts +0 -26
  465. package/dist/src/session-summary.js +0 -32
  466. package/dist/src/session-title.d.ts +0 -1
  467. package/dist/src/session-title.js +0 -2
  468. package/dist/src/sessions.d.ts +2 -122
  469. package/dist/src/sessions.js +7 -178
  470. package/dist/src/shell.d.ts +3 -20
  471. package/dist/src/shell.js +8 -72
  472. package/dist/src/side-panel.d.ts +5 -99
  473. package/dist/src/side-panel.js +76 -133
  474. package/dist/src/sign-in-detection.d.ts +0 -39
  475. package/dist/src/sign-in-detection.js +0 -43
  476. package/dist/src/sign-in-offer.d.ts +1 -19
  477. package/dist/src/sign-in-offer.js +0 -13
  478. package/dist/src/skill-commands.d.ts +0 -1
  479. package/dist/src/skill-commands.js +1 -4
  480. package/dist/src/skills/bundled/control-browser/SKILL.md +1 -1
  481. package/dist/src/skills/bundled/provenance.json +1 -1
  482. package/dist/src/skills/invocable-skills.d.ts +0 -18
  483. package/dist/src/skills/invocable-skills.js +0 -17
  484. package/dist/src/skills/project-skills.d.ts +0 -1
  485. package/dist/src/skills/project-skills.js +0 -3
  486. package/dist/src/skills/prompt-skills.js +0 -14
  487. package/dist/src/skills/runtime-skills.d.ts +0 -13
  488. package/dist/src/skills/runtime-skills.js +0 -37
  489. package/dist/src/stall-recovery.d.ts +0 -25
  490. package/dist/src/stall-recovery.js +0 -38
  491. package/dist/src/stray-files.d.ts +0 -9
  492. package/dist/src/stray-files.js +0 -16
  493. package/dist/src/structured-step.d.ts +0 -22
  494. package/dist/src/structured-step.js +0 -22
  495. package/dist/src/subagent-run.d.ts +0 -163
  496. package/dist/src/subagent-run.js +4 -373
  497. package/dist/src/subagent-tree.d.ts +32 -0
  498. package/dist/src/subagent-tree.js +128 -0
  499. package/dist/src/telemetry/aggregate.d.ts +0 -37
  500. package/dist/src/telemetry/aggregate.js +0 -40
  501. package/dist/src/telemetry/capture-core.d.ts +0 -87
  502. package/dist/src/telemetry/capture-core.js +0 -67
  503. package/dist/src/telemetry/capture.d.ts +0 -1
  504. package/dist/src/telemetry/capture.js +0 -3
  505. package/dist/src/telemetry/classify.d.ts +0 -58
  506. package/dist/src/telemetry/classify.js +0 -60
  507. package/dist/src/telemetry/decision-capture.d.ts +0 -1
  508. package/dist/src/telemetry/emitter.d.ts +0 -30
  509. package/dist/src/telemetry/emitter.js +1 -62
  510. package/dist/src/telemetry/gate.d.ts +0 -29
  511. package/dist/src/telemetry/gate.js +0 -22
  512. package/dist/src/telemetry/identity.d.ts +0 -13
  513. package/dist/src/telemetry/identity.js +0 -29
  514. package/dist/src/telemetry/outbox.d.ts +0 -64
  515. package/dist/src/telemetry/outbox.js +1 -108
  516. package/dist/src/telemetry/schema.d.ts +1 -49
  517. package/dist/src/telemetry/schema.js +1 -82
  518. package/dist/src/telemetry/state.d.ts +0 -53
  519. package/dist/src/telemetry/state.js +0 -64
  520. package/dist/src/telemetry/surface.d.ts +0 -31
  521. package/dist/src/telemetry/surface.js +1 -39
  522. package/dist/src/telemetry/uploader.d.ts +0 -11
  523. package/dist/src/telemetry/uploader.js +0 -46
  524. package/dist/src/telemetry/uploads.d.ts +0 -11
  525. package/dist/src/telemetry/uploads.js +0 -11
  526. package/dist/src/telemetry/version.d.ts +0 -4
  527. package/dist/src/telemetry/version.js +0 -14
  528. package/dist/src/telemetry/workspace.d.ts +0 -7
  529. package/dist/src/telemetry/workspace.js +1 -22
  530. package/dist/src/terminal-ui.d.ts +14 -523
  531. package/dist/src/terminal-ui.js +74 -876
  532. package/dist/src/test-edit-guard.d.ts +74 -0
  533. package/dist/src/test-edit-guard.js +269 -0
  534. package/dist/src/text.d.ts +0 -1
  535. package/dist/src/text.js +0 -1
  536. package/dist/src/time-limit.d.ts +0 -36
  537. package/dist/src/time-limit.js +0 -37
  538. package/dist/src/timers.d.ts +0 -161
  539. package/dist/src/timers.js +0 -126
  540. package/dist/src/todos.d.ts +0 -1
  541. package/dist/src/todos.js +0 -3
  542. package/dist/src/token-rate.d.ts +0 -94
  543. package/dist/src/token-rate.js +0 -154
  544. package/dist/src/tool-activity.d.ts +0 -6
  545. package/dist/src/tool-activity.js +0 -7
  546. package/dist/src/tool-availability.d.ts +0 -13
  547. package/dist/src/tool-availability.js +1 -14
  548. package/dist/src/tool-call-clock.d.ts +1 -4
  549. package/dist/src/tool-call-clock.js +0 -13
  550. package/dist/src/tool-catalog.d.ts +0 -11
  551. package/dist/src/tool-catalog.js +0 -23
  552. package/dist/src/tool-dependencies.d.ts +0 -5
  553. package/dist/src/tool-dependencies.js +0 -4
  554. package/dist/src/tool-diff-stats.d.ts +0 -23
  555. package/dist/src/tool-diff-stats.js +0 -49
  556. package/dist/src/tool-errors.d.ts +9 -7
  557. package/dist/src/tool-errors.js +13 -6
  558. package/dist/src/tool-failure-tracker.d.ts +3 -11
  559. package/dist/src/tool-failure-tracker.js +19 -27
  560. package/dist/src/tool-names.d.ts +0 -16
  561. package/dist/src/tool-names.js +0 -12
  562. package/dist/src/tool-profile.d.ts +6 -0
  563. package/dist/src/tool-profile.js +23 -0
  564. package/dist/src/tool-result-filter.d.ts +0 -19
  565. package/dist/src/tool-result-filter.js +1 -66
  566. package/dist/src/tool-schema-compatibility.d.ts +0 -6
  567. package/dist/src/tool-schema-compatibility.js +0 -9
  568. package/dist/src/tools.d.ts +0 -4
  569. package/dist/src/tools.js +11 -114
  570. package/dist/src/trajectory.d.ts +0 -13
  571. package/dist/src/trajectory.js +23 -79
  572. package/dist/src/transcript.d.ts +0 -41
  573. package/dist/src/transcript.js +2 -60
  574. package/dist/src/types.d.ts +1 -168
  575. package/dist/src/untracked-file-removal.js +0 -20
  576. package/dist/src/update-check.d.ts +0 -14
  577. package/dist/src/update-check.js +1 -15
  578. package/dist/src/update.d.ts +0 -35
  579. package/dist/src/update.js +0 -100
  580. package/dist/src/usage-analytics.d.ts +17 -17
  581. package/dist/src/usage-analytics.js +168 -209
  582. package/dist/src/web-search.d.ts +0 -23
  583. package/dist/src/web-search.js +1 -27
  584. package/dist/src/widgets.d.ts +0 -25
  585. package/dist/src/widgets.js +0 -24
  586. package/dist/src/workspace-facts.d.ts +0 -12
  587. package/dist/src/workspace-facts.js +1 -18
  588. package/dist/src/workspace-git-metadata.d.ts +0 -16
  589. package/dist/src/workspace-git-metadata.js +0 -21
  590. package/dist/src/workspace-instructions.d.ts +3 -15
  591. package/dist/src/workspace-instructions.js +6 -19
  592. package/package.json +2 -2
package/dist/src/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import './process-warnings.js';
2
3
  import { randomUUID } from 'node:crypto';
3
4
  import { bootMark } from './boot-trace.js';
4
5
  import { createSessionTrajectory } from './trajectory.js';
@@ -16,7 +17,7 @@ import { compactHistory, compactedContextEstimate, executeCommand, HELP } from '
16
17
  import { applyModelContextWindow, createAdapter, 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';
@@ -27,10 +28,8 @@ 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,10 @@ 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';
85
78
  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
79
  async function warmRunModules(lastInputAt, stop) {
99
80
  for (const load of [loadTools, () => import('./engine-streams.js').then(module => module.loadEngineStreams()), () => import('typebox/compile')]) {
100
81
  for (;;) {
@@ -111,17 +92,7 @@ async function warmRunModules(lastInputAt, stop) {
111
92
  const updateInstallation = async (...args) => (await import('./update.js')).updateInstallation(...args);
112
93
  const launchGraphEditor = async (noOpen) => (await import('./graph-server.js')).launchGraphEditor(noOpen);
113
94
  const startBrowserServer = async () => (await import('./browser-server.js')).startBrowserServer();
114
- // Only called once startBrowserServer has resolved, so the module is already loaded here.
115
95
  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
96
  export async function cliVersion() {
126
97
  try {
127
98
  const manifest = JSON.parse(await readFile(fileURLToPath(new URL('../../package.json', import.meta.url)), 'utf8'));
@@ -131,12 +102,6 @@ export async function cliVersion() {
131
102
  return 'unknown';
132
103
  }
133
104
  }
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
105
  async function offerStartupUpdate() {
141
106
  try {
142
107
  if (await updateCheckDisabled())
@@ -176,11 +141,6 @@ async function offerStartupUpdate() {
176
141
  return false;
177
142
  }
178
143
  }
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
144
  async function offerStartupSignIns() {
185
145
  let lines;
186
146
  try {
@@ -189,12 +149,11 @@ async function offerStartupSignIns() {
189
149
  ask: question => (lines ??= createInterface({ input: process.stdin, output: process.stdout, terminal: true })).question(question),
190
150
  });
191
151
  }
192
- catch { /* The offer is a convenience; it never decides whether the session starts. */ }
152
+ catch { }
193
153
  finally {
194
154
  lines?.close();
195
155
  }
196
156
  }
197
- /** Display-only Git metadata must never run workspace-controlled PATH helpers. */
198
157
  export async function gitBranch(workspace) {
199
158
  try {
200
159
  const root = await realpath(workspace);
@@ -203,7 +162,6 @@ export async function gitBranch(workspace) {
203
162
  return suffix === '' || (!isAbsolute(suffix) && suffix !== '..' && !suffix.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`));
204
163
  };
205
164
  const metadataPath = async (target) => {
206
- // Check lexical paths before resolution, then reject symlink/junction escapes.
207
165
  if (!contained(resolve(target)))
208
166
  throw new Error('Git metadata is outside the workspace');
209
167
  const canonical = await realpath(target);
@@ -250,55 +208,22 @@ export async function gitBranch(workspace) {
250
208
  export function safeTerminal(text) {
251
209
  return stripVTControlCharacters(text).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '');
252
210
  }
253
- /** Short follow-up directions that mean "continue the unfinished work" rather than start a new task. */
254
211
  export function isContinuationPrompt(text) {
255
212
  const normalized = text.trim().replace(/[.!?]+$/, '').trim();
256
213
  return normalized.length <= 160 && /^(?:continue|resume|retry|try again|keep going|keep working)(?:\b.*)?$/i.test(normalized);
257
214
  }
258
- /** Retain an unfinished run's plan only when the next prompt explicitly continues that work. */
259
215
  export function continuedTodos(task, lastRun) {
260
216
  return lastRun && lastRun.status !== 'succeeded' && isContinuationPrompt(task)
261
217
  ? (lastRun.todos ?? []).map(todo => ({ ...todo }))
262
218
  : [];
263
219
  }
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
220
  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
221
  export async function appendRunEvent(directory, event) {
280
222
  const runId = event.data.runId;
281
223
  if (runId === undefined || runId === null)
282
224
  return;
283
225
  await appendFile(runRecordPath(directory, runId, 'jsonl'), JSON.stringify(event) + '\n', { mode: 0o600 });
284
226
  }
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
227
  export async function withNodeModelResolution(event, lookup) {
303
228
  if (event.type !== 'agent.session.started' || typeof event.data.subagentId === 'string')
304
229
  return event;
@@ -317,14 +242,6 @@ export async function withNodeModelResolution(event, lookup) {
317
242
  return { ...event, data: { ...event.data, reasoningEffort: resolved.reasoningEffort, contextWindow: resolved.contextWindow } };
318
243
  }
319
244
  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
245
  function reportSignOut(json, terminal, reason, journal) {
329
246
  if (json)
330
247
  process.stderr.write(safeTerminal(SIGN_OUT_NOTICE) + '\n');
@@ -339,26 +256,14 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
339
256
  const persistConfig = dependencies.saveConfig ?? saveConfig;
340
257
  const loadGraph = dependencies.loadGraph ?? loadAccessibleGraph;
341
258
  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
259
  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
260
  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
261
  if (argv[0] === 'mcp-server') {
351
262
  if (argv.length !== 2 || argv[1] !== '--stdio')
352
263
  throw new Error('Usage: andorra mcp-server --stdio');
353
264
  const { runAgentMcpServer } = await import('./agent-mcp.js');
354
265
  return await runAgentMcpServer();
355
266
  }
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
267
  const machineOutput = argv.includes('--json') || argv[0] === 'subagent' || argv[0] === 'automations';
363
268
  setAuthSignOutReporter(error => reportSignOut(machineOutput, undefined, error.message));
364
269
  if (argv[0] === 'login' || argv[0] === 'logout' || argv[0] === 'auth') {
@@ -373,10 +278,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
373
278
  process.once('SIGTERM', cancel);
374
279
  try {
375
280
  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
281
  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
282
  lines?.on('SIGINT', cancel);
381
283
  const readCallback = lines ? (prompt, signal) => lines.question(`${prompt} `, { signal }) : undefined;
382
284
  try {
@@ -401,11 +303,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
401
303
  if (argv[0] === 'app-server') {
402
304
  if (argv.length !== 2 || argv[1] !== '--stdio')
403
305
  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
306
  const { runAppServer } = await import('./app-server.js');
407
307
  bootMark('app-server.imported');
408
- // The desktop client owns this process and its stdio; in this mode nothing may print to stdout.
409
308
  return await runAppServer();
410
309
  }
411
310
  if (argv[0] === 'automations') {
@@ -413,8 +312,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
413
312
  return runAutomationCommand(argv.slice(1), line => process.stdout.write(line + '\n'));
414
313
  }
415
314
  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
315
  const { REMOTE_USAGE, runRemoteCommand } = await import('./remote/command.js');
419
316
  if (argv.includes('--help') || argv.includes('-h')) {
420
317
  process.stdout.write(`${REMOTE_USAGE}\n`);
@@ -443,7 +340,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
443
340
  help: { type: 'boolean', short: 'h' }, version: { type: 'boolean' },
444
341
  prompt: { type: 'string', short: 'p' }, 'no-tui': { type: 'boolean' },
445
342
  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' },
343
+ cwd: { type: 'string' }, yolo: { type: 'boolean' }, jev: { type: 'string' }, json: { type: 'boolean' }, debug: { type: 'boolean' }, tools: { type: 'string' }, goal: { type: 'string' },
447
344
  configure: { type: 'boolean' }, 'run-input': { type: 'string' }, 'run-state': { type: 'string' },
448
345
  } });
449
346
  const readValues = async (path, flag) => {
@@ -459,7 +356,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
459
356
  let terminal;
460
357
  const print = (text) => terminal ? terminal.print(text) : process.stdout.write(safeTerminal(text) + '\n');
461
358
  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}`);
359
+ print(`Andorra Code\nUsage: andorra [--cwd path] [--provider id] [--model id] [--graph id] [--run-input file.json] [--run-state file.json] [--goal "text"] [--yolo] [--jev on|off] [--debug]\n andorra --prompt "task" [--json] [--yolo] [--jev on|off] [--tools default|coding] [--debug]\n andorra subagent --prompt "task" [--provider id] [--model id] [--read-only]\n andorra graph [--no-open]\n andorra automations list|run|service|serve\n andorra app-server --stdio\n andorra mcp-server --stdio\n andorra remote serve|status|code|devices|revoke|share|unshare|pair|workspaces|unpair|rotate-cert\n andorra update\n andorra login [--no-browser]\n andorra logout [--all]\n andorra auth status\n\n${HELP}`);
463
360
  return 0;
464
361
  }
465
362
  if (values.version) {
@@ -472,15 +369,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
472
369
  }
473
370
  const interactive = values.prompt === undefined;
474
371
  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
372
  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
373
  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
374
  directory: dependencies.trajectoryDirectory ?? join(configDirectory(), 'trajectories'),
485
375
  onError: message => { if (values.json)
486
376
  process.stderr.write(safeTerminal(message) + '\n');
@@ -491,23 +381,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
491
381
  version: await cliVersion(), interactive,
492
382
  } } : {}),
493
383
  });
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
384
  let sessionStarted = Promise.resolve();
500
385
  const noteSessionStarted = (extra = {}) => {
501
386
  sessionStarted = sessionStarted.then(() => currentGraphSubject().catch(() => undefined)).then(subject => reportSessionStarted({ home: configDirectory(), surface: configuredSurface('cli'), ...(subject === undefined ? {} : { subject }), ...extra })).catch(() => { });
502
387
  };
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
388
  const openSessionTrajectory = async (sessionId) => {
512
389
  const directory = dependencies.trajectoryDirectory ?? join(configDirectory(), 'trajectories');
513
390
  const path = join(directory, `${sessionId}.jsonl`);
@@ -524,25 +401,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
524
401
  noteSessionStarted({ workspace });
525
402
  trajectory.addSecrets(providerSecrets(config.providers));
526
403
  };
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
404
  const debugRecord = (type, data) => values.debug ? trajectory.record(type, data) : undefined;
534
405
  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
406
  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
407
  let releaseCodeIntel;
547
408
  const startupGuard = async (operation) => {
548
409
  try {
@@ -557,16 +418,22 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
557
418
  try {
558
419
  await releaseCodeIntel?.();
559
420
  }
560
- catch { /* Disposal is best effort during startup failure. */ }
421
+ catch { }
561
422
  throw error;
562
423
  }
563
424
  };
564
- /** Fails startup under the journal-closing guard; the guard rethrows the wrapped error. */
565
425
  const startupReject = (message) => startupGuard(async () => { throw new Error(message); });
566
426
  if (values.graph && values.graph !== 'default')
567
427
  await startupGuard(() => loadGraph(values.graph));
568
428
  if (values.json && !values.prompt)
569
429
  await startupReject('--json requires --prompt');
430
+ if (values.tools !== undefined && !values.prompt)
431
+ await startupReject('--tools requires --prompt');
432
+ const startupGoal = values.goal === undefined ? undefined : parseGoalCommand(`/goal ${values.goal}`);
433
+ if (startupGoal && startupGoal.action !== 'set')
434
+ await startupReject(startupGoal.action === 'invalid' ? `--goal: ${startupGoal.reason}` : '--goal takes the goal text, for example --goal "All tests pass"');
435
+ if (values.tools !== undefined && !isToolProfile(values.tools))
436
+ await startupReject(`--tools takes one of: ${TOOL_PROFILES.join(', ')}`);
570
437
  if (values['no-tui'] && !values.prompt)
571
438
  await startupReject('--no-tui requires --prompt');
572
439
  if (values.jev !== undefined && !['on', 'off'].includes(values.jev))
@@ -613,8 +480,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
613
480
  });
614
481
  bootMark('cli.config');
615
482
  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
483
  let jevOverride = values.jev === undefined ? undefined : values.jev === 'on';
619
484
  const jevOn = () => jevOverride ?? config.jevEnabled !== false;
620
485
  const afterJevCommand = (input, result) => {
@@ -626,21 +491,17 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
626
491
  else
627
492
  result.text += `\nThis session started with --jev ${jevOverride ? 'on' : 'off'}, which overrides the saved preference until /jev on|off.`;
628
493
  };
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.
494
+ const state = await startupGuard(async () => ({ config, workspace, graph: values.graph ?? configuredGraphSelection(config, await currentGraphSubject()), permissions, yolo: permissions === 'full-access', usage: { inputTokens: 0, outputTokens: 0, requests: 0 }, notify: print, history: [], ...(startupGoal?.action === 'set' ? { goal: newSessionGoal(startupGoal.text) } : {}),
631
495
  readLine: async (prompt, signal) => {
632
496
  if (!terminal)
633
497
  throw new Error('No interactive terminal to read from.');
634
498
  return terminal.question(prompt, { signal, title: 'Sign in', history: false });
635
499
  },
636
- // Over SSH only the terminal's own clipboard (OSC 52) reaches the machine the user sits at.
637
500
  copyText: (text) => {
638
501
  if (!terminal)
639
502
  throw new Error('No interactive terminal.');
640
503
  terminal.copyText(text, { terminalOnly: Boolean(process.env.SSH_CONNECTION || process.env.SSH_CLIENT || process.env.SSH_TTY) });
641
504
  },
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
505
  confirmModelOverride: async (question) => {
645
506
  if (!terminal)
646
507
  return false;
@@ -650,12 +511,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
650
511
  ], { description: question });
651
512
  return choice === 'override';
652
513
  } }));
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
514
  let startupGraph;
660
515
  let startupGraphSelection;
661
516
  let startupGraphReused = false;
@@ -669,8 +524,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
669
524
  startupGraphSelection = selection;
670
525
  }
671
526
  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
527
  if (error instanceof GraphProviderUnavailableError && values.graph === undefined)
675
528
  return;
676
529
  if (values.graph !== undefined || (!(error instanceof PaidMembershipRequiredError || error instanceof GraphDeletedError) && !missingSavedGraph(error)))
@@ -683,8 +536,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
683
536
  });
684
537
  bootMark('cli.startup-graph');
685
538
  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
539
  const foldCache = (target, cacheRead, cacheWrite) => {
689
540
  const read = (target.cacheRead ?? 0) + (cacheRead ?? 0);
690
541
  if (read > 0)
@@ -693,12 +544,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
693
544
  if (write > 0)
694
545
  target.cacheWrite = write;
695
546
  };
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
547
  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
548
  let runContext;
703
549
  const sessionUsage = () => ({
704
550
  requests: state.usage.requests + activeUsage.requests,
@@ -715,8 +561,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
715
561
  const runtimeProvider = (provider) => ({
716
562
  ...provider, contextWindow: sessionContexts.get(contextKey(provider)) ?? provider.contextWindow,
717
563
  });
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
564
  trajectory.addSecrets(providerSecrets(config.providers));
721
565
  const selectedProvider = config.providers.find(p => p.id === config.provider);
722
566
  await debugRecord('session.context', {
@@ -734,27 +578,21 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
734
578
  if (!savedSession)
735
579
  return;
736
580
  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 };
581
+ savedSession = { projectId: savedSession.projectId ?? projectIdentity(workspace), ...savedSession, goal: state.goal, contextHistory: [...state.history ?? [], ...pendingHistory].slice(-6), updatedAt: new Date().toISOString(), history: [...sessionArchive, ...pendingHistory], usage: { ...state.usage }, trajectoryId: trajectory.sessionId };
738
582
  const record = savedSession;
739
583
  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
584
  let releaseRailLock;
747
585
  try {
748
586
  releaseRailLock = await acquireSessionMutationLock(configDirectory(), record.id);
749
587
  }
750
- catch { /* held elsewhere: save unmerged rather than not at all */ }
588
+ catch { }
751
589
  try {
752
590
  if (releaseRailLock) {
753
591
  let stored;
754
592
  try {
755
593
  stored = JSON.parse(await readFile(join(configDirectory(), 'sessions', `${record.id}.json`), 'utf8'));
756
594
  }
757
- catch { /* no record yet: nothing to carry */ }
595
+ catch { }
758
596
  carryRailOwnedFields(record, stored);
759
597
  }
760
598
  if (browserBridge)
@@ -775,7 +613,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
775
613
  }
776
614
  };
777
615
  const directory = configDirectory();
778
- // Spooled attachments are files, not records: retire the ones no conversation can still reference.
779
616
  void pruneAttachments(directory).catch(() => { });
780
617
  let browserApp;
781
618
  let browserBridge;
@@ -783,9 +620,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
783
620
  let browserPrompt;
784
621
  let browserAcceptance = Promise.resolve();
785
622
  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
623
  let browserDraining = false;
790
624
  let browserCancelPending = false;
791
625
  const rollbackFailureMessage = 'Session storage rollback failed. Repair local storage and inspect session history before restarting this CLI.';
@@ -801,29 +635,15 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
801
635
  process.stderr.write(`CodeGraph: ${String(event.data.detail ?? 'unavailable')}\n`);
802
636
  }
803
637
  };
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
638
  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
639
  const codeIntelOpening = CodeIntelligenceManager.create({
812
640
  permissions: state.permissions,
813
641
  config: homeWorkspace ? { ...resolveCodeIntelConfig(config), enabled: false, enabledRepos: [] } : resolveCodeIntelConfig(config), workspace,
814
642
  onEvent: event => (runEventSink ?? codeIntelNotice)(event),
815
643
  });
816
- // Observed here so a failure cannot surface as an unhandled rejection while recovery runs;
817
- // the startup guard below still receives it.
818
644
  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
645
  try {
824
646
  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
647
  await reportInterruptedRuns({ home: directory, surface: configuredSurface('cli') }, recovered.interrupted);
828
648
  const parts = [];
829
649
  if (recovered.runs.length > 0)
@@ -838,26 +658,12 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
838
658
  print(notice);
839
659
  }
840
660
  }
841
- catch { /* Recovery is best effort. */ }
661
+ catch { }
842
662
  bootMark('cli.reconciled');
843
663
  const codeIntel = await startupGuard(() => codeIntelOpening);
844
664
  bootMark('cli.codeintel');
845
665
  releaseCodeIntel = () => codeIntel.dispose();
846
666
  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
667
  let changesInFlight = false;
862
668
  let changesReadAt = 0;
863
669
  let changesPending;
@@ -868,20 +674,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
868
674
  const CHANGE_REFRESH_MS = 2_000;
869
675
  const TERMINAL_WATCH_MS = 1_000;
870
676
  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
677
  const watchTerminals = (sessions) => {
880
678
  const running = sessions.some(session => session.running);
881
679
  if (running && !terminalsTimer) {
882
680
  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
681
  if (!terminal || !terminal.panelVisible()) {
886
682
  clearInterval(terminalsTimer);
887
683
  terminalsTimer = undefined;
@@ -911,10 +707,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
911
707
  void gitChangeSummary(workspace, { signal: panelReads.signal })
912
708
  .then(changes => { changesReadAt = Date.now(); changesEverRead = true; terminal?.setStatus({ changes }); })
913
709
  .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
710
  changesReadAt = Date.now();
919
711
  if (!changesEverRead) {
920
712
  terminal?.setStatus({ changes: { isGit: true, files: 0, untracked: 0, insertions: 0, deletions: 0, unavailable: 'the working tree could not be read' } });
@@ -926,40 +718,21 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
926
718
  changesPending = undefined;
927
719
  if (panelReads.signal.aborted || pending === undefined)
928
720
  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
721
  if (pending === 'force')
935
722
  refreshPanelStatus(true);
936
723
  else
937
724
  scheduleChanges(CHANGE_REFRESH_MS - (Date.now() - changesReadAt));
938
725
  });
939
726
  };
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
727
  const scheduleChanges = (delayMs) => {
949
728
  if (changesTimer || panelReads.signal.aborted)
950
729
  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
730
  changesTimer = setTimeout(() => { changesTimer = undefined; refreshPanelStatus(true); }, Math.max(0, delayMs));
954
731
  changesTimer.unref?.();
955
732
  };
956
733
  const refreshPanelStatus = (force = false) => {
957
734
  if (!terminal)
958
735
  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
736
  if (!terminal.panelVisible()) {
964
737
  changesPending = undefined;
965
738
  return;
@@ -968,8 +741,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
968
741
  terminal.setStatus({ terminals: sessions });
969
742
  watchTerminals(sessions);
970
743
  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
744
  if (changesInFlight) {
974
745
  changesPending = force || changesPending === 'force' ? 'force' : 'throttled';
975
746
  return;
@@ -986,18 +757,14 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
986
757
  await startupGuard(async () => {
987
758
  const selected = config.providers.find(p => p.id === config.provider);
988
759
  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.
760
+ terminal = new TerminalUI({ goal: state.goal, account: { label: 'Checking account...', notice: 'Checking member access. Local Andorra Agent remains available.' }, workspace, provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, version: await cliVersion(), branch: await gitBranch(workspace), yolo: state.yolo, permissions: permissionLabel(state.permissions), graphSelection: state.graph ?? 'default',
990
761
  graph: startupGraph ?? await loadGraph(state.graph ?? 'default').catch(() => undefined), ...(codeIntelState ? { codeIntel: codeIntelState } : {}), clipboardImageProbe: readClipboardImage, clipboardTextWriter: writeClipboardText });
991
762
  offerSkillCommands(terminal, state.config, directory);
992
763
  terminal.setLocalCommandHandler((input, mode, durationMs) => {
993
- // Local view commands never reach either CLI command loop.
994
764
  void debugRecord('command.started', { input, mode });
995
765
  void debugRecord('command.completed', { input, mode, durationMs });
996
766
  });
997
767
  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
768
  terminal.on('panel', () => refreshPanelStatus(true));
1002
769
  if (graphFallbackNotice)
1003
770
  terminal.print(graphFallbackNotice);
@@ -1006,17 +773,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1006
773
  jevEnabled = jevOn();
1007
774
  const configured = config.providers.find(p => p.id === config.provider);
1008
775
  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() });
776
+ terminal?.setStatus({ provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, yolo: state.yolo, permissions: permissionLabel(state.permissions), jevEnabled, goal: state.goal, ...sessionUsage() });
1010
777
  };
1011
778
  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
779
  const refreshGraphStatus = async (background) => {
1021
780
  if (terminal) {
1022
781
  const controller = background ?? active ?? new AbortController();
@@ -1025,8 +784,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1025
784
  active = controller;
1026
785
  terminal.setStatus({ activity: 'Checking graph models', backgroundActivity: true });
1027
786
  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
787
  startupGraph = undefined;
1031
788
  startupGraphSelection = undefined;
1032
789
  startupGraphReused = false;
@@ -1036,24 +793,14 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1036
793
  graph = await loadGraph(state.graph ?? 'default', controller.signal);
1037
794
  }
1038
795
  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
796
  if (error instanceof GraphProviderUnavailableError) {
1045
797
  const definition = await loadGraph(state.graph ?? 'default', controller.signal, undefined, { bindProviders: false }).catch(() => undefined);
1046
798
  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
799
  terminal.setStatus({ graphSelection: state.graph ?? 'default', ...(definition === undefined ? {} : { graph: definition }), graphNeedsOverride: true, jevEnabled: jevOn() });
1050
800
  print(error.message);
1051
801
  }
1052
802
  return;
1053
803
  }
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
804
  if (values.graph !== undefined || (state.graph ?? 'default') === 'default' || (!(error instanceof PaidMembershipRequiredError || error instanceof GraphDeletedError) && !missingSavedGraph(error)))
1058
805
  throw error;
1059
806
  state.graph = 'default';
@@ -1066,8 +813,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1066
813
  jevEnabled = jevOn();
1067
814
  terminal.setStatus({ graphSelection: state.graph ?? 'default', graph, graphNeedsOverride: false, jevEnabled });
1068
815
  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
816
  const sessionOnly = (state.graph ?? 'default') === 'default' && checkSessionModel !== undefined;
1072
817
  const health = sessionOnly
1073
818
  ? await checkSessionModel(config, controller.signal, { verified: modelHealth })
@@ -1081,14 +826,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1081
826
  finally {
1082
827
  if (ownsController)
1083
828
  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
829
  terminal.setStatus({ activity: background?.signal.aborted ? 'Ready' : graphModelsHealthy ? 'Ready' : 'Graph models unavailable' });
1087
830
  }
1088
831
  }
1089
832
  };
1090
833
  let startupGraphCheck;
1091
- /** Cancel the launch graph check if it is still running, and wait until it has let go. */
1092
834
  const settleStartupGraphCheck = async () => {
1093
835
  const pending = startupGraphCheck;
1094
836
  if (!pending)
@@ -1109,7 +851,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1109
851
  if (!request.signal.aborted)
1110
852
  terminal?.setStatus({ account });
1111
853
  }
1112
- catch { /* Cancellation leaves the next refresh in control. */ }
854
+ catch { }
1113
855
  };
1114
856
  let active;
1115
857
  let exiting = false;
@@ -1122,37 +864,20 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1122
864
  };
1123
865
  let runControl;
1124
866
  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
867
  const sessionTimers = new TimerRegistry();
1132
868
  const timerSteering = [];
1133
869
  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
870
  let timerResumePending = false;
1139
871
  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
872
  if (exiting) {
1143
873
  sessionTimers.takeDue();
1144
874
  return;
1145
875
  }
1146
- // `takeDue` returns prompts soonest-deadline first, so every channel below preserves order.
1147
876
  for (const due of sessionTimers.takeDue())
1148
877
  timerPending.push(`[Timer] ${due.prompt}`);
1149
878
  while (timerPending.length) {
1150
879
  const text = timerPending[0];
1151
880
  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
881
  if (runControl.isPaused) {
1157
882
  if (runControl.resume(text)) {
1158
883
  timerResumePending = true;
@@ -1167,10 +892,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1167
892
  timerSteering.push(timerPending.shift());
1168
893
  continue;
1169
894
  }
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
895
  if (terminal?.acceptConversationPrompt(text)) {
1175
896
  timerPending.shift();
1176
897
  continue;
@@ -1179,10 +900,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1179
900
  }
1180
901
  };
1181
902
  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
903
  const interrupt = () => {
1187
904
  if (runControl) {
1188
905
  if (runControl.isPaused)
@@ -1200,13 +917,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1200
917
  kill();
1201
918
  };
1202
919
  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
920
  let killBackstop;
1211
921
  const kill = () => {
1212
922
  teardown();
@@ -1217,22 +927,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1217
927
  process.on('SIGTERM', teardown);
1218
928
  terminal?.on('SIGINT', interrupt);
1219
929
  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
930
  const rememberTurn = (task, completion, runId, attachments) => {
1232
931
  sessionArchive.push({ task, completion, runId, ...(attachments?.length ? { attachments } : {}) });
1233
932
  state.history = [...state.history ?? [], { task, completion, runId, ...(attachments?.length ? { attachments } : {}) }].slice(-6);
1234
933
  };
1235
- /** Render how an attempt ended as history the next turn can read. */
1236
934
  const outcomeCompletion = (status, reason, limits) => ({
1237
935
  summary: status === 'cancelled'
1238
936
  ? 'This attempt was cancelled before it finished; its work may be incomplete.'
@@ -1240,11 +938,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1240
938
  tests: [], ...(status === 'succeeded' ? {} : { status: status }),
1241
939
  });
1242
940
  const toolActivity = new ToolActivity();
1243
- /** The task text an attachment-only submission runs with; both surfaces substitute the same words. */
1244
941
  const ATTACHMENT_ONLY_TASK = 'See the attached file(s).';
1245
942
  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
943
  await settleStartupGraphCheck();
1249
944
  if (browserRollbackFailed)
1250
945
  throw new Error(rollbackFailureMessage);
@@ -1252,15 +947,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1252
947
  print('Add a provider in /providers before starting a task.');
1253
948
  return 1;
1254
949
  }
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
950
  if (pending.length && terminal)
1258
951
  terminal.print(`⌷ attached: ${pending.map(attachmentLabel).join(' · ')}`);
1259
952
  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
953
  const attachmentSpools = new Set();
1265
954
  const steeredSpools = new Set();
1266
955
  for (const root of await attachmentReadRoots(directory, (state.history ?? []).flatMap(turn => turn.attachments ?? [])))
@@ -1276,7 +965,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1276
965
  for (const root of await attachmentReadRoots(directory, attachments.refs))
1277
966
  attachmentSpools.add(root);
1278
967
  }
1279
- // Cancellation must already own this run while its first snapshot is pending.
1280
968
  active = new AbortController();
1281
969
  if (browserCancelPending) {
1282
970
  browserCancelPending = false;
@@ -1286,7 +974,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1286
974
  trajectory.addSecrets(providerSecrets(config.providers));
1287
975
  if (!savedSession) {
1288
976
  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
977
  noteSessionStarted({ workspace });
1291
978
  }
1292
979
  const accepted = browserAcceptance;
@@ -1301,27 +988,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1301
988
  }
1302
989
  browserBridge?.startRun();
1303
990
  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
991
  const telemetryRunId = randomUUID();
1307
992
  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
993
  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
994
  const runGraphSelection = state.graph ?? 'default';
1320
- // Bind persisted run inspection to the signed-in account at run creation.
1321
995
  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
996
  const telemetrySurface = { home: directory, config, ...(accountSubject ? { subject: accountSubject } : {}), surface: configuredSurface('cli') };
1326
997
  const telemetryHandle = createRunHandle(telemetryRunId, startedAt, {
1327
998
  graphId: runGraphSelection, nodes: 0, subagents: false, permissionMode: state.permissions,
@@ -1330,32 +1001,22 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1330
1001
  let telemetryFinished = false;
1331
1002
  let telemetryStart;
1332
1003
  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
1004
  const startTelemetry = () => {
1336
1005
  telemetryStart ??= reportRunStarted(telemetrySurface, telemetryHandle).catch(() => { });
1337
1006
  return telemetryStart;
1338
1007
  };
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
1008
  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
1009
  let healthProviderFailed = false;
1346
1010
  const finishTelemetry = (status, reason, result) => {
1347
1011
  if (telemetryFinished)
1348
1012
  return;
1349
1013
  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
1014
  const capture = result?.telemetry ?? createRunTelemetry();
1353
1015
  for (const probe of probeModels.values()) {
1354
1016
  const provider = config.providers.find(item => item.id === probe.provider);
1355
1017
  recordModelUse(capture, {
1356
1018
  ...(provider === undefined ? {} : { providerType: provider.type, baseUrl: provider.baseUrl }),
1357
1019
  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
1020
  ...(provider === undefined ? {} : { pricing: pricingFor(config.efficiency?.adaptiveRouting, probe.provider, probe.model) }),
1360
1021
  });
1361
1022
  }
@@ -1367,19 +1028,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1367
1028
  ...(result ? { toolCalls: result.toolCalls } : {}),
1368
1029
  })).catch(() => { });
1369
1030
  };
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
1031
  const finalizeRunRecord = async (status, reason) => {
1374
1032
  const record = { id: runId, status, reason, graphSelection: runGraphSelection,
1375
1033
  ...(accountSubject ? { accountSubject } : {}), usage: { ...activeUsage },
1376
1034
  ...(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
1035
  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
1036
  ...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
1384
1037
  ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }) };
1385
1038
  try {
@@ -1391,44 +1044,15 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1391
1044
  }
1392
1045
  finishTelemetry(status, reason);
1393
1046
  };
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
1047
  const settleRunRecord = async () => {
1402
1048
  await persistSession();
1403
1049
  await clearOpenRunClaim(directory, runId);
1404
1050
  };
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
1051
  const openRecord = {
1423
1052
  id: runId, status: 'running', sessionId: savedSession.id, startedAt, pid: process.pid,
1424
1053
  graphSelection: runGraphSelection, ...(accountSubject ? { accountSubject } : {}),
1425
1054
  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
1055
  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
1056
  telemetry: { runId: telemetryRunId, nodes: 0, subagents: false, jevEnabled: jevOn(), decisionRouting: config.decisions?.mode ?? 'off', permissions: state.permissions, startSent: false },
1433
1057
  ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }),
1434
1058
  };
@@ -1436,20 +1060,12 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1436
1060
  process.stderr.write(`Could not write the open run record: ${error instanceof Error ? error.message : String(error)}\n`);
1437
1061
  return false;
1438
1062
  });
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
1063
  runContext = undefined;
1445
1064
  if (savedSession?.context !== undefined)
1446
1065
  savedSession = { ...savedSession, context: undefined };
1447
1066
  if (openRecordWritten)
1448
1067
  await persistSession(task, runId, attachments?.refs);
1449
1068
  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
1069
  await finalizeRunRecord('cancelled', 'the user stopped this run');
1454
1070
  rememberTurn(task, outcomeCompletion('cancelled', undefined, undefined), runId, attachments?.refs);
1455
1071
  browserDraining = true;
@@ -1464,10 +1080,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1464
1080
  }
1465
1081
  updateTitle();
1466
1082
  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
1083
  let checkpointWrites = Promise.resolve();
1472
1084
  const persistCheckpoint = (nodeId, messages, state, meta) => {
1473
1085
  checkpointWrites = checkpointWrites
@@ -1476,18 +1088,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1476
1088
  await checkpointHealth.failed({ nodeId, generation: meta?.generation }, error);
1477
1089
  process.stderr.write(`Could not write the run checkpoint: ${error instanceof Error ? error.message : String(error)}\n`);
1478
1090
  });
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
1091
  return checkpointWrites;
1483
1092
  };
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
1093
  let previewInFlight = false;
1492
1094
  const tracedAdapter = (provider) => {
1493
1095
  if (provider.apiKey)
@@ -1500,11 +1102,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1500
1102
  return {
1501
1103
  ...(traced.listModels ? { listModels: (signal) => traced.listModels(signal) } : {}),
1502
1104
  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
1105
  const invocationId = request.context?.invocationId;
1509
1106
  const metered = meterStreamedRequest(request, terminal);
1510
1107
  const generate = async (call) => {
@@ -1521,8 +1118,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1521
1118
  return generate(metered);
1522
1119
  previewInFlight = true;
1523
1120
  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
1121
  try {
1527
1122
  return await generate({
1528
1123
  ...metered,
@@ -1538,14 +1133,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1538
1133
  };
1539
1134
  };
1540
1135
  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
1136
  const runResumed = () => runControl?.isPaused
1544
1137
  ? writeActivity(directory, 'awaiting-input', { kind: 'steering', detail: 'Paused - send a message in the terminal to steer the run', runId })
1545
1138
  : writeActivity(directory, 'running', { runId });
1546
1139
  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
1140
  timerResumePending = false;
1550
1141
  if (runControl) {
1551
1142
  runControl.yolo = state.yolo;
@@ -1561,10 +1152,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1561
1152
  void writeActivity(directory, 'running', { runId });
1562
1153
  });
1563
1154
  let liveCommands = Promise.resolve();
1155
+ const livePicker = new AbortController();
1564
1156
  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
1157
  if (!text.startsWith('/')) {
1569
1158
  void debugRecord('command.steer', { input: text });
1570
1159
  return runControl?.isPaused ? runControl.resume(text) : false;
@@ -1578,7 +1167,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1578
1167
  return true;
1579
1168
  }
1580
1169
  if (command === '/attach') {
1581
- // Mid-run, an attachment rides the next steer rather than a new task.
1582
1170
  void debugRecord('command.steer', { input: text });
1583
1171
  const argument = text.slice('/attach'.length).trim().replace(/^"(.*)"$/, '$1');
1584
1172
  const target = argument ? resolve(workspace, argument) : '';
@@ -1595,13 +1183,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1595
1183
  }
1596
1184
  const commandStartedAt = Date.now();
1597
1185
  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
1186
  liveCommands = liveCommands.then(async () => {
1601
1187
  if (command === '/browser') {
1602
1188
  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
1189
  if (exiting)
1606
1190
  await browserApp.close().catch(() => { });
1607
1191
  else {
@@ -1609,9 +1193,32 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1609
1193
  openBrowserUrl(browserApp.url);
1610
1194
  }
1611
1195
  }
1196
+ else if (text.trim() === '/permissions' && terminal) {
1197
+ const before = state.permissions;
1198
+ let picked;
1199
+ try {
1200
+ picked = await pickPermissionMode(state, terminal, livePicker.signal, { yieldToQuestions: true });
1201
+ }
1202
+ catch (error) {
1203
+ if (!(error instanceof Error && error.name === 'AbortError'))
1204
+ throw error;
1205
+ if (!livePicker.signal.aborted)
1206
+ print('Permissions unchanged: the run asked a question, so the picker closed. Type /permissions again afterwards.');
1207
+ }
1208
+ if (picked !== undefined && !livePicker.signal.aborted)
1209
+ await executeCommand(`/permissions ${picked}`, state, persistConfig);
1210
+ if (state.permissions !== before) {
1211
+ if (runControl) {
1212
+ runControl.yolo = state.yolo;
1213
+ runControl.permissions = state.permissions;
1214
+ }
1215
+ if (state.yolo)
1216
+ approvePending?.();
1217
+ print(`Permissions: ${permissionLabel(state.permissions ?? 'ask-for-approval')} (remembered for this workspace).`);
1218
+ refreshStatus();
1219
+ }
1220
+ }
1612
1221
  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
1222
  const commandState = command === '/usage' ? { ...state, usage: sessionUsage() } : command === '/jev' ? { ...state, running: true } : state;
1616
1223
  const result = await executeCommand(text, commandState, persistConfig);
1617
1224
  afterJevCommand(text, result);
@@ -1636,22 +1243,17 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1636
1243
  return true;
1637
1244
  });
1638
1245
  terminal?.startTask();
1639
- // A run's own preflight and teardown both change what the working tree holds.
1640
1246
  refreshPanelStatus(true);
1641
1247
  const retainedTodos = continuedTodos(task, state.lastRun);
1642
1248
  const todoStore = new TodoStore();
1643
1249
  if (retainedTodos.length)
1644
1250
  todoStore.update(retainedTodos);
1645
1251
  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
1252
  if (retainedTodos.length)
1649
1253
  terminal?.setTodos(retainedTodos);
1650
1254
  else
1651
1255
  terminal?.setTodos([]);
1652
1256
  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
1257
  terminal?.setSteering(true);
1656
1258
  const selected = config.providers.find(p => p.id === config.provider);
1657
1259
  const preflight = async (operation) => {
@@ -1672,10 +1274,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1672
1274
  };
1673
1275
  let mcp;
1674
1276
  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
1277
  const loadedGraph = startupGraph && !startupGraphReused && startupGraphSelection === (state.graph ?? 'default')
1680
1278
  ? (startupGraphReused = true, startupGraph)
1681
1279
  : await preflight(signal => loadGraph(state.graph ?? 'default', signal));
@@ -1687,8 +1285,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1687
1285
  onUsage: (delta, reference) => {
1688
1286
  const key = `${reference.provider}\0${reference.model}`;
1689
1287
  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
1288
  for (const field of ['requests', 'inputTokens', 'outputTokens', 'cacheRead', 'cacheWrite']) {
1693
1289
  const value = delta[field];
1694
1290
  if (typeof value === 'number')
@@ -1696,8 +1292,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1696
1292
  }
1697
1293
  probeModels.set(key, entry);
1698
1294
  },
1699
- // The probes are model calls this attempt pays for, so they belong in the trajectory
1700
- // beside the run's own calls.
1701
1295
  createAdapter: provider => tracedAdapter(provider),
1702
1296
  }));
1703
1297
  graphModelsHealthy = health.healthy;
@@ -1706,44 +1300,36 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1706
1300
  throw new Error(formatGraphHealthFailure(health));
1707
1301
  }
1708
1302
  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
1303
  Object.assign(telemetryHandle.dimensions, { graphId: runGraphSelection, ...graphShape(graph) });
1711
1304
  const startQueued = startTelemetry();
1712
1305
  if (!openRecordWritten)
1713
1306
  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
1307
  if (openRecordWritten) {
1719
1308
  await startQueued.catch(() => { });
1720
1309
  openRecord.telemetry = { ...openRecord.telemetry, ...graphShape(graph), startSent: telemetryHandle.started !== false };
1721
1310
  await writeOpenRunRecord(directory, openRecord).catch(() => { });
1722
1311
  }
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
1312
  await writeStudioRunSummary(directory, {
1727
1313
  id: runId, status: 'running', startedAt, graphSelection: runGraphSelection,
1728
1314
  ...(accountSubject ? { accountSubject } : {}),
1729
1315
  graph: { id: graph.id, revision: graph.revision }
1730
1316
  }).catch(() => { });
1731
1317
  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 }));
1318
+ const workspaceGuidance = await preflight(signal => loadWorkspaceInstructions(workspace, signal, systemPromptOverrideFor(graph, config.systemPromptOverride)));
1319
+ const invocations = isBuiltinSlashCommand(task) ? [] : await preflight(signal => resolveSkillInvocations(task, effectiveExtensionConfig(config, workspace), signal, directory));
1320
+ const runSkill = await preflight(signal => skillForRun({ invocations, home: directory, sessionId: savedSession?.id, config: effectiveExtensionConfig(config, workspace), signal }));
1739
1321
  if (runSkill.notice)
1740
1322
  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));
1323
+ const snapshot = await preflight(signal => extensionSnapshot(effectiveExtensionConfig(config, workspace), signal, directory, runSkill.skills?.map(skill => skill.id)));
1742
1324
  for (const notice of snapshot.notices)
1743
1325
  terminal ? terminal.print(notice) : process.stderr.write(safeTerminal(notice) + '\n');
1744
1326
  const instructions = `${workspaceGuidance}${snapshot.instructions}`;
1745
1327
  const resolvedModels = new Map();
1328
+ const runGoal = state.goal?.status === 'active' ? state.goal : undefined;
1329
+ let goalVerified = false;
1746
1330
  const onRunEvent = async (event) => {
1331
+ if (event.type === 'agent.completion.verified' && event.data.source === 'goal_verifier' && !event.data.subagentId)
1332
+ goalVerified = event.data.passed === true;
1747
1333
  if (!/reasoning|thinking\.delta/.test(event.type))
1748
1334
  browserBridge?.event(trajectory.sanitize(event));
1749
1335
  event = { ...event, data: { ...event.data, conversationId: savedSession?.id ?? trajectory.sessionId } };
@@ -1754,13 +1340,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1754
1340
  await appendRunEvent(directory, event);
1755
1341
  await trajectory.recordEvent(event);
1756
1342
  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
1343
  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
1344
  if (event.type === 'node.tool.started' || event.type === 'node.tool.completed' || event.type === 'node.tool.failed')
1765
1345
  refreshPanelStatus();
1766
1346
  if (terminal && event.type === 'graph.todos.updated') {
@@ -1778,8 +1358,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1778
1358
  if (entry) {
1779
1359
  if (terminal)
1780
1360
  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
1361
  else if (event.type === 'agent.message' && entry.detail)
1784
1362
  print(staticToolTimestamp(entry.detail, entry.toolCall));
1785
1363
  else
@@ -1816,7 +1394,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1816
1394
  }
1817
1395
  } };
1818
1396
  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
1397
  return mcpModule.connectMcpServers(snapshot.servers, extensionContext, message => terminal ? terminal.print(message) : process.stderr.write(safeTerminal(message) + '\n'), active.signal, { status: mcpModule.mcpTaskStatusReporter(configDirectory()) });
1821
1398
  }) : { tools: [], close: async () => { } };
1822
1399
  if (terminal) {
@@ -1834,14 +1411,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1834
1411
  }
1835
1412
  refreshStatus();
1836
1413
  }
1837
- // A cancelled metadata lookup must not create a graph run after preflight.
1838
1414
  active.signal.throwIfAborted();
1839
1415
  let membership = !jevOn() ? { paid: false } : await preflight(signal => getMembership(signal));
1840
1416
  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
1417
  membership = await preflight(signal => getMembership(signal));
1846
1418
  }
1847
1419
  if (jevOn() && !membership.subject) {
@@ -1859,7 +1431,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1859
1431
  const commandMemory = config.commandMemory === false ? undefined : await LocalToolMemory.open({ workspace, directory });
1860
1432
  const projectMemory = config.projectMemory === false ? undefined : await ProjectMemory.open({ home: directory, workspace });
1861
1433
  const execute = (options) => runGraph(graph, { ...options, runInput, runState, commandMemory, projectMemory, todoStore,
1862
- ...(runSkill.skill ? { inheritedSkills: [runSkill.skill.id], skillInvocationInstruction: runSkill.skill.instruction } : {}),
1434
+ ...(runSkill.skills?.length ? { inheritedSkills: runSkill.skills.map(skill => skill.id), skillInvocationInstruction: runSkill.instruction } : {}),
1863
1435
  resolveModel: (id, model) => {
1864
1436
  const provider = config.providers.find(item => item.id === id);
1865
1437
  if (!provider)
@@ -1885,8 +1457,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1885
1457
  },
1886
1458
  });
1887
1459
  const result = await execute({ task, runId, provider: selected.id, model: selected.model, ...(attachments ? { attachments } : {}),
1460
+ ...(runGoal ? { goalCompletionVerification: { goal: runGoal.text } } : {}),
1888
1461
  ...(config.efficiency ? { efficiency: config.efficiency } : {}),
1889
- // A `--model`/`--provider` flag is the user's choice; adaptive routing leaves it alone.
1462
+ ...(terminal ? {} : { toolProfile: isToolProfile(values.tools) ? values.tools : config.toolProfile }),
1890
1463
  modelPinned: Boolean(values.model || values.provider),
1891
1464
  configuredModels: config.providers.map(item => ({ id: item.id, model: item.model, ...(item.models ? { models: [...item.models] } : {}) })),
1892
1465
  onNodeCheckpoint: persistCheckpoint,
@@ -1896,43 +1469,20 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1896
1469
  activeUsage.outputTokens += usage.outputTokens;
1897
1470
  activeUsage.cacheRead += usage.cacheRead ?? 0;
1898
1471
  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
1472
  if (usage.inputTokens > 0) {
1907
1473
  contextUsedTokens = usage.inputTokens;
1908
1474
  runContext = { usedTokens: usage.inputTokens, ...(usage.cacheRead === undefined ? {} : { cacheRead: usage.cacheRead }) };
1909
1475
  }
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
1476
  terminal?.noteGeneratedTokens(usage.outputTokens, origin?.invocationId, origin?.final === true, usage.decodeMs);
1918
1477
  terminal?.setStatus(sessionUsage());
1919
1478
  },
1920
1479
  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
1480
  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
1481
  getSteeringMessages: terminal ? async () => {
1927
1482
  if (exiting)
1928
1483
  return [];
1929
1484
  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
1485
  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
1486
  const steered = terminal.takeSteeringTurns();
1937
1487
  const messages = [];
1938
1488
  for (const turn of steered) {
@@ -1946,8 +1496,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1946
1496
  attachmentSpools.add(root);
1947
1497
  steeredSpools.add(root);
1948
1498
  }
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
1499
  messages.push({ role: 'user', content: `${turn.text || ATTACHMENT_ONLY_TASK}\n\n${attachmentReferenceBlock(resolved.refs)}`, ...(resolved.images.length ? { images: resolved.images } : {}) });
1952
1500
  }
1953
1501
  catch (error) {
@@ -1958,9 +1506,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1958
1506
  return messages;
1959
1507
  } : undefined,
1960
1508
  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
1509
  automationDirectory: directory,
1965
1510
  wakeCarry: { provider: selected.id, model: selected.model, graph: runGraphSelection,
1966
1511
  ...(selected.reasoningEffort === undefined ? {} : { reasoningEffort: selected.reasoningEffort }) },
@@ -1982,11 +1527,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1982
1527
  await runResumed();
1983
1528
  }
1984
1529
  } : 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
1530
  approvePlan: terminal ? async () => {
1991
1531
  const saved = state.config.workspacePermissions?.[workspacePermissionKey(workspace)];
1992
1532
  const next = saved === 'ask-for-approval' || saved === 'approve-for-me' || saved === 'full-access' ? saved : 'ask-for-approval';
@@ -1996,7 +1536,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1996
1536
  runControl.yolo = state.yolo;
1997
1537
  runControl.permissions = state.permissions;
1998
1538
  }
1999
- // An editing mode by construction, so the index resumes if plan mode had suspended it.
2000
1539
  await state.codeIntel?.setPermissions(next);
2001
1540
  terminal.setStatus({ permissions: permissionLabel(state.permissions), ...sessionUsage() });
2002
1541
  return next;
@@ -2035,19 +1574,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2035
1574
  state.usage.outputTokens += result.usage.outputTokens;
2036
1575
  foldCache(state.usage, result.usage.cacheRead, result.usage.cacheWrite);
2037
1576
  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
1577
  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
1578
  const finishedRecord = { ...result, graphSelection: runGraphSelection,
2045
1579
  ...(accountSubject ? { accountSubject } : {}),
2046
1580
  ...(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
1581
  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
1582
  ...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
2052
1583
  ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }) };
2053
1584
  await writeFile(runRecordPath(directory, result.id, 'json'), JSON.stringify(finishedRecord, null, 2) + '\n', { mode: 0o600 });
@@ -2058,20 +1589,16 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2058
1589
  graph: { id: result.graph.id, revision: typeof result.graph.revision === 'number' ? result.graph.revision : undefined },
2059
1590
  toolCalls: result.toolCalls
2060
1591
  }).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
1592
  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.
1593
+ const goalMet = runGoal !== undefined && goalVerified && result.status === 'succeeded' && state.goal === runGoal;
1594
+ if (goalMet) {
1595
+ state.goal = metSessionGoal(runGoal);
1596
+ terminal?.setStatus({ goal: state.goal });
1597
+ }
2067
1598
  if (savedSession)
2068
1599
  savedSession = { ...savedSession, widgets: result.widgets, context: runContext };
2069
- // A finished run has nothing to resume: only stopped attempts keep a durable checkpoint.
2070
1600
  if (result.status === 'succeeded') {
2071
1601
  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
1602
  await Promise.all([...steeredSpools].map(root => rm(root, { recursive: true, force: true }).catch(() => { })));
2076
1603
  }
2077
1604
  if (values.json)
@@ -2079,8 +1606,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2079
1606
  else {
2080
1607
  const summary = result.completion?.summary ?? (result.status === 'cancelled' ? 'Cancelled.' : `The run did not finish: ${stopReasonPhrase(result.reason, result.limits)}.`);
2081
1608
  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
1609
  const entry = formatRunResult({ id: result.id, status: result.status, summary, tests: result.completion?.tests });
2085
1610
  terminal.print(entry.text, entry.detail, undefined, true);
2086
1611
  }
@@ -2091,38 +1616,28 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2091
1616
  print(` ${check}`);
2092
1617
  if (!terminal)
2093
1618
  print(`Run ${result.id} · ${result.status}`);
1619
+ if (goalMet)
1620
+ print(`Goal met: ${runGoal.text}`);
2094
1621
  }
2095
1622
  return terminated ? 143 : result.status === 'succeeded' ? 0 : result.status === 'cancelled' ? 130 : 1;
2096
1623
  }
2097
1624
  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
1625
  if (active?.signal.aborted) {
2103
1626
  await finalizeRunRecord('cancelled', 'the user stopped this run');
2104
1627
  rememberTurn(task, outcomeCompletion('cancelled', undefined, undefined), runId, attachments?.refs);
2105
1628
  return terminated ? 143 : 130;
2106
1629
  }
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
1630
  await finalizeRunRecord('infrastructure_error', error instanceof Error ? error.message : 'the run failed unexpectedly');
2110
1631
  rememberTurn(task, outcomeCompletion('infrastructure_error', error instanceof Error ? error.message : 'the run failed unexpectedly', undefined), runId, attachments?.refs);
2111
1632
  throw error;
2112
1633
  }
2113
1634
  finally {
2114
1635
  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
1636
  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.
1637
+ livePicker.abort();
2120
1638
  await checkpointWrites;
2121
1639
  await liveCommands;
2122
- // A crashed run's partial provider spend still happened: fold it into the session
2123
1640
  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
1641
  state.usage.requests += activeUsage.requests;
2127
1642
  state.usage.inputTokens += activeUsage.inputTokens;
2128
1643
  state.usage.outputTokens += activeUsage.outputTokens;
@@ -2130,10 +1645,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2130
1645
  activeUsage = { inputTokens: 0, outputTokens: 0, requests: 0, cacheRead: 0, cacheWrite: 0 };
2131
1646
  terminal?.finishTask();
2132
1647
  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
1648
  removeControlListener?.();
2138
1649
  runControl = undefined;
2139
1650
  approvePending = undefined;
@@ -2142,7 +1653,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2142
1653
  awaitingInput = 0;
2143
1654
  updateTitle(false);
2144
1655
  await settleRunRecord();
2145
- // Deliver what this run queued before the process leaves; a no-op while no endpoint exists.
2146
1656
  await telemetrySettled;
2147
1657
  await sessionStarted;
2148
1658
  await drainTelemetry(telemetrySurface);
@@ -2156,18 +1666,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2156
1666
  }
2157
1667
  await writeActivity(directory, 'idle');
2158
1668
  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
1669
  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
1670
  if (undelivered)
2166
1671
  terminal?.print(`Not delivered — the run had already finished: ${undelivered}`);
2167
1672
  }
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
1673
  for (const queued of timerSteering.splice(0))
2172
1674
  timerPending.push(queued);
2173
1675
  if (terminal)
@@ -2180,9 +1682,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2180
1682
  };
2181
1683
  try {
2182
1684
  if (values.prompt !== undefined) {
1685
+ enablePrivateRunTemp();
2183
1686
  if (!values.json)
2184
1687
  print(sessionDescription());
2185
- // Machine consumers keep stdout pure JSON, so the debug log location goes to stderr.
2186
1688
  else if (values.debug)
2187
1689
  process.stderr.write(safeTerminal(sessionDescription()) + '\n');
2188
1690
  const commandStartedAt = Date.now();
@@ -2195,6 +1697,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2195
1697
  throw error;
2196
1698
  }
2197
1699
  finally {
1700
+ removePrivateRunTemp();
2198
1701
  await debugRecord('command.completed', { input: values.prompt, mode: 'headless', durationMs: Date.now() - commandStartedAt });
2199
1702
  }
2200
1703
  }
@@ -2205,8 +1708,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2205
1708
  ...(savedSession ?? { version: 1, id: trajectory.sessionId, name: 'New CLI session', workspace, updatedAt: new Date(sessionStartedAt).toISOString(), history: [], usage: { ...state.usage } }),
2206
1709
  projectId: projectIdentity(workspace), contextHistory: structuredClone(state.history ?? []), history: sessionArchive, status: browserDraining || (browserPrompt && browserCancelPending) ? 'cancelling' : browserPrompt || (runControl && active) ? active?.signal.aborted ? 'cancelling' : 'running' : 'idle', prompt: browserPrompt, events: [], pending: runControl && active && !active.signal.aborted ? terminal.browserQuestion() : undefined, permissions: state.permissions, provider: config.provider, model: config.providers.find(item => item.id === config.provider)?.model, graph: state.graph,
2207
1710
  };
2208
- // The authenticated bridge also persists this snapshot. Preserve canonical
2209
- // routing/storage metadata; the server separately redacts public paths.
2210
1711
  return { ...trajectory.sanitize(snapshot), id: snapshot.id, parentId: snapshot.parentId, workspace: snapshot.workspace, updatedAt: snapshot.updatedAt, status: snapshot.status };
2211
1712
  }, {
2212
1713
  prompt: async (text) => {
@@ -2215,7 +1716,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2215
1716
  if (browserRollbackFailed)
2216
1717
  throw new Error(rollbackFailureMessage);
2217
1718
  text = text.trim();
2218
- if (text.startsWith('/') && (isBuiltinSlashCommand(text) || !await resolveSkillInvocation(text, config, undefined, directory)))
1719
+ if (text.startsWith('/') && (isBuiltinSlashCommand(text) || !(await resolveSkillInvocations(text, effectiveExtensionConfig(config, workspace), undefined, directory)).length))
2219
1720
  throw new Error('Run built-in slash commands in the terminal, or invoke an enabled skill as /skillname.');
2220
1721
  if (!config.providers.length)
2221
1722
  throw new Error('Add a provider in /providers before starting a task.');
@@ -2225,19 +1726,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2225
1726
  browserPrompt = text;
2226
1727
  if (!savedSession)
2227
1728
  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
1729
  else
2232
1730
  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
1731
  const record = { projectId: projectIdentity(workspace), ...savedSession, history: sessionArchive, contextHistory: state.history ?? [] };
2236
1732
  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
1733
  active = undefined;
2242
1734
  browserPrompt = undefined;
2243
1735
  browserSteering.length = 0;
@@ -2247,9 +1739,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2247
1739
  if (previousSession)
2248
1740
  await browserBridge.persist(() => sessions.save(previousSession));
2249
1741
  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
1742
  const cleanup = await Promise.allSettled([
2254
1743
  rm(join(directory, 'browser-history', `${record.id}.json`), { force: true }),
2255
1744
  rm(join(directory, 'sessions', `${record.id}.json`), { force: true }),
@@ -2260,14 +1749,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2260
1749
  }
2261
1750
  }
2262
1751
  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
1752
  browserRollbackFailed = true;
2267
1753
  const cleanup = await Promise.allSettled([
2268
1754
  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
1755
  ...(!previousSession ? [rm(join(directory, 'sessions', `${record.id}.json`), { force: true })] : []),
2272
1756
  ]);
2273
1757
  const failures = cleanup.filter(result => result.status === 'rejected');
@@ -2281,11 +1765,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2281
1765
  return accepted;
2282
1766
  },
2283
1767
  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
1768
  if (browserDraining || active?.signal.aborted || (!browserPrompt && (!runControl || !active)))
2290
1769
  throw new Error('No task is accepting steering; return to the terminal prompt first.');
2291
1770
  if (runControl?.isPaused)
@@ -2294,10 +1773,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2294
1773
  browserSteering.push(text);
2295
1774
  },
2296
1775
  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
1776
  if (!active && browserPrompt) {
2302
1777
  browserCancelPending = true;
2303
1778
  return;
@@ -2307,21 +1782,15 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2307
1782
  active.abort(new Error('Cancelled from browser'));
2308
1783
  },
2309
1784
  answer: answer => {
2310
- // Configuration wizards also ask terminal questions, but only live
2311
- // graph questions and approvals belong to the browser runtime controls.
2312
1785
  if (!runControl || !active || active.signal.aborted)
2313
1786
  throw new Error('No task is accepting answers; return to the terminal prompt first.');
2314
1787
  terminal.resolveQuestion(answer);
2315
1788
  },
2316
1789
  });
2317
1790
  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
1791
  if (values.debug)
2321
1792
  print(sessionDescription());
2322
1793
  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
1794
  const startupCheckController = new AbortController();
2326
1795
  startupGraphCheck = {
2327
1796
  controller: startupCheckController,
@@ -2331,10 +1800,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2331
1800
  }),
2332
1801
  };
2333
1802
  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
1803
  let lastInputAt = Date.now();
2339
1804
  const noteInput = () => { lastInputAt = Date.now(); };
2340
1805
  process.stdin.on('data', noteInput);
@@ -2348,9 +1813,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2348
1813
  try {
2349
1814
  const asked = terminal.question('Describe a task, or type /help', { conversationPrompt: true });
2350
1815
  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
1816
  deliverTimerPrompts();
2355
1817
  line = (await asked).trim();
2356
1818
  }
@@ -2358,21 +1820,16 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2358
1820
  break;
2359
1821
  }
2360
1822
  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
1823
  if (!(terminal?.hasQueuedAttachments() ?? false))
2364
1824
  continue;
2365
1825
  line = ATTACHMENT_ONLY_TASK;
2366
1826
  }
2367
- // Every command and task below assumes the startup check is no longer touching the graph,
2368
- // `active` or the footer.
2369
1827
  await settleStartupGraphCheck();
2370
1828
  const commandStartedAt = Date.now();
2371
1829
  await debugRecord('command.started', { input: line, mode: 'interactive' });
2372
1830
  try {
2373
1831
  if (line === '/browser') {
2374
1832
  browserApp ??= await startBrowserServer();
2375
- // A pending startup can outlive teardown; close instead of opening.
2376
1833
  if (exiting)
2377
1834
  await browserApp.close().catch(() => { });
2378
1835
  else {
@@ -2392,54 +1849,33 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2392
1849
  const record = records.find(item => item.id === selected);
2393
1850
  if (!record || record.id === savedSession?.id)
2394
1851
  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
1852
  if (!canExtendLineage(record.ancestors)) {
2400
1853
  throw new Error('This session has been resumed too many times to keep its lineage, so it cannot be resumed again.');
2401
1854
  }
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
1855
  const abandonedTimers = sessionTimers.list().length + timerPending.length + timerSteering.length;
2406
1856
  sessionTimers.clear();
2407
1857
  timerPending.length = 0;
2408
1858
  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
1859
  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
1860
  savedSession = { ...resumedRecord, id: randomUUID(), parentId: record.id,
2419
1861
  ancestors: lineageThrough(record.ancestors, record.id), inheritedUsage: { ...record.usage },
2420
1862
  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
1863
  await openSessionTrajectory(savedSession.id);
2424
- // The resumed conversation keeps following the skill its source was.
2425
1864
  await copySessionSkill(directory, record.id, savedSession.id).catch(() => { });
2426
1865
  await trajectory.record('session.resumed', { resumedSessionId: savedSession.id, sourceSessionId: record.id });
2427
1866
  sessionArchive = structuredClone(record.history);
2428
1867
  state.history = structuredClone(record.contextHistory ?? record.history).slice(-6);
2429
1868
  state.usage = { ...record.usage };
1869
+ state.goal = record.goal ? { ...record.goal } : undefined;
1870
+ terminal.setStatus({ goal: state.goal });
2430
1871
  terminal.resetDashboardSession(record.usage);
2431
1872
  delete state.lastRun;
2432
1873
  contextUsedTokens = compactedContextEstimate(state.history);
2433
1874
  sessionContexts.clear();
2434
1875
  terminal.clearConversation();
2435
1876
  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
1877
  for (const turn of displayHistory(sessionArchive)) {
2440
1878
  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
1879
  const answer = formatAnswer(turn.completion.summary);
2444
1880
  terminal.print(answer.text, answer.detail, undefined, true);
2445
1881
  }
@@ -2453,8 +1889,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2453
1889
  continue;
2454
1890
  }
2455
1891
  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
1892
  const argument = line.slice('/attach'.length).trim().replace(/^"(.*)"$/, '$1');
2459
1893
  if (!argument) {
2460
1894
  print('Usage: /attach <path> — queue a file or folder with your next task. Large pastes and dropped files attach automatically.');
@@ -2497,11 +1931,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2497
1931
  terminal.printPrompt(line);
2498
1932
  else
2499
1933
  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.
1934
+ const skillInvocations = line.startsWith('/') && !isBuiltinSlashCommand(line)
1935
+ ? await resolveSkillInvocations(line, effectiveExtensionConfig(config, workspace), undefined, directory) : [];
1936
+ if (line.startsWith('/') && !skillInvocations.length) {
2505
1937
  if (/^\/skill(?:\s|$)/.test(line.trim())) {
2506
1938
  print(await sessionSkillCommand(directory, savedSession?.id, line));
2507
1939
  continue;
@@ -2527,9 +1959,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2527
1959
  if (/^\/graph(?:\s|$)|^\/(?:auth\s+)?logout\s*$/.test(line) || command.clear && /^\/(providers|model)(?:\s|$)/.test(line))
2528
1960
  await refreshGraphStatus();
2529
1961
  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
1962
  if (command.resetScreen)
2534
1963
  terminal?.clearConversation();
2535
1964
  if (command.text)
@@ -2543,13 +1972,10 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2543
1972
  browserBridge?.startRun();
2544
1973
  terminal?.setStatus({ contextUsed: 0 });
2545
1974
  }
2546
- // A cleared conversation starts over, without the skill the old one was following.
2547
1975
  if (line.trim() === '/clear' && savedSession)
2548
1976
  await removeSessionSkill(directory, savedSession.id).catch(() => { });
2549
1977
  if (command.compact && state.history?.length) {
2550
1978
  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
1979
  contextUsedTokens = compactedContextEstimate(state.history);
2554
1980
  terminal?.setStatus({ contextUsed: contextUsedTokens });
2555
1981
  }
@@ -2562,9 +1988,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2562
1988
  const adapter = createAdapter(config.providers.find(p => p.id === config.provider));
2563
1989
  if (!adapter.listModels)
2564
1990
  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
1991
  else
2569
1992
  print((await adapter.listModels(active.signal)).join('\n'));
2570
1993
  }
@@ -2590,11 +2013,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2590
2013
  }
2591
2014
  finally {
2592
2015
  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
2016
  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
2017
  () => {
2599
2018
  panelReads.abort();
2600
2019
  if (terminalsTimer)
@@ -2608,8 +2027,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2608
2027
  () => browserBridge?.close(),
2609
2028
  () => tabTitle.close(),
2610
2029
  () => 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
2030
  () => sessionStarted,
2614
2031
  () => trajectory.flush(),
2615
2032
  () => { if (accountPolling)
@@ -2619,7 +2036,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2619
2036
  () => graphEditor.close(),
2620
2037
  () => codeIntel.dispose(),
2621
2038
  () => modelHealth.flush(),
2622
- // QA dev servers are owned by this CLI session.
2623
2039
  () => Promise.all([disposeAllQaProcesses(), disposeAllQaPtys(), disposePooledPowerShell()]).catch(() => { }),
2624
2040
  ]) {
2625
2041
  try {
@@ -2629,9 +2045,6 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2629
2045
  cleanupErrors.push(error);
2630
2046
  }
2631
2047
  }
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
2048
  if (killBackstop) {
2636
2049
  clearTimeout(killBackstop);
2637
2050
  killBackstop = undefined;
@@ -2646,13 +2059,6 @@ if (process.argv[1] && await realpath(fileURLToPath(import.meta.url)) === await
2646
2059
  process.exitCode = 1;
2647
2060
  });
2648
2061
  }
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
2062
  export function subagentExitCode(outcome, signals) {
2657
2063
  if (signals.interrupted)
2658
2064
  return 130;
@@ -2664,26 +2070,12 @@ export function subagentExitCode(outcome, signals) {
2664
2070
  return 143;
2665
2071
  return 1;
2666
2072
  }
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
2073
  async function runSubagentCommand(argv) {
2677
2074
  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
2075
  const fail = (code, message, extra = {}, exit = 1) => {
2681
2076
  process.stdout.write(JSON.stringify({ ok: false, error: { code, message, ...extra } }) + '\n');
2682
2077
  return exit;
2683
2078
  };
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
2079
  const valued = new Set(['--prompt', '-p', '--provider', '--model', '--cwd']);
2688
2080
  for (let index = 0; index < argv.length; index += 1) {
2689
2081
  const argument = argv[index];
@@ -2706,10 +2098,6 @@ async function runSubagentCommand(argv) {
2706
2098
  } }));
2707
2099
  }
2708
2100
  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
2101
  fail('INVALID_ARGUMENTS', error instanceof Error ? error.message : String(error));
2714
2102
  return 1;
2715
2103
  }
@@ -2727,9 +2115,6 @@ async function runSubagentCommand(argv) {
2727
2115
  fail('INVALID_ARGUMENTS', 'andorra subagent requires --prompt "task".');
2728
2116
  return 1;
2729
2117
  }
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
2118
  if (values.prompt.length > MAX_SUBAGENT_TASK_CHARS) {
2734
2119
  fail('INVALID_ARGUMENTS', `The task must be at most ${MAX_SUBAGENT_TASK_CHARS} characters.`);
2735
2120
  return 1;
@@ -2740,10 +2125,6 @@ async function runSubagentCommand(argv) {
2740
2125
  const cancel = () => { runner.cancel(); };
2741
2126
  const onInterrupt = () => { interrupted = true; cancel(); };
2742
2127
  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
2128
  process.once('SIGINT', onInterrupt);
2748
2129
  process.once('SIGTERM', onTerminate);
2749
2130
  try {
@@ -2754,8 +2135,6 @@ async function runSubagentCommand(argv) {
2754
2135
  throw new Error('--cwd must be a directory');
2755
2136
  }
2756
2137
  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
2138
  const signalled = subagentExitCode({ status: 'infrastructure_error' }, { interrupted, terminated });
2760
2139
  if (signalled !== 1) {
2761
2140
  return fail(interrupted ? 'CANCELLED' : 'TERMINATED', interrupted ? 'The run was interrupted before it started.' : 'The run was terminated before it started.', {}, signalled);
@@ -2763,22 +2142,11 @@ async function runSubagentCommand(argv) {
2763
2142
  fail('INVALID_ARGUMENTS', error instanceof Error ? error.message : String(error));
2764
2143
  return 1;
2765
2144
  }
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
2145
  try {
2774
2146
  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
2147
  await reportInterruptedRuns({ home: configDirectory(), surface: configuredSurface('subagent') }, recovered.interrupted);
2778
2148
  }
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.
2149
+ catch { }
2782
2150
  const signalled = subagentExitCode({ status: 'infrastructure_error' }, { interrupted, terminated });
2783
2151
  if (signalled !== 1) {
2784
2152
  return fail(interrupted ? 'CANCELLED' : 'TERMINATED', interrupted ? 'The run was interrupted before it started.' : 'The run was terminated before it started.', {}, signalled);
@@ -2794,18 +2162,11 @@ async function runSubagentCommand(argv) {
2794
2162
  while (outcome.state === 'running')
2795
2163
  outcome = await runner.result(60_000);
2796
2164
  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
2165
  return subagentExitCode(outcome, { interrupted, terminated });
2801
2166
  }
2802
2167
  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
2168
  const signalled = subagentExitCode({ status: 'infrastructure_error' }, { interrupted, terminated });
2806
2169
  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
2170
  return fail(interrupted ? 'CANCELLED' : 'TERMINATED', interrupted ? 'The run was interrupted before it started.' : 'The run was terminated before it started.', {}, signalled);
2810
2171
  }
2811
2172
  if (error instanceof SubagentProviderNotSetError)
@@ -2819,8 +2180,6 @@ async function runSubagentCommand(argv) {
2819
2180
  return fail('SUBAGENT_FAILED', error instanceof Error ? error.message : String(error));
2820
2181
  }
2821
2182
  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
2183
  process.removeListener('SIGINT', onInterrupt);
2825
2184
  process.removeListener('SIGTERM', onTerminate);
2826
2185
  }