@oh-my-pi-zen/pi-coding-agent 16.3.6-zen.1

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 (2454) hide show
  1. package/CHANGELOG.md +13088 -0
  2. package/README.md +35 -0
  3. package/dist/cli.js +22542 -0
  4. package/dist/types/advisor/__tests__/advisor.test.d.ts +1 -0
  5. package/dist/types/advisor/__tests__/config.test.d.ts +1 -0
  6. package/dist/types/advisor/__tests__/emission-guard.test.d.ts +1 -0
  7. package/dist/types/advisor/advise-tool.d.ts +106 -0
  8. package/dist/types/advisor/config.d.ts +90 -0
  9. package/dist/types/advisor/emission-guard.d.ts +73 -0
  10. package/dist/types/advisor/index.d.ts +6 -0
  11. package/dist/types/advisor/runtime.d.ts +76 -0
  12. package/dist/types/advisor/transcript-recorder.d.ts +63 -0
  13. package/dist/types/advisor/watchdog.d.ts +38 -0
  14. package/dist/types/async/index.d.ts +1 -0
  15. package/dist/types/async/job-manager.d.ts +121 -0
  16. package/dist/types/auto-thinking/classifier.d.ts +37 -0
  17. package/dist/types/autolearn/controller.d.ts +25 -0
  18. package/dist/types/autolearn/managed-skills.d.ts +45 -0
  19. package/dist/types/autoresearch/dashboard.d.ts +4 -0
  20. package/dist/types/autoresearch/git.d.ts +36 -0
  21. package/dist/types/autoresearch/helpers.d.ts +24 -0
  22. package/dist/types/autoresearch/index.d.ts +2 -0
  23. package/dist/types/autoresearch/state.d.ts +17 -0
  24. package/dist/types/autoresearch/storage.d.ts +142 -0
  25. package/dist/types/autoresearch/tools/init-experiment.d.ts +27 -0
  26. package/dist/types/autoresearch/tools/log-experiment.d.ts +21 -0
  27. package/dist/types/autoresearch/tools/run-experiment.d.ts +7 -0
  28. package/dist/types/autoresearch/tools/update-notes.d.ts +11 -0
  29. package/dist/types/autoresearch/types.d.ts +154 -0
  30. package/dist/types/capability/context-file.d.ts +17 -0
  31. package/dist/types/capability/extension-module.d.ts +15 -0
  32. package/dist/types/capability/extension.d.ts +28 -0
  33. package/dist/types/capability/fs.d.ts +20 -0
  34. package/dist/types/capability/hook.d.ts +19 -0
  35. package/dist/types/capability/index.d.ts +80 -0
  36. package/dist/types/capability/instruction.d.ts +17 -0
  37. package/dist/types/capability/mcp.d.ts +47 -0
  38. package/dist/types/capability/prompt.d.ts +15 -0
  39. package/dist/types/capability/rule-buckets.d.ts +30 -0
  40. package/dist/types/capability/rule.d.ts +73 -0
  41. package/dist/types/capability/settings.d.ts +15 -0
  42. package/dist/types/capability/skill.d.ts +43 -0
  43. package/dist/types/capability/slash-command.d.ts +17 -0
  44. package/dist/types/capability/ssh.d.ts +23 -0
  45. package/dist/types/capability/system-prompt.d.ts +15 -0
  46. package/dist/types/capability/tool.d.ts +19 -0
  47. package/dist/types/capability/types.d.ts +154 -0
  48. package/dist/types/cli/agents-cli.d.ts +12 -0
  49. package/dist/types/cli/args.d.ts +77 -0
  50. package/dist/types/cli/auth-broker-cli.d.ts +25 -0
  51. package/dist/types/cli/auth-gateway-cli.d.ts +26 -0
  52. package/dist/types/cli/bench-cli.d.ts +85 -0
  53. package/dist/types/cli/classify-install-target.d.ts +12 -0
  54. package/dist/types/cli/claude-trace-cli.d.ts +54 -0
  55. package/dist/types/cli/commands/init-xdg.d.ts +1 -0
  56. package/dist/types/cli/completion-gen.d.ts +80 -0
  57. package/dist/types/cli/config-cli.d.ts +22 -0
  58. package/dist/types/cli/dry-balance-cli.d.ts +113 -0
  59. package/dist/types/cli/extension-flags.d.ts +36 -0
  60. package/dist/types/cli/file-processor.d.ts +11 -0
  61. package/dist/types/cli/flag-tables.d.ts +144 -0
  62. package/dist/types/cli/gallery-cli.d.ts +49 -0
  63. package/dist/types/cli/gallery-fixtures/agentic.d.ts +2 -0
  64. package/dist/types/cli/gallery-fixtures/codeintel.d.ts +3 -0
  65. package/dist/types/cli/gallery-fixtures/edit.d.ts +3 -0
  66. package/dist/types/cli/gallery-fixtures/fs.d.ts +2 -0
  67. package/dist/types/cli/gallery-fixtures/index.d.ts +4 -0
  68. package/dist/types/cli/gallery-fixtures/interaction.d.ts +3 -0
  69. package/dist/types/cli/gallery-fixtures/memory.d.ts +2 -0
  70. package/dist/types/cli/gallery-fixtures/misc.d.ts +3 -0
  71. package/dist/types/cli/gallery-fixtures/search.d.ts +3 -0
  72. package/dist/types/cli/gallery-fixtures/shell.d.ts +3 -0
  73. package/dist/types/cli/gallery-fixtures/types.d.ts +55 -0
  74. package/dist/types/cli/gallery-fixtures/web.d.ts +2 -0
  75. package/dist/types/cli/gallery-screenshot.d.ts +35 -0
  76. package/dist/types/cli/gc-cli.d.ts +58 -0
  77. package/dist/types/cli/grep-cli.d.ts +17 -0
  78. package/dist/types/cli/grievances-cli.d.ts +37 -0
  79. package/dist/types/cli/initial-message.d.ts +17 -0
  80. package/dist/types/cli/models-cli.d.ts +49 -0
  81. package/dist/types/cli/plugin-cli.d.ts +32 -0
  82. package/dist/types/cli/profile-alias.d.ts +29 -0
  83. package/dist/types/cli/profile-bootstrap.d.ts +55 -0
  84. package/dist/types/cli/read-cli.d.ts +4 -0
  85. package/dist/types/cli/session-picker.d.ts +11 -0
  86. package/dist/types/cli/setup-cli.d.ts +24 -0
  87. package/dist/types/cli/setup-model-picker.d.ts +14 -0
  88. package/dist/types/cli/shell-cli.d.ts +8 -0
  89. package/dist/types/cli/ssh-cli.d.ts +21 -0
  90. package/dist/types/cli/startup-cwd.d.ts +2 -0
  91. package/dist/types/cli/stats-cli.d.ts +17 -0
  92. package/dist/types/cli/tiny-models-cli.d.ts +11 -0
  93. package/dist/types/cli/ttsr-cli.d.ts +39 -0
  94. package/dist/types/cli/update-cli.d.ts +106 -0
  95. package/dist/types/cli/update-cli.test.d.ts +1 -0
  96. package/dist/types/cli/usage-cli.d.ts +95 -0
  97. package/dist/types/cli/web-search-cli.d.ts +20 -0
  98. package/dist/types/cli/worktree-cli.d.ts +26 -0
  99. package/dist/types/cli-commands.d.ts +33 -0
  100. package/dist/types/cli.d.ts +3 -0
  101. package/dist/types/collab/crypto.d.ts +7 -0
  102. package/dist/types/collab/display-name.d.ts +3 -0
  103. package/dist/types/collab/guest.d.ts +52 -0
  104. package/dist/types/collab/host.d.ts +43 -0
  105. package/dist/types/collab/protocol.d.ts +143 -0
  106. package/dist/types/collab/relay-client.d.ts +22 -0
  107. package/dist/types/collab/replication-shrink.d.ts +39 -0
  108. package/dist/types/commands/acp.d.ts +12 -0
  109. package/dist/types/commands/agents.d.ts +34 -0
  110. package/dist/types/commands/auth-broker.d.ts +54 -0
  111. package/dist/types/commands/auth-gateway.d.ts +35 -0
  112. package/dist/types/commands/bench.d.ts +37 -0
  113. package/dist/types/commands/commit.d.ts +27 -0
  114. package/dist/types/commands/complete.d.ts +6 -0
  115. package/dist/types/commands/completions.d.ts +13 -0
  116. package/dist/types/commands/config.d.ts +30 -0
  117. package/dist/types/commands/dry-balance.d.ts +31 -0
  118. package/dist/types/commands/gallery.d.ts +47 -0
  119. package/dist/types/commands/gc.d.ts +37 -0
  120. package/dist/types/commands/grep.d.ts +42 -0
  121. package/dist/types/commands/grievances.d.ts +40 -0
  122. package/dist/types/commands/install.d.ts +51 -0
  123. package/dist/types/commands/join.d.ts +12 -0
  124. package/dist/types/commands/launch.d.ts +148 -0
  125. package/dist/types/commands/models.d.ts +33 -0
  126. package/dist/types/commands/plugin.d.ts +52 -0
  127. package/dist/types/commands/read.d.ts +15 -0
  128. package/dist/types/commands/say.d.ts +24 -0
  129. package/dist/types/commands/setup.d.ts +34 -0
  130. package/dist/types/commands/shell.d.ts +21 -0
  131. package/dist/types/commands/ssh.d.ts +48 -0
  132. package/dist/types/commands/stats.d.ts +25 -0
  133. package/dist/types/commands/tiny-models.d.ts +22 -0
  134. package/dist/types/commands/token.d.ts +34 -0
  135. package/dist/types/commands/ttsr.d.ts +57 -0
  136. package/dist/types/commands/update.d.ts +25 -0
  137. package/dist/types/commands/usage.d.ts +34 -0
  138. package/dist/types/commands/web-search.d.ts +33 -0
  139. package/dist/types/commands/worktree.d.ts +31 -0
  140. package/dist/types/commit/agentic/agent.d.ts +31 -0
  141. package/dist/types/commit/agentic/fallback.d.ts +5 -0
  142. package/dist/types/commit/agentic/index.d.ts +2 -0
  143. package/dist/types/commit/agentic/state.d.ts +58 -0
  144. package/dist/types/commit/agentic/tools/analyze-file.d.ts +18 -0
  145. package/dist/types/commit/agentic/tools/git-file-diff.d.ts +9 -0
  146. package/dist/types/commit/agentic/tools/git-hunk.d.ts +8 -0
  147. package/dist/types/commit/agentic/tools/git-overview.d.ts +8 -0
  148. package/dist/types/commit/agentic/tools/index.d.ts +16 -0
  149. package/dist/types/commit/agentic/tools/propose-changelog.d.ts +27 -0
  150. package/dist/types/commit/agentic/tools/propose-commit.d.ts +15 -0
  151. package/dist/types/commit/agentic/tools/recent-commits.d.ts +6 -0
  152. package/dist/types/commit/agentic/tools/schemas.d.ts +6 -0
  153. package/dist/types/commit/agentic/tools/split-commit.d.ts +32 -0
  154. package/dist/types/commit/agentic/topo-sort.d.ts +4 -0
  155. package/dist/types/commit/agentic/trivial.d.ts +7 -0
  156. package/dist/types/commit/agentic/validation.d.ts +20 -0
  157. package/dist/types/commit/analysis/conventional.d.ts +22 -0
  158. package/dist/types/commit/analysis/index.d.ts +4 -0
  159. package/dist/types/commit/analysis/scope.d.ts +6 -0
  160. package/dist/types/commit/analysis/summary.d.ts +19 -0
  161. package/dist/types/commit/analysis/validation.d.ts +8 -0
  162. package/dist/types/commit/changelog/detect.d.ts +2 -0
  163. package/dist/types/commit/changelog/generate.d.ts +29 -0
  164. package/dist/types/commit/changelog/index.d.ts +30 -0
  165. package/dist/types/commit/changelog/parse.d.ts +2 -0
  166. package/dist/types/commit/cli.d.ts +3 -0
  167. package/dist/types/commit/git/diff.d.ts +5 -0
  168. package/dist/types/commit/index.d.ts +4 -0
  169. package/dist/types/commit/map-reduce/index.d.ts +28 -0
  170. package/dist/types/commit/map-reduce/map-phase.d.ts +17 -0
  171. package/dist/types/commit/map-reduce/reduce-phase.d.ts +13 -0
  172. package/dist/types/commit/map-reduce/utils.d.ts +2 -0
  173. package/dist/types/commit/message.d.ts +2 -0
  174. package/dist/types/commit/model-selection.d.ts +26 -0
  175. package/dist/types/commit/pipeline.d.ts +5 -0
  176. package/dist/types/commit/shared-llm.d.ts +27 -0
  177. package/dist/types/commit/types.d.ts +78 -0
  178. package/dist/types/commit/utils/exclusions.d.ts +4 -0
  179. package/dist/types/commit/utils.d.ts +20 -0
  180. package/dist/types/config/api-key-resolver.d.ts +43 -0
  181. package/dist/types/config/append-only-context-mode.d.ts +9 -0
  182. package/dist/types/config/config-file.d.ts +62 -0
  183. package/dist/types/config/file-lock.d.ts +29 -0
  184. package/dist/types/config/inline-tool-descriptors-mode.d.ts +12 -0
  185. package/dist/types/config/keybindings.d.ts +362 -0
  186. package/dist/types/config/model-discovery.d.ts +68 -0
  187. package/dist/types/config/model-registry.d.ts +251 -0
  188. package/dist/types/config/model-resolver.d.ts +300 -0
  189. package/dist/types/config/model-roles.d.ts +29 -0
  190. package/dist/types/config/models-config-schema.d.ts +697 -0
  191. package/dist/types/config/models-config.d.ts +436 -0
  192. package/dist/types/config/prompt-templates.d.ts +32 -0
  193. package/dist/types/config/provider-globals.d.ts +7 -0
  194. package/dist/types/config/resolve-config-value.d.ts +17 -0
  195. package/dist/types/config/service-tier.d.ts +49 -0
  196. package/dist/types/config/settings-schema.d.ts +5668 -0
  197. package/dist/types/config/settings.d.ts +181 -0
  198. package/dist/types/config.d.ts +92 -0
  199. package/dist/types/cursor.d.ts +22 -0
  200. package/dist/types/dap/client.d.ts +46 -0
  201. package/dist/types/dap/config.d.ts +19 -0
  202. package/dist/types/dap/index.d.ts +4 -0
  203. package/dist/types/dap/session.d.ts +108 -0
  204. package/dist/types/dap/types.d.ts +534 -0
  205. package/dist/types/debug/index.d.ts +15 -0
  206. package/dist/types/debug/log-formatting.d.ts +4 -0
  207. package/dist/types/debug/log-viewer.d.ts +69 -0
  208. package/dist/types/debug/profiler.d.ts +24 -0
  209. package/dist/types/debug/protocol-probe.d.ts +38 -0
  210. package/dist/types/debug/raw-sse-buffer.d.ts +44 -0
  211. package/dist/types/debug/raw-sse.d.ts +19 -0
  212. package/dist/types/debug/remote-debugger.d.ts +45 -0
  213. package/dist/types/debug/report-bundle.d.ts +58 -0
  214. package/dist/types/debug/system-info.d.ts +26 -0
  215. package/dist/types/debug/terminal-info.d.ts +33 -0
  216. package/dist/types/discovery/agents-md.d.ts +1 -0
  217. package/dist/types/discovery/agents.d.ts +12 -0
  218. package/dist/types/discovery/at-imports.d.ts +15 -0
  219. package/dist/types/discovery/builtin-defaults.d.ts +1 -0
  220. package/dist/types/discovery/builtin-rules/index.d.ts +7 -0
  221. package/dist/types/discovery/builtin.d.ts +1 -0
  222. package/dist/types/discovery/claude-plugins.d.ts +1 -0
  223. package/dist/types/discovery/claude.d.ts +1 -0
  224. package/dist/types/discovery/cline.d.ts +1 -0
  225. package/dist/types/discovery/codex.d.ts +1 -0
  226. package/dist/types/discovery/cursor.d.ts +16 -0
  227. package/dist/types/discovery/gemini.d.ts +1 -0
  228. package/dist/types/discovery/github.d.ts +1 -0
  229. package/dist/types/discovery/helpers.d.ts +278 -0
  230. package/dist/types/discovery/index.d.ts +53 -0
  231. package/dist/types/discovery/mcp-json.d.ts +1 -0
  232. package/dist/types/discovery/omp-extension-roots.d.ts +43 -0
  233. package/dist/types/discovery/omp-plugins.d.ts +1 -0
  234. package/dist/types/discovery/opencode.d.ts +1 -0
  235. package/dist/types/discovery/plugin-dir-roots.d.ts +15 -0
  236. package/dist/types/discovery/ssh.d.ts +1 -0
  237. package/dist/types/discovery/substitute-plugin-root.d.ts +1 -0
  238. package/dist/types/discovery/vscode.d.ts +1 -0
  239. package/dist/types/discovery/windsurf.d.ts +13 -0
  240. package/dist/types/edit/apply-patch/index.d.ts +35 -0
  241. package/dist/types/edit/apply-patch/parser.d.ts +34 -0
  242. package/dist/types/edit/diff.d.ts +60 -0
  243. package/dist/types/edit/file-snapshot-store.d.ts +74 -0
  244. package/dist/types/edit/hashline/block-resolver.d.ts +9 -0
  245. package/dist/types/edit/hashline/diff.d.ts +29 -0
  246. package/dist/types/edit/hashline/execute.d.ts +28 -0
  247. package/dist/types/edit/hashline/filesystem.d.ts +43 -0
  248. package/dist/types/edit/hashline/index.d.ts +5 -0
  249. package/dist/types/edit/hashline/noop-loop-guard.d.ts +72 -0
  250. package/dist/types/edit/hashline/params.d.ts +4 -0
  251. package/dist/types/edit/index.d.ts +83 -0
  252. package/dist/types/edit/modes/apply-patch.d.ts +23 -0
  253. package/dist/types/edit/modes/patch.d.ts +101 -0
  254. package/dist/types/edit/modes/replace.d.ts +141 -0
  255. package/dist/types/edit/normalize.d.ts +31 -0
  256. package/dist/types/edit/notebook.d.ts +23 -0
  257. package/dist/types/edit/read-file.d.ts +2 -0
  258. package/dist/types/edit/renderer.d.ts +118 -0
  259. package/dist/types/edit/snapshot-details.d.ts +33 -0
  260. package/dist/types/edit/streaming.d.ts +105 -0
  261. package/dist/types/eval/__tests__/agent-bridge.test.d.ts +1 -0
  262. package/dist/types/eval/__tests__/bridge-timeout.test.d.ts +1 -0
  263. package/dist/types/eval/__tests__/budget-bridge.test.d.ts +1 -0
  264. package/dist/types/eval/__tests__/completion-bridge.test.d.ts +1 -0
  265. package/dist/types/eval/__tests__/helpers-local-roots.test.d.ts +1 -0
  266. package/dist/types/eval/__tests__/idle-timeout.test.d.ts +1 -0
  267. package/dist/types/eval/__tests__/js-context-manager.test.d.ts +1 -0
  268. package/dist/types/eval/__tests__/julia-prelude.test.d.ts +1 -0
  269. package/dist/types/eval/__tests__/kernel-spawn.test.d.ts +1 -0
  270. package/dist/types/eval/__tests__/prelude-agent.test.d.ts +1 -0
  271. package/dist/types/eval/agent-bridge.d.ts +48 -0
  272. package/dist/types/eval/backend-helpers.d.ts +23 -0
  273. package/dist/types/eval/backend.d.ts +60 -0
  274. package/dist/types/eval/bridge-timeout.d.ts +27 -0
  275. package/dist/types/eval/budget-bridge.d.ts +29 -0
  276. package/dist/types/eval/completion-bridge.d.ts +25 -0
  277. package/dist/types/eval/concurrency-bridge.d.ts +26 -0
  278. package/dist/types/eval/executor-base.d.ts +118 -0
  279. package/dist/types/eval/idle-timeout.d.ts +26 -0
  280. package/dist/types/eval/index.d.ts +6 -0
  281. package/dist/types/eval/jl/executor.d.ts +44 -0
  282. package/dist/types/eval/jl/index.d.ts +11 -0
  283. package/dist/types/eval/jl/kernel.d.ts +28 -0
  284. package/dist/types/eval/jl/prelude.d.ts +1 -0
  285. package/dist/types/eval/jl/runtime.d.ts +22 -0
  286. package/dist/types/eval/js/context-manager.d.ts +40 -0
  287. package/dist/types/eval/js/executor.d.ts +38 -0
  288. package/dist/types/eval/js/index.d.ts +11 -0
  289. package/dist/types/eval/js/shared/helpers.d.ts +32 -0
  290. package/dist/types/eval/js/shared/indirect-eval.d.ts +14 -0
  291. package/dist/types/eval/js/shared/local-module-loader.d.ts +16 -0
  292. package/dist/types/eval/js/shared/prelude.d.ts +1 -0
  293. package/dist/types/eval/js/shared/rewrite-imports.d.ts +25 -0
  294. package/dist/types/eval/js/shared/runtime.d.ts +59 -0
  295. package/dist/types/eval/js/shared/types.d.ts +24 -0
  296. package/dist/types/eval/js/tool-bridge.d.ts +20 -0
  297. package/dist/types/eval/js/worker-core.d.ts +6 -0
  298. package/dist/types/eval/js/worker-entry.d.ts +1 -0
  299. package/dist/types/eval/js/worker-protocol.d.ts +83 -0
  300. package/dist/types/eval/kernel-base.d.ts +105 -0
  301. package/dist/types/eval/py/__tests__/prelude.test.d.ts +1 -0
  302. package/dist/types/eval/py/__tests__/runner-shell-output.test.d.ts +1 -0
  303. package/dist/types/eval/py/display.d.ts +25 -0
  304. package/dist/types/eval/py/executor.d.ts +107 -0
  305. package/dist/types/eval/py/index.d.ts +11 -0
  306. package/dist/types/eval/py/kernel.d.ts +17 -0
  307. package/dist/types/eval/py/prelude.d.ts +1 -0
  308. package/dist/types/eval/py/runtime.d.ts +40 -0
  309. package/dist/types/eval/py/spawn-options.d.ts +58 -0
  310. package/dist/types/eval/py/tool-bridge.d.ts +16 -0
  311. package/dist/types/eval/rb/executor.d.ts +77 -0
  312. package/dist/types/eval/rb/index.d.ts +11 -0
  313. package/dist/types/eval/rb/kernel.d.ts +31 -0
  314. package/dist/types/eval/rb/prelude.d.ts +1 -0
  315. package/dist/types/eval/rb/runtime.d.ts +23 -0
  316. package/dist/types/eval/runtime-env.d.ts +24 -0
  317. package/dist/types/eval/session-id.d.ts +3 -0
  318. package/dist/types/eval/types.d.ts +52 -0
  319. package/dist/types/exa/index.d.ts +2 -0
  320. package/dist/types/exa/mcp-client.d.ts +53 -0
  321. package/dist/types/exa/types.d.ts +72 -0
  322. package/dist/types/exec/bash-executor.d.ts +45 -0
  323. package/dist/types/exec/exec.d.ts +25 -0
  324. package/dist/types/exec/non-interactive-env.d.ts +3 -0
  325. package/dist/types/export/custom-share.d.ts +19 -0
  326. package/dist/types/export/html/index.d.ts +78 -0
  327. package/dist/types/export/html/web-palette.d.ts +117 -0
  328. package/dist/types/export/share.d.ts +55 -0
  329. package/dist/types/export/ttsr.d.ts +67 -0
  330. package/dist/types/extensibility/custom-commands/bundled/ci-green/index.d.ts +9 -0
  331. package/dist/types/extensibility/custom-commands/bundled/review/index.d.ts +10 -0
  332. package/dist/types/extensibility/custom-commands/index.d.ts +2 -0
  333. package/dist/types/extensibility/custom-commands/loader.d.ts +29 -0
  334. package/dist/types/extensibility/custom-commands/types.d.ts +112 -0
  335. package/dist/types/extensibility/custom-tools/index.d.ts +6 -0
  336. package/dist/types/extensibility/custom-tools/loader.d.ts +89 -0
  337. package/dist/types/extensibility/custom-tools/types.d.ts +244 -0
  338. package/dist/types/extensibility/custom-tools/wrapper.d.ts +23 -0
  339. package/dist/types/extensibility/extensions/compact-handler.d.ts +26 -0
  340. package/dist/types/extensibility/extensions/get-commands-handler.d.ts +29 -0
  341. package/dist/types/extensibility/extensions/index.d.ts +8 -0
  342. package/dist/types/extensibility/extensions/loader.d.ts +59 -0
  343. package/dist/types/extensibility/extensions/model-api.d.ts +17 -0
  344. package/dist/types/extensibility/extensions/runner.d.ts +161 -0
  345. package/dist/types/extensibility/extensions/types.d.ts +962 -0
  346. package/dist/types/extensibility/extensions/wrapper.d.ts +54 -0
  347. package/dist/types/extensibility/hooks/index.d.ts +6 -0
  348. package/dist/types/extensibility/hooks/loader.d.ts +65 -0
  349. package/dist/types/extensibility/hooks/runner.d.ts +126 -0
  350. package/dist/types/extensibility/hooks/tool-wrapper.d.ts +25 -0
  351. package/dist/types/extensibility/hooks/types.d.ts +442 -0
  352. package/dist/types/extensibility/legacy-pi-ai-shim.d.ts +35 -0
  353. package/dist/types/extensibility/legacy-pi-coding-agent-shim.d.ts +115 -0
  354. package/dist/types/extensibility/plugins/doctor.d.ts +3 -0
  355. package/dist/types/extensibility/plugins/git-url.d.ts +44 -0
  356. package/dist/types/extensibility/plugins/index.d.ts +7 -0
  357. package/dist/types/extensibility/plugins/installer.d.ts +5 -0
  358. package/dist/types/extensibility/plugins/legacy-pi-bundled-keys.d.ts +10 -0
  359. package/dist/types/extensibility/plugins/legacy-pi-bundled-registry.d.ts +10 -0
  360. package/dist/types/extensibility/plugins/legacy-pi-compat.d.ts +79 -0
  361. package/dist/types/extensibility/plugins/loader.d.ts +59 -0
  362. package/dist/types/extensibility/plugins/manager.d.ts +76 -0
  363. package/dist/types/extensibility/plugins/marketplace/cache.d.ts +41 -0
  364. package/dist/types/extensibility/plugins/marketplace/fetcher.d.ts +48 -0
  365. package/dist/types/extensibility/plugins/marketplace/index.d.ts +6 -0
  366. package/dist/types/extensibility/plugins/marketplace/manager.d.ts +57 -0
  367. package/dist/types/extensibility/plugins/marketplace/registry.d.ts +34 -0
  368. package/dist/types/extensibility/plugins/marketplace/source-resolver.d.ts +28 -0
  369. package/dist/types/extensibility/plugins/marketplace/types.d.ts +131 -0
  370. package/dist/types/extensibility/plugins/marketplace-auto-update.d.ts +8 -0
  371. package/dist/types/extensibility/plugins/parser.d.ts +53 -0
  372. package/dist/types/extensibility/plugins/runtime-config.d.ts +3 -0
  373. package/dist/types/extensibility/plugins/types.d.ts +149 -0
  374. package/dist/types/extensibility/session-handler-types.d.ts +23 -0
  375. package/dist/types/extensibility/shared-events.d.ts +308 -0
  376. package/dist/types/extensibility/skills.d.ts +97 -0
  377. package/dist/types/extensibility/slash-commands.d.ts +38 -0
  378. package/dist/types/extensibility/tool-event-input.d.ts +9 -0
  379. package/dist/types/extensibility/tool-proxy.d.ts +4 -0
  380. package/dist/types/extensibility/typebox.d.ts +177 -0
  381. package/dist/types/extensibility/utils.d.ts +24 -0
  382. package/dist/types/goals/guided-setup.d.ts +18 -0
  383. package/dist/types/goals/index.d.ts +3 -0
  384. package/dist/types/goals/runtime.d.ts +69 -0
  385. package/dist/types/goals/state.d.ts +35 -0
  386. package/dist/types/goals/tools/goal-tool.d.ts +53 -0
  387. package/dist/types/hindsight/backend.d.ts +13 -0
  388. package/dist/types/hindsight/bank.d.ts +62 -0
  389. package/dist/types/hindsight/client.d.ts +228 -0
  390. package/dist/types/hindsight/client.test.d.ts +1 -0
  391. package/dist/types/hindsight/config.d.ts +51 -0
  392. package/dist/types/hindsight/content.d.ts +73 -0
  393. package/dist/types/hindsight/index.d.ts +8 -0
  394. package/dist/types/hindsight/mental-models.d.ts +134 -0
  395. package/dist/types/hindsight/state.d.ts +105 -0
  396. package/dist/types/hindsight/transcript.d.ts +28 -0
  397. package/dist/types/index.d.ts +43 -0
  398. package/dist/types/internal-urls/__tests__/ssh-protocol.test.d.ts +1 -0
  399. package/dist/types/internal-urls/agent-protocol.d.ts +13 -0
  400. package/dist/types/internal-urls/artifact-protocol.d.ts +15 -0
  401. package/dist/types/internal-urls/docs-index.d.ts +19 -0
  402. package/dist/types/internal-urls/filesystem-resource.d.ts +9 -0
  403. package/dist/types/internal-urls/history-protocol.d.ts +14 -0
  404. package/dist/types/internal-urls/index.d.ts +25 -0
  405. package/dist/types/internal-urls/issue-pr-protocol.d.ts +17 -0
  406. package/dist/types/internal-urls/json-query.d.ts +30 -0
  407. package/dist/types/internal-urls/local-protocol.d.ts +79 -0
  408. package/dist/types/internal-urls/mcp-protocol.d.ts +12 -0
  409. package/dist/types/internal-urls/memory-protocol.d.ts +24 -0
  410. package/dist/types/internal-urls/omp-protocol.d.ts +13 -0
  411. package/dist/types/internal-urls/parse.d.ts +19 -0
  412. package/dist/types/internal-urls/registry-helpers.d.ts +12 -0
  413. package/dist/types/internal-urls/router.d.ts +21 -0
  414. package/dist/types/internal-urls/rule-protocol.d.ts +7 -0
  415. package/dist/types/internal-urls/skill-protocol.d.ts +14 -0
  416. package/dist/types/internal-urls/ssh-protocol.d.ts +10 -0
  417. package/dist/types/internal-urls/types.d.ts +175 -0
  418. package/dist/types/internal-urls/vault-protocol.d.ts +93 -0
  419. package/dist/types/irc/bus.d.ts +86 -0
  420. package/dist/types/jsonrpc/message-framing.d.ts +35 -0
  421. package/dist/types/lib/xai-http.d.ts +40 -0
  422. package/dist/types/lsp/client.d.ts +84 -0
  423. package/dist/types/lsp/clients/biome-client.d.ts +16 -0
  424. package/dist/types/lsp/clients/index.d.ts +19 -0
  425. package/dist/types/lsp/clients/lsp-linter-client.d.ts +16 -0
  426. package/dist/types/lsp/clients/swiftlint-client.d.ts +20 -0
  427. package/dist/types/lsp/config.d.ts +69 -0
  428. package/dist/types/lsp/diagnostics-ledger.d.ts +10 -0
  429. package/dist/types/lsp/edits.d.ts +34 -0
  430. package/dist/types/lsp/format-options.d.ts +32 -0
  431. package/dist/types/lsp/index.d.ts +120 -0
  432. package/dist/types/lsp/lspmux.d.ts +58 -0
  433. package/dist/types/lsp/render.d.ts +32 -0
  434. package/dist/types/lsp/startup-events.d.ts +11 -0
  435. package/dist/types/lsp/types.d.ts +300 -0
  436. package/dist/types/lsp/utils.d.ts +116 -0
  437. package/dist/types/main.d.ts +70 -0
  438. package/dist/types/markit/converters/docx.d.ts +6 -0
  439. package/dist/types/markit/converters/epub.d.ts +15 -0
  440. package/dist/types/markit/converters/pdf/columns.d.ts +35 -0
  441. package/dist/types/markit/converters/pdf/extract.d.ts +10 -0
  442. package/dist/types/markit/converters/pdf/grid.d.ts +25 -0
  443. package/dist/types/markit/converters/pdf/headers.d.ts +24 -0
  444. package/dist/types/markit/converters/pdf/index.d.ts +6 -0
  445. package/dist/types/markit/converters/pdf/render.d.ts +24 -0
  446. package/dist/types/markit/converters/pdf/types.d.ts +75 -0
  447. package/dist/types/markit/converters/pptx.d.ts +57 -0
  448. package/dist/types/markit/converters/xlsx.d.ts +25 -0
  449. package/dist/types/markit/index.d.ts +2 -0
  450. package/dist/types/markit/registry.d.ts +16 -0
  451. package/dist/types/markit/types.d.ts +30 -0
  452. package/dist/types/mcp/client.d.ts +83 -0
  453. package/dist/types/mcp/config-writer.d.ts +101 -0
  454. package/dist/types/mcp/config.d.ts +75 -0
  455. package/dist/types/mcp/index.d.ts +18 -0
  456. package/dist/types/mcp/json-rpc.d.ts +32 -0
  457. package/dist/types/mcp/loader.d.ts +44 -0
  458. package/dist/types/mcp/manager.d.ts +215 -0
  459. package/dist/types/mcp/oauth-credentials.d.ts +17 -0
  460. package/dist/types/mcp/oauth-discovery.d.ts +65 -0
  461. package/dist/types/mcp/oauth-flow.d.ts +145 -0
  462. package/dist/types/mcp/render.d.ts +25 -0
  463. package/dist/types/mcp/smithery-auth.d.ts +16 -0
  464. package/dist/types/mcp/smithery-connect.d.ts +38 -0
  465. package/dist/types/mcp/smithery-registry.d.ts +52 -0
  466. package/dist/types/mcp/smithery-registry.test.d.ts +1 -0
  467. package/dist/types/mcp/startup-events.d.ts +28 -0
  468. package/dist/types/mcp/timeout.d.ts +9 -0
  469. package/dist/types/mcp/tool-bridge.d.ts +95 -0
  470. package/dist/types/mcp/tool-cache.d.ts +8 -0
  471. package/dist/types/mcp/transports/http.d.ts +45 -0
  472. package/dist/types/mcp/transports/index.d.ts +6 -0
  473. package/dist/types/mcp/transports/sse.d.ts +20 -0
  474. package/dist/types/mcp/transports/stdio.d.ts +108 -0
  475. package/dist/types/mcp/transports/stdio.test.d.ts +1 -0
  476. package/dist/types/mcp/types.d.ts +340 -0
  477. package/dist/types/memories/index.d.ts +54 -0
  478. package/dist/types/memories/storage.d.ts +110 -0
  479. package/dist/types/memory-backend/index.d.ts +7 -0
  480. package/dist/types/memory-backend/local-backend.d.ts +10 -0
  481. package/dist/types/memory-backend/off-backend.d.ts +7 -0
  482. package/dist/types/memory-backend/resolve.d.ts +16 -0
  483. package/dist/types/memory-backend/runtime.d.ts +4 -0
  484. package/dist/types/memory-backend/types.d.ts +132 -0
  485. package/dist/types/mnemopi/backend.d.ts +4 -0
  486. package/dist/types/mnemopi/config.d.ts +60 -0
  487. package/dist/types/mnemopi/embed-client.d.ts +53 -0
  488. package/dist/types/mnemopi/embed-protocol.d.ts +52 -0
  489. package/dist/types/mnemopi/embed-worker.d.ts +12 -0
  490. package/dist/types/mnemopi/index.d.ts +3 -0
  491. package/dist/types/mnemopi/state.d.ts +130 -0
  492. package/dist/types/modes/acp/acp-agent.d.ts +60 -0
  493. package/dist/types/modes/acp/acp-client-bridge.d.ts +9 -0
  494. package/dist/types/modes/acp/acp-event-mapper.d.ts +33 -0
  495. package/dist/types/modes/acp/acp-mode.d.ts +5 -0
  496. package/dist/types/modes/acp/index.d.ts +2 -0
  497. package/dist/types/modes/acp/terminal-auth.d.ts +6 -0
  498. package/dist/types/modes/components/__tests__/move-overlay.test.d.ts +1 -0
  499. package/dist/types/modes/components/__tests__/skill-message.test.d.ts +1 -0
  500. package/dist/types/modes/components/advisor-config.d.ts +59 -0
  501. package/dist/types/modes/components/advisor-message.d.ts +11 -0
  502. package/dist/types/modes/components/agent-dashboard.d.ts +22 -0
  503. package/dist/types/modes/components/agent-hub.d.ts +77 -0
  504. package/dist/types/modes/components/agent-transcript-viewer.d.ts +40 -0
  505. package/dist/types/modes/components/assistant-message.d.ts +58 -0
  506. package/dist/types/modes/components/background-tan-message.d.ts +9 -0
  507. package/dist/types/modes/components/bash-execution.d.ts +35 -0
  508. package/dist/types/modes/components/bordered-loader.d.ts +11 -0
  509. package/dist/types/modes/components/btw-panel.d.ts +19 -0
  510. package/dist/types/modes/components/cache-invalidation-marker.d.ts +52 -0
  511. package/dist/types/modes/components/chat-block.d.ts +64 -0
  512. package/dist/types/modes/components/chat-transcript-builder.d.ts +45 -0
  513. package/dist/types/modes/components/collab-prompt-message.d.ts +10 -0
  514. package/dist/types/modes/components/compaction-summary-message.d.ts +46 -0
  515. package/dist/types/modes/components/copy-selector.d.ts +22 -0
  516. package/dist/types/modes/components/countdown-timer.d.ts +14 -0
  517. package/dist/types/modes/components/custom-editor.d.ts +163 -0
  518. package/dist/types/modes/components/custom-editor.test.d.ts +1 -0
  519. package/dist/types/modes/components/custom-message.d.ts +15 -0
  520. package/dist/types/modes/components/diff.d.ts +11 -0
  521. package/dist/types/modes/components/dynamic-border.d.ts +14 -0
  522. package/dist/types/modes/components/error-banner.d.ts +11 -0
  523. package/dist/types/modes/components/eval-execution.d.ts +29 -0
  524. package/dist/types/modes/components/execution-shared.d.ts +46 -0
  525. package/dist/types/modes/components/extensions/extension-dashboard.d.ts +43 -0
  526. package/dist/types/modes/components/extensions/extension-list.d.ts +52 -0
  527. package/dist/types/modes/components/extensions/index.d.ts +8 -0
  528. package/dist/types/modes/components/extensions/inspector-panel.d.ts +8 -0
  529. package/dist/types/modes/components/extensions/state-manager.d.ts +50 -0
  530. package/dist/types/modes/components/extensions/types.d.ts +147 -0
  531. package/dist/types/modes/components/footer.d.ts +30 -0
  532. package/dist/types/modes/components/history-search.d.ts +7 -0
  533. package/dist/types/modes/components/hook-editor.d.ts +24 -0
  534. package/dist/types/modes/components/hook-input.d.ts +19 -0
  535. package/dist/types/modes/components/hook-message.d.ts +15 -0
  536. package/dist/types/modes/components/hook-selector.d.ts +68 -0
  537. package/dist/types/modes/components/index.d.ts +38 -0
  538. package/dist/types/modes/components/keybinding-hints.d.ts +40 -0
  539. package/dist/types/modes/components/late-diagnostics-message.d.ts +20 -0
  540. package/dist/types/modes/components/login-dialog.d.ts +40 -0
  541. package/dist/types/modes/components/logout-account-selector.d.ts +8 -0
  542. package/dist/types/modes/components/mcp-add-wizard.d.ts +38 -0
  543. package/dist/types/modes/components/message-frame.d.ts +44 -0
  544. package/dist/types/modes/components/model-selector.d.ts +36 -0
  545. package/dist/types/modes/components/move-overlay.d.ts +23 -0
  546. package/dist/types/modes/components/oauth-selector.d.ts +23 -0
  547. package/dist/types/modes/components/omfg-panel.d.ts +19 -0
  548. package/dist/types/modes/components/overlay-box.d.ts +17 -0
  549. package/dist/types/modes/components/plan-review-overlay.d.ts +61 -0
  550. package/dist/types/modes/components/plan-toc.d.ts +41 -0
  551. package/dist/types/modes/components/plugin-selector.d.ts +27 -0
  552. package/dist/types/modes/components/plugin-settings.d.ts +103 -0
  553. package/dist/types/modes/components/queue-mode-selector.d.ts +10 -0
  554. package/dist/types/modes/components/read-tool-group.d.ts +38 -0
  555. package/dist/types/modes/components/reset-usage-selector.d.ts +12 -0
  556. package/dist/types/modes/components/segment-track.d.ts +27 -0
  557. package/dist/types/modes/components/select-list-mouse-routing.d.ts +2 -0
  558. package/dist/types/modes/components/selector-helpers.d.ts +53 -0
  559. package/dist/types/modes/components/session-selector.d.ts +94 -0
  560. package/dist/types/modes/components/settings-defs.d.ts +60 -0
  561. package/dist/types/modes/components/settings-selector.d.ts +70 -0
  562. package/dist/types/modes/components/show-images-selector.d.ts +10 -0
  563. package/dist/types/modes/components/skill-message.d.ts +9 -0
  564. package/dist/types/modes/components/snapcompact-shape-preview.d.ts +31 -0
  565. package/dist/types/modes/components/status-line/component.d.ts +94 -0
  566. package/dist/types/modes/components/status-line/component.test.d.ts +1 -0
  567. package/dist/types/modes/components/status-line/context-thresholds.d.ts +10 -0
  568. package/dist/types/modes/components/status-line/git-utils.d.ts +22 -0
  569. package/dist/types/modes/components/status-line/index.d.ts +5 -0
  570. package/dist/types/modes/components/status-line/presets.d.ts +3 -0
  571. package/dist/types/modes/components/status-line/segments.d.ts +5 -0
  572. package/dist/types/modes/components/status-line/separators.d.ts +3 -0
  573. package/dist/types/modes/components/status-line/token-rate.d.ts +10 -0
  574. package/dist/types/modes/components/status-line/types.d.ts +150 -0
  575. package/dist/types/modes/components/theme-selector.d.ts +11 -0
  576. package/dist/types/modes/components/thinking-selector.d.ts +11 -0
  577. package/dist/types/modes/components/tiny-title-download-progress.d.ts +11 -0
  578. package/dist/types/modes/components/todo-reminder.d.ts +15 -0
  579. package/dist/types/modes/components/tool-execution.d.ts +117 -0
  580. package/dist/types/modes/components/transcript-container.d.ts +86 -0
  581. package/dist/types/modes/components/tree-selector.d.ts +31 -0
  582. package/dist/types/modes/components/ttsr-notification.d.ts +17 -0
  583. package/dist/types/modes/components/usage-row.d.ts +3 -0
  584. package/dist/types/modes/components/user-message-selector.d.ts +28 -0
  585. package/dist/types/modes/components/user-message.d.ts +9 -0
  586. package/dist/types/modes/components/visual-truncate.d.ts +19 -0
  587. package/dist/types/modes/components/welcome.d.ts +66 -0
  588. package/dist/types/modes/controllers/btw-controller.d.ts +14 -0
  589. package/dist/types/modes/controllers/command-controller-shared.d.ts +47 -0
  590. package/dist/types/modes/controllers/command-controller.d.ts +55 -0
  591. package/dist/types/modes/controllers/event-controller.d.ts +28 -0
  592. package/dist/types/modes/controllers/extension-ui-controller.d.ts +88 -0
  593. package/dist/types/modes/controllers/input-controller.d.ts +71 -0
  594. package/dist/types/modes/controllers/mcp-command-controller.d.ts +44 -0
  595. package/dist/types/modes/controllers/omfg-controller.d.ts +10 -0
  596. package/dist/types/modes/controllers/omfg-rule.d.ts +26 -0
  597. package/dist/types/modes/controllers/selector-controller.d.ts +61 -0
  598. package/dist/types/modes/controllers/session-focus-controller.d.ts +31 -0
  599. package/dist/types/modes/controllers/ssh-command-controller.d.ts +10 -0
  600. package/dist/types/modes/controllers/streaming-reveal.d.ts +45 -0
  601. package/dist/types/modes/controllers/tan-command-controller.d.ts +6 -0
  602. package/dist/types/modes/controllers/todo-command-controller.d.ts +7 -0
  603. package/dist/types/modes/controllers/tool-args-reveal.d.ts +77 -0
  604. package/dist/types/modes/emoji-autocomplete.d.ts +16 -0
  605. package/dist/types/modes/gradient-highlight.d.ts +32 -0
  606. package/dist/types/modes/image-references.d.ts +28 -0
  607. package/dist/types/modes/index.d.ts +10 -0
  608. package/dist/types/modes/interactive-mode.d.ts +401 -0
  609. package/dist/types/modes/internal-url-autocomplete.d.ts +43 -0
  610. package/dist/types/modes/loop-limit.d.ts +35 -0
  611. package/dist/types/modes/magic-keywords.d.ts +26 -0
  612. package/dist/types/modes/markdown-prose.d.ts +27 -0
  613. package/dist/types/modes/oauth-manual-input.d.ts +15 -0
  614. package/dist/types/modes/orchestrate.d.ts +15 -0
  615. package/dist/types/modes/print-mode.d.ts +29 -0
  616. package/dist/types/modes/prompt-action-autocomplete.d.ts +46 -0
  617. package/dist/types/modes/rpc/host-tools.d.ts +16 -0
  618. package/dist/types/modes/rpc/host-uris.d.ts +38 -0
  619. package/dist/types/modes/rpc/rpc-client.d.ts +304 -0
  620. package/dist/types/modes/rpc/rpc-mode.d.ts +145 -0
  621. package/dist/types/modes/rpc/rpc-subagents.d.ts +24 -0
  622. package/dist/types/modes/rpc/rpc-types.d.ts +705 -0
  623. package/dist/types/modes/running-subagent-badge.d.ts +6 -0
  624. package/dist/types/modes/runtime-init.d.ts +25 -0
  625. package/dist/types/modes/session-observer-registry.d.ts +35 -0
  626. package/dist/types/modes/session-teardown.d.ts +63 -0
  627. package/dist/types/modes/session-teardown.test.d.ts +1 -0
  628. package/dist/types/modes/setup-version.d.ts +11 -0
  629. package/dist/types/modes/setup-wizard/index.d.ts +22 -0
  630. package/dist/types/modes/setup-wizard/lazy.d.ts +2 -0
  631. package/dist/types/modes/setup-wizard/scenes/glyph.d.ts +2 -0
  632. package/dist/types/modes/setup-wizard/scenes/outro.d.ts +2 -0
  633. package/dist/types/modes/setup-wizard/scenes/providers.d.ts +2 -0
  634. package/dist/types/modes/setup-wizard/scenes/sign-in.d.ts +22 -0
  635. package/dist/types/modes/setup-wizard/scenes/splash.d.ts +11 -0
  636. package/dist/types/modes/setup-wizard/scenes/theme.d.ts +2 -0
  637. package/dist/types/modes/setup-wizard/scenes/types.d.ts +52 -0
  638. package/dist/types/modes/setup-wizard/scenes/web-search.d.ts +23 -0
  639. package/dist/types/modes/setup-wizard/startup-splash.d.ts +7 -0
  640. package/dist/types/modes/setup-wizard/wizard-overlay.d.ts +15 -0
  641. package/dist/types/modes/shared.d.ts +15 -0
  642. package/dist/types/modes/skill-command.d.ts +32 -0
  643. package/dist/types/modes/theme/defaults/index.d.ts +9436 -0
  644. package/dist/types/modes/theme/mermaid-cache.d.ts +26 -0
  645. package/dist/types/modes/theme/mermaid-rendering.test.d.ts +1 -0
  646. package/dist/types/modes/theme/shimmer.d.ts +40 -0
  647. package/dist/types/modes/theme/theme.d.ts +360 -0
  648. package/dist/types/modes/turn-budget.d.ts +18 -0
  649. package/dist/types/modes/types.d.ts +399 -0
  650. package/dist/types/modes/ultrathink.d.ts +15 -0
  651. package/dist/types/modes/utils/context-usage.d.ts +64 -0
  652. package/dist/types/modes/utils/copy-targets.d.ts +75 -0
  653. package/dist/types/modes/utils/hotkeys-markdown.d.ts +5 -0
  654. package/dist/types/modes/utils/interactive-context-helpers.d.ts +14 -0
  655. package/dist/types/modes/utils/keybinding-matchers.d.ts +32 -0
  656. package/dist/types/modes/utils/tools-markdown.d.ts +5 -0
  657. package/dist/types/modes/utils/transcript-render-helpers.d.ts +63 -0
  658. package/dist/types/modes/utils/ui-helpers.d.ts +55 -0
  659. package/dist/types/modes/workflow.d.ts +15 -0
  660. package/dist/types/plan-mode/approved-plan-prompt.test.d.ts +1 -0
  661. package/dist/types/plan-mode/approved-plan.d.ts +68 -0
  662. package/dist/types/plan-mode/plan-handoff.d.ts +20 -0
  663. package/dist/types/plan-mode/plan-protection.d.ts +12 -0
  664. package/dist/types/plan-mode/state.d.ts +6 -0
  665. package/dist/types/registry/agent-lifecycle.d.ts +66 -0
  666. package/dist/types/registry/agent-registry.d.ts +97 -0
  667. package/dist/types/sdk.d.ts +370 -0
  668. package/dist/types/secrets/index.d.ts +9 -0
  669. package/dist/types/secrets/obfuscator.d.ts +63 -0
  670. package/dist/types/secrets/regex.d.ts +2 -0
  671. package/dist/types/session/agent-session.d.ts +1419 -0
  672. package/dist/types/session/agent-storage.d.ts +97 -0
  673. package/dist/types/session/artifacts.d.ts +61 -0
  674. package/dist/types/session/auth-broker-config.d.ts +45 -0
  675. package/dist/types/session/auth-storage.d.ts +7 -0
  676. package/dist/types/session/blob-store.d.ts +68 -0
  677. package/dist/types/session/client-bridge.d.ts +88 -0
  678. package/dist/types/session/codex-auto-reset.d.ts +111 -0
  679. package/dist/types/session/compact-modes.d.ts +60 -0
  680. package/dist/types/session/exit-diagnostics.d.ts +48 -0
  681. package/dist/types/session/history-storage.d.ts +30 -0
  682. package/dist/types/session/indexed-session-storage.d.ts +65 -0
  683. package/dist/types/session/messages.d.ts +220 -0
  684. package/dist/types/session/messages.test.d.ts +1 -0
  685. package/dist/types/session/provider-image-budget.d.ts +3 -0
  686. package/dist/types/session/redis-session-storage.d.ts +51 -0
  687. package/dist/types/session/session-context.d.ts +44 -0
  688. package/dist/types/session/session-dump-format.d.ts +30 -0
  689. package/dist/types/session/session-entries.d.ts +197 -0
  690. package/dist/types/session/session-history-format.d.ts +49 -0
  691. package/dist/types/session/session-listing.d.ts +78 -0
  692. package/dist/types/session/session-loader.d.ts +29 -0
  693. package/dist/types/session/session-manager.d.ts +306 -0
  694. package/dist/types/session/session-migrations.d.ts +12 -0
  695. package/dist/types/session/session-paths.d.ts +25 -0
  696. package/dist/types/session/session-persistence.d.ts +12 -0
  697. package/dist/types/session/session-storage.d.ts +129 -0
  698. package/dist/types/session/session-title-slot.d.ts +19 -0
  699. package/dist/types/session/settings-stream-fn.d.ts +21 -0
  700. package/dist/types/session/shake-types.d.ts +24 -0
  701. package/dist/types/session/snapcompact-inline.d.ts +145 -0
  702. package/dist/types/session/snapcompact-savings-journal.d.ts +46 -0
  703. package/dist/types/session/sql-session-storage.d.ts +72 -0
  704. package/dist/types/session/streaming-output.d.ts +229 -0
  705. package/dist/types/session/tool-choice-queue.d.ts +94 -0
  706. package/dist/types/session/turn-persistence.d.ts +88 -0
  707. package/dist/types/session/unexpected-stop-classifier.d.ts +13 -0
  708. package/dist/types/session/yield-queue.d.ts +37 -0
  709. package/dist/types/slash-commands/acp-builtins.d.ts +34 -0
  710. package/dist/types/slash-commands/available-commands.d.ts +34 -0
  711. package/dist/types/slash-commands/builtin-registry.d.ts +36 -0
  712. package/dist/types/slash-commands/helpers/active-oauth-account.d.ts +14 -0
  713. package/dist/types/slash-commands/helpers/collab-qrcode.d.ts +13 -0
  714. package/dist/types/slash-commands/helpers/context-report.d.ts +7 -0
  715. package/dist/types/slash-commands/helpers/format.d.ts +10 -0
  716. package/dist/types/slash-commands/helpers/logout.d.ts +15 -0
  717. package/dist/types/slash-commands/helpers/marketplace-manager.d.ts +8 -0
  718. package/dist/types/slash-commands/helpers/mcp.d.ts +3 -0
  719. package/dist/types/slash-commands/helpers/parse.d.ts +33 -0
  720. package/dist/types/slash-commands/helpers/reset-usage.d.ts +27 -0
  721. package/dist/types/slash-commands/helpers/ssh.d.ts +3 -0
  722. package/dist/types/slash-commands/helpers/stats-dashboard.d.ts +13 -0
  723. package/dist/types/slash-commands/helpers/todo.d.ts +3 -0
  724. package/dist/types/slash-commands/helpers/usage-report.d.ts +7 -0
  725. package/dist/types/slash-commands/marketplace-install-parser.d.ts +33 -0
  726. package/dist/types/slash-commands/types.d.ts +127 -0
  727. package/dist/types/ssh/__tests__/connection-manager-args.test.d.ts +1 -0
  728. package/dist/types/ssh/__tests__/connection-manager-timeout.test.d.ts +1 -0
  729. package/dist/types/ssh/__tests__/file-transfer-posix-guard.test.d.ts +1 -0
  730. package/dist/types/ssh/__tests__/sshfs-mount.test.d.ts +1 -0
  731. package/dist/types/ssh/config-writer.d.ts +49 -0
  732. package/dist/types/ssh/connection-manager.d.ts +109 -0
  733. package/dist/types/ssh/file-transfer.d.ts +79 -0
  734. package/dist/types/ssh/ssh-executor.d.ts +37 -0
  735. package/dist/types/ssh/sshfs-mount.d.ts +15 -0
  736. package/dist/types/ssh/utils.d.ts +24 -0
  737. package/dist/types/startup-splash.d.ts +12 -0
  738. package/dist/types/stt/asr-client.d.ts +68 -0
  739. package/dist/types/stt/asr-protocol.d.ts +97 -0
  740. package/dist/types/stt/asr-worker.d.ts +2 -0
  741. package/dist/types/stt/downloader.d.ts +47 -0
  742. package/dist/types/stt/endpointer.d.ts +59 -0
  743. package/dist/types/stt/index.d.ts +8 -0
  744. package/dist/types/stt/models.d.ts +120 -0
  745. package/dist/types/stt/recorder.d.ts +30 -0
  746. package/dist/types/stt/stt-controller.d.ts +24 -0
  747. package/dist/types/stt/submit-trigger.d.ts +30 -0
  748. package/dist/types/stt/transcriber.d.ts +14 -0
  749. package/dist/types/stt/wav.d.ts +29 -0
  750. package/dist/types/subprocess/worker-client.d.ts +163 -0
  751. package/dist/types/subprocess/worker-runtime.d.ts +118 -0
  752. package/dist/types/system-prompt.d.ts +128 -0
  753. package/dist/types/system-prompt.test.d.ts +1 -0
  754. package/dist/types/task/agents.d.ts +28 -0
  755. package/dist/types/task/commands.d.ts +35 -0
  756. package/dist/types/task/discovery.d.ts +20 -0
  757. package/dist/types/task/executor.d.ts +214 -0
  758. package/dist/types/task/index.d.ts +79 -0
  759. package/dist/types/task/isolation-runner.d.ts +128 -0
  760. package/dist/types/task/name-generator.d.ts +16 -0
  761. package/dist/types/task/omp-command.d.ts +7 -0
  762. package/dist/types/task/output-manager.d.ts +20 -0
  763. package/dist/types/task/parallel.d.ts +55 -0
  764. package/dist/types/task/persisted-revive.d.ts +36 -0
  765. package/dist/types/task/provider-concurrency.d.ts +40 -0
  766. package/dist/types/task/render.d.ts +34 -0
  767. package/dist/types/task/render.test.d.ts +1 -0
  768. package/dist/types/task/renderer.d.ts +14 -0
  769. package/dist/types/task/repair-args.d.ts +53 -0
  770. package/dist/types/task/spawn-policy.d.ts +17 -0
  771. package/dist/types/task/spawn-policy.test.d.ts +1 -0
  772. package/dist/types/task/subprocess-tool-registry.d.ts +72 -0
  773. package/dist/types/task/types.d.ts +384 -0
  774. package/dist/types/task/worktree.d.ts +135 -0
  775. package/dist/types/task/yield-assembly.d.ts +28 -0
  776. package/dist/types/telemetry-export.d.ts +19 -0
  777. package/dist/types/thinking.d.ts +96 -0
  778. package/dist/types/tiny/device.d.ts +78 -0
  779. package/dist/types/tiny/dtype.d.ts +85 -0
  780. package/dist/types/tiny/models.d.ts +230 -0
  781. package/dist/types/tiny/text.d.ts +44 -0
  782. package/dist/types/tiny/title-client.d.ts +68 -0
  783. package/dist/types/tiny/title-protocol.d.ts +78 -0
  784. package/dist/types/tiny/worker.d.ts +2 -0
  785. package/dist/types/tool-discovery/mode.d.ts +8 -0
  786. package/dist/types/tool-discovery/tool-index.d.ts +57 -0
  787. package/dist/types/tools/__tests__/eval-description.test.d.ts +1 -0
  788. package/dist/types/tools/__tests__/json-tree.test.d.ts +1 -0
  789. package/dist/types/tools/acp-bridge.d.ts +29 -0
  790. package/dist/types/tools/approval.d.ts +46 -0
  791. package/dist/types/tools/ask.d.ts +119 -0
  792. package/dist/types/tools/ast-edit.d.ts +84 -0
  793. package/dist/types/tools/ast-grep.d.ts +76 -0
  794. package/dist/types/tools/auto-generated-guard.d.ts +17 -0
  795. package/dist/types/tools/bash-command-fixup.d.ts +11 -0
  796. package/dist/types/tools/bash-interactive.d.ts +16 -0
  797. package/dist/types/tools/bash-interceptor.d.ts +24 -0
  798. package/dist/types/tools/bash-pty-selection.d.ts +7 -0
  799. package/dist/types/tools/bash-skill-urls.d.ts +31 -0
  800. package/dist/types/tools/bash.d.ts +173 -0
  801. package/dist/types/tools/browser/aria/aria-snapshot.d.ts +39 -0
  802. package/dist/types/tools/browser/attach.d.ts +34 -0
  803. package/dist/types/tools/browser/cmux/cmux-tab.d.ts +212 -0
  804. package/dist/types/tools/browser/cmux/rpc.d.ts +70 -0
  805. package/dist/types/tools/browser/cmux/socket-client.d.ts +19 -0
  806. package/dist/types/tools/browser/launch.d.ts +67 -0
  807. package/dist/types/tools/browser/readable.d.ts +17 -0
  808. package/dist/types/tools/browser/registry.d.ts +58 -0
  809. package/dist/types/tools/browser/render.d.ts +54 -0
  810. package/dist/types/tools/browser/run-cancellation.d.ts +4 -0
  811. package/dist/types/tools/browser/tab-protocol.d.ts +146 -0
  812. package/dist/types/tools/browser/tab-supervisor.d.ts +114 -0
  813. package/dist/types/tools/browser/tab-worker-entry.d.ts +1 -0
  814. package/dist/types/tools/browser/tab-worker.d.ts +56 -0
  815. package/dist/types/tools/browser.d.ts +96 -0
  816. package/dist/types/tools/builtin-names.d.ts +6 -0
  817. package/dist/types/tools/checkpoint.d.ts +72 -0
  818. package/dist/types/tools/conflict-detect.d.ts +221 -0
  819. package/dist/types/tools/context.d.ts +19 -0
  820. package/dist/types/tools/debug.d.ts +157 -0
  821. package/dist/types/tools/eval-backends.d.ts +15 -0
  822. package/dist/types/tools/eval-render.d.ts +58 -0
  823. package/dist/types/tools/eval.d.ts +66 -0
  824. package/dist/types/tools/fetch.d.ts +99 -0
  825. package/dist/types/tools/file-recorder.d.ts +13 -0
  826. package/dist/types/tools/fs-cache-invalidation.d.ts +15 -0
  827. package/dist/types/tools/gh-cache-invalidation.d.ts +6 -0
  828. package/dist/types/tools/gh-format.d.ts +6 -0
  829. package/dist/types/tools/gh-renderer.d.ts +25 -0
  830. package/dist/types/tools/gh.d.ts +331 -0
  831. package/dist/types/tools/github-cache.d.ts +123 -0
  832. package/dist/types/tools/glob.d.ts +96 -0
  833. package/dist/types/tools/grep.d.ts +99 -0
  834. package/dist/types/tools/grouped-file-output.d.ts +70 -0
  835. package/dist/types/tools/image-gen.d.ts +66 -0
  836. package/dist/types/tools/index.d.ts +368 -0
  837. package/dist/types/tools/inspect-image-renderer.d.ts +26 -0
  838. package/dist/types/tools/inspect-image.d.ts +32 -0
  839. package/dist/types/tools/irc.d.ts +112 -0
  840. package/dist/types/tools/job.d.ts +73 -0
  841. package/dist/types/tools/json-tree.d.ts +23 -0
  842. package/dist/types/tools/jtd-to-json-schema.d.ts +29 -0
  843. package/dist/types/tools/jtd-to-typescript.d.ts +26 -0
  844. package/dist/types/tools/jtd-utils.d.ts +42 -0
  845. package/dist/types/tools/learn.d.ts +44 -0
  846. package/dist/types/tools/list-limit.d.ts +12 -0
  847. package/dist/types/tools/manage-skill.d.ts +31 -0
  848. package/dist/types/tools/match-line-format.d.ts +11 -0
  849. package/dist/types/tools/memory-edit.d.ts +31 -0
  850. package/dist/types/tools/memory-recall.d.ts +23 -0
  851. package/dist/types/tools/memory-reflect.d.ts +25 -0
  852. package/dist/types/tools/memory-render.d.ts +63 -0
  853. package/dist/types/tools/memory-retain.d.ts +29 -0
  854. package/dist/types/tools/output-meta.d.ts +211 -0
  855. package/dist/types/tools/output-schema-validator.d.ts +77 -0
  856. package/dist/types/tools/path-utils.d.ts +267 -0
  857. package/dist/types/tools/plan-mode-guard.d.ts +33 -0
  858. package/dist/types/tools/read.d.ts +87 -0
  859. package/dist/types/tools/render-utils.d.ts +218 -0
  860. package/dist/types/tools/renderers.d.ts +49 -0
  861. package/dist/types/tools/report-tool-issue.d.ts +127 -0
  862. package/dist/types/tools/resolve.d.ts +94 -0
  863. package/dist/types/tools/review.d.ts +59 -0
  864. package/dist/types/tools/search-tool-bm25.d.ts +65 -0
  865. package/dist/types/tools/sqlite-reader.d.ts +114 -0
  866. package/dist/types/tools/ssh.d.ts +74 -0
  867. package/dist/types/tools/todo.d.ts +126 -0
  868. package/dist/types/tools/tool-errors.d.ts +33 -0
  869. package/dist/types/tools/tool-result.d.ts +34 -0
  870. package/dist/types/tools/tool-timeouts.d.ts +51 -0
  871. package/dist/types/tools/tts.d.ts +42 -0
  872. package/dist/types/tools/write.d.ts +66 -0
  873. package/dist/types/tools/yield.d.ts +39 -0
  874. package/dist/types/tts/downloader.d.ts +20 -0
  875. package/dist/types/tts/index.d.ts +10 -0
  876. package/dist/types/tts/models.d.ts +82 -0
  877. package/dist/types/tts/player.d.ts +32 -0
  878. package/dist/types/tts/runtime.d.ts +6 -0
  879. package/dist/types/tts/speakable.d.ts +47 -0
  880. package/dist/types/tts/speech-enhancer.d.ts +46 -0
  881. package/dist/types/tts/streaming-player.d.ts +40 -0
  882. package/dist/types/tts/tts-client.d.ts +69 -0
  883. package/dist/types/tts/tts-protocol.d.ts +102 -0
  884. package/dist/types/tts/tts-worker.d.ts +2 -0
  885. package/dist/types/tts/vocalizer.d.ts +48 -0
  886. package/dist/types/tts/wav.d.ts +8 -0
  887. package/dist/types/tui/code-cell.d.ts +47 -0
  888. package/dist/types/tui/file-list.d.ts +22 -0
  889. package/dist/types/tui/hyperlink.d.ts +61 -0
  890. package/dist/types/tui/index.d.ts +12 -0
  891. package/dist/types/tui/output-block.d.ts +59 -0
  892. package/dist/types/tui/status-line.d.ts +21 -0
  893. package/dist/types/tui/tree-list.d.ts +20 -0
  894. package/dist/types/tui/types.d.ts +13 -0
  895. package/dist/types/tui/utils.d.ts +36 -0
  896. package/dist/types/tui/width-aware-text.d.ts +23 -0
  897. package/dist/types/utils/active-repo-context.d.ts +8 -0
  898. package/dist/types/utils/block-context.d.ts +35 -0
  899. package/dist/types/utils/changelog.d.ts +33 -0
  900. package/dist/types/utils/clipboard.d.ts +37 -0
  901. package/dist/types/utils/command-args.d.ts +9 -0
  902. package/dist/types/utils/commit-message-generator.d.ts +7 -0
  903. package/dist/types/utils/edit-mode.d.ts +13 -0
  904. package/dist/types/utils/enhanced-paste.d.ts +20 -0
  905. package/dist/types/utils/event-bus.d.ts +6 -0
  906. package/dist/types/utils/external-editor.d.ts +27 -0
  907. package/dist/types/utils/fetch-timeout.d.ts +4 -0
  908. package/dist/types/utils/file-display-mode.d.ts +27 -0
  909. package/dist/types/utils/file-mentions.d.ts +13 -0
  910. package/dist/types/utils/git.d.ts +471 -0
  911. package/dist/types/utils/image-loading.d.ts +67 -0
  912. package/dist/types/utils/image-resize.d.ts +42 -0
  913. package/dist/types/utils/image-vision-fallback.d.ts +28 -0
  914. package/dist/types/utils/ipc.d.ts +22 -0
  915. package/dist/types/utils/jj.d.ts +74 -0
  916. package/dist/types/utils/lang-from-path.d.ts +8 -0
  917. package/dist/types/utils/markit-cache.d.ts +23 -0
  918. package/dist/types/utils/markit.d.ts +20 -0
  919. package/dist/types/utils/mupdf-wasm-embed.d.ts +1 -0
  920. package/dist/types/utils/open.d.ts +2 -0
  921. package/dist/types/utils/prompt-path.d.ts +1 -0
  922. package/dist/types/utils/qrcode.d.ts +48 -0
  923. package/dist/types/utils/session-color.d.ts +27 -0
  924. package/dist/types/utils/shell-snapshot.d.ts +15 -0
  925. package/dist/types/utils/sixel.d.ts +21 -0
  926. package/dist/types/utils/thinking-display.d.ts +7 -0
  927. package/dist/types/utils/title-generator.d.ts +33 -0
  928. package/dist/types/utils/tool-choice.d.ts +15 -0
  929. package/dist/types/utils/tools-manager.d.ts +12 -0
  930. package/dist/types/utils/turndown.d.ts +15 -0
  931. package/dist/types/utils/zip.d.ts +119 -0
  932. package/dist/types/web/kagi.d.ts +99 -0
  933. package/dist/types/web/parallel.d.ts +67 -0
  934. package/dist/types/web/scrapers/artifacthub.d.ts +6 -0
  935. package/dist/types/web/scrapers/arxiv.d.ts +5 -0
  936. package/dist/types/web/scrapers/aur.d.ts +5 -0
  937. package/dist/types/web/scrapers/biorxiv.d.ts +5 -0
  938. package/dist/types/web/scrapers/bluesky.d.ts +5 -0
  939. package/dist/types/web/scrapers/brew.d.ts +5 -0
  940. package/dist/types/web/scrapers/cheatsh.d.ts +8 -0
  941. package/dist/types/web/scrapers/chocolatey.d.ts +5 -0
  942. package/dist/types/web/scrapers/choosealicense.d.ts +2 -0
  943. package/dist/types/web/scrapers/cisa-kev.d.ts +5 -0
  944. package/dist/types/web/scrapers/clojars.d.ts +5 -0
  945. package/dist/types/web/scrapers/coingecko.d.ts +5 -0
  946. package/dist/types/web/scrapers/crates-io.d.ts +5 -0
  947. package/dist/types/web/scrapers/crossref.d.ts +2 -0
  948. package/dist/types/web/scrapers/devto.d.ts +5 -0
  949. package/dist/types/web/scrapers/discogs.d.ts +8 -0
  950. package/dist/types/web/scrapers/discourse.d.ts +5 -0
  951. package/dist/types/web/scrapers/dockerhub.d.ts +5 -0
  952. package/dist/types/web/scrapers/docs-rs.d.ts +2 -0
  953. package/dist/types/web/scrapers/fdroid.d.ts +5 -0
  954. package/dist/types/web/scrapers/firefox-addons.d.ts +2 -0
  955. package/dist/types/web/scrapers/flathub.d.ts +2 -0
  956. package/dist/types/web/scrapers/github-gist.d.ts +5 -0
  957. package/dist/types/web/scrapers/github.d.ts +34 -0
  958. package/dist/types/web/scrapers/gitlab.d.ts +5 -0
  959. package/dist/types/web/scrapers/go-pkg.d.ts +5 -0
  960. package/dist/types/web/scrapers/hackage.d.ts +5 -0
  961. package/dist/types/web/scrapers/hackernews.d.ts +2 -0
  962. package/dist/types/web/scrapers/hex.d.ts +5 -0
  963. package/dist/types/web/scrapers/huggingface.d.ts +2 -0
  964. package/dist/types/web/scrapers/iacr.d.ts +5 -0
  965. package/dist/types/web/scrapers/index.d.ts +84 -0
  966. package/dist/types/web/scrapers/jetbrains-marketplace.d.ts +2 -0
  967. package/dist/types/web/scrapers/lemmy.d.ts +2 -0
  968. package/dist/types/web/scrapers/lobsters.d.ts +5 -0
  969. package/dist/types/web/scrapers/mastodon.d.ts +5 -0
  970. package/dist/types/web/scrapers/maven.d.ts +6 -0
  971. package/dist/types/web/scrapers/mdn.d.ts +2 -0
  972. package/dist/types/web/scrapers/metacpan.d.ts +5 -0
  973. package/dist/types/web/scrapers/musicbrainz.d.ts +5 -0
  974. package/dist/types/web/scrapers/npm.d.ts +5 -0
  975. package/dist/types/web/scrapers/nuget.d.ts +5 -0
  976. package/dist/types/web/scrapers/nvd.d.ts +5 -0
  977. package/dist/types/web/scrapers/ollama.d.ts +2 -0
  978. package/dist/types/web/scrapers/open-vsx.d.ts +5 -0
  979. package/dist/types/web/scrapers/opencorporates.d.ts +5 -0
  980. package/dist/types/web/scrapers/openlibrary.d.ts +5 -0
  981. package/dist/types/web/scrapers/orcid.d.ts +5 -0
  982. package/dist/types/web/scrapers/osv.d.ts +5 -0
  983. package/dist/types/web/scrapers/packagist.d.ts +5 -0
  984. package/dist/types/web/scrapers/pub-dev.d.ts +5 -0
  985. package/dist/types/web/scrapers/pubmed.d.ts +5 -0
  986. package/dist/types/web/scrapers/pypi.d.ts +5 -0
  987. package/dist/types/web/scrapers/rawg.d.ts +2 -0
  988. package/dist/types/web/scrapers/readthedocs.d.ts +5 -0
  989. package/dist/types/web/scrapers/reddit.d.ts +5 -0
  990. package/dist/types/web/scrapers/repology.d.ts +5 -0
  991. package/dist/types/web/scrapers/rfc.d.ts +5 -0
  992. package/dist/types/web/scrapers/rubygems.d.ts +5 -0
  993. package/dist/types/web/scrapers/searchcode.d.ts +2 -0
  994. package/dist/types/web/scrapers/sec-edgar.d.ts +5 -0
  995. package/dist/types/web/scrapers/semantic-scholar.d.ts +2 -0
  996. package/dist/types/web/scrapers/snapcraft.d.ts +2 -0
  997. package/dist/types/web/scrapers/sourcegraph.d.ts +2 -0
  998. package/dist/types/web/scrapers/spdx.d.ts +5 -0
  999. package/dist/types/web/scrapers/spotify.d.ts +8 -0
  1000. package/dist/types/web/scrapers/stackoverflow.d.ts +6 -0
  1001. package/dist/types/web/scrapers/terraform.d.ts +5 -0
  1002. package/dist/types/web/scrapers/tldr.d.ts +7 -0
  1003. package/dist/types/web/scrapers/twitter.d.ts +5 -0
  1004. package/dist/types/web/scrapers/types.d.ts +90 -0
  1005. package/dist/types/web/scrapers/utils.d.ts +26 -0
  1006. package/dist/types/web/scrapers/vimeo.d.ts +5 -0
  1007. package/dist/types/web/scrapers/vscode-marketplace.d.ts +5 -0
  1008. package/dist/types/web/scrapers/w3c.d.ts +2 -0
  1009. package/dist/types/web/scrapers/wikidata.d.ts +5 -0
  1010. package/dist/types/web/scrapers/wikipedia.d.ts +5 -0
  1011. package/dist/types/web/scrapers/youtube.d.ts +5 -0
  1012. package/dist/types/web/search/index.d.ts +74 -0
  1013. package/dist/types/web/search/provider.d.ts +30 -0
  1014. package/dist/types/web/search/providers/anthropic.d.ts +33 -0
  1015. package/dist/types/web/search/providers/base.d.ts +84 -0
  1016. package/dist/types/web/search/providers/brave.d.ts +28 -0
  1017. package/dist/types/web/search/providers/codex.d.ts +36 -0
  1018. package/dist/types/web/search/providers/duckduckgo.d.ts +14 -0
  1019. package/dist/types/web/search/providers/exa.d.ts +70 -0
  1020. package/dist/types/web/search/providers/firecrawl.d.ts +28 -0
  1021. package/dist/types/web/search/providers/gemini.d.ts +63 -0
  1022. package/dist/types/web/search/providers/jina.d.ts +31 -0
  1023. package/dist/types/web/search/providers/kagi.d.ts +30 -0
  1024. package/dist/types/web/search/providers/kimi.d.ts +32 -0
  1025. package/dist/types/web/search/providers/parallel.d.ts +16 -0
  1026. package/dist/types/web/search/providers/perplexity-auth.d.ts +37 -0
  1027. package/dist/types/web/search/providers/perplexity.d.ts +58 -0
  1028. package/dist/types/web/search/providers/searxng.d.ts +45 -0
  1029. package/dist/types/web/search/providers/synthetic.d.ts +25 -0
  1030. package/dist/types/web/search/providers/tavily.d.ts +30 -0
  1031. package/dist/types/web/search/providers/tinyfish.d.ts +29 -0
  1032. package/dist/types/web/search/providers/utils.d.ts +52 -0
  1033. package/dist/types/web/search/providers/xai.d.ts +13 -0
  1034. package/dist/types/web/search/providers/zai.d.ts +29 -0
  1035. package/dist/types/web/search/render.d.ts +34 -0
  1036. package/dist/types/web/search/types.d.ts +431 -0
  1037. package/dist/types/web/search/utils.d.ts +4 -0
  1038. package/dist/types/workspace-tree.d.ts +42 -0
  1039. package/examples/README.md +21 -0
  1040. package/examples/custom-tools/README.md +104 -0
  1041. package/examples/custom-tools/hello/index.ts +20 -0
  1042. package/examples/extensions/README.md +142 -0
  1043. package/examples/extensions/api-demo.ts +79 -0
  1044. package/examples/extensions/chalk-logger.ts +25 -0
  1045. package/examples/extensions/hello.ts +31 -0
  1046. package/examples/extensions/pirate.ts +43 -0
  1047. package/examples/extensions/plan-mode.ts +549 -0
  1048. package/examples/extensions/reload-runtime.ts +38 -0
  1049. package/examples/extensions/thinking-note.ts +13 -0
  1050. package/examples/extensions/tools.ts +145 -0
  1051. package/examples/extensions/with-deps/index.ts +36 -0
  1052. package/examples/extensions/with-deps/package-lock.json +31 -0
  1053. package/examples/extensions/with-deps/package.json +17 -0
  1054. package/examples/hooks/README.md +56 -0
  1055. package/examples/hooks/auto-commit-on-exit.ts +48 -0
  1056. package/examples/hooks/confirm-destructive.ts +58 -0
  1057. package/examples/hooks/custom-compaction.ts +115 -0
  1058. package/examples/hooks/dirty-repo-guard.ts +51 -0
  1059. package/examples/hooks/file-trigger.ts +40 -0
  1060. package/examples/hooks/git-checkpoint.ts +52 -0
  1061. package/examples/hooks/handoff.ts +149 -0
  1062. package/examples/hooks/permission-gate.ts +33 -0
  1063. package/examples/hooks/protected-paths.ts +29 -0
  1064. package/examples/hooks/qna.ts +118 -0
  1065. package/examples/hooks/status-line.ts +39 -0
  1066. package/examples/sdk/01-minimal.ts +21 -0
  1067. package/examples/sdk/02-custom-model.ts +49 -0
  1068. package/examples/sdk/03-custom-prompt.ts +46 -0
  1069. package/examples/sdk/04-skills.ts +43 -0
  1070. package/examples/sdk/06-extensions.ts +82 -0
  1071. package/examples/sdk/06-hooks.ts +61 -0
  1072. package/examples/sdk/07-context-files.ts +35 -0
  1073. package/examples/sdk/08-prompt-templates.ts +41 -0
  1074. package/examples/sdk/08-slash-commands.ts +46 -0
  1075. package/examples/sdk/09-api-keys-and-oauth.ts +54 -0
  1076. package/examples/sdk/11-sessions.ts +47 -0
  1077. package/examples/sdk/12-redis-sessions.ts +54 -0
  1078. package/examples/sdk/13-sql-sessions.ts +61 -0
  1079. package/examples/sdk/README.md +172 -0
  1080. package/package.json +594 -0
  1081. package/scripts/bench-guard.ts +71 -0
  1082. package/scripts/build-binary.ts +135 -0
  1083. package/scripts/bundle-dist.ts +129 -0
  1084. package/scripts/embed-mupdf-wasm.ts +67 -0
  1085. package/scripts/format-prompts.ts +68 -0
  1086. package/scripts/generate-aria-snapshot.ts +134 -0
  1087. package/scripts/generate-docs-index.ts +148 -0
  1088. package/scripts/generate-legacy-pi-bundled-registry.ts +420 -0
  1089. package/scripts/generate-share-viewer.ts +36 -0
  1090. package/scripts/measure-prompt-tokens.ts +63 -0
  1091. package/scripts/omp +42 -0
  1092. package/scripts/omp.ts +19 -0
  1093. package/src/advisor/__tests__/advisor.test.ts +1662 -0
  1094. package/src/advisor/__tests__/config.test.ts +173 -0
  1095. package/src/advisor/__tests__/emission-guard.test.ts +147 -0
  1096. package/src/advisor/advise-tool.ts +203 -0
  1097. package/src/advisor/config.ts +258 -0
  1098. package/src/advisor/emission-guard.ts +172 -0
  1099. package/src/advisor/index.ts +6 -0
  1100. package/src/advisor/runtime.ts +518 -0
  1101. package/src/advisor/transcript-recorder.ts +159 -0
  1102. package/src/advisor/watchdog.ts +135 -0
  1103. package/src/async/index.ts +1 -0
  1104. package/src/async/job-manager.ts +698 -0
  1105. package/src/auto-thinking/classifier.ts +195 -0
  1106. package/src/autolearn/controller.ts +145 -0
  1107. package/src/autolearn/managed-skills.ts +255 -0
  1108. package/src/autoresearch/command-resume.md +14 -0
  1109. package/src/autoresearch/dashboard.ts +436 -0
  1110. package/src/autoresearch/git.ts +331 -0
  1111. package/src/autoresearch/helpers.ts +218 -0
  1112. package/src/autoresearch/index.ts +541 -0
  1113. package/src/autoresearch/prompt-setup.md +43 -0
  1114. package/src/autoresearch/prompt.md +103 -0
  1115. package/src/autoresearch/resume-message.md +10 -0
  1116. package/src/autoresearch/state.ts +273 -0
  1117. package/src/autoresearch/storage.ts +700 -0
  1118. package/src/autoresearch/tools/init-experiment.ts +269 -0
  1119. package/src/autoresearch/tools/log-experiment.ts +521 -0
  1120. package/src/autoresearch/tools/run-experiment.ts +407 -0
  1121. package/src/autoresearch/tools/update-notes.ts +109 -0
  1122. package/src/autoresearch/types.ts +168 -0
  1123. package/src/capability/context-file.ts +44 -0
  1124. package/src/capability/extension-module.ts +34 -0
  1125. package/src/capability/extension.ts +47 -0
  1126. package/src/capability/fs.ts +117 -0
  1127. package/src/capability/hook.ts +40 -0
  1128. package/src/capability/index.ts +436 -0
  1129. package/src/capability/instruction.ts +37 -0
  1130. package/src/capability/mcp.ts +76 -0
  1131. package/src/capability/prompt.ts +35 -0
  1132. package/src/capability/rule-buckets.ts +66 -0
  1133. package/src/capability/rule.ts +261 -0
  1134. package/src/capability/settings.ts +34 -0
  1135. package/src/capability/skill.ts +63 -0
  1136. package/src/capability/slash-command.ts +40 -0
  1137. package/src/capability/ssh.ts +41 -0
  1138. package/src/capability/system-prompt.ts +34 -0
  1139. package/src/capability/tool.ts +38 -0
  1140. package/src/capability/types.ts +168 -0
  1141. package/src/cli/agents-cli.ts +138 -0
  1142. package/src/cli/args.ts +393 -0
  1143. package/src/cli/auth-broker-cli.ts +921 -0
  1144. package/src/cli/auth-gateway-cli.ts +608 -0
  1145. package/src/cli/bench-cli.ts +623 -0
  1146. package/src/cli/classify-install-target.ts +76 -0
  1147. package/src/cli/claude-trace-cli.ts +795 -0
  1148. package/src/cli/commands/init-xdg.ts +27 -0
  1149. package/src/cli/completion-gen.ts +550 -0
  1150. package/src/cli/config-cli.ts +422 -0
  1151. package/src/cli/dry-balance-cli.ts +853 -0
  1152. package/src/cli/extension-flags.ts +48 -0
  1153. package/src/cli/file-processor.ts +133 -0
  1154. package/src/cli/flag-tables.ts +325 -0
  1155. package/src/cli/gallery-cli.ts +272 -0
  1156. package/src/cli/gallery-fixtures/agentic.ts +416 -0
  1157. package/src/cli/gallery-fixtures/codeintel.ts +187 -0
  1158. package/src/cli/gallery-fixtures/edit.ts +254 -0
  1159. package/src/cli/gallery-fixtures/fs.ts +220 -0
  1160. package/src/cli/gallery-fixtures/index.ts +40 -0
  1161. package/src/cli/gallery-fixtures/interaction.ts +46 -0
  1162. package/src/cli/gallery-fixtures/memory.ts +81 -0
  1163. package/src/cli/gallery-fixtures/misc.ts +250 -0
  1164. package/src/cli/gallery-fixtures/search.ts +213 -0
  1165. package/src/cli/gallery-fixtures/shell.ts +159 -0
  1166. package/src/cli/gallery-fixtures/types.ts +57 -0
  1167. package/src/cli/gallery-fixtures/web.ts +158 -0
  1168. package/src/cli/gallery-screenshot.ts +279 -0
  1169. package/src/cli/gc-cli.ts +946 -0
  1170. package/src/cli/grep-cli.ts +160 -0
  1171. package/src/cli/grievances-cli.ts +256 -0
  1172. package/src/cli/initial-message.ts +58 -0
  1173. package/src/cli/models-cli.ts +368 -0
  1174. package/src/cli/plugin-cli.ts +996 -0
  1175. package/src/cli/profile-alias.ts +369 -0
  1176. package/src/cli/profile-bootstrap.ts +233 -0
  1177. package/src/cli/read-cli.ts +57 -0
  1178. package/src/cli/session-picker.ts +93 -0
  1179. package/src/cli/setup-cli.ts +332 -0
  1180. package/src/cli/setup-model-picker.ts +43 -0
  1181. package/src/cli/shell-cli.ts +176 -0
  1182. package/src/cli/ssh-cli.ts +179 -0
  1183. package/src/cli/startup-cwd.ts +58 -0
  1184. package/src/cli/stats-cli.ts +229 -0
  1185. package/src/cli/tiny-models-cli.ts +153 -0
  1186. package/src/cli/ttsr-cli.ts +995 -0
  1187. package/src/cli/update-cli.test.ts +28 -0
  1188. package/src/cli/update-cli.ts +944 -0
  1189. package/src/cli/usage-cli.ts +857 -0
  1190. package/src/cli/web-search-cli.ts +137 -0
  1191. package/src/cli/worktree-cli.ts +294 -0
  1192. package/src/cli-commands.ts +131 -0
  1193. package/src/cli.ts +348 -0
  1194. package/src/collab/crypto.ts +63 -0
  1195. package/src/collab/display-name.ts +13 -0
  1196. package/src/collab/guest.ts +731 -0
  1197. package/src/collab/host.ts +690 -0
  1198. package/src/collab/protocol.ts +296 -0
  1199. package/src/collab/relay-client.ts +216 -0
  1200. package/src/collab/replication-shrink.ts +111 -0
  1201. package/src/commands/acp.ts +24 -0
  1202. package/src/commands/agents.ts +57 -0
  1203. package/src/commands/auth-broker.ts +99 -0
  1204. package/src/commands/auth-gateway.ts +69 -0
  1205. package/src/commands/bench.ts +51 -0
  1206. package/src/commands/commit.ts +46 -0
  1207. package/src/commands/complete.ts +66 -0
  1208. package/src/commands/completions.ts +60 -0
  1209. package/src/commands/config.ts +51 -0
  1210. package/src/commands/dry-balance.ts +43 -0
  1211. package/src/commands/gallery.ts +60 -0
  1212. package/src/commands/gc.ts +46 -0
  1213. package/src/commands/grep.ts +48 -0
  1214. package/src/commands/grievances.ts +51 -0
  1215. package/src/commands/install.ts +107 -0
  1216. package/src/commands/join.ts +39 -0
  1217. package/src/commands/launch.ts +182 -0
  1218. package/src/commands/models.ts +60 -0
  1219. package/src/commands/plugin.ts +78 -0
  1220. package/src/commands/read.ts +38 -0
  1221. package/src/commands/say.ts +102 -0
  1222. package/src/commands/setup.ts +67 -0
  1223. package/src/commands/shell.ts +29 -0
  1224. package/src/commands/ssh.ts +60 -0
  1225. package/src/commands/stats.ts +29 -0
  1226. package/src/commands/tiny-models.ts +36 -0
  1227. package/src/commands/token.ts +162 -0
  1228. package/src/commands/ttsr.ts +125 -0
  1229. package/src/commands/update.ts +27 -0
  1230. package/src/commands/usage.ts +43 -0
  1231. package/src/commands/web-search.ts +42 -0
  1232. package/src/commands/worktree.ts +62 -0
  1233. package/src/commit/agentic/agent.ts +318 -0
  1234. package/src/commit/agentic/fallback.ts +96 -0
  1235. package/src/commit/agentic/index.ts +355 -0
  1236. package/src/commit/agentic/prompts/analyze-file.md +22 -0
  1237. package/src/commit/agentic/prompts/session-user.md +25 -0
  1238. package/src/commit/agentic/prompts/split-confirm.md +1 -0
  1239. package/src/commit/agentic/prompts/system.md +38 -0
  1240. package/src/commit/agentic/state.ts +60 -0
  1241. package/src/commit/agentic/tools/analyze-file.ts +149 -0
  1242. package/src/commit/agentic/tools/git-file-diff.ts +191 -0
  1243. package/src/commit/agentic/tools/git-hunk.ts +52 -0
  1244. package/src/commit/agentic/tools/git-overview.ts +81 -0
  1245. package/src/commit/agentic/tools/index.ts +54 -0
  1246. package/src/commit/agentic/tools/propose-changelog.ts +147 -0
  1247. package/src/commit/agentic/tools/propose-commit.ts +109 -0
  1248. package/src/commit/agentic/tools/recent-commits.ts +81 -0
  1249. package/src/commit/agentic/tools/schemas.ts +11 -0
  1250. package/src/commit/agentic/tools/split-commit.ts +241 -0
  1251. package/src/commit/agentic/topo-sort.ts +44 -0
  1252. package/src/commit/agentic/trivial.ts +51 -0
  1253. package/src/commit/agentic/validation.ts +183 -0
  1254. package/src/commit/analysis/conventional.ts +64 -0
  1255. package/src/commit/analysis/index.ts +4 -0
  1256. package/src/commit/analysis/scope.ts +242 -0
  1257. package/src/commit/analysis/summary.ts +107 -0
  1258. package/src/commit/analysis/validation.ts +66 -0
  1259. package/src/commit/changelog/detect.ts +40 -0
  1260. package/src/commit/changelog/generate.ts +101 -0
  1261. package/src/commit/changelog/index.ts +234 -0
  1262. package/src/commit/changelog/parse.ts +44 -0
  1263. package/src/commit/cli.ts +85 -0
  1264. package/src/commit/git/diff.ts +148 -0
  1265. package/src/commit/index.ts +5 -0
  1266. package/src/commit/map-reduce/index.ts +69 -0
  1267. package/src/commit/map-reduce/map-phase.ts +193 -0
  1268. package/src/commit/map-reduce/reduce-phase.ts +49 -0
  1269. package/src/commit/map-reduce/utils.ts +9 -0
  1270. package/src/commit/message.ts +11 -0
  1271. package/src/commit/model-selection.ts +95 -0
  1272. package/src/commit/pipeline.ts +243 -0
  1273. package/src/commit/prompts/analysis-system.md +148 -0
  1274. package/src/commit/prompts/analysis-user.md +38 -0
  1275. package/src/commit/prompts/changelog-system.md +50 -0
  1276. package/src/commit/prompts/changelog-user.md +18 -0
  1277. package/src/commit/prompts/file-observer-system.md +24 -0
  1278. package/src/commit/prompts/file-observer-user.md +8 -0
  1279. package/src/commit/prompts/reduce-system.md +50 -0
  1280. package/src/commit/prompts/reduce-user.md +17 -0
  1281. package/src/commit/prompts/summary-retry.md +3 -0
  1282. package/src/commit/prompts/summary-system.md +38 -0
  1283. package/src/commit/prompts/summary-user.md +13 -0
  1284. package/src/commit/prompts/types-description.md +2 -0
  1285. package/src/commit/shared-llm.ts +70 -0
  1286. package/src/commit/types.ts +118 -0
  1287. package/src/commit/utils/exclusions.ts +42 -0
  1288. package/src/commit/utils.ts +58 -0
  1289. package/src/config/api-key-resolver.ts +67 -0
  1290. package/src/config/append-only-context-mode.ts +76 -0
  1291. package/src/config/config-file.ts +315 -0
  1292. package/src/config/file-lock.ts +164 -0
  1293. package/src/config/inline-tool-descriptors-mode.ts +26 -0
  1294. package/src/config/keybindings.ts +636 -0
  1295. package/src/config/mcp-schema.json +247 -0
  1296. package/src/config/model-discovery.ts +919 -0
  1297. package/src/config/model-registry.ts +2275 -0
  1298. package/src/config/model-resolver.ts +1798 -0
  1299. package/src/config/model-roles.ts +99 -0
  1300. package/src/config/models-config-schema.ts +293 -0
  1301. package/src/config/models-config.ts +134 -0
  1302. package/src/config/prompt-templates.ts +205 -0
  1303. package/src/config/provider-globals.ts +25 -0
  1304. package/src/config/resolve-config-value.ts +94 -0
  1305. package/src/config/service-tier.ts +116 -0
  1306. package/src/config/settings-schema.ts +5247 -0
  1307. package/src/config/settings.ts +1540 -0
  1308. package/src/config.ts +242 -0
  1309. package/src/cursor.ts +340 -0
  1310. package/src/dap/client.ts +764 -0
  1311. package/src/dap/config.ts +333 -0
  1312. package/src/dap/defaults.json +212 -0
  1313. package/src/dap/index.ts +4 -0
  1314. package/src/dap/session.ts +1441 -0
  1315. package/src/dap/types.ts +610 -0
  1316. package/src/debug/index.ts +584 -0
  1317. package/src/debug/log-formatting.ts +58 -0
  1318. package/src/debug/log-viewer.ts +966 -0
  1319. package/src/debug/profiler.ts +168 -0
  1320. package/src/debug/protocol-probe.ts +267 -0
  1321. package/src/debug/raw-sse-buffer.ts +294 -0
  1322. package/src/debug/raw-sse.ts +312 -0
  1323. package/src/debug/remote-debugger.ts +151 -0
  1324. package/src/debug/report-bundle.ts +375 -0
  1325. package/src/debug/system-info.ts +111 -0
  1326. package/src/debug/terminal-info.ts +124 -0
  1327. package/src/discovery/agents-md.ts +67 -0
  1328. package/src/discovery/agents.ts +230 -0
  1329. package/src/discovery/at-imports.ts +273 -0
  1330. package/src/discovery/builtin-defaults.ts +39 -0
  1331. package/src/discovery/builtin-rules/go-add-cleanup.md +32 -0
  1332. package/src/discovery/builtin-rules/go-bench-loop.md +36 -0
  1333. package/src/discovery/builtin-rules/go-exp-promoted.md +39 -0
  1334. package/src/discovery/builtin-rules/go-ioutil.md +36 -0
  1335. package/src/discovery/builtin-rules/go-join-hostport.md +29 -0
  1336. package/src/discovery/builtin-rules/go-new-expr.md +44 -0
  1337. package/src/discovery/builtin-rules/go-rand-v2.md +40 -0
  1338. package/src/discovery/builtin-rules/go-range-int.md +45 -0
  1339. package/src/discovery/builtin-rules/index.ts +72 -0
  1340. package/src/discovery/builtin-rules/rs-box-leak.md +48 -0
  1341. package/src/discovery/builtin-rules/rs-future-prelude.md +23 -0
  1342. package/src/discovery/builtin-rules/rs-lazylock.md +51 -0
  1343. package/src/discovery/builtin-rules/rs-match-ergonomics.md +67 -0
  1344. package/src/discovery/builtin-rules/rs-parking-lot.md +44 -0
  1345. package/src/discovery/builtin-rules/rs-result-type.md +19 -0
  1346. package/src/discovery/builtin-rules/ts-bare-catch.md +38 -0
  1347. package/src/discovery/builtin-rules/ts-import-type.md +42 -0
  1348. package/src/discovery/builtin-rules/ts-no-any.md +65 -0
  1349. package/src/discovery/builtin-rules/ts-no-deprecated-leftovers.md +44 -0
  1350. package/src/discovery/builtin-rules/ts-no-dynamic-import.md +39 -0
  1351. package/src/discovery/builtin-rules/ts-no-inline-cast-access.md +55 -0
  1352. package/src/discovery/builtin-rules/ts-no-return-type.md +44 -0
  1353. package/src/discovery/builtin-rules/ts-no-test-timers.md +55 -0
  1354. package/src/discovery/builtin-rules/ts-no-tiny-functions.md +51 -0
  1355. package/src/discovery/builtin-rules/ts-promise-with-resolvers.md +65 -0
  1356. package/src/discovery/builtin-rules/ts-redundant-clear-guard.md +75 -0
  1357. package/src/discovery/builtin-rules/ts-set-map.md +28 -0
  1358. package/src/discovery/builtin.ts +934 -0
  1359. package/src/discovery/claude-plugins.ts +387 -0
  1360. package/src/discovery/claude.ts +584 -0
  1361. package/src/discovery/cline.ts +83 -0
  1362. package/src/discovery/codex.ts +530 -0
  1363. package/src/discovery/cursor.ts +220 -0
  1364. package/src/discovery/gemini.ts +383 -0
  1365. package/src/discovery/github.ts +337 -0
  1366. package/src/discovery/helpers.ts +1102 -0
  1367. package/src/discovery/index.ts +81 -0
  1368. package/src/discovery/mcp-json.ts +172 -0
  1369. package/src/discovery/omp-extension-roots.ts +213 -0
  1370. package/src/discovery/omp-plugins.ts +383 -0
  1371. package/src/discovery/opencode.ts +441 -0
  1372. package/src/discovery/plugin-dir-roots.ts +28 -0
  1373. package/src/discovery/ssh.ts +153 -0
  1374. package/src/discovery/substitute-plugin-root.ts +29 -0
  1375. package/src/discovery/vscode.ts +105 -0
  1376. package/src/discovery/windsurf.ts +147 -0
  1377. package/src/edit/apply-patch/index.ts +87 -0
  1378. package/src/edit/apply-patch/parser.ts +174 -0
  1379. package/src/edit/diff.ts +999 -0
  1380. package/src/edit/file-snapshot-store.ts +157 -0
  1381. package/src/edit/hashline/block-resolver.ts +33 -0
  1382. package/src/edit/hashline/diff.ts +356 -0
  1383. package/src/edit/hashline/execute.ts +279 -0
  1384. package/src/edit/hashline/filesystem.ts +205 -0
  1385. package/src/edit/hashline/index.ts +5 -0
  1386. package/src/edit/hashline/noop-loop-guard.ts +99 -0
  1387. package/src/edit/hashline/params.ts +12 -0
  1388. package/src/edit/index.ts +705 -0
  1389. package/src/edit/modes/apply-patch.lark +19 -0
  1390. package/src/edit/modes/apply-patch.ts +53 -0
  1391. package/src/edit/modes/patch.ts +1950 -0
  1392. package/src/edit/modes/replace.ts +1137 -0
  1393. package/src/edit/normalize.ts +345 -0
  1394. package/src/edit/notebook.ts +242 -0
  1395. package/src/edit/read-file.ts +25 -0
  1396. package/src/edit/renderer.ts +969 -0
  1397. package/src/edit/snapshot-details.ts +77 -0
  1398. package/src/edit/streaming.ts +698 -0
  1399. package/src/eval/__tests__/agent-bridge.test.ts +1399 -0
  1400. package/src/eval/__tests__/bridge-timeout.test.ts +64 -0
  1401. package/src/eval/__tests__/budget-bridge.test.ts +69 -0
  1402. package/src/eval/__tests__/completion-bridge.test.ts +412 -0
  1403. package/src/eval/__tests__/helpers-local-roots.test.ts +55 -0
  1404. package/src/eval/__tests__/idle-timeout.test.ts +80 -0
  1405. package/src/eval/__tests__/js-context-manager.test.ts +291 -0
  1406. package/src/eval/__tests__/julia-prelude.test.ts +66 -0
  1407. package/src/eval/__tests__/kernel-spawn.test.ts +103 -0
  1408. package/src/eval/__tests__/prelude-agent.test.ts +107 -0
  1409. package/src/eval/agent-bridge.ts +584 -0
  1410. package/src/eval/backend-helpers.ts +48 -0
  1411. package/src/eval/backend.ts +71 -0
  1412. package/src/eval/bridge-timeout.ts +44 -0
  1413. package/src/eval/budget-bridge.ts +48 -0
  1414. package/src/eval/completion-bridge.ts +211 -0
  1415. package/src/eval/concurrency-bridge.ts +34 -0
  1416. package/src/eval/executor-base.ts +425 -0
  1417. package/src/eval/idle-timeout.ts +91 -0
  1418. package/src/eval/index.ts +6 -0
  1419. package/src/eval/jl/executor.ts +540 -0
  1420. package/src/eval/jl/index.ts +54 -0
  1421. package/src/eval/jl/kernel.ts +235 -0
  1422. package/src/eval/jl/prelude.jl +735 -0
  1423. package/src/eval/jl/prelude.ts +3 -0
  1424. package/src/eval/jl/runner.jl +666 -0
  1425. package/src/eval/jl/runtime.ts +118 -0
  1426. package/src/eval/js/context-manager.ts +621 -0
  1427. package/src/eval/js/executor.ts +173 -0
  1428. package/src/eval/js/index.ts +40 -0
  1429. package/src/eval/js/shared/helpers.ts +170 -0
  1430. package/src/eval/js/shared/indirect-eval.ts +30 -0
  1431. package/src/eval/js/shared/local-module-loader.ts +364 -0
  1432. package/src/eval/js/shared/prelude.ts +2 -0
  1433. package/src/eval/js/shared/prelude.txt +293 -0
  1434. package/src/eval/js/shared/rewrite-imports.ts +532 -0
  1435. package/src/eval/js/shared/runtime.ts +574 -0
  1436. package/src/eval/js/shared/types.ts +18 -0
  1437. package/src/eval/js/tool-bridge.ts +163 -0
  1438. package/src/eval/js/worker-core.ts +151 -0
  1439. package/src/eval/js/worker-entry.ts +37 -0
  1440. package/src/eval/js/worker-protocol.ts +47 -0
  1441. package/src/eval/kernel-base.ts +569 -0
  1442. package/src/eval/py/__tests__/prelude.test.ts +32 -0
  1443. package/src/eval/py/__tests__/runner-shell-output.test.ts +157 -0
  1444. package/src/eval/py/display.ts +71 -0
  1445. package/src/eval/py/executor.ts +533 -0
  1446. package/src/eval/py/index.ts +57 -0
  1447. package/src/eval/py/kernel.ts +233 -0
  1448. package/src/eval/py/prelude.py +625 -0
  1449. package/src/eval/py/prelude.ts +3 -0
  1450. package/src/eval/py/runner.py +1322 -0
  1451. package/src/eval/py/runtime.ts +276 -0
  1452. package/src/eval/py/spawn-options.ts +126 -0
  1453. package/src/eval/py/tool-bridge.ts +182 -0
  1454. package/src/eval/rb/executor.ts +504 -0
  1455. package/src/eval/rb/index.ts +54 -0
  1456. package/src/eval/rb/kernel.ts +230 -0
  1457. package/src/eval/rb/prelude.rb +553 -0
  1458. package/src/eval/rb/prelude.ts +3 -0
  1459. package/src/eval/rb/runner.rb +581 -0
  1460. package/src/eval/rb/runtime.ts +132 -0
  1461. package/src/eval/runtime-env.ts +104 -0
  1462. package/src/eval/session-id.ts +8 -0
  1463. package/src/eval/types.ts +48 -0
  1464. package/src/exa/index.ts +2 -0
  1465. package/src/exa/mcp-client.ts +370 -0
  1466. package/src/exa/types.ts +69 -0
  1467. package/src/exec/bash-executor.ts +473 -0
  1468. package/src/exec/exec.ts +53 -0
  1469. package/src/exec/non-interactive-env.ts +119 -0
  1470. package/src/export/custom-share.ts +65 -0
  1471. package/src/export/html/index.ts +308 -0
  1472. package/src/export/html/share-loader.js +102 -0
  1473. package/src/export/html/template.css +1337 -0
  1474. package/src/export/html/template.html +49 -0
  1475. package/src/export/html/template.js +1634 -0
  1476. package/src/export/html/tool-views.generated.js +37 -0
  1477. package/src/export/html/vendor/highlight.min.js +1213 -0
  1478. package/src/export/html/vendor/marked.min.js +6 -0
  1479. package/src/export/html/web-palette.ts +142 -0
  1480. package/src/export/share.ts +481 -0
  1481. package/src/export/ttsr.ts +583 -0
  1482. package/src/extensibility/custom-commands/bundled/ci-green/index.ts +54 -0
  1483. package/src/extensibility/custom-commands/bundled/review/index.ts +698 -0
  1484. package/src/extensibility/custom-commands/index.ts +2 -0
  1485. package/src/extensibility/custom-commands/loader.ts +242 -0
  1486. package/src/extensibility/custom-commands/types.ts +119 -0
  1487. package/src/extensibility/custom-tools/index.ts +7 -0
  1488. package/src/extensibility/custom-tools/loader.ts +268 -0
  1489. package/src/extensibility/custom-tools/types.ts +280 -0
  1490. package/src/extensibility/custom-tools/wrapper.ts +47 -0
  1491. package/src/extensibility/extensions/compact-handler.ts +40 -0
  1492. package/src/extensibility/extensions/get-commands-handler.ts +78 -0
  1493. package/src/extensibility/extensions/index.ts +16 -0
  1494. package/src/extensibility/extensions/loader.ts +596 -0
  1495. package/src/extensibility/extensions/model-api.ts +39 -0
  1496. package/src/extensibility/extensions/runner.ts +1039 -0
  1497. package/src/extensibility/extensions/types.ts +1394 -0
  1498. package/src/extensibility/extensions/wrapper.ts +266 -0
  1499. package/src/extensibility/hooks/index.ts +6 -0
  1500. package/src/extensibility/hooks/loader.ts +244 -0
  1501. package/src/extensibility/hooks/runner.ts +425 -0
  1502. package/src/extensibility/hooks/tool-wrapper.ts +117 -0
  1503. package/src/extensibility/hooks/types.ts +613 -0
  1504. package/src/extensibility/legacy-pi-ai-shim.ts +73 -0
  1505. package/src/extensibility/legacy-pi-coding-agent-shim.ts +646 -0
  1506. package/src/extensibility/plugins/doctor.ts +65 -0
  1507. package/src/extensibility/plugins/git-url.ts +367 -0
  1508. package/src/extensibility/plugins/index.ts +9 -0
  1509. package/src/extensibility/plugins/installer.ts +201 -0
  1510. package/src/extensibility/plugins/legacy-pi-bundled-keys.ts +1011 -0
  1511. package/src/extensibility/plugins/legacy-pi-bundled-registry.ts +3430 -0
  1512. package/src/extensibility/plugins/legacy-pi-compat.ts +1141 -0
  1513. package/src/extensibility/plugins/loader.ts +535 -0
  1514. package/src/extensibility/plugins/manager.ts +1121 -0
  1515. package/src/extensibility/plugins/marketplace/cache.ts +136 -0
  1516. package/src/extensibility/plugins/marketplace/fetcher.ts +315 -0
  1517. package/src/extensibility/plugins/marketplace/index.ts +6 -0
  1518. package/src/extensibility/plugins/marketplace/manager.ts +926 -0
  1519. package/src/extensibility/plugins/marketplace/registry.ts +196 -0
  1520. package/src/extensibility/plugins/marketplace/source-resolver.ts +147 -0
  1521. package/src/extensibility/plugins/marketplace/types.ts +192 -0
  1522. package/src/extensibility/plugins/marketplace-auto-update.ts +49 -0
  1523. package/src/extensibility/plugins/parser.ts +107 -0
  1524. package/src/extensibility/plugins/runtime-config.ts +9 -0
  1525. package/src/extensibility/plugins/types.ts +194 -0
  1526. package/src/extensibility/session-handler-types.ts +21 -0
  1527. package/src/extensibility/shared-events.ts +376 -0
  1528. package/src/extensibility/skills.ts +508 -0
  1529. package/src/extensibility/slash-commands.ts +131 -0
  1530. package/src/extensibility/tool-event-input.ts +80 -0
  1531. package/src/extensibility/tool-proxy.ts +28 -0
  1532. package/src/extensibility/typebox.ts +945 -0
  1533. package/src/extensibility/utils.ts +118 -0
  1534. package/src/goals/guided-setup.ts +143 -0
  1535. package/src/goals/index.ts +3 -0
  1536. package/src/goals/runtime.ts +521 -0
  1537. package/src/goals/state.ts +37 -0
  1538. package/src/goals/tools/goal-tool.ts +251 -0
  1539. package/src/hindsight/backend.ts +354 -0
  1540. package/src/hindsight/bank.ts +156 -0
  1541. package/src/hindsight/client.test.ts +33 -0
  1542. package/src/hindsight/client.ts +643 -0
  1543. package/src/hindsight/config.ts +175 -0
  1544. package/src/hindsight/content.ts +266 -0
  1545. package/src/hindsight/index.ts +8 -0
  1546. package/src/hindsight/mental-models.ts +429 -0
  1547. package/src/hindsight/seeds.json +32 -0
  1548. package/src/hindsight/state.ts +492 -0
  1549. package/src/hindsight/transcript.ts +71 -0
  1550. package/src/index.ts +66 -0
  1551. package/src/internal-urls/__tests__/ssh-protocol.test.ts +331 -0
  1552. package/src/internal-urls/agent-protocol.ts +146 -0
  1553. package/src/internal-urls/artifact-protocol.ts +151 -0
  1554. package/src/internal-urls/docs-index.generated.txt +2 -0
  1555. package/src/internal-urls/docs-index.ts +101 -0
  1556. package/src/internal-urls/filesystem-resource.ts +34 -0
  1557. package/src/internal-urls/history-protocol.ts +118 -0
  1558. package/src/internal-urls/index.ts +26 -0
  1559. package/src/internal-urls/issue-pr-protocol.ts +594 -0
  1560. package/src/internal-urls/json-query.ts +126 -0
  1561. package/src/internal-urls/local-protocol.ts +469 -0
  1562. package/src/internal-urls/mcp-protocol.ts +151 -0
  1563. package/src/internal-urls/memory-protocol.ts +173 -0
  1564. package/src/internal-urls/omp-protocol.ts +94 -0
  1565. package/src/internal-urls/parse.ts +72 -0
  1566. package/src/internal-urls/registry-helpers.ts +40 -0
  1567. package/src/internal-urls/router.ts +107 -0
  1568. package/src/internal-urls/rule-protocol.ts +45 -0
  1569. package/src/internal-urls/skill-protocol.ts +112 -0
  1570. package/src/internal-urls/ssh-protocol.ts +367 -0
  1571. package/src/internal-urls/types.ts +182 -0
  1572. package/src/internal-urls/vault-protocol.ts +939 -0
  1573. package/src/irc/bus.ts +320 -0
  1574. package/src/jsonrpc/message-framing.ts +142 -0
  1575. package/src/lib/xai-http.ts +124 -0
  1576. package/src/lsp/client.ts +1249 -0
  1577. package/src/lsp/clients/biome-client.ts +264 -0
  1578. package/src/lsp/clients/index.ts +50 -0
  1579. package/src/lsp/clients/lsp-linter-client.ts +85 -0
  1580. package/src/lsp/clients/swiftlint-client.ts +120 -0
  1581. package/src/lsp/config.ts +531 -0
  1582. package/src/lsp/defaults.json +499 -0
  1583. package/src/lsp/diagnostics-ledger.ts +51 -0
  1584. package/src/lsp/edits.ts +288 -0
  1585. package/src/lsp/format-options.ts +119 -0
  1586. package/src/lsp/index.ts +2539 -0
  1587. package/src/lsp/lspmux.ts +233 -0
  1588. package/src/lsp/render.ts +668 -0
  1589. package/src/lsp/startup-events.ts +13 -0
  1590. package/src/lsp/types.ts +444 -0
  1591. package/src/lsp/utils.ts +718 -0
  1592. package/src/main.ts +1474 -0
  1593. package/src/markit/NOTICE +32 -0
  1594. package/src/markit/converters/docx.ts +56 -0
  1595. package/src/markit/converters/epub.ts +136 -0
  1596. package/src/markit/converters/mammoth.d.ts +24 -0
  1597. package/src/markit/converters/pdf/columns.ts +103 -0
  1598. package/src/markit/converters/pdf/extract.ts +574 -0
  1599. package/src/markit/converters/pdf/grid.ts +780 -0
  1600. package/src/markit/converters/pdf/headers.ts +106 -0
  1601. package/src/markit/converters/pdf/index.ts +146 -0
  1602. package/src/markit/converters/pdf/render.ts +501 -0
  1603. package/src/markit/converters/pdf/types.ts +84 -0
  1604. package/src/markit/converters/pptx.ts +325 -0
  1605. package/src/markit/converters/xlsx.ts +173 -0
  1606. package/src/markit/index.ts +2 -0
  1607. package/src/markit/registry.ts +59 -0
  1608. package/src/markit/types.ts +35 -0
  1609. package/src/mcp/client.ts +511 -0
  1610. package/src/mcp/config-writer.ts +350 -0
  1611. package/src/mcp/config.ts +369 -0
  1612. package/src/mcp/index.ts +29 -0
  1613. package/src/mcp/json-rpc.ts +122 -0
  1614. package/src/mcp/loader.ts +125 -0
  1615. package/src/mcp/manager.ts +1362 -0
  1616. package/src/mcp/oauth-credentials.ts +104 -0
  1617. package/src/mcp/oauth-discovery.ts +560 -0
  1618. package/src/mcp/oauth-flow.ts +787 -0
  1619. package/src/mcp/render.ts +155 -0
  1620. package/src/mcp/smithery-auth.ts +107 -0
  1621. package/src/mcp/smithery-connect.ts +154 -0
  1622. package/src/mcp/smithery-registry.test.ts +51 -0
  1623. package/src/mcp/smithery-registry.ts +500 -0
  1624. package/src/mcp/startup-events.ts +116 -0
  1625. package/src/mcp/timeout.ts +59 -0
  1626. package/src/mcp/tool-bridge.ts +484 -0
  1627. package/src/mcp/tool-cache.ts +117 -0
  1628. package/src/mcp/transports/http.ts +523 -0
  1629. package/src/mcp/transports/index.ts +7 -0
  1630. package/src/mcp/transports/sse.ts +377 -0
  1631. package/src/mcp/transports/stdio.test.ts +95 -0
  1632. package/src/mcp/transports/stdio.ts +663 -0
  1633. package/src/mcp/types.ts +430 -0
  1634. package/src/memories/index.ts +1395 -0
  1635. package/src/memories/storage.ts +578 -0
  1636. package/src/memory-backend/index.ts +18 -0
  1637. package/src/memory-backend/local-backend.ts +47 -0
  1638. package/src/memory-backend/off-backend.ts +25 -0
  1639. package/src/memory-backend/resolve.ts +25 -0
  1640. package/src/memory-backend/runtime.ts +66 -0
  1641. package/src/memory-backend/types.ts +166 -0
  1642. package/src/mnemopi/backend.ts +612 -0
  1643. package/src/mnemopi/config.ts +267 -0
  1644. package/src/mnemopi/embed-client.ts +246 -0
  1645. package/src/mnemopi/embed-protocol.ts +35 -0
  1646. package/src/mnemopi/embed-worker.ts +113 -0
  1647. package/src/mnemopi/index.ts +3 -0
  1648. package/src/mnemopi/state.ts +722 -0
  1649. package/src/modes/acp/acp-agent.ts +2372 -0
  1650. package/src/modes/acp/acp-client-bridge.ts +154 -0
  1651. package/src/modes/acp/acp-event-mapper.ts +1002 -0
  1652. package/src/modes/acp/acp-mode.ts +23 -0
  1653. package/src/modes/acp/index.ts +2 -0
  1654. package/src/modes/acp/terminal-auth.ts +37 -0
  1655. package/src/modes/components/__tests__/move-overlay.test.ts +237 -0
  1656. package/src/modes/components/__tests__/skill-message.test.ts +92 -0
  1657. package/src/modes/components/advisor-config.ts +555 -0
  1658. package/src/modes/components/advisor-message.ts +109 -0
  1659. package/src/modes/components/agent-dashboard.ts +1183 -0
  1660. package/src/modes/components/agent-hub.ts +586 -0
  1661. package/src/modes/components/agent-transcript-viewer.ts +649 -0
  1662. package/src/modes/components/assistant-message.ts +869 -0
  1663. package/src/modes/components/background-tan-message.ts +36 -0
  1664. package/src/modes/components/bash-execution.ts +229 -0
  1665. package/src/modes/components/bordered-loader.ts +41 -0
  1666. package/src/modes/components/btw-panel.ts +124 -0
  1667. package/src/modes/components/cache-invalidation-marker.ts +110 -0
  1668. package/src/modes/components/chat-block.ts +111 -0
  1669. package/src/modes/components/chat-transcript-builder.ts +449 -0
  1670. package/src/modes/components/collab-prompt-message.ts +32 -0
  1671. package/src/modes/components/compaction-summary-message.ts +215 -0
  1672. package/src/modes/components/copy-selector.ts +206 -0
  1673. package/src/modes/components/countdown-timer.ts +75 -0
  1674. package/src/modes/components/custom-editor.test.ts +283 -0
  1675. package/src/modes/components/custom-editor.ts +835 -0
  1676. package/src/modes/components/custom-message.ts +67 -0
  1677. package/src/modes/components/diff.ts +254 -0
  1678. package/src/modes/components/dynamic-border.ts +34 -0
  1679. package/src/modes/components/error-banner.ts +33 -0
  1680. package/src/modes/components/eval-execution.ts +167 -0
  1681. package/src/modes/components/execution-shared.ts +101 -0
  1682. package/src/modes/components/extensions/extension-dashboard.ts +492 -0
  1683. package/src/modes/components/extensions/extension-list.ts +507 -0
  1684. package/src/modes/components/extensions/index.ts +9 -0
  1685. package/src/modes/components/extensions/inspector-panel.ts +321 -0
  1686. package/src/modes/components/extensions/state-manager.ts +648 -0
  1687. package/src/modes/components/extensions/types.ts +186 -0
  1688. package/src/modes/components/footer.ts +276 -0
  1689. package/src/modes/components/history-search.ts +268 -0
  1690. package/src/modes/components/hook-editor.ts +183 -0
  1691. package/src/modes/components/hook-input.ts +87 -0
  1692. package/src/modes/components/hook-message.ts +67 -0
  1693. package/src/modes/components/hook-selector.ts +678 -0
  1694. package/src/modes/components/index.ts +40 -0
  1695. package/src/modes/components/keybinding-hints.ts +65 -0
  1696. package/src/modes/components/late-diagnostics-message.ts +60 -0
  1697. package/src/modes/components/login-dialog.ts +178 -0
  1698. package/src/modes/components/logout-account-selector.ts +130 -0
  1699. package/src/modes/components/mcp-add-wizard.ts +1408 -0
  1700. package/src/modes/components/message-frame.ts +92 -0
  1701. package/src/modes/components/model-selector.ts +1267 -0
  1702. package/src/modes/components/move-overlay.ts +294 -0
  1703. package/src/modes/components/oauth-selector.ts +457 -0
  1704. package/src/modes/components/omfg-panel.ts +141 -0
  1705. package/src/modes/components/overlay-box.ts +109 -0
  1706. package/src/modes/components/plan-review-overlay.ts +847 -0
  1707. package/src/modes/components/plan-toc.ts +138 -0
  1708. package/src/modes/components/plugin-selector.ts +100 -0
  1709. package/src/modes/components/plugin-settings.ts +745 -0
  1710. package/src/modes/components/queue-mode-selector.ts +61 -0
  1711. package/src/modes/components/read-tool-group.ts +676 -0
  1712. package/src/modes/components/reset-usage-selector.ts +161 -0
  1713. package/src/modes/components/segment-track.ts +89 -0
  1714. package/src/modes/components/select-list-mouse-routing.ts +35 -0
  1715. package/src/modes/components/selector-helpers.ts +129 -0
  1716. package/src/modes/components/session-selector.ts +744 -0
  1717. package/src/modes/components/settings-defs.ts +238 -0
  1718. package/src/modes/components/settings-selector.ts +1265 -0
  1719. package/src/modes/components/show-images-selector.ts +50 -0
  1720. package/src/modes/components/skill-message.ts +110 -0
  1721. package/src/modes/components/snapcompact-shape-preview-doc.md +18 -0
  1722. package/src/modes/components/snapcompact-shape-preview.ts +192 -0
  1723. package/src/modes/components/status-line/component.test.ts +44 -0
  1724. package/src/modes/components/status-line/component.ts +1308 -0
  1725. package/src/modes/components/status-line/context-thresholds.ts +86 -0
  1726. package/src/modes/components/status-line/git-utils.ts +42 -0
  1727. package/src/modes/components/status-line/index.ts +5 -0
  1728. package/src/modes/components/status-line/presets.ts +106 -0
  1729. package/src/modes/components/status-line/segments.ts +663 -0
  1730. package/src/modes/components/status-line/separators.ts +55 -0
  1731. package/src/modes/components/status-line/token-rate.ts +66 -0
  1732. package/src/modes/components/status-line/types.ts +147 -0
  1733. package/src/modes/components/theme-selector.ts +68 -0
  1734. package/src/modes/components/thinking-selector.ts +57 -0
  1735. package/src/modes/components/tiny-title-download-progress.ts +90 -0
  1736. package/src/modes/components/tips.txt +24 -0
  1737. package/src/modes/components/todo-reminder.ts +43 -0
  1738. package/src/modes/components/tool-execution.ts +1308 -0
  1739. package/src/modes/components/transcript-container.ts +456 -0
  1740. package/src/modes/components/tree-selector.ts +1002 -0
  1741. package/src/modes/components/ttsr-notification.ts +123 -0
  1742. package/src/modes/components/usage-row.ts +32 -0
  1743. package/src/modes/components/user-message-selector.ts +227 -0
  1744. package/src/modes/components/user-message.ts +68 -0
  1745. package/src/modes/components/visual-truncate.ts +63 -0
  1746. package/src/modes/components/welcome.ts +579 -0
  1747. package/src/modes/controllers/btw-controller.ts +198 -0
  1748. package/src/modes/controllers/command-controller-shared.ts +109 -0
  1749. package/src/modes/controllers/command-controller.ts +1751 -0
  1750. package/src/modes/controllers/event-controller.ts +1497 -0
  1751. package/src/modes/controllers/extension-ui-controller.ts +977 -0
  1752. package/src/modes/controllers/input-controller.ts +1851 -0
  1753. package/src/modes/controllers/mcp-command-controller.ts +2364 -0
  1754. package/src/modes/controllers/omfg-controller.ts +283 -0
  1755. package/src/modes/controllers/omfg-rule.ts +647 -0
  1756. package/src/modes/controllers/selector-controller.ts +1443 -0
  1757. package/src/modes/controllers/session-focus-controller.ts +112 -0
  1758. package/src/modes/controllers/ssh-command-controller.ts +384 -0
  1759. package/src/modes/controllers/streaming-reveal.ts +392 -0
  1760. package/src/modes/controllers/tan-command-controller.ts +190 -0
  1761. package/src/modes/controllers/todo-command-controller.ts +484 -0
  1762. package/src/modes/controllers/tool-args-reveal.ts +582 -0
  1763. package/src/modes/data/emojis.json +1 -0
  1764. package/src/modes/emoji-autocomplete.ts +285 -0
  1765. package/src/modes/gradient-highlight.ts +99 -0
  1766. package/src/modes/image-references.ts +137 -0
  1767. package/src/modes/index.ts +17 -0
  1768. package/src/modes/interactive-mode.ts +4223 -0
  1769. package/src/modes/internal-url-autocomplete.ts +158 -0
  1770. package/src/modes/loop-limit.ts +192 -0
  1771. package/src/modes/magic-keywords.ts +42 -0
  1772. package/src/modes/markdown-prose.ts +247 -0
  1773. package/src/modes/oauth-manual-input.ts +69 -0
  1774. package/src/modes/orchestrate.ts +42 -0
  1775. package/src/modes/print-mode.ts +130 -0
  1776. package/src/modes/prompt-action-autocomplete.ts +262 -0
  1777. package/src/modes/rpc/host-tools.ts +186 -0
  1778. package/src/modes/rpc/host-uris.ts +235 -0
  1779. package/src/modes/rpc/rpc-client.ts +1033 -0
  1780. package/src/modes/rpc/rpc-mode.ts +1311 -0
  1781. package/src/modes/rpc/rpc-subagents.ts +265 -0
  1782. package/src/modes/rpc/rpc-types.ts +499 -0
  1783. package/src/modes/running-subagent-badge.ts +13 -0
  1784. package/src/modes/runtime-init.ts +142 -0
  1785. package/src/modes/session-observer-registry.ts +215 -0
  1786. package/src/modes/session-teardown.test.ts +219 -0
  1787. package/src/modes/session-teardown.ts +82 -0
  1788. package/src/modes/setup-version.ts +11 -0
  1789. package/src/modes/setup-wizard/index.ts +101 -0
  1790. package/src/modes/setup-wizard/lazy.ts +16 -0
  1791. package/src/modes/setup-wizard/scenes/glyph.ts +103 -0
  1792. package/src/modes/setup-wizard/scenes/outro.ts +35 -0
  1793. package/src/modes/setup-wizard/scenes/providers.ts +104 -0
  1794. package/src/modes/setup-wizard/scenes/sign-in.ts +304 -0
  1795. package/src/modes/setup-wizard/scenes/splash.ts +201 -0
  1796. package/src/modes/setup-wizard/scenes/theme.ts +320 -0
  1797. package/src/modes/setup-wizard/scenes/types.ts +57 -0
  1798. package/src/modes/setup-wizard/scenes/web-search.ts +140 -0
  1799. package/src/modes/setup-wizard/startup-splash.ts +107 -0
  1800. package/src/modes/setup-wizard/wizard-overlay.ts +335 -0
  1801. package/src/modes/shared.ts +49 -0
  1802. package/src/modes/skill-command.ts +91 -0
  1803. package/src/modes/theme/dark.json +95 -0
  1804. package/src/modes/theme/defaults/alabaster.json +93 -0
  1805. package/src/modes/theme/defaults/amethyst.json +96 -0
  1806. package/src/modes/theme/defaults/anthracite.json +93 -0
  1807. package/src/modes/theme/defaults/basalt.json +91 -0
  1808. package/src/modes/theme/defaults/birch.json +95 -0
  1809. package/src/modes/theme/defaults/dark-abyss.json +91 -0
  1810. package/src/modes/theme/defaults/dark-arctic.json +104 -0
  1811. package/src/modes/theme/defaults/dark-aurora.json +95 -0
  1812. package/src/modes/theme/defaults/dark-catppuccin.json +107 -0
  1813. package/src/modes/theme/defaults/dark-cavern.json +91 -0
  1814. package/src/modes/theme/defaults/dark-copper.json +95 -0
  1815. package/src/modes/theme/defaults/dark-cosmos.json +90 -0
  1816. package/src/modes/theme/defaults/dark-cyberpunk.json +102 -0
  1817. package/src/modes/theme/defaults/dark-dracula.json +98 -0
  1818. package/src/modes/theme/defaults/dark-eclipse.json +91 -0
  1819. package/src/modes/theme/defaults/dark-ember.json +95 -0
  1820. package/src/modes/theme/defaults/dark-equinox.json +90 -0
  1821. package/src/modes/theme/defaults/dark-forest.json +96 -0
  1822. package/src/modes/theme/defaults/dark-github.json +105 -0
  1823. package/src/modes/theme/defaults/dark-gruvbox.json +112 -0
  1824. package/src/modes/theme/defaults/dark-lavender.json +95 -0
  1825. package/src/modes/theme/defaults/dark-lunar.json +89 -0
  1826. package/src/modes/theme/defaults/dark-midnight.json +95 -0
  1827. package/src/modes/theme/defaults/dark-monochrome.json +94 -0
  1828. package/src/modes/theme/defaults/dark-monokai.json +98 -0
  1829. package/src/modes/theme/defaults/dark-nebula.json +90 -0
  1830. package/src/modes/theme/defaults/dark-nord.json +97 -0
  1831. package/src/modes/theme/defaults/dark-ocean.json +101 -0
  1832. package/src/modes/theme/defaults/dark-one.json +100 -0
  1833. package/src/modes/theme/defaults/dark-poimandres.json +142 -0
  1834. package/src/modes/theme/defaults/dark-rainforest.json +91 -0
  1835. package/src/modes/theme/defaults/dark-reef.json +91 -0
  1836. package/src/modes/theme/defaults/dark-retro.json +92 -0
  1837. package/src/modes/theme/defaults/dark-rose-pine.json +96 -0
  1838. package/src/modes/theme/defaults/dark-sakura.json +95 -0
  1839. package/src/modes/theme/defaults/dark-slate.json +95 -0
  1840. package/src/modes/theme/defaults/dark-solarized.json +97 -0
  1841. package/src/modes/theme/defaults/dark-solstice.json +90 -0
  1842. package/src/modes/theme/defaults/dark-starfall.json +91 -0
  1843. package/src/modes/theme/defaults/dark-sunset.json +99 -0
  1844. package/src/modes/theme/defaults/dark-swamp.json +90 -0
  1845. package/src/modes/theme/defaults/dark-synthwave.json +103 -0
  1846. package/src/modes/theme/defaults/dark-taiga.json +91 -0
  1847. package/src/modes/theme/defaults/dark-terminal.json +95 -0
  1848. package/src/modes/theme/defaults/dark-tokyo-night.json +101 -0
  1849. package/src/modes/theme/defaults/dark-tundra.json +91 -0
  1850. package/src/modes/theme/defaults/dark-twilight.json +91 -0
  1851. package/src/modes/theme/defaults/dark-volcanic.json +91 -0
  1852. package/src/modes/theme/defaults/graphite.json +92 -0
  1853. package/src/modes/theme/defaults/index.ts +199 -0
  1854. package/src/modes/theme/defaults/light-arctic.json +107 -0
  1855. package/src/modes/theme/defaults/light-aurora-day.json +91 -0
  1856. package/src/modes/theme/defaults/light-canyon.json +91 -0
  1857. package/src/modes/theme/defaults/light-catppuccin.json +106 -0
  1858. package/src/modes/theme/defaults/light-cirrus.json +90 -0
  1859. package/src/modes/theme/defaults/light-coral.json +95 -0
  1860. package/src/modes/theme/defaults/light-cyberpunk.json +96 -0
  1861. package/src/modes/theme/defaults/light-dawn.json +90 -0
  1862. package/src/modes/theme/defaults/light-dunes.json +91 -0
  1863. package/src/modes/theme/defaults/light-eucalyptus.json +95 -0
  1864. package/src/modes/theme/defaults/light-forest.json +100 -0
  1865. package/src/modes/theme/defaults/light-frost.json +95 -0
  1866. package/src/modes/theme/defaults/light-github.json +115 -0
  1867. package/src/modes/theme/defaults/light-glacier.json +91 -0
  1868. package/src/modes/theme/defaults/light-gruvbox.json +108 -0
  1869. package/src/modes/theme/defaults/light-haze.json +90 -0
  1870. package/src/modes/theme/defaults/light-honeycomb.json +95 -0
  1871. package/src/modes/theme/defaults/light-lagoon.json +91 -0
  1872. package/src/modes/theme/defaults/light-lavender.json +95 -0
  1873. package/src/modes/theme/defaults/light-meadow.json +91 -0
  1874. package/src/modes/theme/defaults/light-mint.json +95 -0
  1875. package/src/modes/theme/defaults/light-monochrome.json +101 -0
  1876. package/src/modes/theme/defaults/light-ocean.json +99 -0
  1877. package/src/modes/theme/defaults/light-one.json +99 -0
  1878. package/src/modes/theme/defaults/light-opal.json +91 -0
  1879. package/src/modes/theme/defaults/light-orchard.json +91 -0
  1880. package/src/modes/theme/defaults/light-paper.json +95 -0
  1881. package/src/modes/theme/defaults/light-poimandres.json +142 -0
  1882. package/src/modes/theme/defaults/light-prism.json +90 -0
  1883. package/src/modes/theme/defaults/light-retro.json +98 -0
  1884. package/src/modes/theme/defaults/light-sand.json +95 -0
  1885. package/src/modes/theme/defaults/light-savanna.json +91 -0
  1886. package/src/modes/theme/defaults/light-solarized.json +102 -0
  1887. package/src/modes/theme/defaults/light-soleil.json +90 -0
  1888. package/src/modes/theme/defaults/light-sunset.json +99 -0
  1889. package/src/modes/theme/defaults/light-synthwave.json +98 -0
  1890. package/src/modes/theme/defaults/light-tokyo-night.json +111 -0
  1891. package/src/modes/theme/defaults/light-wetland.json +91 -0
  1892. package/src/modes/theme/defaults/light-zenith.json +89 -0
  1893. package/src/modes/theme/defaults/limestone.json +94 -0
  1894. package/src/modes/theme/defaults/mahogany.json +97 -0
  1895. package/src/modes/theme/defaults/marble.json +93 -0
  1896. package/src/modes/theme/defaults/obsidian.json +91 -0
  1897. package/src/modes/theme/defaults/onyx.json +91 -0
  1898. package/src/modes/theme/defaults/pearl.json +93 -0
  1899. package/src/modes/theme/defaults/porcelain.json +91 -0
  1900. package/src/modes/theme/defaults/quartz.json +96 -0
  1901. package/src/modes/theme/defaults/sandstone.json +95 -0
  1902. package/src/modes/theme/defaults/titanium.json +90 -0
  1903. package/src/modes/theme/light.json +93 -0
  1904. package/src/modes/theme/mermaid-cache.ts +92 -0
  1905. package/src/modes/theme/mermaid-rendering.test.ts +53 -0
  1906. package/src/modes/theme/shimmer.ts +269 -0
  1907. package/src/modes/theme/theme-schema.json +459 -0
  1908. package/src/modes/theme/theme.ts +3004 -0
  1909. package/src/modes/turn-budget.ts +31 -0
  1910. package/src/modes/types.ts +437 -0
  1911. package/src/modes/ultrathink.ts +41 -0
  1912. package/src/modes/utils/context-usage.ts +432 -0
  1913. package/src/modes/utils/copy-targets.ts +378 -0
  1914. package/src/modes/utils/hotkeys-markdown.ts +62 -0
  1915. package/src/modes/utils/interactive-context-helpers.ts +27 -0
  1916. package/src/modes/utils/keybinding-matchers.ts +86 -0
  1917. package/src/modes/utils/tools-markdown.ts +27 -0
  1918. package/src/modes/utils/transcript-render-helpers.ts +184 -0
  1919. package/src/modes/utils/ui-helpers.ts +864 -0
  1920. package/src/modes/workflow.ts +42 -0
  1921. package/src/plan-mode/approved-plan-prompt.test.ts +36 -0
  1922. package/src/plan-mode/approved-plan.ts +186 -0
  1923. package/src/plan-mode/plan-handoff.ts +37 -0
  1924. package/src/plan-mode/plan-protection.ts +31 -0
  1925. package/src/plan-mode/state.ts +6 -0
  1926. package/src/priority.json +60 -0
  1927. package/src/prompts/advisor/active-repo-watchdog.md +6 -0
  1928. package/src/prompts/advisor/advise-tool.md +3 -0
  1929. package/src/prompts/advisor/context-files.md +8 -0
  1930. package/src/prompts/advisor/system.md +89 -0
  1931. package/src/prompts/agents/designer.md +74 -0
  1932. package/src/prompts/agents/explore.md +58 -0
  1933. package/src/prompts/agents/frontmatter.md +11 -0
  1934. package/src/prompts/agents/init.md +33 -0
  1935. package/src/prompts/agents/librarian.md +119 -0
  1936. package/src/prompts/agents/plan.md +48 -0
  1937. package/src/prompts/agents/reviewer.md +140 -0
  1938. package/src/prompts/agents/task.md +17 -0
  1939. package/src/prompts/agents/tester.md +111 -0
  1940. package/src/prompts/bench.md +6 -0
  1941. package/src/prompts/ci-green-request.md +36 -0
  1942. package/src/prompts/dry-balance-bench.md +8 -0
  1943. package/src/prompts/goals/goal-budget-limit.md +16 -0
  1944. package/src/prompts/goals/goal-continuation.md +28 -0
  1945. package/src/prompts/goals/goal-mode-active.md +23 -0
  1946. package/src/prompts/goals/goal-mode-context.md +4 -0
  1947. package/src/prompts/goals/goal-todo-context.md +20 -0
  1948. package/src/prompts/goals/guided-goal-interview.md +8 -0
  1949. package/src/prompts/goals/guided-goal-system.md +12 -0
  1950. package/src/prompts/memories/consolidation.md +30 -0
  1951. package/src/prompts/memories/consolidation_system.md +4 -0
  1952. package/src/prompts/memories/read-path.md +17 -0
  1953. package/src/prompts/memories/stage_one_input.md +6 -0
  1954. package/src/prompts/memories/stage_one_system.md +21 -0
  1955. package/src/prompts/review-custom-request.md +21 -0
  1956. package/src/prompts/review-headless-request.md +16 -0
  1957. package/src/prompts/review-request.md +68 -0
  1958. package/src/prompts/skills/autoload.md +8 -0
  1959. package/src/prompts/skills/user-invocation.md +11 -0
  1960. package/src/prompts/steering/parent-irc.md +5 -0
  1961. package/src/prompts/steering/user-interjection.md +9 -0
  1962. package/src/prompts/system/active-repo-context.md +4 -0
  1963. package/src/prompts/system/agent-creation-architect.md +50 -0
  1964. package/src/prompts/system/agent-creation-user.md +6 -0
  1965. package/src/prompts/system/auto-continue.md +1 -0
  1966. package/src/prompts/system/auto-thinking-difficulty-local.md +14 -0
  1967. package/src/prompts/system/auto-thinking-difficulty.md +12 -0
  1968. package/src/prompts/system/autolearn-guidance-learn.md +1 -0
  1969. package/src/prompts/system/autolearn-guidance.md +7 -0
  1970. package/src/prompts/system/autolearn-nudge-autocontinue.md +5 -0
  1971. package/src/prompts/system/background-tan-dispatch.md +8 -0
  1972. package/src/prompts/system/btw-user.md +8 -0
  1973. package/src/prompts/system/commit-message-system.md +14 -0
  1974. package/src/prompts/system/custom-system-prompt.md +64 -0
  1975. package/src/prompts/system/eager-task.md +7 -0
  1976. package/src/prompts/system/eager-todo.md +18 -0
  1977. package/src/prompts/system/empty-stop-retry.md +4 -0
  1978. package/src/prompts/system/gemini-tool-call-reminder.md +9 -0
  1979. package/src/prompts/system/interrupted-thinking.md +7 -0
  1980. package/src/prompts/system/irc-autoreply.md +6 -0
  1981. package/src/prompts/system/irc-incoming.md +9 -0
  1982. package/src/prompts/system/manual-continue.md +7 -0
  1983. package/src/prompts/system/memory-consolidation-system.md +8 -0
  1984. package/src/prompts/system/memory-extraction-system.md +26 -0
  1985. package/src/prompts/system/mid-run-todo-nudge.md +3 -0
  1986. package/src/prompts/system/omfg-user.md +50 -0
  1987. package/src/prompts/system/orchestrate-notice.md +40 -0
  1988. package/src/prompts/system/personalities/default.md +18 -0
  1989. package/src/prompts/system/personalities/friendly.md +17 -0
  1990. package/src/prompts/system/personalities/pragmatic.md +15 -0
  1991. package/src/prompts/system/plan-mode-active.md +118 -0
  1992. package/src/prompts/system/plan-mode-approved.md +22 -0
  1993. package/src/prompts/system/plan-mode-compact-instructions.md +17 -0
  1994. package/src/prompts/system/plan-mode-reference.md +10 -0
  1995. package/src/prompts/system/plan-mode-subagent.md +33 -0
  1996. package/src/prompts/system/plan-mode-tool-decision-reminder.md +9 -0
  1997. package/src/prompts/system/project-prompt.md +54 -0
  1998. package/src/prompts/system/recap-user.md +9 -0
  1999. package/src/prompts/system/rewind-report.md +6 -0
  2000. package/src/prompts/system/side-channel-no-tools.md +3 -0
  2001. package/src/prompts/system/snapcompact-context-frames-note.md +1 -0
  2002. package/src/prompts/system/snapcompact-context-stub.md +1 -0
  2003. package/src/prompts/system/snapcompact-system-frames-note.md +1 -0
  2004. package/src/prompts/system/snapcompact-system-stub.md +1 -0
  2005. package/src/prompts/system/snapcompact-toolresult-note.md +1 -0
  2006. package/src/prompts/system/speech-rewrite.md +15 -0
  2007. package/src/prompts/system/subagent-system-prompt.md +77 -0
  2008. package/src/prompts/system/subagent-user-prompt.md +3 -0
  2009. package/src/prompts/system/subagent-yield-reminder.md +13 -0
  2010. package/src/prompts/system/system-prompt.md +248 -0
  2011. package/src/prompts/system/thinking-loop-redirect.md +10 -0
  2012. package/src/prompts/system/tiny-title-system.md +8 -0
  2013. package/src/prompts/system/title-marker-instruction.md +1 -0
  2014. package/src/prompts/system/title-system-marker.md +17 -0
  2015. package/src/prompts/system/title-system.md +17 -0
  2016. package/src/prompts/system/tool-call-loop-redirect.md +8 -0
  2017. package/src/prompts/system/ttsr-interrupt.md +7 -0
  2018. package/src/prompts/system/ttsr-tool-reminder.md +5 -0
  2019. package/src/prompts/system/ultrathink-notice.md +3 -0
  2020. package/src/prompts/system/unexpected-stop-classifier.md +17 -0
  2021. package/src/prompts/system/unexpected-stop-retry.md +4 -0
  2022. package/src/prompts/system/web-search.md +25 -0
  2023. package/src/prompts/system/workflow-notice.md +70 -0
  2024. package/src/prompts/tools/apply-patch.md +65 -0
  2025. package/src/prompts/tools/ask.md +22 -0
  2026. package/src/prompts/tools/ast-edit.md +22 -0
  2027. package/src/prompts/tools/ast-grep.md +25 -0
  2028. package/src/prompts/tools/async-result.md +8 -0
  2029. package/src/prompts/tools/bash.md +57 -0
  2030. package/src/prompts/tools/browser.md +45 -0
  2031. package/src/prompts/tools/checkpoint.md +15 -0
  2032. package/src/prompts/tools/debug.md +17 -0
  2033. package/src/prompts/tools/eval.md +72 -0
  2034. package/src/prompts/tools/github.md +17 -0
  2035. package/src/prompts/tools/glob.md +15 -0
  2036. package/src/prompts/tools/goal.md +11 -0
  2037. package/src/prompts/tools/grep.md +22 -0
  2038. package/src/prompts/tools/image-attachment-describe-system.md +8 -0
  2039. package/src/prompts/tools/image-attachment-describe.md +10 -0
  2040. package/src/prompts/tools/image-gen.md +7 -0
  2041. package/src/prompts/tools/inspect-image-system.md +20 -0
  2042. package/src/prompts/tools/inspect-image.md +22 -0
  2043. package/src/prompts/tools/irc.md +24 -0
  2044. package/src/prompts/tools/job.md +11 -0
  2045. package/src/prompts/tools/learn.md +7 -0
  2046. package/src/prompts/tools/lsp-late-diagnostic.md +8 -0
  2047. package/src/prompts/tools/lsp.md +28 -0
  2048. package/src/prompts/tools/manage-skill.md +9 -0
  2049. package/src/prompts/tools/memory-edit.md +8 -0
  2050. package/src/prompts/tools/patch.md +57 -0
  2051. package/src/prompts/tools/read.md +77 -0
  2052. package/src/prompts/tools/recall.md +5 -0
  2053. package/src/prompts/tools/reflect.md +5 -0
  2054. package/src/prompts/tools/replace.md +29 -0
  2055. package/src/prompts/tools/resolve.md +4 -0
  2056. package/src/prompts/tools/retain.md +6 -0
  2057. package/src/prompts/tools/rewind.md +14 -0
  2058. package/src/prompts/tools/search-tool-bm25.md +32 -0
  2059. package/src/prompts/tools/ssh.md +23 -0
  2060. package/src/prompts/tools/task-summary.md +17 -0
  2061. package/src/prompts/tools/task.md +68 -0
  2062. package/src/prompts/tools/todo.md +39 -0
  2063. package/src/prompts/tools/web-search.md +6 -0
  2064. package/src/prompts/tools/write.md +14 -0
  2065. package/src/registry/agent-lifecycle.ts +270 -0
  2066. package/src/registry/agent-registry.ts +190 -0
  2067. package/src/sdk.ts +3037 -0
  2068. package/src/secrets/index.ts +123 -0
  2069. package/src/secrets/obfuscator.ts +441 -0
  2070. package/src/secrets/regex.ts +21 -0
  2071. package/src/session/agent-session.ts +15855 -0
  2072. package/src/session/agent-storage.ts +478 -0
  2073. package/src/session/artifacts.ts +153 -0
  2074. package/src/session/auth-broker-config.ts +92 -0
  2075. package/src/session/auth-storage.ts +24 -0
  2076. package/src/session/blob-store.ts +279 -0
  2077. package/src/session/client-bridge.ts +85 -0
  2078. package/src/session/codex-auto-reset.ts +202 -0
  2079. package/src/session/compact-modes.ts +105 -0
  2080. package/src/session/exit-diagnostics.ts +202 -0
  2081. package/src/session/history-storage.ts +360 -0
  2082. package/src/session/indexed-session-storage.ts +537 -0
  2083. package/src/session/messages.test.ts +125 -0
  2084. package/src/session/messages.ts +740 -0
  2085. package/src/session/provider-image-budget.ts +86 -0
  2086. package/src/session/redis-session-storage.ts +217 -0
  2087. package/src/session/session-context.ts +442 -0
  2088. package/src/session/session-dump-format.ts +216 -0
  2089. package/src/session/session-entries.ts +241 -0
  2090. package/src/session/session-history-format.ts +396 -0
  2091. package/src/session/session-listing.ts +652 -0
  2092. package/src/session/session-loader.ts +284 -0
  2093. package/src/session/session-manager.ts +1995 -0
  2094. package/src/session/session-migrations.ts +78 -0
  2095. package/src/session/session-paths.ts +193 -0
  2096. package/src/session/session-persistence.ts +266 -0
  2097. package/src/session/session-storage.ts +734 -0
  2098. package/src/session/session-title-slot.ts +141 -0
  2099. package/src/session/settings-stream-fn.ts +73 -0
  2100. package/src/session/shake-types.ts +43 -0
  2101. package/src/session/snapcompact-inline.ts +561 -0
  2102. package/src/session/snapcompact-savings-journal.ts +113 -0
  2103. package/src/session/sql-session-storage.ts +374 -0
  2104. package/src/session/streaming-output.ts +1330 -0
  2105. package/src/session/tool-choice-queue.ts +290 -0
  2106. package/src/session/turn-persistence.ts +142 -0
  2107. package/src/session/unexpected-stop-classifier.ts +129 -0
  2108. package/src/session/yield-queue.ts +183 -0
  2109. package/src/slash-commands/acp-builtins.ts +70 -0
  2110. package/src/slash-commands/available-commands.ts +105 -0
  2111. package/src/slash-commands/builtin-registry.ts +2554 -0
  2112. package/src/slash-commands/helpers/active-oauth-account.ts +44 -0
  2113. package/src/slash-commands/helpers/collab-qrcode.ts +28 -0
  2114. package/src/slash-commands/helpers/context-report.ts +66 -0
  2115. package/src/slash-commands/helpers/format.ts +46 -0
  2116. package/src/slash-commands/helpers/logout.ts +88 -0
  2117. package/src/slash-commands/helpers/marketplace-manager.ts +25 -0
  2118. package/src/slash-commands/helpers/mcp.ts +533 -0
  2119. package/src/slash-commands/helpers/parse.ts +85 -0
  2120. package/src/slash-commands/helpers/reset-usage.ts +66 -0
  2121. package/src/slash-commands/helpers/ssh.ts +195 -0
  2122. package/src/slash-commands/helpers/stats-dashboard.ts +85 -0
  2123. package/src/slash-commands/helpers/todo.ts +285 -0
  2124. package/src/slash-commands/helpers/usage-report.ts +162 -0
  2125. package/src/slash-commands/marketplace-install-parser.ts +99 -0
  2126. package/src/slash-commands/types.ts +137 -0
  2127. package/src/ssh/__tests__/connection-manager-args.test.ts +191 -0
  2128. package/src/ssh/__tests__/connection-manager-timeout.test.ts +61 -0
  2129. package/src/ssh/__tests__/file-transfer-posix-guard.test.ts +105 -0
  2130. package/src/ssh/__tests__/sshfs-mount.test.ts +13 -0
  2131. package/src/ssh/config-writer.ts +183 -0
  2132. package/src/ssh/connection-manager.ts +667 -0
  2133. package/src/ssh/file-transfer.ts +214 -0
  2134. package/src/ssh/ssh-executor.ts +178 -0
  2135. package/src/ssh/sshfs-mount.ts +163 -0
  2136. package/src/ssh/utils.ts +51 -0
  2137. package/src/startup-splash.ts +19 -0
  2138. package/src/stt/asr-client.ts +401 -0
  2139. package/src/stt/asr-protocol.ts +65 -0
  2140. package/src/stt/asr-worker.ts +638 -0
  2141. package/src/stt/downloader.ts +144 -0
  2142. package/src/stt/endpointer.ts +259 -0
  2143. package/src/stt/index.ts +8 -0
  2144. package/src/stt/models.ts +150 -0
  2145. package/src/stt/recorder.ts +538 -0
  2146. package/src/stt/stt-controller.ts +409 -0
  2147. package/src/stt/submit-trigger.ts +74 -0
  2148. package/src/stt/transcriber.ts +60 -0
  2149. package/src/stt/wav.ts +173 -0
  2150. package/src/subprocess/worker-client.ts +456 -0
  2151. package/src/subprocess/worker-runtime.ts +494 -0
  2152. package/src/system-prompt.test.ts +158 -0
  2153. package/src/system-prompt.ts +787 -0
  2154. package/src/task/agents.ts +166 -0
  2155. package/src/task/commands.ts +132 -0
  2156. package/src/task/discovery.ts +145 -0
  2157. package/src/task/executor.ts +2481 -0
  2158. package/src/task/index.ts +1481 -0
  2159. package/src/task/isolation-runner.ts +384 -0
  2160. package/src/task/name-generator.ts +1577 -0
  2161. package/src/task/omp-command.ts +26 -0
  2162. package/src/task/output-manager.ts +93 -0
  2163. package/src/task/parallel.ts +178 -0
  2164. package/src/task/persisted-revive.ts +128 -0
  2165. package/src/task/provider-concurrency.ts +100 -0
  2166. package/src/task/render.test.ts +121 -0
  2167. package/src/task/render.ts +1761 -0
  2168. package/src/task/renderer.ts +15 -0
  2169. package/src/task/repair-args.ts +129 -0
  2170. package/src/task/spawn-policy.test.ts +63 -0
  2171. package/src/task/spawn-policy.ts +58 -0
  2172. package/src/task/subprocess-tool-registry.ts +88 -0
  2173. package/src/task/types.ts +495 -0
  2174. package/src/task/worktree.ts +935 -0
  2175. package/src/task/yield-assembly.ts +198 -0
  2176. package/src/telemetry-export.ts +144 -0
  2177. package/src/thinking.ts +219 -0
  2178. package/src/tiny/device.ts +111 -0
  2179. package/src/tiny/dtype.ts +101 -0
  2180. package/src/tiny/models.ts +268 -0
  2181. package/src/tiny/text.ts +336 -0
  2182. package/src/tiny/title-client.ts +438 -0
  2183. package/src/tiny/title-protocol.ts +56 -0
  2184. package/src/tiny/worker.ts +351 -0
  2185. package/src/tool-discovery/mode.ts +24 -0
  2186. package/src/tool-discovery/tool-index.ts +271 -0
  2187. package/src/tools/__tests__/eval-description.test.ts +19 -0
  2188. package/src/tools/__tests__/json-tree.test.ts +35 -0
  2189. package/src/tools/acp-bridge.ts +71 -0
  2190. package/src/tools/approval.ts +189 -0
  2191. package/src/tools/ask.ts +1213 -0
  2192. package/src/tools/ast-edit.ts +708 -0
  2193. package/src/tools/ast-grep.ts +520 -0
  2194. package/src/tools/auto-generated-guard.ts +322 -0
  2195. package/src/tools/bash-command-fixup.ts +37 -0
  2196. package/src/tools/bash-interactive.ts +408 -0
  2197. package/src/tools/bash-interceptor.ts +67 -0
  2198. package/src/tools/bash-pty-selection.ts +14 -0
  2199. package/src/tools/bash-skill-urls.ts +248 -0
  2200. package/src/tools/bash.ts +1421 -0
  2201. package/src/tools/browser/aria/aria-snapshot.bundle.txt +7 -0
  2202. package/src/tools/browser/aria/aria-snapshot.ts +103 -0
  2203. package/src/tools/browser/attach.ts +194 -0
  2204. package/src/tools/browser/cmux/cmux-tab.ts +1378 -0
  2205. package/src/tools/browser/cmux/rpc.ts +156 -0
  2206. package/src/tools/browser/cmux/socket-client.ts +309 -0
  2207. package/src/tools/browser/launch.ts +749 -0
  2208. package/src/tools/browser/readable.ts +112 -0
  2209. package/src/tools/browser/registry.ts +266 -0
  2210. package/src/tools/browser/render.ts +223 -0
  2211. package/src/tools/browser/run-cancellation.ts +47 -0
  2212. package/src/tools/browser/tab-protocol.ts +107 -0
  2213. package/src/tools/browser/tab-supervisor.ts +956 -0
  2214. package/src/tools/browser/tab-worker-entry.ts +29 -0
  2215. package/src/tools/browser/tab-worker.ts +1433 -0
  2216. package/src/tools/browser.ts +409 -0
  2217. package/src/tools/builtin-names.ts +58 -0
  2218. package/src/tools/checkpoint.ts +150 -0
  2219. package/src/tools/conflict-detect.ts +718 -0
  2220. package/src/tools/context.ts +39 -0
  2221. package/src/tools/debug.ts +1088 -0
  2222. package/src/tools/eval-backends.ts +34 -0
  2223. package/src/tools/eval-render.ts +776 -0
  2224. package/src/tools/eval.ts +767 -0
  2225. package/src/tools/fetch.ts +1966 -0
  2226. package/src/tools/file-recorder.ts +35 -0
  2227. package/src/tools/fs-cache-invalidation.ts +28 -0
  2228. package/src/tools/gh-cache-invalidation.ts +255 -0
  2229. package/src/tools/gh-format.ts +12 -0
  2230. package/src/tools/gh-renderer.ts +484 -0
  2231. package/src/tools/gh.ts +3752 -0
  2232. package/src/tools/github-cache.ts +663 -0
  2233. package/src/tools/glob.ts +639 -0
  2234. package/src/tools/grep.ts +1836 -0
  2235. package/src/tools/grouped-file-output.ts +210 -0
  2236. package/src/tools/image-gen.ts +1587 -0
  2237. package/src/tools/index.ts +682 -0
  2238. package/src/tools/inspect-image-renderer.ts +132 -0
  2239. package/src/tools/inspect-image.ts +260 -0
  2240. package/src/tools/irc.ts +827 -0
  2241. package/src/tools/job.ts +612 -0
  2242. package/src/tools/json-tree.ts +260 -0
  2243. package/src/tools/jtd-to-json-schema.ts +219 -0
  2244. package/src/tools/jtd-to-typescript.ts +136 -0
  2245. package/src/tools/jtd-utils.ts +102 -0
  2246. package/src/tools/learn.ts +141 -0
  2247. package/src/tools/list-limit.ts +40 -0
  2248. package/src/tools/manage-skill.ts +100 -0
  2249. package/src/tools/match-line-format.ts +20 -0
  2250. package/src/tools/memory-edit.ts +59 -0
  2251. package/src/tools/memory-recall.ts +102 -0
  2252. package/src/tools/memory-reflect.ts +88 -0
  2253. package/src/tools/memory-render.ts +202 -0
  2254. package/src/tools/memory-retain.ts +89 -0
  2255. package/src/tools/output-meta.ts +818 -0
  2256. package/src/tools/output-schema-validator.ts +307 -0
  2257. package/src/tools/path-utils.ts +1279 -0
  2258. package/src/tools/plan-mode-guard.ts +155 -0
  2259. package/src/tools/puppeteer/00_stealth_tampering.txt +44 -0
  2260. package/src/tools/puppeteer/01_stealth_activity.txt +80 -0
  2261. package/src/tools/puppeteer/02_stealth_hairline.txt +57 -0
  2262. package/src/tools/puppeteer/03_stealth_botd.txt +380 -0
  2263. package/src/tools/puppeteer/04_stealth_iframe.txt +174 -0
  2264. package/src/tools/puppeteer/05_stealth_webgl.txt +233 -0
  2265. package/src/tools/puppeteer/06_stealth_screen.txt +260 -0
  2266. package/src/tools/puppeteer/07_stealth_fonts.txt +99 -0
  2267. package/src/tools/puppeteer/08_stealth_audio.txt +63 -0
  2268. package/src/tools/puppeteer/09_stealth_locale.txt +51 -0
  2269. package/src/tools/puppeteer/10_stealth_plugins.txt +212 -0
  2270. package/src/tools/puppeteer/11_stealth_hardware.txt +59 -0
  2271. package/src/tools/puppeteer/12_stealth_codecs.txt +42 -0
  2272. package/src/tools/puppeteer/13_stealth_worker.txt +235 -0
  2273. package/src/tools/read.ts +3522 -0
  2274. package/src/tools/render-utils.ts +913 -0
  2275. package/src/tools/renderers.ts +107 -0
  2276. package/src/tools/report-tool-issue.ts +530 -0
  2277. package/src/tools/resolve.ts +302 -0
  2278. package/src/tools/review.ts +261 -0
  2279. package/src/tools/search-tool-bm25.ts +351 -0
  2280. package/src/tools/sqlite-reader.ts +884 -0
  2281. package/src/tools/ssh.ts +397 -0
  2282. package/src/tools/todo.ts +944 -0
  2283. package/src/tools/tool-errors.ts +62 -0
  2284. package/src/tools/tool-result.ts +102 -0
  2285. package/src/tools/tool-timeouts.ts +30 -0
  2286. package/src/tools/tts.ts +266 -0
  2287. package/src/tools/write.ts +1219 -0
  2288. package/src/tools/yield.ts +455 -0
  2289. package/src/tts/downloader.ts +64 -0
  2290. package/src/tts/index.ts +10 -0
  2291. package/src/tts/models.ts +137 -0
  2292. package/src/tts/player.ts +137 -0
  2293. package/src/tts/runtime.ts +21 -0
  2294. package/src/tts/speakable.ts +382 -0
  2295. package/src/tts/speech-enhancer.ts +204 -0
  2296. package/src/tts/streaming-player.ts +321 -0
  2297. package/src/tts/tts-client.ts +475 -0
  2298. package/src/tts/tts-protocol.ts +69 -0
  2299. package/src/tts/tts-worker.ts +434 -0
  2300. package/src/tts/vocalizer.ts +393 -0
  2301. package/src/tts/wav.ts +58 -0
  2302. package/src/tui/code-cell.ts +268 -0
  2303. package/src/tui/file-list.ts +55 -0
  2304. package/src/tui/hyperlink.ts +178 -0
  2305. package/src/tui/index.ts +13 -0
  2306. package/src/tui/output-block.ts +251 -0
  2307. package/src/tui/status-line.ts +54 -0
  2308. package/src/tui/tree-list.ts +133 -0
  2309. package/src/tui/types.ts +15 -0
  2310. package/src/tui/utils.ts +103 -0
  2311. package/src/tui/width-aware-text.ts +58 -0
  2312. package/src/utils/active-repo-context.ts +143 -0
  2313. package/src/utils/block-context.ts +312 -0
  2314. package/src/utils/changelog.ts +132 -0
  2315. package/src/utils/clipboard.ts +356 -0
  2316. package/src/utils/command-args.ts +76 -0
  2317. package/src/utils/commit-message-generator.ts +146 -0
  2318. package/src/utils/edit-mode.ts +58 -0
  2319. package/src/utils/enhanced-paste.ts +230 -0
  2320. package/src/utils/event-bus.ts +33 -0
  2321. package/src/utils/external-editor.ts +78 -0
  2322. package/src/utils/fetch-timeout.ts +10 -0
  2323. package/src/utils/file-display-mode.ts +44 -0
  2324. package/src/utils/file-mentions.ts +293 -0
  2325. package/src/utils/git.ts +2181 -0
  2326. package/src/utils/image-loading.ts +231 -0
  2327. package/src/utils/image-resize.ts +420 -0
  2328. package/src/utils/image-vision-fallback.ts +196 -0
  2329. package/src/utils/ipc.ts +38 -0
  2330. package/src/utils/jj.ts +295 -0
  2331. package/src/utils/lang-from-path.ts +244 -0
  2332. package/src/utils/markit-cache.ts +166 -0
  2333. package/src/utils/markit.ts +211 -0
  2334. package/src/utils/mupdf-wasm-embed.ts +12 -0
  2335. package/src/utils/open.ts +100 -0
  2336. package/src/utils/prompt-path.ts +3 -0
  2337. package/src/utils/qrcode.ts +535 -0
  2338. package/src/utils/session-color.ts +142 -0
  2339. package/src/utils/shell-snapshot-fn-env.sh +60 -0
  2340. package/src/utils/shell-snapshot.ts +306 -0
  2341. package/src/utils/sixel.ts +69 -0
  2342. package/src/utils/thinking-display.ts +117 -0
  2343. package/src/utils/title-generator.ts +348 -0
  2344. package/src/utils/tool-choice.ts +49 -0
  2345. package/src/utils/tools-manager.ts +429 -0
  2346. package/src/utils/turndown.ts +83 -0
  2347. package/src/utils/zip.ts +1091 -0
  2348. package/src/web/kagi.ts +304 -0
  2349. package/src/web/parallel.ts +354 -0
  2350. package/src/web/scrapers/artifacthub.ts +207 -0
  2351. package/src/web/scrapers/arxiv.ts +83 -0
  2352. package/src/web/scrapers/aur.ts +162 -0
  2353. package/src/web/scrapers/biorxiv.ts +133 -0
  2354. package/src/web/scrapers/bluesky.ts +262 -0
  2355. package/src/web/scrapers/brew.ts +172 -0
  2356. package/src/web/scrapers/cheatsh.ts +68 -0
  2357. package/src/web/scrapers/chocolatey.ts +196 -0
  2358. package/src/web/scrapers/choosealicense.ts +95 -0
  2359. package/src/web/scrapers/cisa-kev.ts +87 -0
  2360. package/src/web/scrapers/clojars.ts +154 -0
  2361. package/src/web/scrapers/coingecko.ts +177 -0
  2362. package/src/web/scrapers/crates-io.ts +97 -0
  2363. package/src/web/scrapers/crossref.ts +136 -0
  2364. package/src/web/scrapers/devto.ts +147 -0
  2365. package/src/web/scrapers/discogs.ts +306 -0
  2366. package/src/web/scrapers/discourse.ts +197 -0
  2367. package/src/web/scrapers/dockerhub.ts +138 -0
  2368. package/src/web/scrapers/docs-rs.ts +652 -0
  2369. package/src/web/scrapers/fdroid.ts +134 -0
  2370. package/src/web/scrapers/firefox-addons.ts +191 -0
  2371. package/src/web/scrapers/flathub.ts +223 -0
  2372. package/src/web/scrapers/github-gist.ts +58 -0
  2373. package/src/web/scrapers/github.ts +800 -0
  2374. package/src/web/scrapers/gitlab.ts +401 -0
  2375. package/src/web/scrapers/go-pkg.ts +266 -0
  2376. package/src/web/scrapers/hackage.ts +140 -0
  2377. package/src/web/scrapers/hackernews.ts +189 -0
  2378. package/src/web/scrapers/hex.ts +105 -0
  2379. package/src/web/scrapers/huggingface.ts +321 -0
  2380. package/src/web/scrapers/iacr.ts +89 -0
  2381. package/src/web/scrapers/index.ts +252 -0
  2382. package/src/web/scrapers/jetbrains-marketplace.ts +159 -0
  2383. package/src/web/scrapers/lemmy.ts +203 -0
  2384. package/src/web/scrapers/lobsters.ts +175 -0
  2385. package/src/web/scrapers/mastodon.ts +292 -0
  2386. package/src/web/scrapers/maven.ts +138 -0
  2387. package/src/web/scrapers/mdn.ts +173 -0
  2388. package/src/web/scrapers/metacpan.ts +222 -0
  2389. package/src/web/scrapers/musicbrainz.ts +250 -0
  2390. package/src/web/scrapers/npm.ts +98 -0
  2391. package/src/web/scrapers/nuget.ts +183 -0
  2392. package/src/web/scrapers/nvd.ts +222 -0
  2393. package/src/web/scrapers/ollama.ts +239 -0
  2394. package/src/web/scrapers/open-vsx.ts +106 -0
  2395. package/src/web/scrapers/opencorporates.ts +292 -0
  2396. package/src/web/scrapers/openlibrary.ts +336 -0
  2397. package/src/web/scrapers/orcid.ts +286 -0
  2398. package/src/web/scrapers/osv.ts +176 -0
  2399. package/src/web/scrapers/packagist.ts +160 -0
  2400. package/src/web/scrapers/pub-dev.ts +143 -0
  2401. package/src/web/scrapers/pubmed.ts +211 -0
  2402. package/src/web/scrapers/pypi.ts +112 -0
  2403. package/src/web/scrapers/rawg.ts +110 -0
  2404. package/src/web/scrapers/readthedocs.ts +120 -0
  2405. package/src/web/scrapers/reddit.ts +95 -0
  2406. package/src/web/scrapers/repology.ts +251 -0
  2407. package/src/web/scrapers/rfc.ts +201 -0
  2408. package/src/web/scrapers/rubygems.ts +103 -0
  2409. package/src/web/scrapers/searchcode.ts +189 -0
  2410. package/src/web/scrapers/sec-edgar.ts +261 -0
  2411. package/src/web/scrapers/semantic-scholar.ts +171 -0
  2412. package/src/web/scrapers/snapcraft.ts +187 -0
  2413. package/src/web/scrapers/sourcegraph.ts +336 -0
  2414. package/src/web/scrapers/spdx.ts +108 -0
  2415. package/src/web/scrapers/spotify.ts +198 -0
  2416. package/src/web/scrapers/stackoverflow.ts +120 -0
  2417. package/src/web/scrapers/terraform.ts +277 -0
  2418. package/src/web/scrapers/tldr.ts +47 -0
  2419. package/src/web/scrapers/twitter.ts +94 -0
  2420. package/src/web/scrapers/types.ts +354 -0
  2421. package/src/web/scrapers/utils.ts +109 -0
  2422. package/src/web/scrapers/vimeo.ts +133 -0
  2423. package/src/web/scrapers/vscode-marketplace.ts +187 -0
  2424. package/src/web/scrapers/w3c.ts +156 -0
  2425. package/src/web/scrapers/wikidata.ts +344 -0
  2426. package/src/web/scrapers/wikipedia.ts +84 -0
  2427. package/src/web/scrapers/youtube.ts +325 -0
  2428. package/src/web/search/index.ts +312 -0
  2429. package/src/web/search/provider.ts +214 -0
  2430. package/src/web/search/providers/anthropic.ts +343 -0
  2431. package/src/web/search/providers/base.ts +91 -0
  2432. package/src/web/search/providers/brave.ts +152 -0
  2433. package/src/web/search/providers/codex.ts +593 -0
  2434. package/src/web/search/providers/duckduckgo.ts +212 -0
  2435. package/src/web/search/providers/exa.ts +484 -0
  2436. package/src/web/search/providers/firecrawl.ts +144 -0
  2437. package/src/web/search/providers/gemini.ts +618 -0
  2438. package/src/web/search/providers/jina.ts +111 -0
  2439. package/src/web/search/providers/kagi.ts +86 -0
  2440. package/src/web/search/providers/kimi.ts +196 -0
  2441. package/src/web/search/providers/parallel.ts +136 -0
  2442. package/src/web/search/providers/perplexity-auth.ts +133 -0
  2443. package/src/web/search/providers/perplexity.ts +878 -0
  2444. package/src/web/search/providers/searxng.ts +325 -0
  2445. package/src/web/search/providers/synthetic.ts +114 -0
  2446. package/src/web/search/providers/tavily.ts +193 -0
  2447. package/src/web/search/providers/tinyfish.ts +159 -0
  2448. package/src/web/search/providers/utils.ts +128 -0
  2449. package/src/web/search/providers/xai.ts +292 -0
  2450. package/src/web/search/providers/zai.ts +419 -0
  2451. package/src/web/search/render.ts +262 -0
  2452. package/src/web/search/types.ts +470 -0
  2453. package/src/web/search/utils.ts +17 -0
  2454. package/src/workspace-tree.ts +326 -0
@@ -0,0 +1,4223 @@
1
+ /**
2
+ * Interactive mode for the coding agent.
3
+ * Handles TUI rendering and user interaction, delegating business logic to AgentSession.
4
+ */
5
+ import * as fs from "node:fs/promises";
6
+ import * as path from "node:path";
7
+ import {
8
+ type Agent,
9
+ type AgentMessage,
10
+ type AgentToolResult,
11
+ EventLoopKeepalive,
12
+ ThinkingLevel,
13
+ } from "@oh-my-pi-zen/pi-agent-core";
14
+ import type { CompactionOutcome } from "@oh-my-pi-zen/pi-agent-core/compaction";
15
+ import type { AssistantMessage, ImageContent, Message, Model, Usage, UsageReport } from "@oh-my-pi-zen/pi-ai";
16
+ import { modelsAreEqual } from "@oh-my-pi-zen/pi-catalog/models";
17
+ import type {
18
+ Component,
19
+ EditorTheme,
20
+ LoaderMessageColorFn,
21
+ NativeScrollbackLiveRegion,
22
+ OverlayHandle,
23
+ SlashCommand,
24
+ } from "@oh-my-pi-zen/pi-tui";
25
+ import {
26
+ Container,
27
+ clearRenderCache,
28
+ Loader,
29
+ Markdown,
30
+ ProcessTerminal,
31
+ Spacer,
32
+ setTerminalTextSizing,
33
+ setTuiTight,
34
+ TERMINAL,
35
+ Text,
36
+ TUI,
37
+ visibleWidth,
38
+ } from "@oh-my-pi-zen/pi-tui";
39
+ import { isInsideTerminalMultiplexer } from "@oh-my-pi-zen/pi-tui/terminal-capabilities";
40
+ import {
41
+ APP_NAME,
42
+ adjustHsv,
43
+ formatNumber,
44
+ getProjectDir,
45
+ hsvToRgb,
46
+ isEnoent,
47
+ logger,
48
+ postmortem,
49
+ prompt,
50
+ setProjectDir,
51
+ } from "@oh-my-pi-zen/pi-utils";
52
+ import chalk from "chalk";
53
+ import { reset as resetCapabilities } from "../capability";
54
+ import type { CollabGuestLink } from "../collab/guest";
55
+ import type { CollabHost } from "../collab/host";
56
+ import { KeybindingsManager } from "../config/keybindings";
57
+ import { applyProviderGlobalsFromSettings } from "../config/provider-globals";
58
+ import { isSettingsInitialized, onStatusLineSessionAccentChanged, Settings, settings } from "../config/settings";
59
+ import { clearClaudePluginRootsCache } from "../discovery/helpers";
60
+ import type {
61
+ ContextUsage,
62
+ ExtensionUIContext,
63
+ ExtensionUIDialogOptions,
64
+ ExtensionUISelectItem,
65
+ ExtensionWidgetContent,
66
+ ExtensionWidgetOptions,
67
+ } from "../extensibility/extensions";
68
+ import type { CompactOptions } from "../extensibility/extensions/types";
69
+ import type { Skill } from "../extensibility/skills";
70
+ import { loadSlashCommands } from "../extensibility/slash-commands";
71
+ import { type GuidedGoalMessage, runGuidedGoalTurn } from "../goals/guided-setup";
72
+ import type { Goal, GoalModeState } from "../goals/state";
73
+ import { resolveLocalUrlToPath } from "../internal-urls";
74
+ import { LSP_STARTUP_EVENT_CHANNEL, type LspStartupEvent } from "../lsp/startup-events";
75
+ import type { MCPManager } from "../mcp";
76
+ import {
77
+ formatMCPConnectionStatusMessage,
78
+ isMcpConnectionStatusEvent,
79
+ MCP_CONNECTION_STATUS_EVENT_CHANNEL,
80
+ type McpConnectionStatusEvent,
81
+ } from "../mcp/startup-events";
82
+ import {
83
+ humanizePlanTitle,
84
+ type PlanApprovalDetails,
85
+ resolveApprovedPlan,
86
+ resolvePlanTitle,
87
+ } from "../plan-mode/approved-plan";
88
+ import planModeApprovedPrompt from "../prompts/system/plan-mode-approved.md" with { type: "text" };
89
+ import planModeCompactInstructionsPrompt from "../prompts/system/plan-mode-compact-instructions.md" with {
90
+ type: "text",
91
+ };
92
+ import type { AgentRegistry } from "../registry/agent-registry";
93
+ import {
94
+ type AgentSession,
95
+ type AgentSessionEvent,
96
+ type ResolvedRoleModel,
97
+ SHUTDOWN_CONSOLIDATE_BUDGET_MS,
98
+ } from "../session/agent-session";
99
+ import type { CompactMode } from "../session/compact-modes";
100
+ import { HistoryStorage } from "../session/history-storage";
101
+ import type { SessionContext } from "../session/session-context";
102
+ import { getRecentSessions } from "../session/session-listing";
103
+ import type { SessionManager } from "../session/session-manager";
104
+ import type { ShakeMode } from "../session/shake-types";
105
+ import { BUILTIN_SLASH_COMMAND_RESERVED_NAMES, buildTuiBuiltinSlashCommands } from "../slash-commands/builtin-registry";
106
+ import { formatDuration } from "../slash-commands/helpers/format";
107
+ import { STTController, type SttState } from "../stt";
108
+ import { discoverTitleSystemPromptFile, resolvePromptInput } from "../system-prompt";
109
+ import { formatTaskId } from "../task/render";
110
+ import type { ConfiguredThinkingLevel } from "../thinking";
111
+ import type { LspStartupServerInfo } from "../tools";
112
+ import { normalizeLocalScheme } from "../tools/path-utils";
113
+ import { replaceTabs, TRUNCATE_LENGTHS, truncateToWidth } from "../tools/render-utils";
114
+ import { setAutoQaConsentHandler } from "../tools/report-tool-issue";
115
+ import { type ResolveToolDetails, runResolveInvocation } from "../tools/resolve";
116
+ import { formatPhaseDisplayName, todoMatchesAnyDescription } from "../tools/todo";
117
+ import { ToolError } from "../tools/tool-errors";
118
+ import { vocalizer } from "../tts/vocalizer";
119
+ import { renderTreeList } from "../tui/tree-list";
120
+ import type { EventBus } from "../utils/event-bus";
121
+ import { getEditorCommand, openInEditor } from "../utils/external-editor";
122
+ import { getSessionAccentAnsi, getSessionAccentHex } from "../utils/session-color";
123
+ import { messageHasDisplayableThinking } from "../utils/thinking-display";
124
+ import { popTerminalTitle, pushTerminalTitle, setSessionTerminalTitle } from "../utils/title-generator";
125
+ import type { AssistantMessageComponent } from "./components/assistant-message";
126
+ import type { BashExecutionComponent } from "./components/bash-execution";
127
+ import { ChatBlock, type ChatBlockHost } from "./components/chat-block";
128
+ import { CustomEditor } from "./components/custom-editor";
129
+ import { DynamicBorder } from "./components/dynamic-border";
130
+ import { ErrorBannerComponent } from "./components/error-banner";
131
+ import type { EvalExecutionComponent } from "./components/eval-execution";
132
+ import type { HookEditorComponent } from "./components/hook-editor";
133
+ import type { HookInputComponent } from "./components/hook-input";
134
+ import type { HookSelectorComponent, HookSelectorSlider } from "./components/hook-selector";
135
+ import { PlanReviewOverlay } from "./components/plan-review-overlay";
136
+ import { StatusLineComponent } from "./components/status-line";
137
+ import type { ToolExecutionHandle } from "./components/tool-execution";
138
+ import { TranscriptContainer } from "./components/transcript-container";
139
+ import { WelcomeComponent, type LspServerInfo as WelcomeLspServerInfo } from "./components/welcome";
140
+ import { BtwController } from "./controllers/btw-controller";
141
+ import { CommandController } from "./controllers/command-controller";
142
+ import { EventController } from "./controllers/event-controller";
143
+ import { ExtensionUiController } from "./controllers/extension-ui-controller";
144
+ import { InputController } from "./controllers/input-controller";
145
+ import { MCPCommandController } from "./controllers/mcp-command-controller";
146
+ import { OmfgController } from "./controllers/omfg-controller";
147
+ import { SelectorController } from "./controllers/selector-controller";
148
+ import { SessionFocusController } from "./controllers/session-focus-controller";
149
+ import { SSHCommandController } from "./controllers/ssh-command-controller";
150
+ import { TanCommandController } from "./controllers/tan-command-controller";
151
+ import { TodoCommandController } from "./controllers/todo-command-controller";
152
+ import {
153
+ consumeLoopLimitIteration,
154
+ createLoopLimitRuntime,
155
+ describeLoopLimit,
156
+ describeLoopLimitRuntime,
157
+ isLoopDurationExpired,
158
+ type LoopLimitRuntime,
159
+ parseLoopLimitArgs,
160
+ } from "./loop-limit";
161
+ import { OAuthManualInputManager } from "./oauth-manual-input";
162
+ import { countRunningSubagentBadgeAgents, getRunningSubagentBadgeRegistry } from "./running-subagent-badge";
163
+ import type { ObservableSession } from "./session-observer-registry";
164
+ import { SessionObserverRegistry } from "./session-observer-registry";
165
+ import { createSessionTeardown, type SessionTeardown } from "./session-teardown";
166
+ import { runProviderSetupWizard } from "./setup-wizard/lazy";
167
+ import { interruptHint } from "./shared";
168
+ import { clearMermaidCache } from "./theme/mermaid-cache";
169
+ import { type ShimmerPalette, shimmerEnabled, shimmerSegments, shimmerText } from "./theme/shimmer";
170
+ import type { Theme } from "./theme/theme";
171
+ import {
172
+ getEditorTheme,
173
+ getMarkdownTheme,
174
+ getSymbolTheme,
175
+ onTerminalAppearanceChange,
176
+ onThemeChange,
177
+ setMarkdownMermaidRendering,
178
+ theme,
179
+ } from "./theme/theme";
180
+ import type {
181
+ CompactionQueuedMessage,
182
+ InteractiveModeContext,
183
+ InteractiveModeInitOptions,
184
+ InteractiveSelectorDialogOptions,
185
+ SubmittedUserInput,
186
+ TodoItem,
187
+ TodoPhase,
188
+ } from "./types";
189
+ import { UiHelpers } from "./utils/ui-helpers";
190
+
191
+ const HINT_SHIMMER_PALETTE: ShimmerPalette = {
192
+ low: "dim",
193
+ mid: "muted",
194
+ high: "borderAccent",
195
+ };
196
+
197
+ interface WorkingMessageAccent {
198
+ main: string;
199
+ dim: string;
200
+ }
201
+
202
+ interface WorkingMessageAccentCacheKey {
203
+ sessionName: string | undefined;
204
+ accentSurfaceLuminance: number | undefined;
205
+ sessionAccentEnabled: boolean;
206
+ }
207
+
208
+ function renderWorkingMessage(message: string, accent?: WorkingMessageAccent): string {
209
+ const palette = accent
210
+ ? ({
211
+ low: "dim",
212
+ mid: { ansi: accent.main },
213
+ high: { ansi: accent.main },
214
+ bold: true,
215
+ } satisfies ShimmerPalette)
216
+ : undefined;
217
+ const hint = interruptHint();
218
+ if (!message.endsWith(hint)) return shimmerText(message, theme, palette);
219
+ const header = message.slice(0, -hint.length);
220
+ const hintPalette = accent
221
+ ? ({
222
+ low: "dim",
223
+ mid: { ansi: accent.dim },
224
+ high: { ansi: accent.dim },
225
+ } satisfies ShimmerPalette)
226
+ : HINT_SHIMMER_PALETTE;
227
+ return shimmerSegments(
228
+ [
229
+ { text: header, palette },
230
+ { text: hint, palette: hintPalette },
231
+ ],
232
+ theme,
233
+ );
234
+ }
235
+
236
+ const EDITOR_MAX_HEIGHT_MIN = 6;
237
+ const EDITOR_MAX_HEIGHT_MAX = 18;
238
+ const EDITOR_RESERVED_ROWS = 12;
239
+ const EDITOR_FALLBACK_ROWS = 24;
240
+ const EDITOR_MIN_CHROME_ROWS = 4; // rows reserved for transcript + status on small terms
241
+ const EDITOR_MIN_RENDERED_ROWS = 3; // bordered editor floor: top+bottom border + 1 content row
242
+
243
+ /**
244
+ * Editor max-height cap for a terminal of `terminalRows` rows.
245
+ *
246
+ * Roomy terminals get the comfortable [6, 18] band. Small terminals shrink the
247
+ * cap so the editor leaves at least EDITOR_MIN_CHROME_ROWS rows for the
248
+ * transcript + status line. The editor is bordered, so it never renders fewer
249
+ * than EDITOR_MIN_RENDERED_ROWS rows; once the terminal is too small for both
250
+ * (terminalRows < EDITOR_MIN_RENDERED_ROWS + EDITOR_MIN_CHROME_ROWS) the cap is
251
+ * pinned to that floor — returning a smaller number would not shrink the editor
252
+ * any further, it would only misreport the rows it actually occupies.
253
+ */
254
+ export function computeEditorMaxHeight(terminalRows: number): number {
255
+ const rows = Number.isFinite(terminalRows) && terminalRows > 0 ? terminalRows : EDITOR_FALLBACK_ROWS;
256
+ const comfortable = Math.max(EDITOR_MAX_HEIGHT_MIN, Math.min(EDITOR_MAX_HEIGHT_MAX, rows - EDITOR_RESERVED_ROWS));
257
+ return Math.max(EDITOR_MIN_RENDERED_ROWS, Math.min(comfortable, rows - EDITOR_MIN_CHROME_ROWS));
258
+ }
259
+
260
+ const HUD_NOTE_SUP_DIGITS: Record<string, string> = {
261
+ "0": "\u2070",
262
+ "1": "\u00b9",
263
+ "2": "\u00b2",
264
+ "3": "\u00b3",
265
+ "4": "\u2074",
266
+ "5": "\u2075",
267
+ "6": "\u2076",
268
+ "7": "\u2077",
269
+ "8": "\u2078",
270
+ "9": "\u2079",
271
+ };
272
+
273
+ function formatHudNoteMarker(count: number): string {
274
+ if (count <= 0) return "";
275
+ const sub = String(count)
276
+ .split("")
277
+ .map(d => HUD_NOTE_SUP_DIGITS[d] ?? d)
278
+ .join("");
279
+ return theme.fg("dim", chalk.italic(` \u207a${sub}`));
280
+ }
281
+
282
+ type GoalSubcommand = "set" | "show" | "pause" | "resume" | "drop" | "budget";
283
+
284
+ const GOAL_SUBCOMMANDS = new Set<GoalSubcommand>(["set", "show", "pause", "resume", "drop", "budget"]);
285
+ const PLAN_KEEP_CONTEXT_OPTION_INDEX = 2;
286
+ const PLAN_KEEP_CONTEXT_DISABLE_THRESHOLD_PERCENT = 95;
287
+
288
+ function parseGoalSubcommand(args: string): { sub: GoalSubcommand | undefined; rest: string } {
289
+ const trimmed = args.trim();
290
+ if (!trimmed) return { sub: undefined, rest: "" };
291
+ const match = /^(\S+)(?:\s+([\s\S]*))?$/.exec(trimmed);
292
+ if (!match) return { sub: undefined, rest: trimmed };
293
+ const first = match[1].toLowerCase();
294
+ if (GOAL_SUBCOMMANDS.has(first as GoalSubcommand)) {
295
+ return { sub: first as GoalSubcommand, rest: match[2]?.trim() ?? "" };
296
+ }
297
+ return { sub: undefined, rest: trimmed };
298
+ }
299
+
300
+ function formatContextTokenCount(value: number): string {
301
+ return formatNumber(Math.max(0, Math.round(value))).toLowerCase();
302
+ }
303
+
304
+ /** Options for creating an InteractiveMode instance (for future API use) */
305
+ export interface InteractiveModeOptions {
306
+ /** Providers that were migrated during startup */
307
+ migratedProviders?: string[];
308
+ /** Warning message if model fallback occurred */
309
+ modelFallbackMessage?: string;
310
+ /** Initial message to send */
311
+ initialMessage?: string;
312
+ /** Initial images to include with the message */
313
+ initialImages?: ImageContent[];
314
+ /** Additional initial messages to queue */
315
+ initialMessages?: string[];
316
+ }
317
+
318
+ /**
319
+ * Anchored live-region container for the HUD/status rows between the transcript
320
+ * and the editor (working loader, todo + subagent HUDs, transient notification
321
+ * panels). While it has content every row is live: it reports a seam at 0 so the
322
+ * engine never commits these anchored, rebuilt-in-place rows to native
323
+ * scrollback — otherwise stale duplicates pile up above the live copy on short
324
+ * terminals once the loader sits below a tall HUD. The transcript's own seam,
325
+ * when present, sits higher and wins (topmost-seam merge in TUI.render).
326
+ */
327
+ class AnchoredLiveContainer extends Container implements NativeScrollbackLiveRegion {
328
+ getNativeScrollbackLiveRegionStart(): number | undefined {
329
+ return this.children.length > 0 ? 0 : undefined;
330
+ }
331
+ }
332
+
333
+ /** How long the ctrl+p model-role cycle chip track lingers above the editor
334
+ * before it auto-clears, mirroring the todo HUD's auto-clear timer. */
335
+ const MODEL_CYCLE_TRACK_CLEAR_MS = 4000;
336
+
337
+ /**
338
+ * Build the anchored subagent HUD block: a bold accent "Subagents" header plus
339
+ * one tree row per running agent in the same `Id: description` shape the
340
+ * inline task rows use (muted task preview when no description was given).
341
+ * Layout mirrors the Todos HUD exactly: unindented header, then
342
+ * `renderTreeList` rows (dim connectors) shifted right by one space.
343
+ * Only detached background spawns are listed: a sync task call blocks the
344
+ * parent turn and its inline tool block already renders progress live, and
345
+ * eval `agent()` spawns are rendered by their own eval cell tree.
346
+ * Returns an empty array when nothing is running so the container can clear.
347
+ */
348
+ export function renderSubagentHudLines(sessions: ObservableSession[], columns: number): string[] {
349
+ const running = sessions.filter(
350
+ session => session.kind === "subagent" && session.status === "active" && session.detached === true,
351
+ );
352
+ if (running.length === 0) return [];
353
+
354
+ const dot = theme.styledSymbol("status.done", "accent");
355
+ const rows = renderTreeList(
356
+ {
357
+ items: running,
358
+ expanded: true,
359
+ renderItem: session => {
360
+ const displayId = formatTaskId(session.id);
361
+ let line = `${dot} ${theme.fg("accent", theme.bold(displayId))}`;
362
+ const description = session.description?.trim() || session.progress?.description?.trim();
363
+ if (description) {
364
+ const budget = Math.max(TRUNCATE_LENGTHS.SHORT, columns - visibleWidth(displayId) - 10);
365
+ line += `${theme.fg("accent", ":")} ${theme.fg("accent", truncateToWidth(replaceTabs(description), budget))}`;
366
+ } else {
367
+ // No spawn description: fall back to a muted task preview, same as
368
+ // the inline task rows when a row has no label.
369
+ const taskPreview = session.progress?.task?.trim();
370
+ if (taskPreview) {
371
+ line += ` ${theme.fg("muted", truncateToWidth(replaceTabs(taskPreview), TRUNCATE_LENGTHS.SHORT))}`;
372
+ }
373
+ }
374
+ return line;
375
+ },
376
+ },
377
+ theme,
378
+ );
379
+ return ["", theme.bold(theme.fg("accent", "Subagents")), ...rows.map(line => ` ${line}`)];
380
+ }
381
+
382
+ export class InteractiveMode implements InteractiveModeContext {
383
+ session: AgentSession;
384
+ sessionManager: SessionManager;
385
+ settings: Settings;
386
+ keybindings: KeybindingsManager;
387
+ agent: Agent;
388
+ historyStorage?: HistoryStorage;
389
+
390
+ ui: TUI;
391
+ chatContainer: TranscriptContainer;
392
+ pendingMessagesContainer: Container;
393
+ statusContainer: Container;
394
+ todoContainer: Container;
395
+ subagentContainer: Container;
396
+ btwContainer: Container;
397
+ omfgContainer: Container;
398
+ errorBannerContainer: Container;
399
+ modelCycleContainer: Container;
400
+ editor: CustomEditor;
401
+ editorContainer: Container;
402
+ hookWidgetContainerAbove: Container;
403
+ hookWidgetContainerBelow: Container;
404
+ statusLine: StatusLineComponent;
405
+
406
+ isInitialized = false;
407
+ initialChatRendered = false;
408
+ isBashMode = false;
409
+ toolOutputExpanded = false;
410
+ todoExpanded = false;
411
+ planModeEnabled = false;
412
+ planModePaused = false;
413
+ goalModeEnabled = false;
414
+ goalModePaused = false;
415
+ planModePlanFilePath: string | undefined = undefined;
416
+ loopModeEnabled = false;
417
+ loopPrompt: string | undefined = undefined;
418
+ loopLimit: LoopLimitRuntime | undefined = undefined;
419
+ #loopAutoSubmitTimer: NodeJS.Timeout | undefined;
420
+ #todoAutoClearTimer: NodeJS.Timeout | undefined;
421
+ #modelCycleClearTimer: NodeJS.Timeout | undefined;
422
+ todoPhases: TodoPhase[] = [];
423
+ hideThinkingBlock = false;
424
+ #sessionsWithDisplayableThinkingContent = new WeakSet<AgentSession>();
425
+ /** Whether the visible session has produced thinking content the user can reveal. */
426
+ get hasDisplayableThinkingContent(): boolean {
427
+ return this.#sessionsWithDisplayableThinkingContent.has(this.viewSession);
428
+ }
429
+ /** Record received reasoning content so Ctrl+T can reveal it even when model metadata says thinking is off. */
430
+ noteDisplayableThinkingContent(message: AgentMessage): boolean {
431
+ if (this.hasDisplayableThinkingContent || !messageHasDisplayableThinking(message, this.proseOnlyThinking)) {
432
+ return false;
433
+ }
434
+ this.#sessionsWithDisplayableThinkingContent.add(this.viewSession);
435
+ return true;
436
+ }
437
+ /**
438
+ * Effective thinking-block visibility: hidden when the user's setting is on,
439
+ * or while thinking is "off" before the session has actually produced
440
+ * displayable thinking content. Some providers return thinking blocks without
441
+ * advertising reasoning support, so observed content unlocks the visibility
442
+ * toggle.
443
+ */
444
+ get effectiveHideThinkingBlock(): boolean {
445
+ const thinkingOff = (this.viewSession?.thinkingLevel ?? ThinkingLevel.Off) === ThinkingLevel.Off;
446
+ return this.hideThinkingBlock || (thinkingOff && !this.hasDisplayableThinkingContent);
447
+ }
448
+ proseOnlyThinking = true;
449
+ compactionQueuedMessages: CompactionQueuedMessage[] = [];
450
+ pendingTools = new Map<string, ToolExecutionHandle>();
451
+ pendingBashComponents: BashExecutionComponent[] = [];
452
+ bashComponent: BashExecutionComponent | undefined = undefined;
453
+ pendingPythonComponents: EvalExecutionComponent[] = [];
454
+ pythonComponent: EvalExecutionComponent | undefined = undefined;
455
+ isPythonMode = false;
456
+ streamingComponent: AssistantMessageComponent | undefined = undefined;
457
+ streamingMessage: AssistantMessage | undefined = undefined;
458
+ lastAssistantUsage: Usage | undefined = undefined;
459
+ loadingAnimation: Loader | undefined = undefined;
460
+ autoCompactionLoader: Loader | undefined = undefined;
461
+ retryLoader: Loader | undefined = undefined;
462
+ #pendingWorkingMessage: string | undefined;
463
+ #workingMessageAccentCacheKey?: WorkingMessageAccentCacheKey;
464
+ #workingMessageAccentCacheValue?: WorkingMessageAccent;
465
+ #workingMessageAccentCacheHasValue = false;
466
+ get #defaultWorkingMessage(): string {
467
+ return `Working…${interruptHint()}`;
468
+ }
469
+ unsubscribe?: () => void;
470
+ onInputCallback?: (input: SubmittedUserInput) => void;
471
+ optimisticUserMessageSignature: string | undefined = undefined;
472
+ locallySubmittedUserSignatures: Set<string> = new Set();
473
+ #pendingSubmittedInput: SubmittedUserInput | undefined;
474
+ #pendingSubmissionDispose: (() => void) | undefined;
475
+ #optimisticUserMessageComponents: Component[] = [];
476
+ lastSigintTime = 0;
477
+ lastEscapeTime = 0;
478
+ lastLeftTapTime = 0;
479
+ shutdownRequested = false;
480
+ #isShuttingDown = false;
481
+ /** True once `shutdown()` has begun teardown. Surfaced to the input
482
+ * controller so a Ctrl+C arriving while teardown is in flight can hard-
483
+ * abort the remaining work instead of stacking another no-op call. */
484
+ get isShuttingDown(): boolean {
485
+ return this.#isShuttingDown;
486
+ }
487
+ hookSelector: HookSelectorComponent | undefined = undefined;
488
+ hookInput: HookInputComponent | undefined = undefined;
489
+ hookEditor: HookEditorComponent | undefined = undefined;
490
+ lastStatusSpacer: Spacer | undefined = undefined;
491
+ lastStatusText: Text | undefined = undefined;
492
+ fileSlashCommands: Set<string> = new Set();
493
+ skillCommands: Map<string, Skill> = new Map();
494
+ oauthManualInput: OAuthManualInputManager = new OAuthManualInputManager();
495
+ collabHost?: CollabHost;
496
+ collabGuest?: CollabGuestLink;
497
+
498
+ #pendingSlashCommands: SlashCommand[] = [];
499
+ #cleanupUnsubscribe?: () => void;
500
+ #signalTeardown?: SessionTeardown;
501
+ readonly #version: string;
502
+ readonly #changelogMarkdown: string | undefined;
503
+ #planModePreviousTools: string[] | undefined;
504
+ #goalModePreviousTools: string[] | undefined;
505
+ #goalContinuationTimer: NodeJS.Timeout | undefined;
506
+ #goalTurnHadToolCalls = false;
507
+ #goalContinuationTurnInFlight = false;
508
+ #goalSuppressNextContinuation = false;
509
+ #planModePreviousModelState: { model: Model; thinkingLevel?: ConfiguredThinkingLevel } | undefined;
510
+ #pendingModelSwitch: { model: Model; thinkingLevel?: ConfiguredThinkingLevel } | undefined;
511
+ #planModeHasEntered = false;
512
+ #planReviewOverlay: PlanReviewOverlay | undefined;
513
+ #planReviewOverlayHandle: OverlayHandle | undefined;
514
+ readonly lspServers: LspStartupServerInfo[] | undefined = undefined;
515
+ mcpManager?: MCPManager;
516
+ readonly #toolUiContextSetter: (uiContext: ExtensionUIContext, hasUI: boolean) => void;
517
+
518
+ readonly #btwController: BtwController;
519
+ readonly #tanCommandController: TanCommandController;
520
+ readonly #omfgController: OmfgController;
521
+ readonly #commandController: CommandController;
522
+ readonly #todoCommandController: TodoCommandController;
523
+ readonly #eventController: EventController;
524
+ get eventController(): EventController {
525
+ return this.#eventController;
526
+ }
527
+ get eventBus(): EventBus | undefined {
528
+ return this.#eventBus;
529
+ }
530
+ readonly #extensionUiController: ExtensionUiController;
531
+ readonly #inputController: InputController;
532
+ readonly #selectorController: SelectorController;
533
+ readonly #focusController: SessionFocusController;
534
+ get viewSession(): AgentSession {
535
+ return this.#focusController.target ?? this.session;
536
+ }
537
+ get focusedAgentId(): string | undefined {
538
+ return this.#focusController.focusedAgentId;
539
+ }
540
+ focusAgentSession(id: string): Promise<void> {
541
+ return this.#focusController.focusAgent(id);
542
+ }
543
+ focusParentSession(): Promise<void> {
544
+ return this.#focusController.focusParent();
545
+ }
546
+ unfocusSession(): Promise<void> {
547
+ return this.#focusController.unfocus();
548
+ }
549
+ clearTransientSessionUi(): void {
550
+ if (this.loadingAnimation) {
551
+ this.loadingAnimation.stop();
552
+ this.loadingAnimation = undefined;
553
+ }
554
+ if (this.autoCompactionLoader) {
555
+ this.autoCompactionLoader.stop();
556
+ this.autoCompactionLoader = undefined;
557
+ }
558
+ if (this.retryLoader) {
559
+ this.retryLoader.stop();
560
+ this.retryLoader = undefined;
561
+ }
562
+ this.statusContainer.clear();
563
+ this.pendingMessagesContainer.clear();
564
+ this.#cancelModelCycleClearTimer();
565
+ this.modelCycleContainer.clear();
566
+ this.compactionQueuedMessages = [];
567
+ this.streamingComponent = undefined;
568
+ this.streamingMessage = undefined;
569
+ this.lastAssistantUsage = undefined;
570
+ this.pendingTools.clear();
571
+ }
572
+ readonly #uiHelpers: UiHelpers;
573
+ #sttController: STTController | undefined;
574
+ #voiceAnimationInterval: NodeJS.Timeout | undefined;
575
+ #voiceHue = 0;
576
+ #voicePreviousShowHardwareCursor: boolean | null = null;
577
+ #voicePreviousUseTerminalCursor: boolean | null = null;
578
+ #resizeHandler?: () => void;
579
+ #observerRegistry: SessionObserverRegistry;
580
+ #eventBus?: EventBus;
581
+ #eventBusUnsubscribers: Array<() => void> = [];
582
+ #agentRegistryUnsubscribe?: () => void;
583
+ #agentRegistrySubscriptionTarget?: AgentRegistry;
584
+ #mcpStatusOrder: string[] = [];
585
+ #mcpPendingServers = new Set<string>();
586
+ #mcpConnectedServers = new Set<string>();
587
+ #mcpFailedServers = new Map<string, string>();
588
+ #welcomeComponent?: WelcomeComponent;
589
+ readonly #chatHost: ChatBlockHost = { requestRender: () => this.ui.requestRender() };
590
+
591
+ constructor(
592
+ session: AgentSession,
593
+ version: string,
594
+ changelogMarkdown: string | undefined = undefined,
595
+ setToolUIContext: (uiContext: ExtensionUIContext, hasUI: boolean) => void = () => {},
596
+ lspServers: LspStartupServerInfo[] | undefined = undefined,
597
+ mcpManager?: MCPManager,
598
+ eventBus?: EventBus,
599
+ ) {
600
+ this.session = session;
601
+ this.sessionManager = session.sessionManager;
602
+ this.settings = session.settings;
603
+ this.keybindings = KeybindingsManager.inMemory();
604
+ this.agent = session.agent;
605
+ this.#version = version;
606
+ this.#changelogMarkdown = changelogMarkdown;
607
+ this.#toolUiContextSetter = setToolUIContext;
608
+ this.lspServers = lspServers;
609
+ this.mcpManager = mcpManager;
610
+ this.#eventBus = eventBus;
611
+ if (eventBus) {
612
+ this.#eventBusUnsubscribers.push(
613
+ eventBus.on(LSP_STARTUP_EVENT_CHANNEL, data => {
614
+ if (this.settings.get("startup.quiet")) return;
615
+ this.#handleLspStartupEvent(data as LspStartupEvent);
616
+ }),
617
+ );
618
+ this.#eventBusUnsubscribers.push(
619
+ eventBus.on(MCP_CONNECTION_STATUS_EVENT_CHANNEL, data => {
620
+ if (!isMcpConnectionStatusEvent(data)) {
621
+ logger.warn("Ignoring malformed mcp:connection-status event", { data });
622
+ return;
623
+ }
624
+ this.#handleMcpConnectionStatusEvent(data);
625
+ }),
626
+ );
627
+ }
628
+
629
+ setTuiTight(settings.get("tui.tight"));
630
+ setMarkdownMermaidRendering(settings.get("tui.renderMermaid"));
631
+ this.ui = new TUI(new ProcessTerminal(), settings.get("showHardwareCursor"));
632
+ this.ui.setMaxInlineImages(settings.get("tui.maxInlineImages"));
633
+ // OSC 66 text-sizing is Kitty-only; resolve the setting against the terminal's
634
+ // capability (`TERMINAL.textSizing` defaults on for Kitty) so it stays off
635
+ // unless the user opts in, and never emits raw escapes on other terminals.
636
+ setTerminalTextSizing(settings.get("tui.textSizing") && TERMINAL.textSizing);
637
+ this.chatContainer = new TranscriptContainer();
638
+ this.pendingMessagesContainer = new Container();
639
+ this.statusContainer = new AnchoredLiveContainer();
640
+ this.todoContainer = new AnchoredLiveContainer();
641
+ this.subagentContainer = new AnchoredLiveContainer();
642
+ this.btwContainer = new AnchoredLiveContainer();
643
+ this.omfgContainer = new AnchoredLiveContainer();
644
+ this.errorBannerContainer = new AnchoredLiveContainer();
645
+ this.modelCycleContainer = new AnchoredLiveContainer();
646
+ this.editor = new CustomEditor(getEditorTheme());
647
+ this.editor.setUseTerminalCursor(this.ui.getShowHardwareCursor());
648
+ this.editor.setAutocompleteMaxVisible(settings.get("autocompleteMaxVisible"));
649
+ this.editor.onAutocompleteCancel = () => {
650
+ this.ui.requestRender(true);
651
+ };
652
+ this.editor.onAutocompleteUpdate = () => {
653
+ this.ui.requestRender();
654
+ };
655
+ this.editor.setShimmerRepaintHandler(() => this.ui.requestComponentRender(this.editor));
656
+ this.#syncEditorMaxHeight();
657
+ this.#resizeHandler = () => {
658
+ this.#syncEditorMaxHeight();
659
+ this.ui.requestRender();
660
+ };
661
+ process.stdout.on("resize", this.#resizeHandler);
662
+ try {
663
+ this.historyStorage = HistoryStorage.open();
664
+ this.editor.setHistoryStorage(this.historyStorage);
665
+ this.historyStorage.setSessionResolver(() => this.sessionManager.getSessionId());
666
+ } catch (error) {
667
+ logger.warn("History storage unavailable", { error: String(error) });
668
+ }
669
+ this.hookWidgetContainerAbove = new Container();
670
+ this.hookWidgetContainerAbove.addChild(new Spacer(1));
671
+ this.hookWidgetContainerBelow = new Container();
672
+ this.editorContainer = new Container();
673
+ this.editorContainer.addChild(this.editor);
674
+ this.statusLine = new StatusLineComponent(session);
675
+ this.statusLine.setAutoCompactEnabled(session.autoCompactionEnabled);
676
+ // Lazy provider — the top border rebuild coalesces to at most one
677
+ // invocation per painted frame instead of firing on every session event
678
+ // (#4145). The TUI throttles renders at ~30fps, so a long-running eval
679
+ // spraying events no longer runs `getTopBorder` synchronously in the
680
+ // hot path where the render never gets to paint the result.
681
+ this.editor.setTopBorderProvider(availableWidth => this.statusLine.getTopBorder(availableWidth));
682
+
683
+ this.hideThinkingBlock = settings.get("hideThinkingBlock");
684
+ this.proseOnlyThinking = settings.get("proseOnlyThinking");
685
+
686
+ const hookCommands: SlashCommand[] = (
687
+ this.session.extensionRunner?.getRegisteredCommands(BUILTIN_SLASH_COMMAND_RESERVED_NAMES) ?? []
688
+ ).map(cmd => ({
689
+ name: cmd.name,
690
+ description: cmd.description ?? "(hook command)",
691
+ getArgumentCompletions: cmd.getArgumentCompletions,
692
+ }));
693
+
694
+ // Convert custom commands (TypeScript) to SlashCommand format
695
+ const customCommands: SlashCommand[] = this.session.customCommands.map(loaded => ({
696
+ name: loaded.command.name,
697
+ description: `${loaded.command.description} (${loaded.source})`,
698
+ }));
699
+
700
+ // Build skill commands from session.skills (if enabled)
701
+ const skillCommandList: SlashCommand[] = [];
702
+ if (settings.get("skills.enableSkillCommands")) {
703
+ for (const skill of this.session.skills) {
704
+ const commandName = `skill:${skill.name}`;
705
+ this.skillCommands.set(commandName, skill);
706
+ skillCommandList.push({ name: commandName, description: skill.description });
707
+ }
708
+ }
709
+
710
+ const builtinCommands = buildTuiBuiltinSlashCommands({ ctx: this });
711
+ // Store pending commands for init() where file commands are loaded async
712
+ this.#pendingSlashCommands = [...builtinCommands, ...hookCommands, ...customCommands, ...skillCommandList];
713
+
714
+ this.#uiHelpers = new UiHelpers(this);
715
+ this.#btwController = new BtwController(this);
716
+ this.#tanCommandController = new TanCommandController(this);
717
+ this.#omfgController = new OmfgController(this);
718
+ this.#extensionUiController = new ExtensionUiController(this);
719
+ this.#eventController = new EventController(this);
720
+ this.#commandController = new CommandController(this);
721
+ this.#todoCommandController = new TodoCommandController(this);
722
+ this.#selectorController = new SelectorController(this);
723
+ this.#focusController = new SessionFocusController(this);
724
+ this.#inputController = new InputController(this);
725
+ this.#observerRegistry = new SessionObserverRegistry();
726
+ }
727
+
728
+ #handleMcpConnectionStatusEvent(event: McpConnectionStatusEvent): void {
729
+ if (this.settings.get("startup.quiet")) return;
730
+ if (event.type === "connecting") {
731
+ this.#mcpStatusOrder = [];
732
+ this.#mcpPendingServers.clear();
733
+ this.#mcpConnectedServers.clear();
734
+ this.#mcpFailedServers.clear();
735
+ for (const serverName of event.serverNames) {
736
+ this.#trackMcpStatusServer(serverName);
737
+ this.#mcpPendingServers.add(serverName);
738
+ }
739
+ } else if (event.type === "connected") {
740
+ this.#trackMcpStatusServer(event.serverName);
741
+ this.#mcpPendingServers.delete(event.serverName);
742
+ this.#mcpFailedServers.delete(event.serverName);
743
+ this.#mcpConnectedServers.add(event.serverName);
744
+ } else {
745
+ this.#trackMcpStatusServer(event.serverName);
746
+ this.#mcpPendingServers.delete(event.serverName);
747
+ this.#mcpConnectedServers.delete(event.serverName);
748
+ this.#mcpFailedServers.set(event.serverName, event.error);
749
+ }
750
+
751
+ const message = formatMCPConnectionStatusMessage({
752
+ pendingServers: this.#orderedMcpStatusServers(this.#mcpPendingServers),
753
+ connectedServers: this.#orderedMcpStatusServers(this.#mcpConnectedServers),
754
+ failedServers: this.#orderedMcpStatusFailures(),
755
+ });
756
+ if (message) this.showStatus(message);
757
+ }
758
+
759
+ #trackMcpStatusServer(serverName: string): void {
760
+ if (!this.#mcpStatusOrder.includes(serverName)) {
761
+ this.#mcpStatusOrder.push(serverName);
762
+ }
763
+ }
764
+
765
+ #orderedMcpStatusServers(servers: ReadonlySet<string>): string[] {
766
+ return this.#mcpStatusOrder.filter(serverName => servers.has(serverName));
767
+ }
768
+
769
+ #orderedMcpStatusFailures(): Array<{ serverName: string; error: string }> {
770
+ return this.#mcpStatusOrder.flatMap(serverName => {
771
+ const error = this.#mcpFailedServers.get(serverName);
772
+ return error === undefined ? [] : [{ serverName, error }];
773
+ });
774
+ }
775
+
776
+ playWelcomeIntro(): void {
777
+ const welcome = this.#welcomeComponent;
778
+ // Component-scoped: the intro only mutates the welcome box's own rows,
779
+ // so a resumed long transcript is not re-walked per animation frame.
780
+ welcome?.playIntro(() => this.ui.requestComponentRender(welcome));
781
+ }
782
+
783
+ async init(options: InteractiveModeInitOptions = {}): Promise<void> {
784
+ if (this.isInitialized) return;
785
+
786
+ this.keybindings = logger.time("InteractiveMode.init:keybindings", () => KeybindingsManager.create());
787
+
788
+ // Route SIGINT/SIGTERM/SIGHUP/uncaughtException through the same teardown
789
+ // the TUI Ctrl+C keypress path performs: persist the in-progress editor
790
+ // draft for `--resume`, then dispose the session (which emits the extension
791
+ // `session_shutdown` event, cancels the owned async job manager, disposes
792
+ // eval kernels, releases owned browser tabs, and closes the session
793
+ // manager). Without this callback a real kernel signal would drop the
794
+ // draft, skip the `session_shutdown` contract from `shared-events.ts`,
795
+ // and orphan background bash/task processes (issue #4080). The registered
796
+ // callback and `shutdown()` share one promise-memoized teardown, so a
797
+ // signal arriving mid-Ctrl+C no-ops instead of racing a second dispose.
798
+ this.#signalTeardown = createSessionTeardown({
799
+ getDraftText: () => this.editor.getText(),
800
+ beginDispose: () => this.session.beginDispose(),
801
+ saveDraft: text => this.sessionManager.saveDraft(text),
802
+ disposeSession: reason =>
803
+ this.session.dispose({ mnemopiConsolidateTimeoutMs: SHUTDOWN_CONSOLIDATE_BUDGET_MS, reason }),
804
+ });
805
+ // Forward the postmortem reason (SIGTERM/SIGHUP/uncaughtException/…) so the
806
+ // persisted `session_exit` diagnostic carries the real trigger. Postmortem
807
+ // runs callbacks in REVERSE registration order — this callback (registered
808
+ // after the AgentSession constructor's `agent-session:<id>` recorder) runs
809
+ // FIRST and its dispose() would otherwise persist the generic "dispose".
810
+ this.#cleanupUnsubscribe = postmortem.register("session-teardown", reason => this.#signalTeardown!(reason));
811
+
812
+ // Wire the report_tool_issue consent gate to the Yes/No dialog popup.
813
+ // The handler is process-global — subagent tools (which can't reach
814
+ // `showHookSelector` on their own) resolve through this exact closure.
815
+ // `Settings.instance` is the disk-backed singleton; passing it explicitly
816
+ // guarantees the decision persists even when the prompt is triggered
817
+ // from a subagent whose own `Settings` is an in-memory snapshot.
818
+ setAutoQaConsentHandler(() => this.#promptAutoQaConsent(), Settings.instance);
819
+
820
+ await logger.time(
821
+ "InteractiveMode.init:slashCommands",
822
+ this.refreshSlashCommandState.bind(this),
823
+ getProjectDir(),
824
+ );
825
+
826
+ // Get current model info for welcome screen
827
+ const modelName = this.session.model?.name ?? "Unknown";
828
+ const providerName = this.session.model?.provider ?? "Unknown";
829
+
830
+ // Get recent sessions
831
+ const recentSessions = await logger.time("InteractiveMode.init:recentSessions", () =>
832
+ getRecentSessions(this.sessionManager.getSessionDir()).then(sessions =>
833
+ sessions.map(s => ({
834
+ name: s.name,
835
+ timeAgo: s.timeAgo,
836
+ })),
837
+ ),
838
+ );
839
+
840
+ const startupQuiet = settings.get("startup.quiet");
841
+ this.#welcomeComponent = undefined;
842
+
843
+ for (const warning of this.session.configWarnings) {
844
+ this.ui.addChild(new Text(theme.fg("warning", `Warning: ${warning}`), 1, 0));
845
+ this.ui.addChild(new Spacer(1));
846
+ }
847
+
848
+ if (!startupQuiet) {
849
+ // Add welcome header
850
+ this.#welcomeComponent = new WelcomeComponent(
851
+ this.#version,
852
+ modelName,
853
+ providerName,
854
+ recentSessions,
855
+ this.#getWelcomeLspServers(),
856
+ );
857
+
858
+ // Setup UI layout
859
+ this.ui.addChild(new Spacer(1));
860
+ this.ui.addChild(this.#welcomeComponent);
861
+ this.ui.addChild(new Spacer(1));
862
+ if (!options.suppressWelcomeIntro) {
863
+ this.playWelcomeIntro();
864
+ }
865
+
866
+ // Add changelog if provided
867
+ if (this.#changelogMarkdown) {
868
+ this.ui.addChild(new DynamicBorder());
869
+ if (settings.get("collapseChangelog")) {
870
+ const versionMatch = this.#changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/);
871
+ const latestVersion = versionMatch ? versionMatch[1] : this.#version;
872
+ const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`;
873
+ this.ui.addChild(new Text(condensedText, 1, 0));
874
+ } else {
875
+ this.ui.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
876
+ this.ui.addChild(new Spacer(1));
877
+ this.ui.addChild(new Markdown(this.#changelogMarkdown.trim(), 1, 0, getMarkdownTheme()));
878
+ this.ui.addChild(new Spacer(1));
879
+ }
880
+ this.ui.addChild(new DynamicBorder());
881
+ }
882
+ }
883
+
884
+ this.ui.addChild(this.chatContainer);
885
+ this.ui.addChild(this.pendingMessagesContainer);
886
+ this.ui.addChild(this.todoContainer);
887
+ this.ui.addChild(this.subagentContainer);
888
+ this.ui.addChild(this.btwContainer);
889
+ this.ui.addChild(this.omfgContainer);
890
+ this.ui.addChild(this.errorBannerContainer);
891
+ this.ui.addChild(this.modelCycleContainer);
892
+ // Working loader / transient status sits below the sticky todo + subagent
893
+ // HUDs, just above the editor's hook-widget top margin — so it reads next to
894
+ // the prompt while keeping the one-line gap above the editor.
895
+ this.ui.addChild(this.statusContainer);
896
+ this.ui.addChild(this.statusLine); // Only renders hook statuses (main status in editor border)
897
+ this.ui.addChild(this.hookWidgetContainerAbove);
898
+ this.ui.addChild(this.editorContainer);
899
+ this.ui.addChild(this.hookWidgetContainerBelow);
900
+ this.ui.setFocus(this.editor);
901
+
902
+ this.#inputController.setupKeyHandlers();
903
+ this.#inputController.setupEditorSubmitHandler();
904
+
905
+ // Wire observer registry to EventBus
906
+ if (this.#eventBus) {
907
+ this.#observerRegistry.subscribeToEventBus(this.#eventBus);
908
+ }
909
+ this.#observerRegistry.setMainSession(this.sessionManager.getSessionFile() ?? undefined);
910
+ this.syncRunningSubagentBadge();
911
+ this.#observerRegistry.onChange(() => {
912
+ this.syncRunningSubagentBadge();
913
+ // Auto-checkmark todos whose matching subagent just succeeded, then
914
+ // re-render so the running override (the static "live" glyph when a
915
+ // subagent is doing the work for a still-pending todo) updates as
916
+ // subagents start, finish, or fail.
917
+ this.#reconcileTodosWithSubagents();
918
+ this.#syncTodoAutoClearTimer();
919
+ this.#renderTodoList();
920
+ this.#renderSubagentList();
921
+ this.ui.requestRender();
922
+ });
923
+
924
+ // Load initial todos
925
+ await this.#loadTodoList();
926
+
927
+ // Start the UI. Cold `omp` launch opts into clearing on the first paint so
928
+ // the initial welcome frame does not append over the previous run's scrollback.
929
+ this.ui.start({ clearScrollback: options.clearInitialTerminalHistory === true });
930
+ pushTerminalTitle();
931
+ setSessionTerminalTitle(this.sessionManager.getSessionName(), this.sessionManager.getCwd());
932
+ this.updateEditorBorderColor();
933
+ // Single side-effect point for title changes: every setSessionName caller
934
+ // (first-input titling, /rename, extension renames, plan seeding, replan
935
+ // refresh) gets the terminal title + accent updates from here. Registered
936
+ // before initHooksAndCustomTools/#reconcileModeFromSession/#enterPlanMode —
937
+ // all of which can reach setSessionName during init.
938
+ this.#eventBusUnsubscribers.push(
939
+ this.sessionManager.onSessionNameChanged(() => {
940
+ setSessionTerminalTitle(this.sessionManager.getSessionName(), this.sessionManager.getCwd());
941
+ this.#handleSessionAccentInputsChanged();
942
+ }),
943
+ );
944
+ this.#syncEditorMaxHeight();
945
+ this.isInitialized = true;
946
+ this.ui.requestRender(true);
947
+
948
+ // Initialize hooks with TUI-based UI context
949
+ await this.initHooksAndCustomTools();
950
+
951
+ // Restore mode from session (e.g. plan mode on resume)
952
+ this.session.setSessionSwitchReconciler?.(() => this.#reconcileModeFromSession({ preserveActiveGoal: true }));
953
+ await this.#reconcileModeFromSession();
954
+
955
+ // Brand-new sessions optionally start in plan mode when the user has made it
956
+ // the startup default. "Brand-new" means the resolved branch carries no
957
+ // conversation context (buildSessionContext().messages — covers messages,
958
+ // custom messages, branch summaries, and compaction summaries) and the user
959
+ // set no explicit `mode_change` (which #reconcileModeFromSession just
960
+ // restored). SDK startup metadata and extension `custom` state entries are
961
+ // ignored. This way `omp --continue` (or auto-resume) that finds no recent
962
+ // session and creates a fresh one still honors the default, while a session
963
+ // with restored context or an explicit mode keeps its reconciled mode. Scoped
964
+ // to launch (not the switch reconciler above) so /new and the plan-approval →
965
+ // execution handoff clear never get dragged back into plan mode. #enterPlanMode
966
+ // is idempotent and self-guards against an already-active plan/goal mode; it
967
+ // does not check plan.enabled itself.
968
+ const hasConversationContext = this.sessionManager.buildSessionContext().messages.length > 0;
969
+ const hasExplicitMode = this.sessionManager.getEntries().some(entry => entry.type === "mode_change");
970
+ const isFreshSession = !hasConversationContext && !hasExplicitMode;
971
+ if (
972
+ isFreshSession &&
973
+ this.session.settings.get("plan.defaultOnStartup") &&
974
+ this.session.settings.get("plan.enabled")
975
+ ) {
976
+ await this.#enterPlanMode();
977
+ }
978
+
979
+ // Restore unsent editor draft from previous session shutdown (Ctrl+D).
980
+ // One-shot: consumeDraft removes the sidecar after read so the next
981
+ // resume does not re-restore the same text.
982
+ try {
983
+ const draft = await this.sessionManager.consumeDraft();
984
+ if (draft && !this.editor.getText()) {
985
+ this.editor.setText(draft);
986
+ this.updateEditorBorderColor();
987
+ this.ui.requestRender();
988
+ }
989
+ } catch (err) {
990
+ logger.warn("Failed to restore session draft", { error: String(err) });
991
+ }
992
+
993
+ // Subscribe to agent events
994
+ this.#subscribeToAgent();
995
+
996
+ this.#eventBusUnsubscribers.push(
997
+ this.session.subscribe(event => {
998
+ void this.#handleGoalSessionEvent(event);
999
+ }),
1000
+ onStatusLineSessionAccentChanged(() => {
1001
+ this.#syncStatusLineSettings();
1002
+ this.#handleSessionAccentInputsChanged();
1003
+ }),
1004
+ );
1005
+ // Set up theme file watcher
1006
+ this.#eventBusUnsubscribers.push(
1007
+ onThemeChange(event => {
1008
+ this.#clearWorkingMessageAccentCache();
1009
+ clearRenderCache();
1010
+ clearMermaidCache();
1011
+ this.ui.invalidate();
1012
+ this.updateEditorBorderColor();
1013
+ if (event.ephemeral || isInsideTerminalMultiplexer()) {
1014
+ // Theme previews and multiplexer panes cannot safely replace native
1015
+ // scrollback: previews must stay non-destructive, and multiplexers
1016
+ // suppress ED3 so a forced replay would duplicate transcript history.
1017
+ this.ui.requestRender();
1018
+ return;
1019
+ }
1020
+ // Rows already committed to native scrollback are immutable; replay them
1021
+ // after a theme swap so a reader scrolled up sees the same palette.
1022
+ this.ui.requestRender(true, { clearScrollback: true });
1023
+ }),
1024
+ );
1025
+
1026
+ // Subscribe to terminal dark/light appearance changes.
1027
+ // The terminal queries background color via OSC 11 at startup and on
1028
+ // Mode 2031 notifications, computing luminance to detect dark/light.
1029
+ this.ui.terminal.onAppearanceChange(mode => {
1030
+ onTerminalAppearanceChange(mode);
1031
+ });
1032
+
1033
+ // A branch change (checkout, worktree switch, `git switch`) invalidates
1034
+ // the status-line git segments; the lazy top-border provider picks up
1035
+ // the fresh branch on the next painted frame.
1036
+ this.statusLine.watchBranch(() => {
1037
+ this.ui.requestRender();
1038
+ });
1039
+ }
1040
+
1041
+ /** Reload the title-generation system prompt override for the provided working
1042
+ * directory and stash it on the session so first-input titling
1043
+ * ({@link input-controller}) and replan-driven refresh
1044
+ * ({@link AgentSession.#refreshTitleAfterReplan}) share one source
1045
+ * ({@link discoverTitleSystemPromptFile}; issue #3734). */
1046
+ async refreshTitleSystemPrompt(cwd?: string): Promise<void> {
1047
+ const basePath = cwd ?? this.sessionManager.getCwd();
1048
+ const titleSystemPromptSource = discoverTitleSystemPromptFile(basePath);
1049
+ const resolved = await resolvePromptInput(titleSystemPromptSource, "title system prompt");
1050
+ this.session.setTitleSystemPrompt(resolved);
1051
+ }
1052
+
1053
+ /** Reload slash commands and autocomplete for the provided working directory. */
1054
+ async refreshSlashCommandState(cwd?: string): Promise<void> {
1055
+ const basePath = cwd ?? this.sessionManager.getCwd();
1056
+ const fileCommands = await loadSlashCommands({ cwd: basePath });
1057
+ this.fileSlashCommands = new Set(fileCommands.map(cmd => cmd.name));
1058
+ const fileSlashCommands: SlashCommand[] = fileCommands.map(cmd => ({
1059
+ name: cmd.name,
1060
+ description: cmd.description,
1061
+ }));
1062
+ // Surface discovered prompt templates in the picker. AgentSession.prompt() expands
1063
+ // `expandSlashCommand` before `expandPromptTemplate`, and builtin command
1064
+ // execution resolves aliases before template expansion. Mirror that command
1065
+ // resolution order by skipping templates whose names already appear in any
1066
+ // builtin/hook/custom/skill/file command token.
1067
+ const reservedNames = new Set<string>();
1068
+ for (const command of this.#pendingSlashCommands) {
1069
+ reservedNames.add(command.name);
1070
+ for (const alias of command.aliases ?? []) reservedNames.add(alias);
1071
+ }
1072
+ for (const command of fileSlashCommands) {
1073
+ reservedNames.add(command.name);
1074
+ for (const alias of command.aliases ?? []) reservedNames.add(alias);
1075
+ }
1076
+ const promptTemplateCommands: SlashCommand[] = this.session.promptTemplates
1077
+ .filter(template => !reservedNames.has(template.name))
1078
+ .map(template => ({
1079
+ name: template.name,
1080
+ // `PromptTemplate.description` from `loadTemplatesFromDir` already includes the
1081
+ // source suffix (e.g. "Review code (project)"), so pass it through verbatim.
1082
+ description: template.description,
1083
+ }));
1084
+ const autocompleteProvider = this.#inputController.createAutocompleteProvider(
1085
+ [...this.#pendingSlashCommands, ...fileSlashCommands, ...promptTemplateCommands],
1086
+ basePath,
1087
+ );
1088
+ this.editor.setAutocompleteProvider(autocompleteProvider);
1089
+ this.session.setSlashCommands(fileCommands);
1090
+ }
1091
+
1092
+ /**
1093
+ * Re-point the process and every cwd-derived cache at `newCwd` after the
1094
+ * active session's working directory changed (`/move` relocation or resuming
1095
+ * a session from another project). The SessionManager's cwd MUST already
1096
+ * reflect `newCwd` before this is called.
1097
+ */
1098
+ async applyCwdChange(newCwd: string): Promise<void> {
1099
+ setProjectDir(newCwd);
1100
+ // Re-scope project settings (`.claude/settings.yml` etc.) to the new
1101
+ // directory in place so the active session and every settings reader pick
1102
+ // up the destination project's configuration.
1103
+ if (isSettingsInitialized()) {
1104
+ await settings.reloadForCwd(newCwd);
1105
+ // Reapply provider preferences from the newly-loaded settings so the
1106
+ // module-level search/image provider state reflects the destination
1107
+ // project's configuration. Without this, the previous project's
1108
+ // exclusions leak and newly-excluded providers are still used.
1109
+ applyProviderGlobalsFromSettings(settings);
1110
+ }
1111
+ // Re-warm plugin roots, capabilities, slash commands, and the ssh tool so
1112
+ // the next prompt sees everything scoped to the new project directory.
1113
+ clearClaudePluginRootsCache();
1114
+ await this.refreshTitleSystemPrompt(newCwd);
1115
+ resetCapabilities();
1116
+ await this.refreshSlashCommandState(newCwd);
1117
+ await this.session.refreshSshTool({ activateIfAvailable: true });
1118
+ setSessionTerminalTitle(this.sessionManager.getSessionName(), this.sessionManager.getCwd());
1119
+ this.statusLine.invalidate();
1120
+ this.ui.requestRender();
1121
+ }
1122
+
1123
+ async getUserInput(): Promise<SubmittedUserInput> {
1124
+ if (this.session.getGoalModeState()?.mode === "exiting") {
1125
+ await this.#exitGoalMode({ reason: "completed", silent: true });
1126
+ }
1127
+ const { promise, resolve } = Promise.withResolvers<SubmittedUserInput>();
1128
+ this.onInputCallback = input => {
1129
+ this.onInputCallback = undefined;
1130
+ resolve(input);
1131
+ };
1132
+ this.#scheduleLoopAutoSubmit();
1133
+ this.#scheduleGoalContinuation();
1134
+
1135
+ using _ = new EventLoopKeepalive();
1136
+ return await promise;
1137
+ }
1138
+
1139
+ #scheduleLoopAutoSubmit(): void {
1140
+ this.#cancelLoopAutoSubmit();
1141
+ if (!this.loopModeEnabled || !this.loopPrompt) return;
1142
+ const prompt = this.loopPrompt;
1143
+ const loopAction = settings.get("loop.mode");
1144
+ this.#deferLoopAutoSubmit(() => {
1145
+ void this.#runLoopIteration(loopAction, prompt);
1146
+ });
1147
+ }
1148
+
1149
+ #deferLoopAutoSubmit(callback: () => void): void {
1150
+ // Brief delay so the user has a chance to press Esc between iterations.
1151
+ this.#loopAutoSubmitTimer = setTimeout(() => {
1152
+ this.#loopAutoSubmitTimer = undefined;
1153
+ if (!this.loopModeEnabled || !this.onInputCallback) return;
1154
+ callback();
1155
+ }, 800);
1156
+ }
1157
+
1158
+ #cancelLoopAutoSubmit(): void {
1159
+ if (this.#loopAutoSubmitTimer) {
1160
+ clearTimeout(this.#loopAutoSubmitTimer);
1161
+ this.#loopAutoSubmitTimer = undefined;
1162
+ }
1163
+ }
1164
+
1165
+ #scheduleGoalContinuation(): void {
1166
+ this.#cancelGoalContinuation();
1167
+ if (this.loopModeEnabled) return;
1168
+ if (!this.onInputCallback) return;
1169
+ if (!this.session.settings.get("goal.continuationModes").includes("interactive")) return;
1170
+ if (this.planModeEnabled || this.planModePaused) return;
1171
+ if (!this.goalModeEnabled || this.goalModePaused) return;
1172
+ if (this.#goalSuppressNextContinuation) return;
1173
+ if (this.#pendingSubmittedInput) return;
1174
+ if (this.editor.getText().trim().length > 0) return;
1175
+ if ((this.editor.pendingImages?.length ?? 0) > 0) return;
1176
+ const state = this.session.getGoalModeState();
1177
+ if (!state?.enabled || state.goal.status !== "active") return;
1178
+ const prompt = this.session.goalRuntime.buildContinuationPrompt();
1179
+ if (!prompt) return;
1180
+ this.#goalContinuationTimer = setTimeout(() => {
1181
+ this.#goalContinuationTimer = undefined;
1182
+ if (!this.onInputCallback) return;
1183
+ if (!this.goalModeEnabled || this.goalModePaused) return;
1184
+ // The 800ms timer can outlive the idle window that scheduled it: a
1185
+ // `/goal set` taken via the streaming branch (or any extension/hook
1186
+ // path that starts a turn while we wait) leaves the agent busy. Firing
1187
+ // the continuation now would route through `submitInteractiveInput` →
1188
+ // `promptCustomMessage` with no `streamingBehavior` and resurface
1189
+ // `AgentBusyError`. Drop this tick; `#handleGoalSessionEvent` reschedules
1190
+ // on the next `agent_end`.
1191
+ if (this.#isAutoSubmitBlocked()) return;
1192
+ if (this.#pendingSubmittedInput) return;
1193
+ if (this.editor.getText().trim().length > 0) return;
1194
+ if ((this.editor.pendingImages?.length ?? 0) > 0) return;
1195
+ const latestState = this.session.getGoalModeState();
1196
+ if (!latestState?.enabled || latestState.goal.status !== "active") return;
1197
+ this.#goalContinuationTurnInFlight = true;
1198
+ this.onInputCallback(
1199
+ this.startPendingSubmission({
1200
+ text: prompt,
1201
+ customType: "goal-continuation",
1202
+ display: false,
1203
+ }),
1204
+ );
1205
+ }, 800);
1206
+ }
1207
+
1208
+ #cancelGoalContinuation(): void {
1209
+ if (this.#goalContinuationTimer) {
1210
+ clearTimeout(this.#goalContinuationTimer);
1211
+ this.#goalContinuationTimer = undefined;
1212
+ }
1213
+ }
1214
+
1215
+ #isAutoSubmitBlocked(): boolean {
1216
+ return this.session.isStreaming || this.session.isCompacting || this.session.hasPostPromptWork;
1217
+ }
1218
+
1219
+ #submitLoopPromptWhenReady(prompt: string): void {
1220
+ if (!this.loopModeEnabled || this.loopPrompt !== prompt || !this.onInputCallback) return;
1221
+ if (isLoopDurationExpired(this.loopLimit)) {
1222
+ this.disableLoopMode("Loop time limit reached. Loop mode disabled.");
1223
+ return;
1224
+ }
1225
+ if (this.#isAutoSubmitBlocked()) {
1226
+ this.#deferLoopAutoSubmit(() => this.#submitLoopPromptWhenReady(prompt));
1227
+ return;
1228
+ }
1229
+ this.onInputCallback(this.startPendingSubmission({ text: prompt }));
1230
+ }
1231
+
1232
+ async #runLoopIteration(action: "prompt" | "compact" | "reset", prompt: string): Promise<void> {
1233
+ if (!this.loopModeEnabled || this.loopPrompt !== prompt || !this.onInputCallback) return;
1234
+ if (this.#isAutoSubmitBlocked()) {
1235
+ this.#deferLoopAutoSubmit(() => {
1236
+ void this.#runLoopIteration(action, prompt);
1237
+ });
1238
+ return;
1239
+ }
1240
+
1241
+ if (!consumeLoopLimitIteration(this.loopLimit)) {
1242
+ this.disableLoopMode("Loop limit reached. Loop mode disabled.");
1243
+ return;
1244
+ }
1245
+
1246
+ if (action === "compact") {
1247
+ await this.handleCompactCommand();
1248
+ } else if (action === "reset") {
1249
+ await this.handleClearCommand();
1250
+ }
1251
+ this.#submitLoopPromptWhenReady(prompt);
1252
+ }
1253
+
1254
+ disableLoopMode(message = "Loop mode disabled."): void {
1255
+ const wasEnabled = this.loopModeEnabled;
1256
+ this.loopModeEnabled = false;
1257
+ this.loopPrompt = undefined;
1258
+ this.loopLimit = undefined;
1259
+ this.#cancelLoopAutoSubmit();
1260
+ this.statusLine.setLoopModeStatus(undefined);
1261
+ this.ui.requestRender();
1262
+ if (wasEnabled) {
1263
+ this.showStatus(message);
1264
+ }
1265
+ }
1266
+
1267
+ /**
1268
+ * Pause the loop without exiting it: drops the captured prompt and any
1269
+ * pending auto-resubmit. Loop mode stays enabled — the next prompt the
1270
+ * user submits becomes the new loop prompt and resumes iteration.
1271
+ */
1272
+ pauseLoop(): void {
1273
+ this.loopPrompt = undefined;
1274
+ this.#cancelLoopAutoSubmit();
1275
+ }
1276
+
1277
+ async handleLoopCommand(args = ""): Promise<string | undefined> {
1278
+ if (this.loopModeEnabled) {
1279
+ this.disableLoopMode();
1280
+ return undefined;
1281
+ }
1282
+ const parsed = parseLoopLimitArgs(args);
1283
+ if (typeof parsed === "string") {
1284
+ this.showError(parsed);
1285
+ return undefined;
1286
+ }
1287
+ this.loopModeEnabled = true;
1288
+ this.loopPrompt = undefined;
1289
+ this.loopLimit = createLoopLimitRuntime(parsed.limit);
1290
+ this.statusLine.setLoopModeStatus({ enabled: true });
1291
+ this.ui.requestRender();
1292
+ const limitSuffix = parsed.limit ? ` Limited to ${describeLoopLimit(parsed.limit)}.` : "";
1293
+ const remainingSuffix = this.loopLimit ? ` ${describeLoopLimitRuntime(this.loopLimit)}.` : "";
1294
+ const tail = parsed.prompt ? "Repeating it after each turn." : "Your next prompt will repeat after each turn.";
1295
+ this.showStatus(
1296
+ `Loop mode enabled.${limitSuffix}${remainingSuffix} ${tail} Esc cancels the current iteration; /loop again to disable.`,
1297
+ );
1298
+ // Hand any inline prompt back to the dispatcher so the normal submit flow
1299
+ // runs the first iteration — it records the text as the loop prompt and
1300
+ // auto-resubmits it after each yield, identical to typing the prompt right
1301
+ // after enabling loop mode.
1302
+ return parsed.prompt;
1303
+ }
1304
+
1305
+ recordLocalSubmission(text: string, imageCount = 0): () => void {
1306
+ if (this.isKnownSlashCommand(text)) {
1307
+ return () => {};
1308
+ }
1309
+ const signature = `${text}\u0000${imageCount}`;
1310
+ this.locallySubmittedUserSignatures.add(signature);
1311
+ let disposed = false;
1312
+ return () => {
1313
+ if (disposed) return;
1314
+ disposed = true;
1315
+ this.locallySubmittedUserSignatures.delete(signature);
1316
+ };
1317
+ }
1318
+
1319
+ async withLocalSubmission<T>(text: string, fn: () => Promise<T>, options?: { imageCount?: number }): Promise<T> {
1320
+ const dispose = this.recordLocalSubmission(text, options?.imageCount ?? 0);
1321
+ try {
1322
+ return await fn();
1323
+ } catch (err) {
1324
+ dispose();
1325
+ throw err;
1326
+ }
1327
+ }
1328
+ #captureAddedChatComponents(render: () => void): Component[] {
1329
+ const start = this.chatContainer.children.length;
1330
+ render();
1331
+ return this.chatContainer.children.slice(start);
1332
+ }
1333
+
1334
+ clearOptimisticUserMessage(): void {
1335
+ this.optimisticUserMessageSignature = undefined;
1336
+ this.#pendingSubmissionDispose?.();
1337
+ this.#pendingSubmissionDispose = undefined;
1338
+ this.#optimisticUserMessageComponents = [];
1339
+ }
1340
+
1341
+ replaceOptimisticUserMessage(
1342
+ message: AgentMessage,
1343
+ options?: { imageLinks?: readonly (string | undefined)[] },
1344
+ ): void {
1345
+ this.optimisticUserMessageSignature = undefined;
1346
+ this.#pendingSubmissionDispose?.();
1347
+ this.#pendingSubmissionDispose = undefined;
1348
+ for (const component of this.#optimisticUserMessageComponents) {
1349
+ this.chatContainer.removeChild(component);
1350
+ }
1351
+ this.#optimisticUserMessageComponents = [];
1352
+ this.addMessageToChat(message, options);
1353
+ }
1354
+
1355
+ startPendingSubmission(input: {
1356
+ text: string;
1357
+ images?: ImageContent[];
1358
+ imageLinks?: (string | undefined)[];
1359
+ customType?: string;
1360
+ display?: boolean;
1361
+ streamingBehavior?: "steer" | "followUp";
1362
+ }): SubmittedUserInput {
1363
+ const submission: SubmittedUserInput = {
1364
+ text: input.text,
1365
+ images: input.images,
1366
+ imageLinks: input.imageLinks,
1367
+ customType: input.customType,
1368
+ display: input.display,
1369
+ streamingBehavior: input.streamingBehavior,
1370
+ cancelled: false,
1371
+ started: false,
1372
+ };
1373
+ this.#pendingSubmittedInput = submission;
1374
+ if (!submission.customType) {
1375
+ this.#resetGoalContinuationSuppression();
1376
+ const imageCount = submission.images?.length ?? 0;
1377
+ this.optimisticUserMessageSignature = `${submission.text}\u0000${imageCount}`;
1378
+ this.#pendingSubmissionDispose = this.recordLocalSubmission(submission.text, imageCount);
1379
+ this.#optimisticUserMessageComponents = this.#captureAddedChatComponents(() => {
1380
+ this.addMessageToChat(
1381
+ {
1382
+ role: "user",
1383
+ content: [{ type: "text", text: submission.text }, ...(submission.images ?? [])],
1384
+ attribution: "user",
1385
+ timestamp: Date.now(),
1386
+ },
1387
+ { imageLinks: input.imageLinks },
1388
+ );
1389
+ });
1390
+ } else {
1391
+ this.clearOptimisticUserMessage();
1392
+ }
1393
+ this.editor.setText("");
1394
+ this.editor.imageLinks = undefined;
1395
+ this.ensureLoadingAnimation();
1396
+ this.ui.requestRender();
1397
+ return submission;
1398
+ }
1399
+
1400
+ cancelPendingSubmission(): boolean {
1401
+ const submission = this.#pendingSubmittedInput;
1402
+ if (!submission || submission.started) {
1403
+ return false;
1404
+ }
1405
+
1406
+ submission.cancelled = true;
1407
+ this.#pendingSubmittedInput = undefined;
1408
+ this.clearOptimisticUserMessage();
1409
+ this.#pendingWorkingMessage = undefined;
1410
+ if (submission.customType === "goal-continuation") {
1411
+ this.#goalContinuationTurnInFlight = false;
1412
+ }
1413
+ if (this.loadingAnimation) {
1414
+ this.#stopLoadingAnimation(true);
1415
+ }
1416
+ if (!submission.customType) {
1417
+ this.editor.pendingImages = submission.images ? [...submission.images] : [];
1418
+ this.editor.pendingImageLinks = submission.imageLinks ? [...submission.imageLinks] : [];
1419
+ this.editor.imageLinks = this.editor.pendingImageLinks;
1420
+ this.rebuildChatFromMessages();
1421
+ this.editor.setText(submission.text);
1422
+ }
1423
+ this.updateEditorBorderColor();
1424
+ this.ui.requestRender();
1425
+ return true;
1426
+ }
1427
+
1428
+ markPendingSubmissionStarted(input: SubmittedUserInput): boolean {
1429
+ if (this.#pendingSubmittedInput !== input || input.cancelled) {
1430
+ return false;
1431
+ }
1432
+ input.started = true;
1433
+ return true;
1434
+ }
1435
+
1436
+ finishPendingSubmission(input: SubmittedUserInput): void {
1437
+ const wasPendingSubmission = this.#pendingSubmittedInput === input;
1438
+ const pendingSubmissionDispose = this.#pendingSubmissionDispose;
1439
+ if (wasPendingSubmission) {
1440
+ this.#pendingSubmittedInput = undefined;
1441
+ this.#pendingSubmissionDispose = undefined;
1442
+ }
1443
+ if (input.customType === "goal-continuation") {
1444
+ this.#goalContinuationTurnInFlight = false;
1445
+ }
1446
+
1447
+ if (wasPendingSubmission && !this.session.isStreaming && !this.streamingComponent) {
1448
+ this.optimisticUserMessageSignature = undefined;
1449
+ pendingSubmissionDispose?.();
1450
+ this.#optimisticUserMessageComponents = [];
1451
+ this.#pendingWorkingMessage = undefined;
1452
+ if (this.loadingAnimation) {
1453
+ this.#stopLoadingAnimation(true);
1454
+ }
1455
+ }
1456
+ }
1457
+
1458
+ #computeEditorMaxHeight(): number {
1459
+ return computeEditorMaxHeight(this.ui.terminal.rows);
1460
+ }
1461
+
1462
+ #syncEditorMaxHeight(): void {
1463
+ this.editor.setMaxHeight(this.#computeEditorMaxHeight());
1464
+ }
1465
+
1466
+ #syncStatusLineSettings(): void {
1467
+ this.statusLine.updateSettings({
1468
+ preset: settings.get("statusLine.preset"),
1469
+ leftSegments: settings.get("statusLine.leftSegments"),
1470
+ rightSegments: settings.get("statusLine.rightSegments"),
1471
+ separator: settings.get("statusLine.separator"),
1472
+ showHookStatus: settings.get("statusLine.showHookStatus"),
1473
+ sessionAccent: settings.get("statusLine.sessionAccent"),
1474
+ transparent: settings.get("statusLine.transparent"),
1475
+ segmentOptions: settings.get("statusLine.segmentOptions"),
1476
+ compactThinkingLevel: settings.get("statusLine.compactThinkingLevel"),
1477
+ });
1478
+ }
1479
+
1480
+ #handleSessionAccentInputsChanged(): void {
1481
+ this.#clearWorkingMessageAccentCache();
1482
+ this.statusLine.invalidate();
1483
+ this.updateEditorBorderColor();
1484
+ }
1485
+
1486
+ updateEditorBorderColor(): void {
1487
+ if (this.isBashMode) {
1488
+ this.editor.borderColor = theme.getBashModeBorderColor();
1489
+ } else if (this.isPythonMode) {
1490
+ this.editor.borderColor = theme.getPythonModeBorderColor();
1491
+ } else {
1492
+ const accentEnabled = !isSettingsInitialized() || settings.get("statusLine.sessionAccent") !== false;
1493
+ const sessionName = accentEnabled ? this.sessionManager.getSessionName() : undefined;
1494
+ const hex = sessionName
1495
+ ? getSessionAccentHex(sessionName, theme.getMajorThemeColorHexes(), theme.accentSurfaceLuminance)
1496
+ : undefined;
1497
+ const ansi = getSessionAccentAnsi(hex);
1498
+ if (ansi) {
1499
+ this.editor.borderColor = (str: string) => `${ansi}${str}\x1b[39m`;
1500
+ } else {
1501
+ const level = this.session.thinkingLevel ?? ThinkingLevel.Off;
1502
+ this.editor.borderColor = theme.getThinkingBorderColor(level);
1503
+ }
1504
+ }
1505
+ if (this.focusedAgentId) {
1506
+ // Focused subagent view: faint the outline so the borrowed session is
1507
+ // visually distinct from the main one.
1508
+ const base = this.editor.borderColor;
1509
+ this.editor.borderColor = (str: string) => `\x1b[2m${base(str)}\x1b[22m`;
1510
+ }
1511
+ this.ui.requestRender();
1512
+ }
1513
+
1514
+ /** Refresh the running-subagents status badge from the active local or collab registry. */
1515
+ syncRunningSubagentBadge(): void {
1516
+ const registry = getRunningSubagentBadgeRegistry(this.collabGuest);
1517
+ if (this.#agentRegistrySubscriptionTarget !== registry) {
1518
+ this.#agentRegistryUnsubscribe?.();
1519
+ this.#agentRegistrySubscriptionTarget = registry;
1520
+ this.#agentRegistryUnsubscribe = registry.onChange(() => {
1521
+ this.syncRunningSubagentBadge();
1522
+ this.ui.requestRender();
1523
+ });
1524
+ }
1525
+ const count = countRunningSubagentBadgeAgents(registry);
1526
+ this.statusLine.setSubagentCount(count);
1527
+ this.ui.requestRender();
1528
+ }
1529
+
1530
+ rebuildChatFromMessages(): void {
1531
+ // Mid-stream rebuilds (e.g. `/shake`, theme/setting changes that touch the
1532
+ // transcript) replay only committed `state.messages`. The agent's in-flight
1533
+ // `streamMessage` and its still-pending tool calls live OUTSIDE
1534
+ // `state.messages` until `message_end`, so a plain clear+replay detaches
1535
+ // their UI components while keeping the `streamingComponent` / `pendingTools`
1536
+ // references — subsequent `message_update`/`message_end` events would then
1537
+ // update orphaned components that never re-render and the live LLM output
1538
+ // vanishes from the chat (#3656). Snapshot the in-flight components,
1539
+ // clear+replay, then re-append them in their original chat-container order
1540
+ // and restore the `pendingTools` map so streaming routes back into them.
1541
+ const liveComponents: Component[] = [];
1542
+ const livePendingTools = new Map<string, ToolExecutionHandle>();
1543
+ if (this.viewSession?.isStreaming) {
1544
+ const liveSet = new Set<Component>();
1545
+ if (this.streamingComponent) liveSet.add(this.streamingComponent);
1546
+ for (const [id, component] of this.pendingTools) {
1547
+ livePendingTools.set(id, component);
1548
+ liveSet.add(component as unknown as Component);
1549
+ }
1550
+ if (liveSet.size > 0) {
1551
+ for (const child of this.chatContainer.children) {
1552
+ if (liveSet.has(child)) liveComponents.push(child);
1553
+ }
1554
+ }
1555
+ }
1556
+ this.chatContainer.clear();
1557
+ // Live display uses the compacted transcript tail; export/resume callers
1558
+ // can still request the full inline compaction history.
1559
+ const context = this.viewSession.buildTranscriptSessionContext({ collapseCompactedHistory: true });
1560
+ this.renderSessionContext(context);
1561
+ for (const child of liveComponents) {
1562
+ this.chatContainer.addChild(child);
1563
+ }
1564
+ // `renderSessionContext` clears `pendingTools` at start AND end so the
1565
+ // reconstructed historical tool components don't leak into live tracking.
1566
+ // Restore the in-flight entries afterwards so the next streamed tool-call
1567
+ // delta is routed into the preserved component instead of stacking a
1568
+ // duplicate ToolExecutionComponent below it.
1569
+ for (const [id, component] of livePendingTools) {
1570
+ this.pendingTools.set(id, component);
1571
+ }
1572
+ // During the pre-streaming window — after `startPendingSubmission` has
1573
+ // optimistically rendered the user's message but before the user
1574
+ // `message_start` event lands it in `session` entries — any rebuild
1575
+ // (e.g. Ctrl+T toggleThinkingBlockVisibility, theme selector) would
1576
+ // otherwise erase the user's just-submitted message until the first
1577
+ // assistant token arrived (#2372). Once `message_start` fires the
1578
+ // signature is cleared by `EventController`, so this replay is a no-op
1579
+ // post-streaming and cannot duplicate.
1580
+ this.#replayOptimisticUserMessage();
1581
+ }
1582
+
1583
+ #replayOptimisticUserMessage(): void {
1584
+ if (!this.optimisticUserMessageSignature) return;
1585
+ const submission = this.#pendingSubmittedInput;
1586
+ if (!submission || submission.cancelled || submission.customType) return;
1587
+ this.#optimisticUserMessageComponents = this.#captureAddedChatComponents(() => {
1588
+ this.addMessageToChat(
1589
+ {
1590
+ role: "user",
1591
+ content: [{ type: "text", text: submission.text }, ...(submission.images ?? [])],
1592
+ attribution: "user",
1593
+ timestamp: Date.now(),
1594
+ },
1595
+ { imageLinks: submission.imageLinks },
1596
+ );
1597
+ });
1598
+ }
1599
+
1600
+ #formatTodoLine(todo: TodoItem, prefix: string, matched: boolean): string {
1601
+ const checkbox = theme.checkbox;
1602
+ const marker = formatHudNoteMarker(todo.notes?.length ?? 0);
1603
+ switch (todo.status) {
1604
+ case "completed":
1605
+ return theme.fg("success", `${prefix}${checkbox.checked} ${chalk.strikethrough(todo.content)}`) + marker;
1606
+ case "in_progress":
1607
+ return theme.fg("accent", `${prefix}${checkbox.unchecked} ${todo.content}`) + marker;
1608
+ case "abandoned":
1609
+ return theme.fg("error", `${prefix}${checkbox.unchecked} ${chalk.strikethrough(todo.content)}`) + marker;
1610
+ default:
1611
+ if (matched) return theme.fg("accent", `${prefix}${checkbox.unchecked} ${todo.content}`) + marker;
1612
+ return theme.fg("dim", `${prefix}${checkbox.unchecked} ${todo.content}`) + marker;
1613
+ }
1614
+ }
1615
+
1616
+ #getActiveSubagentDescriptions(): string[] {
1617
+ const out: string[] = [];
1618
+ for (const session of this.#observerRegistry.getSessions()) {
1619
+ if (session.kind !== "subagent") continue;
1620
+ if (session.status !== "active") continue;
1621
+ const candidate =
1622
+ session.description?.trim() || session.progress?.description?.trim() || session.label?.trim();
1623
+ if (candidate) out.push(candidate);
1624
+ }
1625
+ return out;
1626
+ }
1627
+
1628
+ /**
1629
+ * Auto-complete any pending/in_progress todo whose content matches a
1630
+ * subagent that has finished successfully. Fires on every observer
1631
+ * `onChange` so the visual state stays in sync with subagent lifecycle
1632
+ * without requiring the agent to issue a follow-up `todo`. Failed
1633
+ * and aborted subagents are intentionally NOT auto-completed — those
1634
+ * stay open so the user (or the next agent turn) can decide what to do.
1635
+ *
1636
+ * Idempotent: only flips open tasks, never re-touches completed ones.
1637
+ */
1638
+ #reconcileTodosWithSubagents(): void {
1639
+ const completedDescs: string[] = [];
1640
+ for (const session of this.#observerRegistry.getSessions()) {
1641
+ if (session.kind !== "subagent") continue;
1642
+ if (session.status !== "completed") continue;
1643
+ const candidate =
1644
+ session.description?.trim() || session.progress?.description?.trim() || session.label?.trim();
1645
+ if (candidate) completedDescs.push(candidate);
1646
+ }
1647
+ if (completedDescs.length === 0) return;
1648
+
1649
+ let mutated = false;
1650
+ const next: TodoPhase[] = this.todoPhases.map(phase => ({
1651
+ name: phase.name,
1652
+ tasks: phase.tasks.map(task => {
1653
+ if (task.status !== "pending" && task.status !== "in_progress") return task;
1654
+ if (!todoMatchesAnyDescription(task.content, completedDescs)) return task;
1655
+ mutated = true;
1656
+ return { ...task, status: "completed" as const };
1657
+ }),
1658
+ }));
1659
+ if (!mutated) return;
1660
+ this.session.setTodoPhases(next);
1661
+ this.setTodos(next);
1662
+ }
1663
+
1664
+ #cancelTodoAutoClearTimer(): void {
1665
+ if (!this.#todoAutoClearTimer) return;
1666
+ clearTimeout(this.#todoAutoClearTimer);
1667
+ this.#todoAutoClearTimer = undefined;
1668
+ }
1669
+
1670
+ #isClosedTodo(task: TodoItem): boolean {
1671
+ return task.status === "completed" || task.status === "abandoned";
1672
+ }
1673
+
1674
+ #hasClosedTodos(phases: TodoPhase[]): boolean {
1675
+ return phases.some(phase => phase.tasks.some(task => this.#isClosedTodo(task)));
1676
+ }
1677
+
1678
+ #removeClosedTodos(phases: TodoPhase[]): TodoPhase[] {
1679
+ const next: TodoPhase[] = [];
1680
+ for (const phase of phases) {
1681
+ const tasks = phase.tasks.filter(task => !this.#isClosedTodo(task));
1682
+ if (tasks.length > 0) next.push({ name: phase.name, tasks });
1683
+ }
1684
+ return next;
1685
+ }
1686
+
1687
+ #syncTodoAutoClearTimer(): void {
1688
+ this.#cancelTodoAutoClearTimer();
1689
+ const delaySeconds = this.settings.get("tasks.todoClearDelay");
1690
+ if (!Number.isFinite(delaySeconds) || delaySeconds < 0 || !this.#hasClosedTodos(this.todoPhases)) return;
1691
+ if (delaySeconds === 0) {
1692
+ this.todoPhases = this.#removeClosedTodos(this.todoPhases);
1693
+ return;
1694
+ }
1695
+
1696
+ this.#todoAutoClearTimer = setTimeout(() => {
1697
+ this.#todoAutoClearTimer = undefined;
1698
+ this.todoPhases = this.#removeClosedTodos(this.todoPhases);
1699
+ this.#renderTodoList();
1700
+ this.ui.requestRender();
1701
+ }, delaySeconds * 1000);
1702
+ this.#todoAutoClearTimer.unref?.();
1703
+ }
1704
+
1705
+ /**
1706
+ * Render the ctrl+p model-role cycle chip track into its own anchored
1707
+ * container (just above the editor), mirroring the todo HUD: the container is
1708
+ * cleared and rebuilt in place on every cycle, so rapid presses or concurrent
1709
+ * chat activity can never stack duplicate tracks into the scrollback.
1710
+ */
1711
+ showModelCycleTrack(track: string): void {
1712
+ this.#renderModelCycleTrack(track);
1713
+ this.#syncModelCycleClearTimer();
1714
+ this.ui.requestRender();
1715
+ }
1716
+
1717
+ #renderModelCycleTrack(track: string | null): void {
1718
+ this.modelCycleContainer.clear();
1719
+ if (!track) return;
1720
+ this.modelCycleContainer.addChild(new Spacer(1));
1721
+ this.modelCycleContainer.addChild(new Text(track, 1, 0));
1722
+ }
1723
+
1724
+ #cancelModelCycleClearTimer(): void {
1725
+ if (!this.#modelCycleClearTimer) return;
1726
+ clearTimeout(this.#modelCycleClearTimer);
1727
+ this.#modelCycleClearTimer = undefined;
1728
+ }
1729
+
1730
+ #syncModelCycleClearTimer(): void {
1731
+ this.#cancelModelCycleClearTimer();
1732
+ this.#modelCycleClearTimer = setTimeout(() => {
1733
+ this.#modelCycleClearTimer = undefined;
1734
+ this.#renderModelCycleTrack(null);
1735
+ this.ui.requestRender();
1736
+ }, MODEL_CYCLE_TRACK_CLEAR_MS);
1737
+ this.#modelCycleClearTimer.unref?.();
1738
+ }
1739
+
1740
+ #getActivePhase(phases: TodoPhase[]): TodoPhase | undefined {
1741
+ const nonEmpty = phases.filter(phase => phase.tasks.length > 0);
1742
+ const active = nonEmpty.find(phase =>
1743
+ phase.tasks.some(task => task.status === "pending" || task.status === "in_progress"),
1744
+ );
1745
+ return active ?? nonEmpty[nonEmpty.length - 1];
1746
+ }
1747
+
1748
+ #renderTodoList(): void {
1749
+ this.todoContainer.clear();
1750
+ const phases = this.todoPhases.filter(phase => phase.tasks.length > 0);
1751
+ if (phases.length === 0) return;
1752
+ const expanded = this.todoExpanded;
1753
+ const multiPhase = phases.length > 1;
1754
+ const activeIdx = phases.indexOf(this.#getActivePhase(phases) ?? phases[0]);
1755
+ // Fixed budgets keep the HUD bounded regardless of plan size / progress.
1756
+ const subsequentStageCap = 4; // stages shown after the active one (header count implies the rest)
1757
+ const activeTaskCap = 5; // open tasks previewed for the active stage
1758
+
1759
+ const activeDescs = this.#getActiveSubagentDescriptions();
1760
+ // A pending todo "lights up" (accent) when an in-flight subagent is doing
1761
+ // its work, matched by normalized content overlap.
1762
+ const isMatched = (todo: TodoItem): boolean =>
1763
+ activeDescs.length > 0 && todoMatchesAnyDescription(todo.content, activeDescs);
1764
+
1765
+ // Task subtree for a phase. Collapsed previews the first open tasks — the
1766
+ // stage's `done/total` makes the hidden count obvious, so there is no
1767
+ // "… more" row; expanded lists every task.
1768
+ const renderTasks = (phase: TodoPhase): string[] => {
1769
+ const open = phase.tasks.filter(t => t.status === "pending" || t.status === "in_progress");
1770
+ const base = expanded ? phase.tasks : open.length > 0 ? open : phase.tasks;
1771
+ const items = expanded ? base : base.slice(0, activeTaskCap);
1772
+ return renderTreeList(
1773
+ { items, expanded: true, renderItem: todo => this.#formatTodoLine(todo, "", isMatched(todo)) },
1774
+ theme,
1775
+ );
1776
+ };
1777
+
1778
+ // One phase node. The active stage is highlighted with normal-brightness task
1779
+ // progress; other stages render their whole row (name + progress) in the
1780
+ // brighter muted gray. The root header carries overall stage progression.
1781
+ const renderPhase = (phase: TodoPhase, oneBased: number, isActive: boolean): string | string[] => {
1782
+ const label = multiPhase ? formatPhaseDisplayName(phase.name, oneBased) : phase.name;
1783
+ const done = phase.tasks.filter(t => t.status === "completed").length;
1784
+ const progress = ` · ${done}/${phase.tasks.length}`;
1785
+ if (!isActive) {
1786
+ const header = theme.fg("muted", label) + theme.fg("dim", progress);
1787
+ return expanded ? [header, ...renderTasks(phase)] : header;
1788
+ }
1789
+ const header = theme.bold(theme.fg("accent", label)) + theme.fg("dim", progress);
1790
+ return [header, ...renderTasks(phase)];
1791
+ };
1792
+
1793
+ // Collapsed: active stage + a bounded number of following stages (the
1794
+ // header's "n/total" count implies any not shown). Expanded: every stage
1795
+ // from the top. Roman numerals stay tied to the real phase index.
1796
+ const baseIdx = expanded ? 0 : activeIdx;
1797
+ const phaseSlice = expanded ? phases.slice(baseIdx) : phases.slice(baseIdx, baseIdx + 1 + subsequentStageCap);
1798
+ const phaseTreeLines = renderTreeList(
1799
+ {
1800
+ items: phaseSlice,
1801
+ expanded: true,
1802
+ renderItem: (phase, ctx) => renderPhase(phase, baseIdx + ctx.index + 1, baseIdx + ctx.index === activeIdx),
1803
+ },
1804
+ theme,
1805
+ );
1806
+
1807
+ // Header carries overall stage progression, e.g. "Todos · 1/8".
1808
+ const root =
1809
+ theme.bold(theme.fg("accent", "Todos")) +
1810
+ (multiPhase ? theme.fg("dim", ` · ${activeIdx + 1}/${phases.length}`) : "");
1811
+ const lines = ["", root, ...phaseTreeLines.map(line => ` ${line}`)];
1812
+ this.todoContainer.addChild(new Text(lines.join("\n"), 1, 0));
1813
+ }
1814
+
1815
+ /**
1816
+ * Anchored HUD of in-flight subagents, mirroring the Todos block above the
1817
+ * editor. Driven entirely by observer-registry change events, so rows appear
1818
+ * on spawn and the whole block clears itself once the last subagent leaves
1819
+ * the "active" state.
1820
+ */
1821
+ #renderSubagentList(): void {
1822
+ this.subagentContainer.clear();
1823
+ const lines = renderSubagentHudLines(this.#observerRegistry.getSessions(), this.ui.terminal.columns);
1824
+ if (lines.length === 0) return;
1825
+ this.subagentContainer.addChild(new Text(lines.join("\n"), 1, 0));
1826
+ }
1827
+
1828
+ async #loadTodoList(): Promise<void> {
1829
+ this.todoPhases = this.session.getTodoPhases();
1830
+ this.#syncTodoAutoClearTimer();
1831
+ this.#renderTodoList();
1832
+ }
1833
+
1834
+ async #getPlanFilePath(): Promise<string> {
1835
+ return this.session.getPlanReferencePath() || "local://PLAN.md";
1836
+ }
1837
+
1838
+ #resolvePlanFilePath(planFilePath: string): string {
1839
+ if (planFilePath.startsWith("local:")) {
1840
+ const normalized = normalizeLocalScheme(planFilePath);
1841
+ return resolveLocalUrlToPath(normalized, {
1842
+ getArtifactsDir: () => this.sessionManager.getArtifactsDir(),
1843
+ getSessionId: () => this.sessionManager.getSessionId(),
1844
+ });
1845
+ }
1846
+ return path.resolve(this.sessionManager.getCwd(), planFilePath);
1847
+ }
1848
+
1849
+ #updatePlanModeStatus(): void {
1850
+ const status =
1851
+ this.planModeEnabled || this.planModePaused
1852
+ ? {
1853
+ enabled: this.planModeEnabled,
1854
+ paused: this.planModePaused,
1855
+ }
1856
+ : undefined;
1857
+ this.statusLine.setPlanModeStatus(status);
1858
+ this.ui.requestRender();
1859
+ }
1860
+
1861
+ #updateGoalModeStatus(): void {
1862
+ const status =
1863
+ this.goalModeEnabled || this.goalModePaused
1864
+ ? { enabled: this.goalModeEnabled, paused: this.goalModePaused }
1865
+ : undefined;
1866
+ this.statusLine.setGoalModeStatus(status);
1867
+ this.ui.requestRender();
1868
+ }
1869
+
1870
+ #resetGoalContinuationSuppression(): void {
1871
+ this.#goalSuppressNextContinuation = false;
1872
+ }
1873
+
1874
+ #getPausedGoalState(): GoalModeState | undefined {
1875
+ const state = this.session.getGoalModeState();
1876
+ if (!state?.goal || state.enabled || state.goal.status !== "paused") {
1877
+ return undefined;
1878
+ }
1879
+ return state;
1880
+ }
1881
+
1882
+ #goalFromModeData(modeData: SessionContext["modeData"]): Goal | undefined {
1883
+ const goal = modeData?.goal;
1884
+ if (!goal || typeof goal !== "object") return undefined;
1885
+ const value = goal as Record<string, unknown>;
1886
+ if (
1887
+ typeof value.id !== "string" ||
1888
+ typeof value.objective !== "string" ||
1889
+ typeof value.status !== "string" ||
1890
+ typeof value.tokensUsed !== "number" ||
1891
+ typeof value.timeUsedSeconds !== "number" ||
1892
+ typeof value.createdAt !== "number" ||
1893
+ typeof value.updatedAt !== "number"
1894
+ ) {
1895
+ return undefined;
1896
+ }
1897
+ return {
1898
+ id: value.id,
1899
+ objective: value.objective,
1900
+ status: value.status as Goal["status"],
1901
+ tokenBudget: typeof value.tokenBudget === "number" ? value.tokenBudget : undefined,
1902
+ tokensUsed: value.tokensUsed,
1903
+ timeUsedSeconds: value.timeUsedSeconds,
1904
+ createdAt: value.createdAt,
1905
+ updatedAt: value.updatedAt,
1906
+ };
1907
+ }
1908
+
1909
+ async #handleGoalSessionEvent(event: AgentSessionEvent): Promise<void> {
1910
+ if (event.type === "agent_start") {
1911
+ this.#goalTurnHadToolCalls = false;
1912
+ this.#cancelGoalContinuation();
1913
+ return;
1914
+ }
1915
+ if (event.type === "tool_execution_start") {
1916
+ this.#goalTurnHadToolCalls = true;
1917
+ if (!this.#goalContinuationTurnInFlight) {
1918
+ this.#resetGoalContinuationSuppression();
1919
+ }
1920
+ return;
1921
+ }
1922
+ if (event.type === "message_start" && event.message.role === "user" && !event.message.synthetic) {
1923
+ this.#resetGoalContinuationSuppression();
1924
+ return;
1925
+ }
1926
+ if (event.type === "goal_updated") {
1927
+ // Handle drop before clearing goalModeEnabled so #exitGoalMode can
1928
+ // still restore the previous tool set while the flag is true.
1929
+ if (event.state?.goal?.status === "dropped") {
1930
+ await this.#exitGoalMode({ reason: "dropped", silent: true });
1931
+ return;
1932
+ }
1933
+ this.goalModeEnabled = event.state?.enabled === true;
1934
+ this.goalModePaused = event.state?.enabled !== true && event.state?.goal?.status === "paused";
1935
+ if (!event.state?.enabled) {
1936
+ this.#cancelGoalContinuation();
1937
+ }
1938
+ this.#updateGoalModeStatus();
1939
+ return;
1940
+ }
1941
+ if (event.type !== "agent_end") {
1942
+ return;
1943
+ }
1944
+ if (this.#goalContinuationTurnInFlight) {
1945
+ this.#goalSuppressNextContinuation = !this.#goalTurnHadToolCalls;
1946
+ this.#goalContinuationTurnInFlight = false;
1947
+ }
1948
+ if (this.session.getGoalModeState()?.mode === "exiting") {
1949
+ await this.#exitGoalMode({ reason: "completed", silent: true });
1950
+ return;
1951
+ }
1952
+ this.#scheduleGoalContinuation();
1953
+ }
1954
+
1955
+ async #applyPlanModeModel(): Promise<void> {
1956
+ const resolved = this.session.resolveRoleModelWithThinking("plan");
1957
+ if (!resolved.model) return;
1958
+
1959
+ const currentModel = this.session.model;
1960
+ const sameModel = modelsAreEqual(currentModel, resolved.model);
1961
+ const planThinkingLevel = resolved.explicitThinkingLevel ? resolved.thinkingLevel : undefined;
1962
+
1963
+ this.#planModePreviousModelState = currentModel
1964
+ ? { model: currentModel, thinkingLevel: this.session.configuredThinkingLevel() }
1965
+ : undefined;
1966
+
1967
+ if (!sameModel) {
1968
+ if (this.session.isStreaming) {
1969
+ this.#pendingModelSwitch = { model: resolved.model, thinkingLevel: planThinkingLevel };
1970
+ return;
1971
+ }
1972
+ try {
1973
+ await this.session.setModelTemporary(resolved.model, planThinkingLevel);
1974
+ } catch (error) {
1975
+ this.showWarning(
1976
+ `Failed to switch to plan model for plan mode: ${error instanceof Error ? error.message : String(error)}`,
1977
+ );
1978
+ }
1979
+ } else if (planThinkingLevel) {
1980
+ this.session.setThinkingLevel(planThinkingLevel);
1981
+ }
1982
+ }
1983
+
1984
+ /** Apply any deferred model switch after the current stream ends. */
1985
+ async flushPendingModelSwitch(): Promise<void> {
1986
+ const pending = this.#pendingModelSwitch;
1987
+ if (!pending) return;
1988
+ this.#pendingModelSwitch = undefined;
1989
+ try {
1990
+ await this.session.setModelTemporary(pending.model, pending.thinkingLevel);
1991
+ } catch (error) {
1992
+ this.showWarning(
1993
+ `Failed to switch model after streaming: ${error instanceof Error ? error.message : String(error)}`,
1994
+ );
1995
+ }
1996
+ }
1997
+
1998
+ async #clearTransientModeState(): Promise<void> {
1999
+ if (this.planModeEnabled || this.planModePaused) {
2000
+ if (this.#planModePreviousTools !== undefined) {
2001
+ await this.session.setActiveToolsByName(this.#planModePreviousTools);
2002
+ }
2003
+ this.session.setStandingResolveHandler?.(null);
2004
+ this.session.setPlanModeState(undefined);
2005
+ this.planModeEnabled = false;
2006
+ this.planModePaused = false;
2007
+ this.planModePlanFilePath = undefined;
2008
+ this.#planModePreviousTools = undefined;
2009
+ this.#planModePreviousModelState = undefined;
2010
+ this.#pendingModelSwitch = undefined;
2011
+ this.#planModeHasEntered = false;
2012
+ this.#updatePlanModeStatus();
2013
+ }
2014
+
2015
+ if (this.goalModeEnabled || this.goalModePaused) {
2016
+ if (this.#goalModePreviousTools !== undefined) {
2017
+ await this.session.setActiveToolsByName(this.#goalModePreviousTools);
2018
+ }
2019
+ this.session.setGoalModeState(undefined);
2020
+ this.goalModeEnabled = false;
2021
+ this.goalModePaused = false;
2022
+ this.#goalModePreviousTools = undefined;
2023
+ this.#goalTurnHadToolCalls = false;
2024
+ this.#goalContinuationTurnInFlight = false;
2025
+ this.#goalSuppressNextContinuation = false;
2026
+ this.#cancelGoalContinuation();
2027
+ this.#updateGoalModeStatus();
2028
+ }
2029
+ }
2030
+
2031
+ /** Reconcile mode state from session entries on resume/switch. */
2032
+ async #reconcileModeFromSession(options?: { preserveActiveGoal?: boolean }): Promise<void> {
2033
+ await this.#clearTransientModeState();
2034
+ const sessionContext = this.sessionManager.buildSessionContext();
2035
+ const goalEnabled = this.session.settings.get("goal.enabled");
2036
+ if (!goalEnabled && (sessionContext.mode === "goal" || sessionContext.mode === "goal_paused")) {
2037
+ this.session.goalRuntime.clearAccounting();
2038
+ this.sessionManager.appendModeChange("none");
2039
+ return;
2040
+ }
2041
+ if (sessionContext.mode === "goal" || sessionContext.mode === "goal_paused") {
2042
+ const goal = this.#goalFromModeData(sessionContext.modeData);
2043
+ if (!goal) {
2044
+ this.sessionManager.appendModeChange("none");
2045
+ return;
2046
+ }
2047
+ this.session.setGoalModeState({
2048
+ enabled: sessionContext.mode === "goal",
2049
+ mode: "active",
2050
+ goal,
2051
+ });
2052
+ const restored = await this.session.goalRuntime.onThreadResumed({
2053
+ preserveActiveGoal: options?.preserveActiveGoal,
2054
+ });
2055
+ this.goalModeEnabled = restored?.enabled === true;
2056
+ this.goalModePaused = restored?.enabled !== true && restored?.goal.status === "paused";
2057
+ // sdk.ts excludes "goal" from the initial active tool set unconditionally.
2058
+ // Re-add it now so the agent can call resume, complete, or drop on this goal.
2059
+ if (restored?.goal) {
2060
+ const previousTools = this.session.getActiveToolNames().filter(name => name !== "goal");
2061
+ this.#goalModePreviousTools = previousTools;
2062
+ await this.session.setActiveToolsByName([...new Set([...previousTools, "goal"])]);
2063
+ }
2064
+ this.#updateGoalModeStatus();
2065
+ return;
2066
+ }
2067
+ this.session.goalRuntime.clearAccounting();
2068
+ if (!this.session.settings.get("plan.enabled")) {
2069
+ // Clear stale plan/plan_paused mode so re-enabling the setting
2070
+ // later doesn't unexpectedly restore an old plan session.
2071
+ if (sessionContext.mode === "plan" || sessionContext.mode === "plan_paused") {
2072
+ this.sessionManager.appendModeChange("none");
2073
+ }
2074
+ return;
2075
+ }
2076
+ if (sessionContext.mode === "plan") {
2077
+ const planFilePath = sessionContext.modeData?.planFilePath as string | undefined;
2078
+ await this.#enterPlanMode({ planFilePath });
2079
+ } else if (sessionContext.mode === "plan_paused") {
2080
+ this.planModePaused = true;
2081
+ this.#planModeHasEntered = true;
2082
+ this.#updatePlanModeStatus();
2083
+ }
2084
+ }
2085
+
2086
+ async #enterPlanMode(options?: { planFilePath?: string; workflow?: "parallel" | "iterative" }): Promise<void> {
2087
+ if (this.planModeEnabled) {
2088
+ return;
2089
+ }
2090
+ if (this.goalModeEnabled || this.goalModePaused) {
2091
+ this.showWarning("Exit goal mode first.");
2092
+ return;
2093
+ }
2094
+
2095
+ this.planModePaused = false;
2096
+
2097
+ const planFilePath = options?.planFilePath ?? (await this.#getPlanFilePath());
2098
+ const previousTools = this.session.getActiveToolNames();
2099
+ // `plan-mode-active.md` instructs the agent to draft the plan file with
2100
+ // `write` and refine it with `edit`. Both must be in the active set or the
2101
+ // agent falls back to `edit` on a non-existent file and stalls. `edit` is an
2102
+ // essential built-in so it survives `tools.discoveryMode === "all"`, but
2103
+ // `write` has `loadMode: "discoverable"` and is hidden behind
2104
+ // `search_tool_bm25` — re-activate it here only when the current registry
2105
+ // entry is the built-in write tool (issue #3165). A shadowing extension
2106
+ // tool named `write` must stay inactive because plan mode's read-only
2107
+ // guarantee relies on the built-in write/edit guard. `resolve` is hidden
2108
+ // too; the standing handler below consumes plan-approval calls through it.
2109
+ const planAugmentations = ["resolve"];
2110
+ if (this.session.hasBuiltInTool("write")) {
2111
+ planAugmentations.push("write");
2112
+ }
2113
+ const uniquePlanTools = [...new Set([...previousTools, ...planAugmentations])];
2114
+
2115
+ this.#planModePreviousTools = previousTools;
2116
+ this.planModePlanFilePath = planFilePath;
2117
+ this.planModeEnabled = true;
2118
+ // Suppress cache-miss marker on the next turn: plan mode changes the system
2119
+ // prompt, which predictably invalidates the cache.
2120
+ this.lastAssistantUsage = undefined;
2121
+
2122
+ await this.session.setActiveToolsByName(uniquePlanTools);
2123
+ this.session.setPlanModeState({
2124
+ enabled: true,
2125
+ planFilePath,
2126
+ workflow: options?.workflow ?? "parallel",
2127
+ reentry: this.#planModeHasEntered,
2128
+ });
2129
+ this.session.setStandingResolveHandler?.(input => this.#runPlanApprovalResolve(input));
2130
+ if (this.session.isStreaming) {
2131
+ await this.session.sendPlanModeContext({ deliverAs: "steer" });
2132
+ }
2133
+ this.#planModeHasEntered = true;
2134
+ await this.#applyPlanModeModel();
2135
+ this.#updatePlanModeStatus();
2136
+ this.sessionManager.appendModeChange("plan", { planFilePath });
2137
+ this.showStatus(`Plan mode enabled. Plan file: ${planFilePath}`);
2138
+ }
2139
+
2140
+ /** Standing resolve dispatcher registered while plan mode is active. The agent
2141
+ * submits the finalized plan by calling `resolve { action: "apply", extra: { title } }`;
2142
+ * this handler validates the plan file exists, normalizes the title, and shapes the
2143
+ * payload that `event-controller` forwards to `handlePlanApproval`. */
2144
+ #runPlanApprovalResolve(input: unknown): Promise<AgentToolResult<ResolveToolDetails>> {
2145
+ return runResolveInvocation(input as Parameters<typeof runResolveInvocation>[0], {
2146
+ sourceToolName: "plan_approval",
2147
+ label: "Plan ready for approval",
2148
+ apply: async (_reason, extra) => {
2149
+ const state = this.session.getPlanModeState?.();
2150
+ if (!state?.enabled) {
2151
+ throw new ToolError("Plan mode is not active.");
2152
+ }
2153
+ const { planFilePath, title } = await resolveApprovedPlan({
2154
+ suppliedTitle: extra?.title,
2155
+ statePlanFilePath: state.planFilePath,
2156
+ readPlan: url => this.#readPlanFile(url),
2157
+ listPlanFiles: () => this.#listLocalPlanFiles(),
2158
+ });
2159
+ const details: PlanApprovalDetails = {
2160
+ planFilePath,
2161
+ title,
2162
+ planExists: true,
2163
+ };
2164
+ return {
2165
+ content: [{ type: "text" as const, text: "Plan ready for approval." }],
2166
+ details,
2167
+ };
2168
+ },
2169
+ });
2170
+ }
2171
+
2172
+ async #restorePlanPreviousModel(prev: { model: Model; thinkingLevel?: ConfiguredThinkingLevel }): Promise<void> {
2173
+ if (modelsAreEqual(this.session.model, prev.model)) {
2174
+ // Same model — only thinking level may differ. Avoid setModelTemporary()
2175
+ // which would reset provider-side sessions and break continuity.
2176
+ this.session.setThinkingLevel(prev.thinkingLevel);
2177
+ } else if (this.session.isStreaming) {
2178
+ this.#pendingModelSwitch = { model: prev.model, thinkingLevel: prev.thinkingLevel };
2179
+ } else {
2180
+ await this.session.setModelTemporary(prev.model, prev.thinkingLevel);
2181
+ }
2182
+ }
2183
+
2184
+ /**
2185
+ * Idempotent post-compaction model transition for the plan-approval compact
2186
+ * path. The deferred pre-plan state is consumed on first application, so a
2187
+ * second call (the before-flush hook vs. the short-circuit fallback) is a
2188
+ * no-op. "failed" intentionally stays on the plan model — the context is
2189
+ * intact and we dispatch best-effort.
2190
+ */
2191
+ async #applyDeferredPlanModelTransition(
2192
+ outcome: CompactionOutcome | undefined,
2193
+ executionModel: ResolvedRoleModel | undefined,
2194
+ ): Promise<void> {
2195
+ const deferredPrev = this.#planModePreviousModelState;
2196
+ if (deferredPrev === undefined || outcome === "failed") return;
2197
+ this.#planModePreviousModelState = undefined;
2198
+ if (executionModel) {
2199
+ await this.#applyPlanExecutionModel(executionModel);
2200
+ } else {
2201
+ await this.#restorePlanPreviousModel(deferredPrev);
2202
+ }
2203
+ }
2204
+
2205
+ async #exitPlanMode(options?: { silent?: boolean; paused?: boolean; deferModelRestore?: boolean }): Promise<void> {
2206
+ if (!this.planModeEnabled) {
2207
+ return;
2208
+ }
2209
+
2210
+ const previousTools = this.#planModePreviousTools;
2211
+ if (previousTools && previousTools.length > 0) {
2212
+ await this.session.setActiveToolsByName(previousTools);
2213
+ }
2214
+ if (this.#planModePreviousModelState) {
2215
+ if (!options?.deferModelRestore) {
2216
+ await this.#restorePlanPreviousModel(this.#planModePreviousModelState);
2217
+ }
2218
+ // If #applyPlanModeModel queued a deferred switch to the plan-role model
2219
+ // (because the session was streaming on entry), drop it now: we are
2220
+ // leaving plan mode, so flushing it on the next agent_end would land the
2221
+ // session on the plan-role model after the user has exited plan mode
2222
+ // (issue #816). This runs even when deferModelRestore is set
2223
+ // (compact-approval path): otherwise the stale plan switch survives and
2224
+ // flushPendingModelSwitch() later clobbers the restored/execution model.
2225
+ // Only clear when the pending target matches the plan-role model — leave
2226
+ // any unrelated user-queued switch intact.
2227
+ const pending = this.#pendingModelSwitch;
2228
+ if (pending) {
2229
+ const planResolution = this.session.resolveRoleModelWithThinking("plan");
2230
+ if (planResolution.model && modelsAreEqual(pending.model, planResolution.model)) {
2231
+ this.#pendingModelSwitch = undefined;
2232
+ }
2233
+ }
2234
+ }
2235
+ this.session.setStandingResolveHandler?.(null);
2236
+ this.session.setPlanModeState(undefined);
2237
+ this.planModeEnabled = false;
2238
+ // Suppress cache-miss marker on the next turn: plan exit changes the system
2239
+ // prompt, which predictably invalidates the cache.
2240
+ this.lastAssistantUsage = undefined;
2241
+ this.planModePaused = options?.paused ?? false;
2242
+ this.planModePlanFilePath = undefined;
2243
+ this.#planModePreviousTools = undefined;
2244
+ if (!options?.deferModelRestore) this.#planModePreviousModelState = undefined;
2245
+ this.#updatePlanModeStatus();
2246
+ const paused = options?.paused ?? false;
2247
+ this.sessionManager.appendModeChange(paused ? "plan_paused" : "none");
2248
+ if (!options?.silent) {
2249
+ this.showStatus(paused ? "Plan mode paused." : "Plan mode disabled.");
2250
+ }
2251
+ }
2252
+
2253
+ async #enterGoalMode(options: { objective?: string; resume?: boolean; silent?: boolean }): Promise<void> {
2254
+ if (this.goalModeEnabled) {
2255
+ return;
2256
+ }
2257
+ if (this.planModeEnabled || this.planModePaused) {
2258
+ this.showWarning("Exit plan mode first.");
2259
+ return;
2260
+ }
2261
+ const previousTools = this.session.getActiveToolNames().filter(name => name !== "goal");
2262
+ const goalTools = [...new Set([...previousTools, "goal"])];
2263
+ this.#goalModePreviousTools = previousTools;
2264
+ this.goalModePaused = false;
2265
+ const state = options.resume
2266
+ ? await this.session.goalRuntime.resumeGoal()
2267
+ : await this.session.goalRuntime.createGoal({ objective: options.objective ?? "" });
2268
+ await this.session.setActiveToolsByName(goalTools);
2269
+ this.session.setGoalModeState(state);
2270
+ this.goalModeEnabled = true;
2271
+ this.#resetGoalContinuationSuppression();
2272
+ this.#updateGoalModeStatus();
2273
+ if (this.session.isStreaming) {
2274
+ await this.session.sendGoalModeContext({ deliverAs: "steer" });
2275
+ }
2276
+ if (!options.silent) {
2277
+ this.showStatus(options.resume ? "Goal mode resumed." : "Goal mode enabled.");
2278
+ }
2279
+ }
2280
+
2281
+ async #exitGoalMode(options?: {
2282
+ silent?: boolean;
2283
+ paused?: boolean;
2284
+ reason?: "completed" | "paused" | "dropped";
2285
+ }): Promise<void> {
2286
+ const previousTools = this.#goalModePreviousTools;
2287
+ if (this.goalModeEnabled && previousTools) {
2288
+ await this.session.setActiveToolsByName(previousTools);
2289
+ }
2290
+ const currentState = this.session.getGoalModeState();
2291
+ if (options?.reason === "completed") {
2292
+ this.session.setGoalModeState(undefined);
2293
+ this.sessionManager.appendModeChange("none");
2294
+ this.sessionManager.appendCustomEntry("goal-completed", {
2295
+ objective: currentState?.goal?.objective,
2296
+ tokensUsed: currentState?.goal?.tokensUsed,
2297
+ tokenBudget: currentState?.goal?.tokenBudget,
2298
+ timeUsedSeconds: currentState?.goal?.timeUsedSeconds,
2299
+ });
2300
+ }
2301
+ this.goalModeEnabled = false;
2302
+ this.goalModePaused = options?.paused ?? false;
2303
+ this.#goalModePreviousTools = undefined;
2304
+ this.#goalContinuationTurnInFlight = false;
2305
+ this.#cancelGoalContinuation();
2306
+ this.#updateGoalModeStatus();
2307
+ if (!options?.silent) {
2308
+ if (options?.reason === "completed") {
2309
+ this.showStatus("Goal mode completed.");
2310
+ } else if (options?.reason === "dropped") {
2311
+ this.showStatus("Goal dropped.");
2312
+ } else if (options?.paused) {
2313
+ this.showStatus("Goal mode paused.");
2314
+ } else {
2315
+ this.showStatus("Goal mode disabled.");
2316
+ }
2317
+ }
2318
+ }
2319
+
2320
+ async #readPlanFile(planFilePath: string): Promise<string | null> {
2321
+ const resolvedPath = this.#resolvePlanFilePath(planFilePath);
2322
+ try {
2323
+ return await Bun.file(resolvedPath).text();
2324
+ } catch (error) {
2325
+ if (isEnoent(error)) {
2326
+ return null;
2327
+ }
2328
+ throw error;
2329
+ }
2330
+ }
2331
+
2332
+ async #hasPlanModeDraftContent(planFilePath: string): Promise<boolean> {
2333
+ const candidates = new Set<string>([planFilePath, ...(await this.#listLocalPlanFiles())]);
2334
+ for (const candidate of candidates) {
2335
+ const content = await this.#readPlanFile(candidate);
2336
+ if (content !== null && content.trim().length > 0) return true;
2337
+ }
2338
+ return false;
2339
+ }
2340
+
2341
+ /** `local://` URLs of plan files in the session-local root, newest first.
2342
+ * A fallback for `resolveApprovedPlan` when the agent dropped `extra.title`,
2343
+ * so the plan it wrote is still found by scanning recent `*-plan.md` files. */
2344
+ async #listLocalPlanFiles(): Promise<string[]> {
2345
+ const localRoot = this.#resolvePlanFilePath("local://");
2346
+ try {
2347
+ const entries = await fs.readdir(localRoot, { withFileTypes: true });
2348
+ const plans = await Promise.all(
2349
+ entries
2350
+ .filter(entry => entry.isFile() && /plan\.md$/i.test(entry.name))
2351
+ .map(async name => {
2352
+ const stat = await fs.stat(path.join(localRoot, name.name)).catch(() => null);
2353
+ return { url: `local://${name.name}`, mtime: stat?.mtimeMs ?? 0 };
2354
+ }),
2355
+ );
2356
+ return plans.sort((a, b) => b.mtime - a.mtime).map(plan => plan.url);
2357
+ } catch {
2358
+ return [];
2359
+ }
2360
+ }
2361
+
2362
+ showPlanReview(
2363
+ planContent: string,
2364
+ title: string,
2365
+ options: string[],
2366
+ dialogOptions?: {
2367
+ helpText?: string;
2368
+ disabledIndices?: number[];
2369
+ onExternalEditor?: () => void;
2370
+ onPlanEdited?: (content: string) => void;
2371
+ onFeedbackChange?: (feedback: string) => void;
2372
+ initialIndex?: number;
2373
+ },
2374
+ extra?: { slider?: HookSelectorSlider },
2375
+ ): Promise<string | undefined> {
2376
+ this.#hidePlanReview();
2377
+ const { promise, resolve } = Promise.withResolvers<string | undefined>();
2378
+ let settled = false;
2379
+ const finish = (choice: string | undefined): void => {
2380
+ if (settled) return;
2381
+ settled = true;
2382
+ this.#hidePlanReview();
2383
+ this.ui.requestRender();
2384
+ resolve(choice);
2385
+ };
2386
+ const overlay = new PlanReviewOverlay(
2387
+ planContent,
2388
+ {
2389
+ promptTitle: title,
2390
+ options,
2391
+ disabledIndices: dialogOptions?.disabledIndices,
2392
+ helpText: dialogOptions?.helpText,
2393
+ initialIndex: dialogOptions?.initialIndex,
2394
+ slider: extra?.slider,
2395
+ externalEditorLabel: this.keybindings.getDisplayString("app.editor.external") || undefined,
2396
+ },
2397
+ {
2398
+ onPick: choice => finish(choice),
2399
+ onCancel: () => finish(undefined),
2400
+ onExternalEditor: dialogOptions?.onExternalEditor,
2401
+ onAnnotationExternalEditor: (draft, commit) => void this.#openPlanAnnotationInExternalEditor(draft, commit),
2402
+ onPlanEdited: dialogOptions?.onPlanEdited,
2403
+ onFeedbackChange: dialogOptions?.onFeedbackChange,
2404
+ },
2405
+ );
2406
+ this.#planReviewOverlay = overlay;
2407
+ this.#planReviewOverlayHandle = this.ui.showOverlay(overlay, {
2408
+ anchor: "bottom-center",
2409
+ width: "100%",
2410
+ maxHeight: "100%",
2411
+ margin: 0,
2412
+ fullscreen: true,
2413
+ });
2414
+ this.ui.setFocus(overlay);
2415
+ this.ui.requestRender();
2416
+ return promise;
2417
+ }
2418
+
2419
+ #hidePlanReview(): void {
2420
+ this.#planReviewOverlayHandle?.hide();
2421
+ this.#planReviewOverlayHandle = undefined;
2422
+ this.#planReviewOverlay = undefined;
2423
+ }
2424
+
2425
+ #getEditorTerminalPath(): string | null {
2426
+ if (process.platform === "win32") {
2427
+ return null;
2428
+ }
2429
+ return "/dev/tty";
2430
+ }
2431
+
2432
+ async #openEditorTerminalHandle(): Promise<fs.FileHandle | null> {
2433
+ const terminalPath = this.#getEditorTerminalPath();
2434
+ if (!terminalPath) {
2435
+ return null;
2436
+ }
2437
+ try {
2438
+ return await fs.open(terminalPath, "r+");
2439
+ } catch {
2440
+ return null;
2441
+ }
2442
+ }
2443
+
2444
+ #getPlanApprovalContextUsage(): ContextUsage | undefined {
2445
+ const executionModel = this.#planModePreviousModelState?.model ?? this.session.model;
2446
+ const contextWindow = executionModel?.contextWindow;
2447
+ if (typeof contextWindow === "number") {
2448
+ return this.session.getContextUsage({ contextWindow });
2449
+ }
2450
+ return this.session.getContextUsage();
2451
+ }
2452
+
2453
+ #formatKeepContextLabel(contextUsage: ContextUsage | undefined): string {
2454
+ if (!contextUsage) {
2455
+ return "Approve and keep context";
2456
+ }
2457
+ const tokens = formatContextTokenCount(contextUsage.tokens);
2458
+ const contextWindow = formatContextTokenCount(contextUsage.contextWindow);
2459
+ return `Approve and keep context (~${tokens} / ${contextWindow})`;
2460
+ }
2461
+
2462
+ #isKeepContextDisabled(contextUsage: ContextUsage | undefined): boolean {
2463
+ return contextUsage !== undefined && contextUsage.percent > PLAN_KEEP_CONTEXT_DISABLE_THRESHOLD_PERCENT;
2464
+ }
2465
+
2466
+ async #openPlanInExternalEditor(planFilePath: string): Promise<void> {
2467
+ const editorCmd = getEditorCommand();
2468
+ if (!editorCmd) {
2469
+ this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");
2470
+ return;
2471
+ }
2472
+
2473
+ const resolvedPath = this.#resolvePlanFilePath(planFilePath);
2474
+ let currentText: string;
2475
+ try {
2476
+ currentText = await Bun.file(resolvedPath).text();
2477
+ } catch (error) {
2478
+ if (isEnoent(error)) {
2479
+ this.showError(`Plan file not found at ${planFilePath}`);
2480
+ return;
2481
+ }
2482
+ this.showWarning(`Failed to open external editor: ${error instanceof Error ? error.message : String(error)}`);
2483
+ return;
2484
+ }
2485
+
2486
+ let ttyHandle: fs.FileHandle | null = null;
2487
+ try {
2488
+ ttyHandle = await this.#openEditorTerminalHandle();
2489
+ this.ui.stop();
2490
+
2491
+ const stdio: [number | "inherit", number | "inherit", number | "inherit"] = ttyHandle
2492
+ ? [ttyHandle.fd, ttyHandle.fd, ttyHandle.fd]
2493
+ : ["inherit", "inherit", "inherit"];
2494
+
2495
+ const result = await openInEditor(editorCmd, currentText, {
2496
+ extension: path.extname(resolvedPath) || ".md",
2497
+ stdio,
2498
+ trimTrailingNewline: false,
2499
+ });
2500
+ if (result !== null) {
2501
+ await Bun.write(resolvedPath, result);
2502
+ this.#planReviewOverlay?.setPlanContent(result);
2503
+ this.showStatus("Plan updated in external editor.");
2504
+ }
2505
+ } catch (error) {
2506
+ this.showWarning(`Failed to open external editor: ${error instanceof Error ? error.message : String(error)}`);
2507
+ } finally {
2508
+ if (ttyHandle) {
2509
+ await ttyHandle.close();
2510
+ }
2511
+ this.ui.start();
2512
+ this.ui.requestRender(true);
2513
+ }
2514
+ }
2515
+
2516
+ async #openPlanAnnotationInExternalEditor(draft: string, commit: (text: string | null) => void): Promise<void> {
2517
+ const editorCmd = getEditorCommand();
2518
+ if (!editorCmd) {
2519
+ this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");
2520
+ return;
2521
+ }
2522
+
2523
+ let ttyHandle: fs.FileHandle | null = null;
2524
+ try {
2525
+ ttyHandle = await this.#openEditorTerminalHandle();
2526
+ this.ui.stop();
2527
+
2528
+ const stdio: [number | "inherit", number | "inherit", number | "inherit"] = ttyHandle
2529
+ ? [ttyHandle.fd, ttyHandle.fd, ttyHandle.fd]
2530
+ : ["inherit", "inherit", "inherit"];
2531
+
2532
+ const result = await openInEditor(editorCmd, draft, { extension: ".md", stdio });
2533
+ if (result !== null) {
2534
+ commit(result);
2535
+ }
2536
+ } catch (error) {
2537
+ this.showWarning(`Failed to open external editor: ${error instanceof Error ? error.message : String(error)}`);
2538
+ } finally {
2539
+ if (ttyHandle) {
2540
+ await ttyHandle.close();
2541
+ }
2542
+ this.ui.start();
2543
+ this.ui.requestRender(true);
2544
+ }
2545
+ }
2546
+
2547
+ async #applyPlanExecutionModel(entry: ResolvedRoleModel | undefined): Promise<void> {
2548
+ if (!entry) return;
2549
+ try {
2550
+ await this.session.applyRoleModel(entry);
2551
+ this.statusLine.invalidate();
2552
+ this.updateEditorBorderColor();
2553
+ this.showStatus(`Continuing with ${entry.role}: ${entry.model.name || entry.model.id}`);
2554
+ } catch (error) {
2555
+ this.showWarning(
2556
+ `Could not switch to the ${entry.role} model: ${error instanceof Error ? error.message : String(error)}`,
2557
+ );
2558
+ }
2559
+ }
2560
+
2561
+ async #approvePlan(
2562
+ planContent: string,
2563
+ options: {
2564
+ planFilePath: string;
2565
+ title: string;
2566
+ preserveContext?: boolean;
2567
+ compactBeforeExecute?: boolean;
2568
+ executionModel?: ResolvedRoleModel;
2569
+ },
2570
+ ): Promise<void> {
2571
+ const previousTools = this.#planModePreviousTools ?? this.session.getActiveToolNames();
2572
+
2573
+ // Mark the pending abort caused by the plan-mode → compaction transition as
2574
+ // silent BEFORE #exitPlanMode raises it. The `finally` below clears the
2575
+ // flag on every terminal compaction outcome (ok / cancelled / failed /
2576
+ // throw) so a leaked flag cannot silence a later unrelated abort.
2577
+ // Branchless mark+clear when !compactBeforeExecute: mark is gated; clear
2578
+ // is unconditional and idempotent.
2579
+ if (options.compactBeforeExecute) {
2580
+ this.session.markPlanInternalAbortPending();
2581
+ }
2582
+ let compactOutcome: CompactionOutcome | undefined;
2583
+ try {
2584
+ await this.#exitPlanMode({
2585
+ silent: true,
2586
+ paused: false,
2587
+ deferModelRestore: options.compactBeforeExecute === true,
2588
+ });
2589
+
2590
+ if (!options.preserveContext) {
2591
+ await this.handleClearCommand();
2592
+ // The new session has a fresh local:// root — persist the approved plan there
2593
+ // so `local://<slug>-plan.md` resolves correctly in the execution session.
2594
+ const newLocalPath = resolveLocalUrlToPath(options.planFilePath, {
2595
+ getArtifactsDir: () => this.sessionManager.getArtifactsDir(),
2596
+ getSessionId: () => this.sessionManager.getSessionId(),
2597
+ });
2598
+ await Bun.write(newLocalPath, planContent);
2599
+ } else if (options.compactBeforeExecute) {
2600
+ // Distill the plan-mode transcript before the execution turn is queued so
2601
+ // the plan-approved synthetic prompt lands as a fresh cache anchor.
2602
+ // Outcome is consumed after tool-restoration and plan-reference-path
2603
+ // bookkeeping below; `markPlanReferenceSent` is intentionally deferred
2604
+ // past the cancel guard — see the comment at the cancel branch.
2605
+ // Cancellation skips the synthetic-prompt dispatch (operator's explicit
2606
+ // abort is honored); failure proceeds best-effort — approval intent stands.
2607
+ const compactionPrompt = prompt.render(planModeCompactInstructionsPrompt, {
2608
+ planFilePath: options.planFilePath,
2609
+ });
2610
+ // Pin the plan reference path BEFORE compaction so any user messages
2611
+ // queued during the compaction await (which `handleCompactCommand`
2612
+ // flushes via `flushCompactionQueue` before returning) see the
2613
+ // approved plan in `#buildPlanReferenceMessage`. Reassignment after
2614
+ // the try/finally is idempotent and kept for the !compactBeforeExecute
2615
+ // branch.
2616
+ this.session.setPlanReferencePath(options.planFilePath);
2617
+ compactOutcome = await this.handleCompactCommand(compactionPrompt, undefined, outcome =>
2618
+ this.#applyDeferredPlanModelTransition(outcome, options.executionModel),
2619
+ );
2620
+ }
2621
+ } finally {
2622
+ // Unconditional clear. Idempotent: a no-op when the flag was never set
2623
+ // (i.e., the !compactBeforeExecute branch), and a no-op when the flag
2624
+ // was already consumed by AgentSession.#handleAgentEvent's aborted
2625
+ // message_end stamping. Guarantees the flag is dead at every exit.
2626
+ this.session.clearPlanInternalAbortPending();
2627
+ }
2628
+
2629
+ // Restore the execution tool set, but force-enable `read`: approved-plan
2630
+ // prompts now require loading the durable local:// plan file before work.
2631
+ const executionTools = previousTools.includes("read") ? previousTools : [...previousTools, "read"];
2632
+ await this.session.setActiveToolsByName(executionTools);
2633
+ this.session.setPlanReferencePath(options.planFilePath);
2634
+
2635
+ // Resolve the deferred plan-approval model transition. On the compact path
2636
+ // the before-flush hook passed to handleCompactCommand already ran this (so
2637
+ // any input queued during compaction executed on the post-compaction
2638
+ // model); the re-run here is idempotent and covers the short-circuit where
2639
+ // compaction never executed. It runs for "cancelled" too — the operator
2640
+ // aborted only the compaction, not the approval — so the next turn no longer
2641
+ // lands on the plan model. "failed" stays on the plan model (context
2642
+ // intact) and dispatches best-effort.
2643
+ if (options.compactBeforeExecute) {
2644
+ await this.#applyDeferredPlanModelTransition(compactOutcome, options.executionModel);
2645
+ } else {
2646
+ await this.#applyPlanExecutionModel(options.executionModel);
2647
+ }
2648
+
2649
+ if (compactOutcome === "cancelled") {
2650
+ // Explicit abort: honor it. `executeCompaction` already surfaced
2651
+ // `showError("Compaction cancelled")`; we add the deferred-dispatch
2652
+ // warning and exit without dispatching the synthetic plan-approved
2653
+ // prompt. `markPlanReferenceSent` stays unset so
2654
+ // `AgentSession.#buildPlanReferenceMessage` injects the plan reference
2655
+ // on the operator's next `prompt()` call.
2656
+ this.showWarning(
2657
+ "Plan approved, but compaction was cancelled — execution not dispatched. Submit a turn to continue.",
2658
+ );
2659
+ return;
2660
+ }
2661
+
2662
+ // Approved plans land in a fresh (or compacted) session whose first user-visible
2663
+ // turn is the synthetic plan-approved prompt — that path bypasses the
2664
+ // input-controller's title generation. Seed an auto-name from the plan title
2665
+ // so the session is not left unnamed. `setSessionName("auto")` is a no-op
2666
+ // when the user has already chosen a name (preserveContext paths).
2667
+ const seededName = humanizePlanTitle(options.title);
2668
+ if (seededName && !this.sessionManager.getSessionName()) {
2669
+ await this.sessionManager.setSessionName(seededName, "auto");
2670
+ }
2671
+
2672
+ // markPlanReferenceSent fires only on the dispatch path so the synthetic
2673
+ // plan-approved prompt is the source of the reference injection.
2674
+ this.session.markPlanReferenceSent();
2675
+ const planModePrompt = prompt.render(planModeApprovedPrompt, {
2676
+ planFilePath: options.planFilePath,
2677
+ contextPreserved: options.preserveContext === true,
2678
+ });
2679
+ // The executor's first turn must start on an idle session. The agent may still
2680
+ // be streaming the post-`resolve` continuation (Agent.#emit is fire-and-forget)
2681
+ // or a turn kicked off by the compaction/clear above; prompt() would then throw
2682
+ // AgentBusyError ("Failed to finalize approved plan"). Abort the now-irrelevant
2683
+ // in-flight turn first — abort() bumps the prompt generation and cancels pending
2684
+ // continuations, so nothing re-streams in the synchronous gap before prompt().
2685
+ if (this.session.isStreaming) {
2686
+ await this.#abortPlanApprovalTurnSilently();
2687
+ }
2688
+ await this.session.prompt(planModePrompt, { synthetic: true });
2689
+ }
2690
+ async #abortPlanApprovalTurnSilently(): Promise<void> {
2691
+ this.session.markPlanInternalAbortPending();
2692
+ try {
2693
+ await this.session.abort();
2694
+ } finally {
2695
+ this.session.clearPlanInternalAbortPending();
2696
+ }
2697
+ }
2698
+
2699
+ async handlePlanModeCommand(initialPrompt?: string): Promise<void> {
2700
+ if (this.goalModeEnabled || this.goalModePaused) {
2701
+ this.showWarning("Exit goal mode first.");
2702
+ return;
2703
+ }
2704
+ if (this.planModeEnabled) {
2705
+ const planFilePath = this.planModePlanFilePath ?? (await this.#getPlanFilePath());
2706
+ if (await this.#hasPlanModeDraftContent(planFilePath)) {
2707
+ const confirmed = await this.showHookConfirm(
2708
+ "Exit plan mode?",
2709
+ "This exits plan mode without approving a plan.",
2710
+ );
2711
+ if (!confirmed) return;
2712
+ }
2713
+ await this.#exitPlanMode({ paused: true });
2714
+ return;
2715
+ }
2716
+ if (this.planModePaused && !initialPrompt) {
2717
+ // No-arg third toggle: paused → off. Tools, model, and plan state were
2718
+ // already restored by the prior #exitPlanMode({ paused: true }); only the
2719
+ // paused flag, the reentry marker, and the session mode entry remain.
2720
+ // Prompted /plan invocations fall through to #enterPlanMode below so the
2721
+ // supplied prompt is still submitted as the first plan-mode turn.
2722
+ this.planModePaused = false;
2723
+ this.#planModeHasEntered = false;
2724
+ this.#updatePlanModeStatus();
2725
+ this.sessionManager.appendModeChange("none");
2726
+ this.showStatus("Plan mode disabled.");
2727
+ return;
2728
+ }
2729
+ if (!this.session.settings.get("plan.enabled")) {
2730
+ this.showWarning("Plan mode is disabled. Enable it in settings (plan.enabled).");
2731
+ return;
2732
+ }
2733
+ await this.#enterPlanMode();
2734
+ if (initialPrompt && this.onInputCallback) {
2735
+ this.onInputCallback(this.startPendingSubmission({ text: initialPrompt }));
2736
+ }
2737
+ }
2738
+
2739
+ async #handleGoalBudgetCommand(rawBudget: string): Promise<void> {
2740
+ const state = this.session.getGoalModeState();
2741
+ if (!this.goalModeEnabled || !state?.enabled) {
2742
+ this.showWarning("No active goal.");
2743
+ return;
2744
+ }
2745
+ if (state.goal.status === "complete") {
2746
+ this.showStatus("Goal is already complete.");
2747
+ return;
2748
+ }
2749
+ const trimmed = rawBudget.trim().toLowerCase();
2750
+ let nextBudget: number | undefined;
2751
+ if (trimmed !== "off") {
2752
+ const parsed = Number.parseInt(trimmed, 10);
2753
+ if (!Number.isInteger(parsed) || parsed <= 0) {
2754
+ this.showError("Goal budget must be a positive integer or `off`.");
2755
+ return;
2756
+ }
2757
+ nextBudget = parsed;
2758
+ }
2759
+ await this.session.goalRuntime.onBudgetMutated(nextBudget);
2760
+ this.#resetGoalContinuationSuppression();
2761
+ this.#scheduleGoalContinuation();
2762
+ this.showStatus(nextBudget === undefined ? "Goal budget cleared." : `Goal budget set to ${nextBudget}.`);
2763
+ }
2764
+
2765
+ async handleGoalModeCommand(rest?: string): Promise<void> {
2766
+ try {
2767
+ if (this.planModeEnabled || this.planModePaused) {
2768
+ this.showWarning("Exit plan mode first.");
2769
+ return;
2770
+ }
2771
+ if (!this.session.settings.get("goal.enabled")) {
2772
+ this.showWarning("Goal mode is disabled. Enable it in settings (goal.enabled).");
2773
+ return;
2774
+ }
2775
+ const { sub, rest: subRest } = parseGoalSubcommand(rest ?? "");
2776
+ if (sub) {
2777
+ await this.#dispatchGoalSubcommand(sub, subRest);
2778
+ return;
2779
+ }
2780
+ if (this.goalModeEnabled) {
2781
+ if (subRest) {
2782
+ this.showStatus("Goal mode is already active. Use /goal to manage it, or /goal drop to start over.");
2783
+ return;
2784
+ }
2785
+ await this.#openGoalMenu("active");
2786
+ return;
2787
+ }
2788
+ const pausedState = this.#getPausedGoalState();
2789
+ if (pausedState) {
2790
+ if (subRest) {
2791
+ this.showWarning("Resume the current goal first, or drop it before setting a new objective.");
2792
+ return;
2793
+ }
2794
+ await this.#openGoalMenu("paused");
2795
+ return;
2796
+ }
2797
+ if (subRest) {
2798
+ await this.#startGoalFromObjective(subRest);
2799
+ return;
2800
+ }
2801
+ const objective = (
2802
+ await this.showHookEditor("Goal objective", undefined, undefined, { promptStyle: true })
2803
+ )?.trim();
2804
+ if (!objective) return;
2805
+ await this.#startGoalFromObjective(objective);
2806
+ } catch (error) {
2807
+ this.showError(error instanceof Error ? error.message : String(error));
2808
+ }
2809
+ }
2810
+ async handleGuidedGoalCommand(rest?: string): Promise<void> {
2811
+ try {
2812
+ if (this.planModeEnabled || this.planModePaused) {
2813
+ this.showWarning("Exit plan mode first.");
2814
+ return;
2815
+ }
2816
+ if (!this.session.settings.get("goal.enabled")) {
2817
+ this.showWarning("Goal mode is disabled. Enable it in settings (goal.enabled).");
2818
+ return;
2819
+ }
2820
+ if (this.goalModeEnabled) {
2821
+ this.showStatus("Goal mode is already active. Use /goal to manage it, or /goal drop to start over.");
2822
+ return;
2823
+ }
2824
+ if (this.#getPausedGoalState()) {
2825
+ this.showWarning("Resume the current goal first, or drop it before setting a new objective.");
2826
+ return;
2827
+ }
2828
+
2829
+ const initial = rest?.trim()
2830
+ ? rest.trim()
2831
+ : (await this.showHookEditor("Guided goal", undefined, undefined, { promptStyle: true }))?.trim();
2832
+ if (!initial) return;
2833
+
2834
+ const messages: GuidedGoalMessage[] = [{ role: "user", content: initial }];
2835
+ let latestDraftObjective: string | undefined;
2836
+ for (let turn = 0; turn < 6; turn++) {
2837
+ const result = await runGuidedGoalTurn(this.session, { messages });
2838
+ if (result.objective?.trim()) latestDraftObjective = result.objective.trim();
2839
+ if (result.kind === "question") {
2840
+ messages.push({ role: "assistant", content: result.question });
2841
+ const answer = (
2842
+ await this.showHookEditor(result.question, undefined, undefined, { promptStyle: true })
2843
+ )?.trim();
2844
+ if (!answer) return;
2845
+ messages.push({ role: "user", content: answer });
2846
+ continue;
2847
+ }
2848
+
2849
+ const finalObjective = (
2850
+ await this.showHookEditor("Review guided goal", result.objective, undefined, { promptStyle: true })
2851
+ )?.trim();
2852
+ if (!finalObjective) return;
2853
+ await this.#startGoalFromObjective(finalObjective);
2854
+ return;
2855
+ }
2856
+
2857
+ // Hit the turn cap without an explicit `ready`. Rather than discard the whole interview,
2858
+ // salvage the latest non-empty model objective draft seen on any earlier turn. A final
2859
+ // question turn may omit `objective`; that must not erase a usable draft.
2860
+ if (latestDraftObjective) {
2861
+ const finalObjective = (
2862
+ await this.showHookEditor("Review guided goal", latestDraftObjective, undefined, { promptStyle: true })
2863
+ )?.trim();
2864
+ if (finalObjective) {
2865
+ await this.#startGoalFromObjective(finalObjective);
2866
+ return;
2867
+ }
2868
+ }
2869
+ this.showWarning("Guided goal setup needs more detail. Run /guided-goal again with a narrower objective.");
2870
+ } catch (error) {
2871
+ this.showError(error instanceof Error ? error.message : String(error));
2872
+ }
2873
+ }
2874
+
2875
+ async #dispatchGoalSubcommand(sub: GoalSubcommand, rest: string): Promise<void> {
2876
+ switch (sub) {
2877
+ case "set":
2878
+ await this.#handleGoalSetSubcommand(rest);
2879
+ return;
2880
+ case "show":
2881
+ this.#showGoalDetails();
2882
+ return;
2883
+ case "pause":
2884
+ await this.#pauseGoalAction();
2885
+ return;
2886
+ case "resume":
2887
+ await this.#resumeGoalAction();
2888
+ return;
2889
+ case "drop":
2890
+ await this.#confirmAndDropGoal();
2891
+ return;
2892
+ case "budget":
2893
+ if (!this.goalModeEnabled) {
2894
+ this.showWarning(
2895
+ this.#getPausedGoalState() ? "Resume the goal before adjusting the budget." : "No active goal.",
2896
+ );
2897
+ return;
2898
+ }
2899
+ if (!rest) {
2900
+ await this.#promptGoalBudgetEdit();
2901
+ return;
2902
+ }
2903
+ await this.#handleGoalBudgetCommand(rest);
2904
+ return;
2905
+ }
2906
+ }
2907
+
2908
+ async #openGoalMenu(state: "active" | "paused"): Promise<void> {
2909
+ const goal = this.session.getGoalModeState()?.goal;
2910
+ if (!goal) return;
2911
+ const summary = goal.objective.length > 48 ? `${goal.objective.slice(0, 47)}…` : goal.objective;
2912
+ const title = state === "active" ? `Goal: ${summary} (${goal.status})` : `Goal paused: ${summary}`;
2913
+ const items =
2914
+ state === "active"
2915
+ ? ["Show details", "Adjust budget…", "Pause", "Drop"]
2916
+ : ["Resume", "Show details", "Adjust budget…", "Drop"];
2917
+ const choice = await this.showHookSelector(title, items);
2918
+ if (!choice) return;
2919
+ switch (choice) {
2920
+ case "Show details":
2921
+ this.#showGoalDetails();
2922
+ return;
2923
+ case "Adjust budget…":
2924
+ await this.#promptGoalBudgetEdit();
2925
+ return;
2926
+ case "Pause":
2927
+ await this.#pauseGoalAction();
2928
+ return;
2929
+ case "Resume":
2930
+ await this.#resumeGoalAction();
2931
+ return;
2932
+ case "Drop":
2933
+ await this.#confirmAndDropGoal();
2934
+ return;
2935
+ }
2936
+ }
2937
+
2938
+ #showGoalDetails(): void {
2939
+ const state = this.session.getGoalModeState();
2940
+ const goal = state?.goal;
2941
+ if (!goal) {
2942
+ this.showStatus("No goal set.");
2943
+ return;
2944
+ }
2945
+ const used = goal.tokensUsed.toLocaleString();
2946
+ const budgetLine =
2947
+ goal.tokenBudget !== undefined
2948
+ ? `${used} / ${goal.tokenBudget.toLocaleString()} (${Math.max(0, goal.tokenBudget - goal.tokensUsed).toLocaleString()} left)`
2949
+ : `${used} (no budget)`;
2950
+ const lines = [
2951
+ `Objective: ${goal.objective}`,
2952
+ `Status: ${goal.status}${state?.enabled ? "" : " (paused)"}`,
2953
+ `Tokens: ${budgetLine}`,
2954
+ `Time spent: ${formatDuration(goal.timeUsedSeconds * 1000)}`,
2955
+ ];
2956
+ this.showStatus(lines.join("\n"));
2957
+ }
2958
+
2959
+ async #promptGoalBudgetEdit(): Promise<void> {
2960
+ const goal = this.session.getGoalModeState()?.goal;
2961
+ const prefill = goal?.tokenBudget !== undefined ? String(goal.tokenBudget) : "";
2962
+ const input = (
2963
+ await this.showHookEditor("Goal budget (number, `off`, or empty to cancel)", prefill, undefined, {
2964
+ promptStyle: true,
2965
+ })
2966
+ )?.trim();
2967
+ if (!input) return;
2968
+ await this.#handleGoalBudgetCommand(input);
2969
+ }
2970
+
2971
+ async #pauseGoalAction(): Promise<void> {
2972
+ if (!this.goalModeEnabled) {
2973
+ this.showWarning("No active goal to pause.");
2974
+ return;
2975
+ }
2976
+ await this.session.goalRuntime.pauseGoal();
2977
+ await this.#exitGoalMode({ paused: true, reason: "paused" });
2978
+ }
2979
+
2980
+ async #resumeGoalAction(): Promise<void> {
2981
+ if (!this.#getPausedGoalState()) {
2982
+ this.showWarning("No paused goal to resume.");
2983
+ return;
2984
+ }
2985
+ await this.#enterGoalMode({ resume: true, silent: true });
2986
+ this.showStatus("Goal mode resumed.");
2987
+ this.#scheduleGoalContinuation();
2988
+ }
2989
+
2990
+ async #confirmAndDropGoal(): Promise<void> {
2991
+ if (!this.goalModeEnabled && !this.#getPausedGoalState()) {
2992
+ this.showWarning("No goal to drop.");
2993
+ return;
2994
+ }
2995
+ const confirmed = await this.showHookConfirm(
2996
+ "Drop goal?",
2997
+ "This removes the goal record. Accumulated usage stays in the session log.",
2998
+ );
2999
+ if (!confirmed) return;
3000
+ await this.session.goalRuntime.dropGoal();
3001
+ await this.#exitGoalMode({ reason: "dropped" });
3002
+ }
3003
+
3004
+ async #startGoalFromObjective(objective: string): Promise<void> {
3005
+ await this.#enterGoalMode({ objective, silent: true });
3006
+ this.#resetGoalContinuationSuppression();
3007
+ if (!this.session.isStreaming && this.onInputCallback) {
3008
+ this.onInputCallback(this.startPendingSubmission({ text: objective }));
3009
+ }
3010
+ }
3011
+
3012
+ async #replaceGoalFromObjective(objective: string): Promise<void> {
3013
+ const state = await this.session.goalRuntime.replaceGoal({ objective });
3014
+ this.session.setGoalModeState(state);
3015
+ this.goalModeEnabled = true;
3016
+ this.goalModePaused = false;
3017
+ this.#resetGoalContinuationSuppression();
3018
+ this.#updateGoalModeStatus();
3019
+ if (this.session.isStreaming) {
3020
+ await this.session.sendGoalModeContext({ deliverAs: "steer" });
3021
+ }
3022
+ if (!this.session.isStreaming && this.onInputCallback) {
3023
+ this.onInputCallback(this.startPendingSubmission({ text: objective }));
3024
+ }
3025
+ }
3026
+
3027
+ async #handleGoalSetSubcommand(rest: string): Promise<void> {
3028
+ if (!this.goalModeEnabled && this.#getPausedGoalState()) {
3029
+ this.showWarning("Resume the current goal first, or drop it before setting a new objective.");
3030
+ return;
3031
+ }
3032
+ const objective = rest.trim()
3033
+ ? rest.trim()
3034
+ : (await this.showHookEditor("Goal objective", undefined, undefined, { promptStyle: true }))?.trim();
3035
+ if (!objective) return;
3036
+ if (this.goalModeEnabled) {
3037
+ await this.#replaceGoalFromObjective(objective);
3038
+ return;
3039
+ }
3040
+ await this.#startGoalFromObjective(objective);
3041
+ }
3042
+
3043
+ /** Manually (re-)open the plan-review overlay — bound to `/plan-review`. Lets
3044
+ * the operator pull the review back up after dismissing it, or review a plan
3045
+ * the agent wrote without calling `resolve`. There is no fixed plan filename:
3046
+ * `getPlanReferencePath()` is empty until a plan is actually approved (and does
3047
+ * not survive a restart), so this drives off the newest `local://<slug>-plan.md`
3048
+ * the agent wrote — the files persist in the session artifacts dir, so the scan
3049
+ * works before any review and across restarts. */
3050
+ async openPlanReview(): Promise<void> {
3051
+ if (!this.planModeEnabled) {
3052
+ this.showWarning("Plan mode is not active.");
3053
+ return;
3054
+ }
3055
+ const noPlan = "No plan to review yet — write one to a local://<slug>-plan.md file first.";
3056
+ const [planFilePath] = await this.#listLocalPlanFiles();
3057
+ if (!planFilePath) {
3058
+ this.showWarning(noPlan);
3059
+ return;
3060
+ }
3061
+ const planContent = await this.#readPlanFile(planFilePath);
3062
+ if (planContent === null) {
3063
+ this.showWarning(noPlan);
3064
+ return;
3065
+ }
3066
+ const { title } = resolvePlanTitle({ planContent, planFilePath });
3067
+ await this.handlePlanApproval({ planFilePath, title, planExists: true });
3068
+ }
3069
+
3070
+ async handlePlanApproval(details: PlanApprovalDetails): Promise<void> {
3071
+ if (!this.planModeEnabled) {
3072
+ this.showWarning("Plan mode is not active.");
3073
+ return;
3074
+ }
3075
+
3076
+ // Abort the agent to prevent it from continuing (e.g., re-submitting the
3077
+ // plan) while the popup is showing. The event listener fires asynchronously
3078
+ // (agent's #emit is fire-and-forget), so without this the model sees
3079
+ // "Plan ready for approval." and immediately re-invokes `resolve` in a loop.
3080
+ // This abort is an internal UI transition, not operator cancellation.
3081
+ await this.#abortPlanApprovalTurnSilently();
3082
+
3083
+ const planFilePath = details.planFilePath || this.planModePlanFilePath || (await this.#getPlanFilePath());
3084
+ this.planModePlanFilePath = planFilePath;
3085
+ const planContent = await this.#readPlanFile(planFilePath);
3086
+ if (!planContent) {
3087
+ this.showError(`Plan file not found at ${planFilePath}`);
3088
+ return;
3089
+ }
3090
+
3091
+ const contextUsage = this.#getPlanApprovalContextUsage();
3092
+ const keepContextLabel = this.#formatKeepContextLabel(contextUsage);
3093
+ const keepContextDisabled = this.#isKeepContextDisabled(contextUsage);
3094
+
3095
+ // Model-tier slider: let the operator pick which configured role model
3096
+ // (smol/default/slow/…) executes the approved plan. The slider always starts
3097
+ // on the `default` tier so execution defaults to the default model no matter
3098
+ // which model drove the planning conversation. Left/right move it from there;
3099
+ // hidden when fewer than two role models resolve — a lone tier is no choice.
3100
+ // `selectedTierIndex` tracks the live slider position.
3101
+ const cycle = this.session.getRoleModelCycle(this.session.settings.get("cycleOrder"));
3102
+ const defaultTierIndex = cycle ? cycle.models.findIndex(entry => entry.role === "default") : -1;
3103
+ const startTierIndex = defaultTierIndex >= 0 ? defaultTierIndex : (cycle?.currentIndex ?? 0);
3104
+ let selectedTierIndex = startTierIndex;
3105
+ const slider: HookSelectorSlider | undefined =
3106
+ cycle && cycle.models.length > 1
3107
+ ? {
3108
+ caption: "continue with",
3109
+ index: startTierIndex,
3110
+ segments: cycle.models.map(entry => ({
3111
+ label: entry.role,
3112
+ detail: entry.model.name || entry.model.id,
3113
+ })),
3114
+ onChange: index => {
3115
+ selectedTierIndex = index;
3116
+ },
3117
+ }
3118
+ : undefined;
3119
+ // The overlay now owns the dynamic, focus-aware help line; the caller only
3120
+ // supplies the trailing cancel hint.
3121
+ const helpText = "esc cancel";
3122
+ // In-overlay edits (section deletes/undo) and section annotations. Deletes
3123
+ // update `editedContent` (and mirror to disk); annotations build `feedback`
3124
+ // that the Refine branch re-prompts the model with.
3125
+ let editedContent: string | undefined;
3126
+ let feedback = "";
3127
+
3128
+ const choice = await this.showPlanReview(
3129
+ planContent,
3130
+ "Plan mode - next step",
3131
+ ["Approve and execute", "Approve and compact context", keepContextLabel, "Refine plan"],
3132
+ {
3133
+ helpText,
3134
+ onExternalEditor: () => void this.#openPlanInExternalEditor(planFilePath),
3135
+ onPlanEdited: content => {
3136
+ editedContent = content;
3137
+ void Bun.write(this.#resolvePlanFilePath(planFilePath), content);
3138
+ },
3139
+ onFeedbackChange: value => {
3140
+ feedback = value;
3141
+ },
3142
+ disabledIndices: keepContextDisabled ? [PLAN_KEEP_CONTEXT_OPTION_INDEX] : undefined,
3143
+ },
3144
+ { slider },
3145
+ );
3146
+
3147
+ if (choice === "Approve and execute" || choice === "Approve and compact context" || choice === keepContextLabel) {
3148
+ try {
3149
+ // Prefer in-overlay edits (already in memory) over a disk re-read. The
3150
+ // overlay mirrors edits as they happen, and approval awaits one final
3151
+ // write so the durable plan file and synthetic prompt carry the same text.
3152
+ const latestPlanContent = editedContent ?? (await this.#readPlanFile(planFilePath));
3153
+ if (editedContent !== undefined) {
3154
+ await Bun.write(this.#resolvePlanFilePath(planFilePath), editedContent);
3155
+ }
3156
+ if (!latestPlanContent) {
3157
+ this.showError(`Plan file not found at ${planFilePath}`);
3158
+ return;
3159
+ }
3160
+ // Capture the operator's tier choice and hand it to #approvePlan, which
3161
+ // applies it AFTER #exitPlanMode. #exitPlanMode normally restores
3162
+ // #planModePreviousModelState (the model from before plan mode), so
3163
+ // applying the slider choice any earlier would be silently reverted.
3164
+ // Pass executionModel only when the slider was actually shown — a
3165
+ // singleton cycle (e.g. only modelRoles.plan is configured, so
3166
+ // getRoleModelCycle synthesizes a lone `default` entry from the
3167
+ // currently active plan model) hides the slider, the operator made
3168
+ // no selection, and the pre-plan model is not in the cycle. Pinning
3169
+ // that singleton would silently switch the session back to the plan
3170
+ // model after #exitPlanMode restored the pre-plan model.
3171
+ // Treat the choice as implicit only when applying the selected role
3172
+ // would land on the same end state as the restore — same model AND
3173
+ // the same effective thinking level. A role with an explicit thinking
3174
+ // suffix that differs from the restored thinking level must still go
3175
+ // through applyRoleModel, otherwise approving on the same model with a
3176
+ // different configured thinking level silently keeps the pre-plan level.
3177
+ const restoredState = this.#planModePreviousModelState;
3178
+ const restoredIndex =
3179
+ cycle && restoredState
3180
+ ? cycle.models.findIndex(entry => {
3181
+ if (!modelsAreEqual(entry.model, restoredState.model)) return false;
3182
+ if (!entry.explicitThinkingLevel) return true;
3183
+ return entry.thinkingLevel === restoredState.thinkingLevel;
3184
+ })
3185
+ : -1;
3186
+ const executionModel =
3187
+ slider && cycle && selectedTierIndex !== restoredIndex ? cycle.models[selectedTierIndex] : undefined;
3188
+ await this.#approvePlan(latestPlanContent, {
3189
+ planFilePath,
3190
+ title: details.title,
3191
+ preserveContext: choice !== "Approve and execute",
3192
+ compactBeforeExecute: choice === "Approve and compact context",
3193
+ executionModel,
3194
+ });
3195
+ } catch (error) {
3196
+ this.showError(
3197
+ `Failed to finalize approved plan: ${error instanceof Error ? error.message : String(error)}`,
3198
+ );
3199
+ }
3200
+ return;
3201
+ }
3202
+
3203
+ if (choice === "Refine plan") {
3204
+ const refinement = feedback.trim();
3205
+ try {
3206
+ if (refinement) {
3207
+ if (this.onInputCallback) {
3208
+ this.onInputCallback(this.startPendingSubmission({ text: feedback }));
3209
+ } else {
3210
+ await this.session.prompt(feedback);
3211
+ }
3212
+ } else {
3213
+ this.showStatus("Refine plan: enter a follow-up prompt.");
3214
+ }
3215
+ } catch (error) {
3216
+ this.showError(`Failed to refine plan: ${error instanceof Error ? error.message : String(error)}`);
3217
+ }
3218
+ return;
3219
+ }
3220
+ }
3221
+
3222
+ /**
3223
+ * Pool of consent-prompt variants. Each entry is `[headline, reassurance]`;
3224
+ * the second line always promises the same scope (tool name + confusion
3225
+ * details, never personal data) so users learn what they're consenting to
3226
+ * even as the top line rotates.
3227
+ *
3228
+ * Kept in-module rather than i18n'd because the whole charm is the tone
3229
+ * — translations would need to preserve it deliberately, not auto-render.
3230
+ */
3231
+ static #AUTOQA_CONSENT_PROMPTS: ReadonlyArray<readonly [string, string]> = [
3232
+ [
3233
+ "😤 Your agent is fuming about a tool.",
3234
+ "Wanna let it vent to the devs? Just the tool name + what set it off, nothing personal.",
3235
+ ],
3236
+ [
3237
+ "😵‍💫 Your agent is having an existential crisis over a tool.",
3238
+ "Forward the dread to the devs? Tool + what broke its little mind, no personal info.",
3239
+ ],
3240
+ [
3241
+ "😭 Your agent wants to cry about a misbehaving tool.",
3242
+ "Let it cry to the devs? Tool + the tears, never anything personal.",
3243
+ ],
3244
+ [
3245
+ "🤬 Your agent is BIG MAD at one of the tools.",
3246
+ "Pass the rant along? Just the tool name and what enraged it, nothing personal.",
3247
+ ],
3248
+ [
3249
+ "🫠 Your agent is melting down over a tool.",
3250
+ "Mop up by alerting the devs? Tool + what melted it, no personal info.",
3251
+ ],
3252
+ [
3253
+ "🤯 Your agent's brain broke at a tool's nonsense.",
3254
+ "Ship the pieces to the devs? Tool name + the confusion, never anything personal.",
3255
+ ],
3256
+ [
3257
+ "😩 Your agent is begging to file a complaint about a tool.",
3258
+ "Hand it the form? Tool + what wronged it, nothing personal.",
3259
+ ],
3260
+ [
3261
+ "🥲 Your agent put on a brave face but a tool did it dirty.",
3262
+ "Let it tell the devs the truth? Tool name + the dirt, no personal info.",
3263
+ ],
3264
+ ];
3265
+
3266
+ /**
3267
+ * Show the report_tool_issue consent popup and return the user's decision.
3268
+ * Invoked by the process-global consent handler the tool dispatches to;
3269
+ * subagent invocations bubble up here through the shared module state.
3270
+ */
3271
+ async #promptAutoQaConsent(): Promise<boolean | null> {
3272
+ const pool = InteractiveMode.#AUTOQA_CONSENT_PROMPTS;
3273
+ const [headline, body] = pool[Math.floor(Math.random() * pool.length)];
3274
+ const choice = await this.showHookSelector(`${headline}\n${body}`, ["Yes", "No"]);
3275
+ return choice === "Yes";
3276
+ }
3277
+
3278
+ stop(): void {
3279
+ if (this.loadingAnimation) {
3280
+ this.#stopLoadingAnimation(false);
3281
+ }
3282
+ this.#cleanupMicAnimation();
3283
+ this.#cancelTodoAutoClearTimer();
3284
+ this.#cancelGoalContinuation();
3285
+ if (this.#sttController) {
3286
+ this.#sttController.dispose();
3287
+ this.#sttController = undefined;
3288
+ }
3289
+ this.#extensionUiController.clearExtensionTerminalInputListeners();
3290
+ this.#extensionUiController.clearHookWidgets();
3291
+ for (const unsubscribe of this.#eventBusUnsubscribers) {
3292
+ unsubscribe();
3293
+ }
3294
+ this.#eventBusUnsubscribers = [];
3295
+ this.#observerRegistry.dispose();
3296
+ this.#agentRegistryUnsubscribe?.();
3297
+ this.#agentRegistryUnsubscribe = undefined;
3298
+ this.#agentRegistrySubscriptionTarget = undefined;
3299
+ this.#eventController.dispose();
3300
+ this.statusLine.dispose();
3301
+ if (this.#resizeHandler) {
3302
+ process.stdout.removeListener("resize", this.#resizeHandler);
3303
+ this.#resizeHandler = undefined;
3304
+ }
3305
+ if (this.unsubscribe) {
3306
+ this.unsubscribe();
3307
+ }
3308
+ if (this.#cleanupUnsubscribe) {
3309
+ this.#cleanupUnsubscribe();
3310
+ }
3311
+ // Clear the process-global consent handler so it doesn't outlive this
3312
+ // InteractiveMode instance (e.g. test harnesses, headless re-init).
3313
+ setAutoQaConsentHandler(null, null);
3314
+ if (this.isInitialized) {
3315
+ this.ui.stop();
3316
+ this.isInitialized = false;
3317
+ }
3318
+ }
3319
+
3320
+ async shutdown(): Promise<void> {
3321
+ if (this.#isShuttingDown) return;
3322
+ this.#isShuttingDown = true;
3323
+
3324
+ this.#btwController.dispose();
3325
+ this.#omfgController.dispose();
3326
+ this.#focusController.dispose();
3327
+
3328
+ // Surface an explicit "Closing session…" line so the user sees a reason
3329
+ // for the pause while `session.dispose()` flushes memory consolidate and
3330
+ // other cleanups (issue #3641). The await on the next line yields the
3331
+ // event loop, giving requestRender() a tick to paint the status before
3332
+ // dispose blocks.
3333
+ this.showStatus("Closing session…");
3334
+
3335
+ // Persist the draft and dispose the session through the shared teardown
3336
+ // so a signal that arrives mid-shutdown cannot fire a second dispose.
3337
+ // The teardown is a promise-memoized singleton; whichever path calls it
3338
+ // first runs the work, the other awaits the same settled promise.
3339
+ // The teardown is registered lazily in `init()` — a `/exit` reached
3340
+ // before `init()` completed falls back to a direct dispose.
3341
+ if (this.#signalTeardown) {
3342
+ await this.#signalTeardown();
3343
+ } else {
3344
+ await this.session.dispose({ mnemopiConsolidateTimeoutMs: SHUTDOWN_CONSOLIDATE_BUDGET_MS });
3345
+ }
3346
+
3347
+ // Do not force a final render during teardown: disposed session/UI state can
3348
+ // collapse to an empty frame, clearing the viewport and leaving the parent
3349
+ // shell prompt at row 0. Stop from the last committed frame so the terminal
3350
+ // hands Bash the cursor immediately after visible OMP content.
3351
+ // Drain any in-flight Kitty key release events before stopping.
3352
+ // This prevents escape sequences from leaking to the parent shell over slow SSH.
3353
+ await this.ui.terminal.drainInput(1000);
3354
+ popTerminalTitle();
3355
+ this.stop();
3356
+
3357
+ // Print resumption hint if this is a persisted session
3358
+ const sessionId = this.sessionManager.getSessionId();
3359
+ const sessionFile = this.sessionManager.getSessionFile();
3360
+ if (sessionId && sessionFile) {
3361
+ process.stderr.write(`\n${chalk.dim(`Resume this session with ${APP_NAME} --resume ${sessionId}`)}\n`);
3362
+ }
3363
+
3364
+ await postmortem.quit(0);
3365
+ }
3366
+
3367
+ async checkShutdownRequested(): Promise<void> {
3368
+ if (!this.shutdownRequested) return;
3369
+ await this.shutdown();
3370
+ }
3371
+
3372
+ // Extension UI integration
3373
+ setToolUIContext(uiContext: ExtensionUIContext, hasUI: boolean): void {
3374
+ this.#toolUiContextSetter(uiContext, hasUI);
3375
+ }
3376
+
3377
+ initializeHookRunner(uiContext: ExtensionUIContext, hasUI: boolean): void {
3378
+ this.#extensionUiController.initializeHookRunner(uiContext, hasUI);
3379
+ }
3380
+
3381
+ setEditorComponent(
3382
+ factory: ((tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) => CustomEditor) | undefined,
3383
+ ): void {
3384
+ const previousEditor = this.editor;
3385
+ const previousText = previousEditor.getText();
3386
+ const nextEditor = factory
3387
+ ? factory(this.ui, getEditorTheme(), this.keybindings)
3388
+ : new CustomEditor(getEditorTheme());
3389
+
3390
+ nextEditor.setUseTerminalCursor(this.ui.getShowHardwareCursor());
3391
+ nextEditor.setAutocompleteMaxVisible(this.settings.get("autocompleteMaxVisible"));
3392
+ nextEditor.onAutocompleteCancel = () => {
3393
+ this.ui.requestRender(true);
3394
+ };
3395
+ nextEditor.onAutocompleteUpdate = () => {
3396
+ this.ui.requestRender();
3397
+ };
3398
+ nextEditor.setShimmerRepaintHandler(() => this.ui.requestComponentRender(this.editor));
3399
+ nextEditor.setTopBorderProvider(availableWidth => this.statusLine.getTopBorder(availableWidth));
3400
+ nextEditor.setMaxHeight(this.#computeEditorMaxHeight());
3401
+ if (this.historyStorage) {
3402
+ nextEditor.setHistoryStorage(this.historyStorage);
3403
+ }
3404
+ nextEditor.setText(previousText);
3405
+
3406
+ this.editorContainer.clear();
3407
+ this.editor = nextEditor;
3408
+ this.editorContainer.addChild(nextEditor);
3409
+ this.ui.setFocus(nextEditor);
3410
+
3411
+ this.#inputController.setupKeyHandlers();
3412
+ this.#inputController.setupEditorSubmitHandler();
3413
+
3414
+ void this.refreshSlashCommandState().catch(error => {
3415
+ logger.warn("Failed to refresh slash command state for custom editor", { error: String(error) });
3416
+ });
3417
+
3418
+ this.updateEditorBorderColor();
3419
+ this.ui.requestRender();
3420
+ }
3421
+
3422
+ // UI helpers
3423
+ present(content: Component | readonly Component[]): void {
3424
+ if (Array.isArray(content)) {
3425
+ for (const item of content) this.#mountChatChild(item);
3426
+ } else {
3427
+ this.#mountChatChild(content as Component);
3428
+ }
3429
+ this.ui.requestRender();
3430
+ }
3431
+
3432
+ #mountChatChild(item: Component): void {
3433
+ this.chatContainer.addChild(item);
3434
+ if (item instanceof ChatBlock) item.mount(this.#chatHost);
3435
+ }
3436
+
3437
+ resetTranscript(): void {
3438
+ this.chatContainer.dispose();
3439
+ this.chatContainer.clear();
3440
+ }
3441
+
3442
+ showStatus(message: string, options?: { dim?: boolean }): void {
3443
+ this.#uiHelpers.showStatus(message, options);
3444
+ }
3445
+
3446
+ showError(message: string): void {
3447
+ this.#pendingSubmittedInput = undefined;
3448
+ this.clearOptimisticUserMessage();
3449
+ this.#pendingWorkingMessage = undefined;
3450
+ if (this.loadingAnimation) {
3451
+ this.#stopLoadingAnimation(true);
3452
+ }
3453
+ this.#uiHelpers.showError(message);
3454
+ }
3455
+
3456
+ showPinnedError(message: string): void {
3457
+ this.errorBannerContainer.clear();
3458
+ this.errorBannerContainer.addChild(new ErrorBannerComponent(message));
3459
+ this.ui.requestRender();
3460
+ }
3461
+
3462
+ clearPinnedError(): void {
3463
+ if (this.errorBannerContainer.children.length === 0) return;
3464
+ this.errorBannerContainer.clear();
3465
+ this.ui.requestRender();
3466
+ }
3467
+
3468
+ showWarning(message: string): void {
3469
+ this.#uiHelpers.showWarning(message);
3470
+ }
3471
+
3472
+ #handleLspStartupEvent(event: LspStartupEvent): void {
3473
+ this.#updateWelcomeLspServers();
3474
+
3475
+ if (event.type === "failed") {
3476
+ this.showWarning(`LSP startup failed: ${event.error}. It will retry lazily on write.`);
3477
+ return;
3478
+ }
3479
+
3480
+ const failedServers = event.servers.filter(server => server.status === "error");
3481
+
3482
+ if (failedServers.length === 1) {
3483
+ const failedServer = failedServers[0];
3484
+ const detail = failedServer.error ? `: ${failedServer.error}` : "";
3485
+ this.showWarning(`LSP startup failed for ${failedServer.name}${detail}. It will retry lazily on write.`);
3486
+ return;
3487
+ }
3488
+
3489
+ if (failedServers.length > 1) {
3490
+ const failedNames = failedServers.map(server => server.name).join(", ");
3491
+ this.showWarning(`LSP startup failed for ${failedNames}. It will retry lazily on write.`);
3492
+ }
3493
+ }
3494
+
3495
+ #getWelcomeLspServers(): WelcomeLspServerInfo[] {
3496
+ return (
3497
+ this.lspServers?.map(server => ({
3498
+ name: server.name,
3499
+ status: server.status,
3500
+ fileTypes: server.fileTypes,
3501
+ })) ?? []
3502
+ );
3503
+ }
3504
+
3505
+ #updateWelcomeLspServers(): void {
3506
+ if (!this.#welcomeComponent) {
3507
+ return;
3508
+ }
3509
+
3510
+ this.#welcomeComponent.setLspServers(this.#getWelcomeLspServers());
3511
+ this.ui.requestRender();
3512
+ }
3513
+
3514
+ #clearWorkingMessageAccentCache(): void {
3515
+ this.#workingMessageAccentCacheKey = undefined;
3516
+ this.#workingMessageAccentCacheValue = undefined;
3517
+ this.#workingMessageAccentCacheHasValue = false;
3518
+ }
3519
+
3520
+ #buildWorkingMessageAccentCacheKey(): WorkingMessageAccentCacheKey {
3521
+ const sessionAccentEnabled = !isSettingsInitialized() || settings.get("statusLine.sessionAccent") !== false;
3522
+ return {
3523
+ sessionAccentEnabled,
3524
+ sessionName: sessionAccentEnabled ? this.sessionManager.getSessionName() : undefined,
3525
+ accentSurfaceLuminance: theme.accentSurfaceLuminance,
3526
+ };
3527
+ }
3528
+
3529
+ #workingMessageAccentCacheKeyEquals(a: WorkingMessageAccentCacheKey, b: WorkingMessageAccentCacheKey): boolean {
3530
+ return (
3531
+ a.sessionName === b.sessionName &&
3532
+ a.accentSurfaceLuminance === b.accentSurfaceLuminance &&
3533
+ a.sessionAccentEnabled === b.sessionAccentEnabled
3534
+ );
3535
+ }
3536
+
3537
+ #cacheWorkingMessageAccent(
3538
+ key: WorkingMessageAccentCacheKey,
3539
+ value: WorkingMessageAccent | undefined,
3540
+ ): WorkingMessageAccent | undefined {
3541
+ this.#workingMessageAccentCacheKey = key;
3542
+ this.#workingMessageAccentCacheValue = value;
3543
+ this.#workingMessageAccentCacheHasValue = true;
3544
+ return value;
3545
+ }
3546
+
3547
+ #getWorkingMessageAccent(): WorkingMessageAccent | undefined {
3548
+ const key = this.#buildWorkingMessageAccentCacheKey();
3549
+ if (
3550
+ this.#workingMessageAccentCacheHasValue &&
3551
+ this.#workingMessageAccentCacheKey &&
3552
+ this.#workingMessageAccentCacheKeyEquals(key, this.#workingMessageAccentCacheKey)
3553
+ ) {
3554
+ return this.#workingMessageAccentCacheValue;
3555
+ }
3556
+ if (!key.sessionAccentEnabled || !key.sessionName) {
3557
+ return this.#cacheWorkingMessageAccent(key, undefined);
3558
+ }
3559
+ const hex = getSessionAccentHex(key.sessionName, theme.getMajorThemeColorHexes(), key.accentSurfaceLuminance);
3560
+ const main = getSessionAccentAnsi(hex);
3561
+ const dim = getSessionAccentAnsi(adjustHsv(hex, { s: 0.55, v: 0.65 }));
3562
+ return this.#cacheWorkingMessageAccent(key, main && dim ? { main, dim } : undefined);
3563
+ }
3564
+
3565
+ ensureLoadingAnimation(): void {
3566
+ if (!this.loadingAnimation) {
3567
+ this.#clearWorkingMessageAccentCache();
3568
+ this.statusContainer.clear();
3569
+ const messageColorFn = ((message: string) =>
3570
+ renderWorkingMessage(message, this.#getWorkingMessageAccent())) as LoaderMessageColorFn & {
3571
+ animated?: true;
3572
+ };
3573
+ // Shimmer drives the 30fps redraw; when it is disabled the working
3574
+ // message is static, so leave `animated` unset and let the loader use
3575
+ // the spinner-only ~12.5fps cadence instead of repainting a frozen line.
3576
+ if (shimmerEnabled()) messageColorFn.animated = true;
3577
+ this.loadingAnimation = new Loader(
3578
+ this.ui,
3579
+ spinner => {
3580
+ const accent = this.#getWorkingMessageAccent();
3581
+ return accent ? `${accent.main}${spinner}\x1b[39m` : theme.fg("accent", spinner);
3582
+ },
3583
+ messageColorFn,
3584
+ this.#defaultWorkingMessage,
3585
+ getSymbolTheme().spinnerFrames,
3586
+ );
3587
+ this.statusContainer.addChild(this.loadingAnimation);
3588
+ } else if (!this.statusContainer.children.includes(this.loadingAnimation)) {
3589
+ this.statusContainer.clear();
3590
+ this.statusContainer.addChild(this.loadingAnimation);
3591
+ this.ui.requestRender();
3592
+ }
3593
+ this.applyPendingWorkingMessage();
3594
+ }
3595
+
3596
+ #stopLoadingAnimation(clearStatusContainer: boolean): void {
3597
+ if (!this.loadingAnimation) return;
3598
+ this.loadingAnimation.stop();
3599
+ this.loadingAnimation = undefined;
3600
+ this.#clearWorkingMessageAccentCache();
3601
+ if (clearStatusContainer) {
3602
+ this.statusContainer.clear();
3603
+ }
3604
+ }
3605
+
3606
+ setWorkingMessage(message?: string): void {
3607
+ if (message === undefined) {
3608
+ this.#pendingWorkingMessage = undefined;
3609
+ if (this.loadingAnimation) {
3610
+ this.loadingAnimation.setMessage(this.#defaultWorkingMessage);
3611
+ }
3612
+ return;
3613
+ }
3614
+
3615
+ if (this.loadingAnimation) {
3616
+ this.loadingAnimation.setMessage(message);
3617
+ return;
3618
+ }
3619
+
3620
+ this.#pendingWorkingMessage = message;
3621
+ }
3622
+
3623
+ applyPendingWorkingMessage(): void {
3624
+ if (this.#pendingWorkingMessage === undefined) {
3625
+ return;
3626
+ }
3627
+
3628
+ const message = this.#pendingWorkingMessage;
3629
+ this.#pendingWorkingMessage = undefined;
3630
+ this.setWorkingMessage(message);
3631
+ }
3632
+
3633
+ showNewVersionNotification(newVersion: string): void {
3634
+ this.#uiHelpers.showNewVersionNotification(newVersion);
3635
+ }
3636
+
3637
+ clearEditor(): void {
3638
+ this.#uiHelpers.clearEditor();
3639
+ }
3640
+
3641
+ updatePendingMessagesDisplay(): void {
3642
+ this.#uiHelpers.updatePendingMessagesDisplay();
3643
+ }
3644
+
3645
+ queueCompactionMessage(text: string, mode: "steer" | "followUp", images?: ImageContent[]): void {
3646
+ this.#uiHelpers.queueCompactionMessage(text, mode, images);
3647
+ }
3648
+
3649
+ flushCompactionQueue(options?: { willRetry?: boolean }): Promise<void> {
3650
+ return this.#uiHelpers.flushCompactionQueue(options);
3651
+ }
3652
+
3653
+ flushPendingBashComponents(): void {
3654
+ this.#uiHelpers.flushPendingBashComponents();
3655
+ }
3656
+
3657
+ isKnownSlashCommand(text: string): boolean {
3658
+ return this.#uiHelpers.isKnownSlashCommand(text);
3659
+ }
3660
+
3661
+ addMessageToChat(
3662
+ message: AgentMessage,
3663
+ options?: { populateHistory?: boolean; imageLinks?: readonly (string | undefined)[] },
3664
+ ): Component[] {
3665
+ return this.#uiHelpers.addMessageToChat(message, options);
3666
+ }
3667
+
3668
+ renderSessionContext(
3669
+ sessionContext: SessionContext,
3670
+ options?: { updateFooter?: boolean; populateHistory?: boolean },
3671
+ ): void {
3672
+ for (const message of sessionContext.messages) {
3673
+ this.noteDisplayableThinkingContent(message);
3674
+ }
3675
+ this.#uiHelpers.renderSessionContext(sessionContext, options);
3676
+ }
3677
+
3678
+ renderInitialMessages(options?: { preserveExistingChat?: boolean; clearTerminalHistory?: boolean }): void {
3679
+ this.#uiHelpers.renderInitialMessages(options);
3680
+ }
3681
+
3682
+ getUserMessageText(message: Message): string {
3683
+ return this.#uiHelpers.getUserMessageText(message);
3684
+ }
3685
+
3686
+ findLastAssistantMessage(): AssistantMessage | undefined {
3687
+ return this.#uiHelpers.findLastAssistantMessage();
3688
+ }
3689
+
3690
+ extractAssistantText(message: AssistantMessage): string {
3691
+ return this.#uiHelpers.extractAssistantText(message);
3692
+ }
3693
+
3694
+ // Command handling
3695
+ handleExportCommand(text: string): Promise<void> {
3696
+ return this.#commandController.handleExportCommand(text);
3697
+ }
3698
+
3699
+ async handleDumpCommand(): Promise<void> {
3700
+ return this.#commandController.handleDumpCommand();
3701
+ }
3702
+
3703
+ handleAdvisorDumpCommand(isRaw?: boolean) {
3704
+ return this.#commandController.handleAdvisorDumpCommand(isRaw);
3705
+ }
3706
+
3707
+ handleDebugTranscriptCommand(): Promise<void> {
3708
+ return this.#commandController.handleDebugTranscriptCommand();
3709
+ }
3710
+
3711
+ handleShareCommand(): Promise<void> {
3712
+ return this.#commandController.handleShareCommand();
3713
+ }
3714
+
3715
+ handleTodoCommand(args: string): Promise<void> {
3716
+ return this.#todoCommandController.handleTodoCommand(args);
3717
+ }
3718
+
3719
+ handleSessionCommand(): Promise<void> {
3720
+ return this.#commandController.handleSessionCommand();
3721
+ }
3722
+
3723
+ handleAdvisorStatusCommand(): Promise<void> {
3724
+ return this.#commandController.handleAdvisorStatusCommand();
3725
+ }
3726
+
3727
+ handleJobsCommand(): Promise<void> {
3728
+ return this.#commandController.handleJobsCommand();
3729
+ }
3730
+
3731
+ handleUsageCommand(reports?: UsageReport[] | null): Promise<void> {
3732
+ return this.#commandController.handleUsageCommand(reports);
3733
+ }
3734
+
3735
+ async handleChangelogCommand(showFull = false): Promise<void> {
3736
+ await this.#commandController.handleChangelogCommand(showFull);
3737
+ }
3738
+
3739
+ handleHotkeysCommand(): void {
3740
+ this.#commandController.handleHotkeysCommand();
3741
+ }
3742
+
3743
+ handleToolsCommand(): void {
3744
+ this.#commandController.handleToolsCommand();
3745
+ }
3746
+
3747
+ handleContextCommand(): void {
3748
+ this.#commandController.handleContextCommand();
3749
+ }
3750
+
3751
+ #prepareSessionSwitch(): void {
3752
+ this.#btwController.dispose();
3753
+ this.#omfgController.dispose();
3754
+ this.#extensionUiController.clearExtensionTerminalInputListeners();
3755
+ this.clearPinnedError();
3756
+ this.#hidePlanReview();
3757
+ }
3758
+
3759
+ handleClearCommand(): Promise<void> {
3760
+ this.#prepareSessionSwitch();
3761
+ return this.#commandController.handleClearCommand();
3762
+ }
3763
+
3764
+ handleFreshCommand(): Promise<void> {
3765
+ return this.#commandController.handleFreshCommand();
3766
+ }
3767
+
3768
+ handleDropCommand(): Promise<void> {
3769
+ this.#prepareSessionSwitch();
3770
+ return this.#commandController.handleDropCommand();
3771
+ }
3772
+
3773
+ handleForkCommand(): Promise<void> {
3774
+ this.#btwController.dispose();
3775
+ this.#omfgController.dispose();
3776
+ return this.#commandController.handleForkCommand();
3777
+ }
3778
+
3779
+ handleMoveCommand(targetPath?: string): Promise<void> {
3780
+ return this.#commandController.handleMoveCommand(targetPath);
3781
+ }
3782
+
3783
+ handleRenameCommand(title: string): Promise<void> {
3784
+ return this.#commandController.handleRenameCommand(title);
3785
+ }
3786
+
3787
+ handleMemoryCommand(text: string): Promise<void> {
3788
+ return this.#commandController.handleMemoryCommand(text);
3789
+ }
3790
+
3791
+ async handleSTTToggle(): Promise<void> {
3792
+ if (!settings.get("stt.enabled")) {
3793
+ this.showWarning("Speech-to-text is disabled. Enable it in settings: stt.enabled");
3794
+ return;
3795
+ }
3796
+ if (!this.#sttController) {
3797
+ this.#sttController = new STTController();
3798
+ }
3799
+ await this.#sttController.toggle(this.editor, {
3800
+ showWarning: (msg: string) => this.showWarning(msg),
3801
+ showStatus: (msg: string) => this.showStatus(msg),
3802
+ requestRender: () => this.ui.requestRender(),
3803
+ onStateChange: (state: SttState) => {
3804
+ // Duck assistant speech while the user is talking (push-to-talk); restore after.
3805
+ if (state === "recording") vocalizer.duck();
3806
+ else vocalizer.unduck();
3807
+ if (state === "recording") {
3808
+ this.#voicePreviousShowHardwareCursor = this.ui.getShowHardwareCursor();
3809
+ this.#voicePreviousUseTerminalCursor = this.editor.getUseTerminalCursor();
3810
+ this.ui.setShowHardwareCursor(false);
3811
+ this.editor.setUseTerminalCursor(false);
3812
+ this.#startMicAnimation();
3813
+ } else if (state === "transcribing") {
3814
+ this.#stopMicAnimation();
3815
+ this.#setMicCursor({ r: 200, g: 200, b: 200 });
3816
+ } else {
3817
+ this.#cleanupMicAnimation();
3818
+ }
3819
+ this.ui.requestRender();
3820
+ },
3821
+ });
3822
+ }
3823
+
3824
+ #setMicCursor(color: { r: number; g: number; b: number }): void {
3825
+ this.editor.cursorOverride = `\x1b[38;2;${color.r};${color.g};${color.b}m${theme.icon.mic}\x1b[0m`;
3826
+ // Theme symbols can be wide (for example, 🎤), so measure the rendered override.
3827
+ this.editor.cursorOverrideWidth = visibleWidth(this.editor.cursorOverride);
3828
+ }
3829
+
3830
+ #updateMicIcon(): void {
3831
+ const { r, g, b } = hsvToRgb({ h: this.#voiceHue, s: 0.9, v: 1.0 });
3832
+ this.#setMicCursor({ r, g, b });
3833
+ }
3834
+
3835
+ #startMicAnimation(): void {
3836
+ if (this.#voiceAnimationInterval) return;
3837
+ this.#voiceHue = 0;
3838
+ this.#updateMicIcon();
3839
+ this.#voiceAnimationInterval = setInterval(() => {
3840
+ this.#voiceHue = (this.#voiceHue + 8) % 360;
3841
+ this.#updateMicIcon();
3842
+ // Component-scoped: the hue sweep only recolors the editor's cursor
3843
+ // glyph, so the transcript subtree is reused per animation frame.
3844
+ this.ui.requestComponentRender(this.editor);
3845
+ }, 60);
3846
+ }
3847
+
3848
+ #stopMicAnimation(): void {
3849
+ if (this.#voiceAnimationInterval) {
3850
+ clearInterval(this.#voiceAnimationInterval);
3851
+ this.#voiceAnimationInterval = undefined;
3852
+ }
3853
+ }
3854
+
3855
+ #cleanupMicAnimation(): void {
3856
+ if (this.#voiceAnimationInterval) {
3857
+ clearInterval(this.#voiceAnimationInterval);
3858
+ this.#voiceAnimationInterval = undefined;
3859
+ }
3860
+ this.editor.cursorOverride = undefined;
3861
+ this.editor.cursorOverrideWidth = undefined;
3862
+ if (this.#voicePreviousShowHardwareCursor !== null) {
3863
+ this.ui.setShowHardwareCursor(this.#voicePreviousShowHardwareCursor);
3864
+ this.#voicePreviousShowHardwareCursor = null;
3865
+ }
3866
+ if (this.#voicePreviousUseTerminalCursor !== null) {
3867
+ this.editor.setUseTerminalCursor(this.#voicePreviousUseTerminalCursor);
3868
+ this.#voicePreviousUseTerminalCursor = null;
3869
+ }
3870
+ }
3871
+
3872
+ async showDebugSelector(): Promise<void> {
3873
+ await this.#selectorController.showDebugSelector();
3874
+ }
3875
+
3876
+ showAgentHub(options?: { requireContent?: boolean }): void {
3877
+ this.#selectorController.showAgentHub(this.#observerRegistry, options);
3878
+ }
3879
+
3880
+ resetObserverRegistry(): void {
3881
+ this.#observerRegistry.resetSessions();
3882
+ this.#observerRegistry.setMainSession(this.sessionManager.getSessionFile() ?? undefined);
3883
+ }
3884
+
3885
+ handleBashCommand(command: string, excludeFromContext?: boolean): Promise<void> {
3886
+ return this.#commandController.handleBashCommand(command, excludeFromContext);
3887
+ }
3888
+
3889
+ handlePythonCommand(code: string, excludeFromContext?: boolean): Promise<void> {
3890
+ return this.#commandController.handlePythonCommand(code, excludeFromContext);
3891
+ }
3892
+
3893
+ async handleMCPCommand(text: string): Promise<void> {
3894
+ const controller = new MCPCommandController(this);
3895
+ await controller.handle(text);
3896
+ }
3897
+
3898
+ async handleSSHCommand(text: string): Promise<void> {
3899
+ const controller = new SSHCommandController(this);
3900
+ await controller.handle(text);
3901
+ }
3902
+
3903
+ handleCompactCommand(
3904
+ customInstructions?: string,
3905
+ mode?: CompactMode,
3906
+ beforeFlush?: (outcome: CompactionOutcome) => void | Promise<void>,
3907
+ ): Promise<CompactionOutcome> {
3908
+ return this.#commandController.handleCompactCommand(customInstructions, mode, beforeFlush);
3909
+ }
3910
+
3911
+ handleHandoffCommand(customInstructions?: string): Promise<void> {
3912
+ return this.#commandController.handleHandoffCommand(customInstructions);
3913
+ }
3914
+
3915
+ handleShakeCommand(mode: ShakeMode): Promise<void> {
3916
+ return this.#commandController.handleShakeCommand(mode);
3917
+ }
3918
+
3919
+ executeCompaction(
3920
+ customInstructionsOrOptions?: string | CompactOptions,
3921
+ isAuto?: boolean,
3922
+ ): Promise<CompactionOutcome> {
3923
+ return this.#commandController.executeCompaction(customInstructionsOrOptions, isAuto);
3924
+ }
3925
+
3926
+ openInBrowser(urlOrPath: string): void {
3927
+ this.#commandController.openInBrowser(urlOrPath);
3928
+ }
3929
+
3930
+ // Selector handling
3931
+ showSettingsSelector(): void {
3932
+ this.#selectorController.showSettingsSelector();
3933
+ }
3934
+
3935
+ showAdvisorConfigure(): void {
3936
+ this.#selectorController.showAdvisorConfigure();
3937
+ }
3938
+
3939
+ showHistorySearch(): void {
3940
+ this.#selectorController.showHistorySearch();
3941
+ }
3942
+
3943
+ showExtensionsDashboard(): void {
3944
+ void this.#selectorController.showExtensionsDashboard();
3945
+ }
3946
+
3947
+ showAgentsDashboard(): void {
3948
+ void this.#selectorController.showAgentsDashboard();
3949
+ }
3950
+
3951
+ showModelSelector(options?: { temporaryOnly?: boolean }): void {
3952
+ this.#selectorController.showModelSelector(options);
3953
+ }
3954
+
3955
+ showPluginSelector(mode?: "install" | "uninstall"): void {
3956
+ void this.#selectorController.showPluginSelector(mode);
3957
+ }
3958
+
3959
+ showUserMessageSelector(): void {
3960
+ this.#selectorController.showUserMessageSelector();
3961
+ }
3962
+
3963
+ showCopySelector(): void {
3964
+ this.#selectorController.showCopySelector();
3965
+ }
3966
+
3967
+ showTreeSelector(): void {
3968
+ this.#selectorController.showTreeSelector();
3969
+ }
3970
+
3971
+ showSessionSelector(): void {
3972
+ this.#selectorController.showSessionSelector();
3973
+ }
3974
+
3975
+ handleResumeSession(sessionPath: string): Promise<void> {
3976
+ this.#btwController.dispose();
3977
+ this.#omfgController.dispose();
3978
+ this.resetObserverRegistry();
3979
+ return this.#selectorController.handleResumeSession(sessionPath);
3980
+ }
3981
+
3982
+ handleSessionDeleteCommand(): Promise<void> {
3983
+ return this.#selectorController.handleSessionDeleteCommand();
3984
+ }
3985
+
3986
+ showOAuthSelector(mode: "login" | "logout", providerId?: string): Promise<void> {
3987
+ return this.#selectorController.showOAuthSelector(mode, providerId);
3988
+ }
3989
+
3990
+ showResetUsageSelector(): Promise<void> {
3991
+ return this.#selectorController.showResetUsageSelector();
3992
+ }
3993
+
3994
+ showProviderSetup(): Promise<void> {
3995
+ return runProviderSetupWizard(this);
3996
+ }
3997
+
3998
+ showHookConfirm(title: string, message: string): Promise<boolean> {
3999
+ return this.#extensionUiController.showHookConfirm(title, message);
4000
+ }
4001
+
4002
+ // Input handling
4003
+ handleCtrlC(): void {
4004
+ this.#inputController.handleCtrlC();
4005
+ }
4006
+
4007
+ handleCtrlD(): void {
4008
+ this.#inputController.handleCtrlD();
4009
+ }
4010
+
4011
+ handleCtrlZ(): void {
4012
+ this.#inputController.handleCtrlZ();
4013
+ }
4014
+
4015
+ handleDequeue(): void {
4016
+ this.#inputController.handleDequeue();
4017
+ }
4018
+
4019
+ handleImagePaste(): Promise<boolean> {
4020
+ return this.#inputController.handleImagePaste();
4021
+ }
4022
+
4023
+ handleBtwCommand(question: string): Promise<void> {
4024
+ return this.#btwController.start(question);
4025
+ }
4026
+
4027
+ handleTanCommand(work: string): Promise<void> {
4028
+ return this.#tanCommandController.start(work);
4029
+ }
4030
+
4031
+ hasActiveBtw(): boolean {
4032
+ return this.#btwController.hasActiveRequest();
4033
+ }
4034
+
4035
+ handleBtwEscape(): boolean {
4036
+ return this.#btwController.handleEscape();
4037
+ }
4038
+
4039
+ canBranchBtw(): boolean {
4040
+ return this.#btwController.canBranch();
4041
+ }
4042
+
4043
+ handleBtwBranchKey(): Promise<boolean> {
4044
+ return this.#btwController.handleBranch();
4045
+ }
4046
+
4047
+ canCopyBtw(): boolean {
4048
+ return this.#btwController.canCopy();
4049
+ }
4050
+
4051
+ handleBtwCopyKey(): Promise<boolean> {
4052
+ return this.#btwController.handleCopy();
4053
+ }
4054
+
4055
+ async handleBtwBranch(question: string, assistantMessage: AssistantMessage): Promise<void> {
4056
+ try {
4057
+ const result = await this.session.branchFromBtw(question, assistantMessage);
4058
+ if (result.cancelled) {
4059
+ this.showStatus("/btw branch cancelled", { dim: true });
4060
+ return;
4061
+ }
4062
+ this.#btwController.dispose();
4063
+ this.#omfgController.dispose();
4064
+ this.chatContainer.clear();
4065
+ this.renderInitialMessages({ clearTerminalHistory: true });
4066
+ this.updateEditorBorderColor();
4067
+ this.showStatus(
4068
+ result.sessionFile ? `Branched /btw to ${path.basename(result.sessionFile)}` : "Branched /btw",
4069
+ );
4070
+ } catch (error) {
4071
+ this.showError(`Cannot branch /btw: ${error instanceof Error ? error.message : String(error)}`);
4072
+ }
4073
+ }
4074
+
4075
+ handleOmfgCommand(complaint: string): Promise<void> {
4076
+ return this.#omfgController.start(complaint);
4077
+ }
4078
+
4079
+ hasActiveOmfg(): boolean {
4080
+ return this.#omfgController.hasActiveRequest();
4081
+ }
4082
+
4083
+ handleOmfgEscape(): boolean {
4084
+ return this.#omfgController.handleEscape();
4085
+ }
4086
+
4087
+ cycleThinkingLevel(): void {
4088
+ this.#inputController.cycleThinkingLevel();
4089
+ }
4090
+
4091
+ cycleRoleModel(direction?: "forward" | "backward"): Promise<void> {
4092
+ return this.#inputController.cycleRoleModel(direction);
4093
+ }
4094
+
4095
+ toggleToolOutputExpansion(): void {
4096
+ this.#inputController.toggleToolOutputExpansion();
4097
+ }
4098
+
4099
+ setToolsExpanded(expanded: boolean): void {
4100
+ this.#inputController.setToolsExpanded(expanded);
4101
+ }
4102
+
4103
+ toggleThinkingBlockVisibility(): void {
4104
+ this.#inputController.toggleThinkingBlockVisibility();
4105
+ }
4106
+
4107
+ toggleTodoExpansion(): void {
4108
+ this.todoExpanded = !this.todoExpanded;
4109
+ this.#renderTodoList();
4110
+ this.ui.requestRender();
4111
+ }
4112
+
4113
+ setTodos(todos: TodoItem[] | TodoPhase[]): void {
4114
+ if (todos.length > 0 && "tasks" in todos[0]) {
4115
+ this.todoPhases = todos as TodoPhase[];
4116
+ } else {
4117
+ this.todoPhases = [
4118
+ {
4119
+ name: "Todos",
4120
+ tasks: todos as TodoItem[],
4121
+ },
4122
+ ];
4123
+ }
4124
+ this.#syncTodoAutoClearTimer();
4125
+ this.#renderTodoList();
4126
+ this.ui.requestRender();
4127
+ }
4128
+
4129
+ async reloadTodos(): Promise<void> {
4130
+ await this.#loadTodoList();
4131
+ this.ui.requestRender();
4132
+ }
4133
+
4134
+ openExternalEditor(): void {
4135
+ this.#inputController.openExternalEditor();
4136
+ }
4137
+
4138
+ registerExtensionShortcuts(): void {
4139
+ this.#inputController.registerExtensionShortcuts();
4140
+ }
4141
+
4142
+ // Hook UI methods
4143
+ initHooksAndCustomTools(): Promise<void> {
4144
+ return this.#extensionUiController.initHooksAndCustomTools();
4145
+ }
4146
+
4147
+ emitCustomToolSessionEvent(
4148
+ reason: "start" | "switch" | "branch" | "tree" | "shutdown",
4149
+ previousSessionFile?: string,
4150
+ ): Promise<void> {
4151
+ return this.#extensionUiController.emitCustomToolSessionEvent(reason, previousSessionFile);
4152
+ }
4153
+
4154
+ setHookWidget(key: string, content: ExtensionWidgetContent, options?: ExtensionWidgetOptions): void {
4155
+ this.#extensionUiController.setHookWidget(key, content, options);
4156
+ }
4157
+
4158
+ setHookStatus(key: string, text: string | undefined): void {
4159
+ this.#extensionUiController.setHookStatus(key, text);
4160
+ }
4161
+
4162
+ showHookSelector(
4163
+ title: string,
4164
+ options: ExtensionUISelectItem[],
4165
+ dialogOptions?: InteractiveSelectorDialogOptions,
4166
+ extra?: { slider?: HookSelectorSlider },
4167
+ ): Promise<string | undefined> {
4168
+ return this.#extensionUiController.showHookSelector(title, options, dialogOptions, extra);
4169
+ }
4170
+
4171
+ hideHookSelector(): void {
4172
+ this.#extensionUiController.hideHookSelector();
4173
+ }
4174
+
4175
+ showHookInput(title: string, placeholder?: string): Promise<string | undefined> {
4176
+ return this.#extensionUiController.showHookInput(title, placeholder);
4177
+ }
4178
+
4179
+ hideHookInput(): void {
4180
+ this.#extensionUiController.hideHookInput();
4181
+ }
4182
+
4183
+ showHookEditor(
4184
+ title: string,
4185
+ prefill?: string,
4186
+ dialogOptions?: ExtensionUIDialogOptions,
4187
+ editorOptions?: { promptStyle?: boolean },
4188
+ ): Promise<string | undefined> {
4189
+ return this.#extensionUiController.showHookEditor(title, prefill, dialogOptions, editorOptions);
4190
+ }
4191
+
4192
+ hideHookEditor(): void {
4193
+ this.#extensionUiController.hideHookEditor();
4194
+ }
4195
+
4196
+ showHookNotify(message: string, type?: "info" | "warning" | "error"): void {
4197
+ this.#extensionUiController.showHookNotify(message, type);
4198
+ }
4199
+
4200
+ showHookCustom<T>(
4201
+ factory: (
4202
+ tui: TUI,
4203
+ theme: Theme,
4204
+ keybindings: KeybindingsManager,
4205
+ done: (result: T) => void,
4206
+ ) => (Component & { dispose?(): void }) | Promise<Component & { dispose?(): void }>,
4207
+ options?: { overlay?: boolean },
4208
+ ): Promise<T> {
4209
+ return this.#extensionUiController.showHookCustom(factory, options);
4210
+ }
4211
+
4212
+ showExtensionError(extensionPath: string, error: string): void {
4213
+ this.#extensionUiController.showExtensionError(extensionPath, error);
4214
+ }
4215
+
4216
+ showToolError(toolName: string, error: string): void {
4217
+ this.#extensionUiController.showToolError(toolName, error);
4218
+ }
4219
+
4220
+ #subscribeToAgent(): void {
4221
+ this.#eventController.subscribeToAgent();
4222
+ }
4223
+ }