@bastani/atomic 0.7.17 → 0.8.0

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 (1233) hide show
  1. package/CHANGELOG.md +4200 -0
  2. package/README.md +655 -0
  3. package/dist/builtin/intercom/CHANGELOG.md +195 -0
  4. package/dist/builtin/intercom/LICENSE +21 -0
  5. package/dist/builtin/intercom/README.md +484 -0
  6. package/dist/builtin/intercom/broker/broker.ts +346 -0
  7. package/dist/builtin/intercom/broker/client.ts +535 -0
  8. package/dist/builtin/intercom/broker/framing.ts +57 -0
  9. package/dist/builtin/intercom/broker/paths.ts +21 -0
  10. package/dist/builtin/intercom/broker/spawn.ts +308 -0
  11. package/dist/builtin/intercom/config.ts +109 -0
  12. package/dist/builtin/intercom/index.ts +1780 -0
  13. package/dist/builtin/intercom/package.json +59 -0
  14. package/dist/builtin/intercom/reply-tracker.ts +102 -0
  15. package/dist/builtin/intercom/skills/intercom/SKILL.md +513 -0
  16. package/dist/builtin/intercom/types.ts +46 -0
  17. package/dist/builtin/intercom/ui/compose.ts +139 -0
  18. package/dist/builtin/intercom/ui/inline-message.ts +76 -0
  19. package/dist/builtin/intercom/ui/session-list.ts +162 -0
  20. package/dist/builtin/mcp/CHANGELOG.md +346 -0
  21. package/dist/builtin/mcp/LICENSE +21 -0
  22. package/dist/builtin/mcp/OAUTH.md +324 -0
  23. package/dist/builtin/mcp/README.md +373 -0
  24. package/dist/builtin/mcp/agent-dir.ts +21 -0
  25. package/dist/builtin/mcp/app-bridge.bundle.js +67 -0
  26. package/dist/builtin/mcp/cli.js +186 -0
  27. package/dist/builtin/mcp/commands.ts +420 -0
  28. package/dist/builtin/mcp/config.ts +667 -0
  29. package/dist/builtin/mcp/consent-manager.ts +64 -0
  30. package/dist/builtin/mcp/direct-tools.ts +427 -0
  31. package/dist/builtin/mcp/errors.ts +219 -0
  32. package/dist/builtin/mcp/glimpse-ui.ts +80 -0
  33. package/dist/builtin/mcp/host-html-template.ts +427 -0
  34. package/dist/builtin/mcp/index.ts +334 -0
  35. package/dist/builtin/mcp/init.ts +336 -0
  36. package/dist/builtin/mcp/lifecycle.ts +93 -0
  37. package/dist/builtin/mcp/logger.ts +169 -0
  38. package/dist/builtin/mcp/mcp-auth-flow.ts +362 -0
  39. package/dist/builtin/mcp/mcp-auth.ts +297 -0
  40. package/dist/builtin/mcp/mcp-callback-server.ts +284 -0
  41. package/dist/builtin/mcp/mcp-oauth-provider.ts +302 -0
  42. package/dist/builtin/mcp/mcp-panel.ts +826 -0
  43. package/dist/builtin/mcp/mcp-setup-panel.ts +577 -0
  44. package/dist/builtin/mcp/metadata-cache.ts +201 -0
  45. package/dist/builtin/mcp/npx-resolver.ts +424 -0
  46. package/dist/builtin/mcp/oauth-handler.ts +60 -0
  47. package/dist/builtin/mcp/onboarding-state.ts +68 -0
  48. package/dist/builtin/mcp/package.json +61 -0
  49. package/dist/builtin/mcp/proxy-modes.ts +803 -0
  50. package/dist/builtin/mcp/resource-tools.ts +17 -0
  51. package/dist/builtin/mcp/sampling-handler.ts +268 -0
  52. package/dist/builtin/mcp/server-manager.ts +375 -0
  53. package/dist/builtin/mcp/state.ts +41 -0
  54. package/dist/builtin/mcp/tool-metadata.ts +152 -0
  55. package/dist/builtin/mcp/tool-registrar.ts +46 -0
  56. package/dist/builtin/mcp/tool-result-renderer.ts +65 -0
  57. package/dist/builtin/mcp/types.ts +441 -0
  58. package/dist/builtin/mcp/ui-resource-handler.ts +145 -0
  59. package/dist/builtin/mcp/ui-server.ts +623 -0
  60. package/dist/builtin/mcp/ui-session.ts +384 -0
  61. package/dist/builtin/mcp/ui-stream-types.ts +89 -0
  62. package/dist/builtin/mcp/utils.ts +129 -0
  63. package/dist/builtin/subagents/CHANGELOG.md +1019 -0
  64. package/dist/builtin/subagents/README.md +991 -0
  65. package/dist/builtin/subagents/agents/code-simplifier.md +84 -0
  66. package/dist/builtin/subagents/agents/codebase-analyzer.md +158 -0
  67. package/dist/builtin/subagents/agents/codebase-locator.md +113 -0
  68. package/dist/builtin/subagents/agents/codebase-online-researcher.md +317 -0
  69. package/dist/builtin/subagents/agents/codebase-pattern-finder.md +236 -0
  70. package/dist/builtin/subagents/agents/codebase-research-analyzer.md +181 -0
  71. package/dist/builtin/subagents/agents/codebase-research-locator.md +146 -0
  72. package/dist/builtin/subagents/agents/debugger.md +92 -0
  73. package/dist/builtin/subagents/package.json +67 -0
  74. package/dist/builtin/subagents/prompts/gather-context-and-clarify.md +20 -0
  75. package/dist/builtin/subagents/prompts/parallel-cleanup.md +60 -0
  76. package/dist/builtin/subagents/prompts/parallel-context-build.md +55 -0
  77. package/dist/builtin/subagents/prompts/parallel-handoff-plan.md +77 -0
  78. package/dist/builtin/subagents/prompts/parallel-research.md +58 -0
  79. package/dist/builtin/subagents/prompts/parallel-review.md +52 -0
  80. package/dist/builtin/subagents/prompts/review-loop.md +48 -0
  81. package/dist/builtin/subagents/skills/subagent/SKILL.md +734 -0
  82. package/dist/builtin/subagents/src/agents/agent-management.ts +644 -0
  83. package/dist/builtin/subagents/src/agents/agent-scope.ts +6 -0
  84. package/dist/builtin/subagents/src/agents/agent-selection.ts +23 -0
  85. package/dist/builtin/subagents/src/agents/agent-serializer.ts +84 -0
  86. package/dist/builtin/subagents/src/agents/agents.ts +809 -0
  87. package/dist/builtin/subagents/src/agents/chain-serializer.ts +137 -0
  88. package/dist/builtin/subagents/src/agents/frontmatter.ts +29 -0
  89. package/dist/builtin/subagents/src/agents/identity.ts +30 -0
  90. package/dist/builtin/subagents/src/agents/skills.ts +630 -0
  91. package/dist/builtin/subagents/src/extension/control-notices.ts +92 -0
  92. package/dist/builtin/subagents/src/extension/doctor.ts +199 -0
  93. package/dist/builtin/subagents/src/extension/index.ts +586 -0
  94. package/dist/builtin/subagents/src/extension/schemas.ts +168 -0
  95. package/dist/builtin/subagents/src/intercom/intercom-bridge.ts +378 -0
  96. package/dist/builtin/subagents/src/intercom/result-intercom.ts +269 -0
  97. package/dist/builtin/subagents/src/runs/background/async-execution.ts +612 -0
  98. package/dist/builtin/subagents/src/runs/background/async-job-tracker.ts +267 -0
  99. package/dist/builtin/subagents/src/runs/background/async-resume.ts +332 -0
  100. package/dist/builtin/subagents/src/runs/background/async-status.ts +295 -0
  101. package/dist/builtin/subagents/src/runs/background/completion-dedupe.ts +63 -0
  102. package/dist/builtin/subagents/src/runs/background/notify.ts +108 -0
  103. package/dist/builtin/subagents/src/runs/background/parallel-groups.ts +45 -0
  104. package/dist/builtin/subagents/src/runs/background/result-watcher.ts +250 -0
  105. package/dist/builtin/subagents/src/runs/background/run-status.ts +193 -0
  106. package/dist/builtin/subagents/src/runs/background/stale-run-reconciler.ts +291 -0
  107. package/dist/builtin/subagents/src/runs/background/subagent-runner.ts +1760 -0
  108. package/dist/builtin/subagents/src/runs/background/top-level-async.ts +13 -0
  109. package/dist/builtin/subagents/src/runs/foreground/chain-clarify.ts +1333 -0
  110. package/dist/builtin/subagents/src/runs/foreground/chain-execution.ts +932 -0
  111. package/dist/builtin/subagents/src/runs/foreground/execution.ts +902 -0
  112. package/dist/builtin/subagents/src/runs/foreground/subagent-executor.ts +2231 -0
  113. package/dist/builtin/subagents/src/runs/shared/completion-guard.ts +125 -0
  114. package/dist/builtin/subagents/src/runs/shared/long-running-guard.ts +175 -0
  115. package/dist/builtin/subagents/src/runs/shared/model-fallback.ts +103 -0
  116. package/dist/builtin/subagents/src/runs/shared/parallel-utils.ts +108 -0
  117. package/dist/builtin/subagents/src/runs/shared/pi-args.ts +163 -0
  118. package/dist/builtin/subagents/src/runs/shared/pi-spawn.ts +115 -0
  119. package/dist/builtin/subagents/src/runs/shared/run-history.ts +56 -0
  120. package/dist/builtin/subagents/src/runs/shared/single-output.ts +154 -0
  121. package/dist/builtin/subagents/src/runs/shared/subagent-control.ts +226 -0
  122. package/dist/builtin/subagents/src/runs/shared/subagent-prompt-runtime.ts +152 -0
  123. package/dist/builtin/subagents/src/runs/shared/worktree.ts +577 -0
  124. package/dist/builtin/subagents/src/shared/artifacts.ts +99 -0
  125. package/dist/builtin/subagents/src/shared/atomic-json.ts +16 -0
  126. package/dist/builtin/subagents/src/shared/file-coalescer.ts +40 -0
  127. package/dist/builtin/subagents/src/shared/fork-context.ts +76 -0
  128. package/dist/builtin/subagents/src/shared/formatters.ts +133 -0
  129. package/dist/builtin/subagents/src/shared/jsonl-writer.ts +81 -0
  130. package/dist/builtin/subagents/src/shared/model-info.ts +78 -0
  131. package/dist/builtin/subagents/src/shared/post-exit-stdio-guard.ts +85 -0
  132. package/dist/builtin/subagents/src/shared/session-identity.ts +10 -0
  133. package/dist/builtin/subagents/src/shared/session-tokens.ts +44 -0
  134. package/dist/builtin/subagents/src/shared/settings.ts +397 -0
  135. package/dist/builtin/subagents/src/shared/status-format.ts +49 -0
  136. package/dist/builtin/subagents/src/shared/types.ts +732 -0
  137. package/dist/builtin/subagents/src/shared/utils.ts +440 -0
  138. package/dist/builtin/subagents/src/slash/prompt-template-bridge.ts +397 -0
  139. package/dist/builtin/subagents/src/slash/slash-bridge.ts +174 -0
  140. package/dist/builtin/subagents/src/slash/slash-commands.ts +528 -0
  141. package/dist/builtin/subagents/src/slash/slash-live-state.ts +292 -0
  142. package/dist/builtin/subagents/src/tui/render-helpers.ts +80 -0
  143. package/dist/builtin/subagents/src/tui/render.ts +1257 -0
  144. package/dist/builtin/web-access/CHANGELOG.md +387 -0
  145. package/dist/builtin/web-access/LICENSE +21 -0
  146. package/dist/builtin/web-access/README.md +346 -0
  147. package/dist/builtin/web-access/activity.ts +101 -0
  148. package/dist/builtin/web-access/chrome-cookies.ts +322 -0
  149. package/dist/builtin/web-access/code-search.ts +107 -0
  150. package/dist/builtin/web-access/curator-page.ts +3359 -0
  151. package/dist/builtin/web-access/curator-server.ts +605 -0
  152. package/dist/builtin/web-access/exa.ts +521 -0
  153. package/dist/builtin/web-access/extract.ts +701 -0
  154. package/dist/builtin/web-access/gemini-api.ts +113 -0
  155. package/dist/builtin/web-access/gemini-search.ts +362 -0
  156. package/dist/builtin/web-access/gemini-url-context.ts +126 -0
  157. package/dist/builtin/web-access/gemini-web-config.ts +54 -0
  158. package/dist/builtin/web-access/gemini-web.ts +396 -0
  159. package/dist/builtin/web-access/github-api.ts +196 -0
  160. package/dist/builtin/web-access/github-extract.ts +635 -0
  161. package/dist/builtin/web-access/index.ts +2347 -0
  162. package/dist/builtin/web-access/package.json +54 -0
  163. package/dist/builtin/web-access/pdf-extract.ts +192 -0
  164. package/dist/builtin/web-access/perplexity.ts +196 -0
  165. package/dist/builtin/web-access/rsc-extract.ts +338 -0
  166. package/dist/builtin/web-access/storage.ts +72 -0
  167. package/dist/builtin/web-access/summary-review.ts +276 -0
  168. package/dist/builtin/web-access/utils.ts +44 -0
  169. package/dist/builtin/web-access/video-extract.ts +379 -0
  170. package/dist/builtin/web-access/youtube-extract.ts +311 -0
  171. package/dist/builtin/workflows/CHANGELOG.md +20 -0
  172. package/dist/builtin/workflows/README.md +323 -0
  173. package/dist/builtin/workflows/builtin/deep-research-codebase.ts +567 -0
  174. package/dist/builtin/workflows/builtin/index.ts +10 -0
  175. package/dist/builtin/workflows/builtin/open-claude-design.ts +985 -0
  176. package/dist/builtin/workflows/builtin/ralph.ts +613 -0
  177. package/dist/builtin/workflows/package.json +89 -0
  178. package/dist/builtin/workflows/skills/create-spec/SKILL.md +247 -0
  179. package/dist/builtin/workflows/skills/impeccable/SKILL.md +173 -0
  180. package/dist/builtin/workflows/skills/impeccable/reference/adapt.md +190 -0
  181. package/dist/builtin/workflows/skills/impeccable/reference/animate.md +175 -0
  182. package/dist/builtin/workflows/skills/impeccable/reference/audit.md +133 -0
  183. package/dist/builtin/workflows/skills/impeccable/reference/bolder.md +113 -0
  184. package/dist/builtin/workflows/skills/impeccable/reference/brand.md +118 -0
  185. package/dist/builtin/workflows/skills/impeccable/reference/clarify.md +174 -0
  186. package/dist/builtin/workflows/skills/impeccable/reference/codex.md +105 -0
  187. package/dist/builtin/workflows/skills/impeccable/reference/cognitive-load.md +106 -0
  188. package/dist/builtin/workflows/skills/impeccable/reference/color-and-contrast.md +105 -0
  189. package/dist/builtin/workflows/skills/impeccable/reference/colorize.md +154 -0
  190. package/dist/builtin/workflows/skills/impeccable/reference/craft.md +123 -0
  191. package/dist/builtin/workflows/skills/impeccable/reference/critique.md +261 -0
  192. package/dist/builtin/workflows/skills/impeccable/reference/delight.md +302 -0
  193. package/dist/builtin/workflows/skills/impeccable/reference/distill.md +111 -0
  194. package/dist/builtin/workflows/skills/impeccable/reference/document.md +427 -0
  195. package/dist/builtin/workflows/skills/impeccable/reference/extract.md +69 -0
  196. package/dist/builtin/workflows/skills/impeccable/reference/harden.md +347 -0
  197. package/dist/builtin/workflows/skills/impeccable/reference/heuristics-scoring.md +234 -0
  198. package/dist/builtin/workflows/skills/impeccable/reference/interaction-design.md +195 -0
  199. package/dist/builtin/workflows/skills/impeccable/reference/layout.md +141 -0
  200. package/dist/builtin/workflows/skills/impeccable/reference/live.md +622 -0
  201. package/dist/builtin/workflows/skills/impeccable/reference/motion-design.md +109 -0
  202. package/dist/builtin/workflows/skills/impeccable/reference/onboard.md +234 -0
  203. package/dist/builtin/workflows/skills/impeccable/reference/optimize.md +258 -0
  204. package/dist/builtin/workflows/skills/impeccable/reference/overdrive.md +130 -0
  205. package/dist/builtin/workflows/skills/impeccable/reference/personas.md +179 -0
  206. package/dist/builtin/workflows/skills/impeccable/reference/polish.md +242 -0
  207. package/dist/builtin/workflows/skills/impeccable/reference/product.md +62 -0
  208. package/dist/builtin/workflows/skills/impeccable/reference/quieter.md +99 -0
  209. package/dist/builtin/workflows/skills/impeccable/reference/responsive-design.md +114 -0
  210. package/dist/builtin/workflows/skills/impeccable/reference/shape.md +165 -0
  211. package/dist/builtin/workflows/skills/impeccable/reference/spatial-design.md +100 -0
  212. package/dist/builtin/workflows/skills/impeccable/reference/teach.md +156 -0
  213. package/dist/builtin/workflows/skills/impeccable/reference/typeset.md +124 -0
  214. package/dist/builtin/workflows/skills/impeccable/reference/typography.md +159 -0
  215. package/dist/builtin/workflows/skills/impeccable/reference/ux-writing.md +107 -0
  216. package/dist/builtin/workflows/skills/impeccable/scripts/cleanup-deprecated.mjs +284 -0
  217. package/dist/builtin/workflows/skills/impeccable/scripts/command-metadata.json +94 -0
  218. package/dist/builtin/workflows/skills/impeccable/scripts/critique-storage.mjs +226 -0
  219. package/dist/builtin/workflows/skills/impeccable/scripts/design-parser.mjs +820 -0
  220. package/dist/builtin/workflows/skills/impeccable/scripts/detect-csp.mjs +198 -0
  221. package/dist/builtin/workflows/skills/impeccable/scripts/impeccable-paths.mjs +110 -0
  222. package/dist/builtin/workflows/skills/impeccable/scripts/is-generated.mjs +69 -0
  223. package/dist/builtin/workflows/skills/impeccable/scripts/live-accept.mjs +646 -0
  224. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser-session.js +123 -0
  225. package/dist/builtin/workflows/skills/impeccable/scripts/live-browser.js +4865 -0
  226. package/dist/builtin/workflows/skills/impeccable/scripts/live-complete.mjs +75 -0
  227. package/dist/builtin/workflows/skills/impeccable/scripts/live-completion.mjs +18 -0
  228. package/dist/builtin/workflows/skills/impeccable/scripts/live-inject.mjs +446 -0
  229. package/dist/builtin/workflows/skills/impeccable/scripts/live-poll.mjs +200 -0
  230. package/dist/builtin/workflows/skills/impeccable/scripts/live-resume.mjs +48 -0
  231. package/dist/builtin/workflows/skills/impeccable/scripts/live-server.mjs +847 -0
  232. package/dist/builtin/workflows/skills/impeccable/scripts/live-session-store.mjs +254 -0
  233. package/dist/builtin/workflows/skills/impeccable/scripts/live-status.mjs +47 -0
  234. package/dist/builtin/workflows/skills/impeccable/scripts/live-wrap.mjs +632 -0
  235. package/dist/builtin/workflows/skills/impeccable/scripts/live.mjs +247 -0
  236. package/dist/builtin/workflows/skills/impeccable/scripts/load-context.mjs +141 -0
  237. package/dist/builtin/workflows/skills/impeccable/scripts/modern-screenshot.umd.js +14 -0
  238. package/dist/builtin/workflows/skills/impeccable/scripts/pin.mjs +214 -0
  239. package/dist/builtin/workflows/skills/playwright-cli/SKILL.md +392 -0
  240. package/dist/builtin/workflows/skills/playwright-cli/references/element-attributes.md +23 -0
  241. package/dist/builtin/workflows/skills/playwright-cli/references/playwright-tests.md +39 -0
  242. package/dist/builtin/workflows/skills/playwright-cli/references/request-mocking.md +87 -0
  243. package/dist/builtin/workflows/skills/playwright-cli/references/running-code.md +241 -0
  244. package/dist/builtin/workflows/skills/playwright-cli/references/session-management.md +225 -0
  245. package/dist/builtin/workflows/skills/playwright-cli/references/spec-driven-testing.md +305 -0
  246. package/dist/builtin/workflows/skills/playwright-cli/references/storage-state.md +275 -0
  247. package/dist/builtin/workflows/skills/playwright-cli/references/test-generation.md +134 -0
  248. package/dist/builtin/workflows/skills/playwright-cli/references/tracing.md +139 -0
  249. package/dist/builtin/workflows/skills/playwright-cli/references/video-recording.md +143 -0
  250. package/dist/builtin/workflows/skills/prompt-engineer/SKILL.md +263 -0
  251. package/dist/builtin/workflows/skills/prompt-engineer/references/advanced_patterns.md +271 -0
  252. package/dist/builtin/workflows/skills/prompt-engineer/references/core_prompting.md +137 -0
  253. package/dist/builtin/workflows/skills/prompt-engineer/references/quality_improvement.md +193 -0
  254. package/dist/builtin/workflows/skills/research-codebase/SKILL.md +226 -0
  255. package/dist/builtin/workflows/skills/tdd/SKILL.md +109 -0
  256. package/dist/builtin/workflows/skills/tdd/deep-modules.md +33 -0
  257. package/dist/builtin/workflows/skills/tdd/interface-design.md +31 -0
  258. package/dist/builtin/workflows/skills/tdd/mocking.md +59 -0
  259. package/dist/builtin/workflows/skills/tdd/refactoring.md +10 -0
  260. package/dist/builtin/workflows/skills/tdd/tests.md +61 -0
  261. package/dist/builtin/workflows/skills/workflow/SKILL.md +255 -0
  262. package/dist/builtin/workflows/skills/workflow/references/context-engineering/advanced-evaluation.md +404 -0
  263. package/dist/builtin/workflows/skills/workflow/references/context-engineering/bdi-mental-states.md +313 -0
  264. package/dist/builtin/workflows/skills/workflow/references/context-engineering/context-compression.md +274 -0
  265. package/dist/builtin/workflows/skills/workflow/references/context-engineering/context-degradation.md +208 -0
  266. package/dist/builtin/workflows/skills/workflow/references/context-engineering/context-fundamentals.md +203 -0
  267. package/dist/builtin/workflows/skills/workflow/references/context-engineering/context-optimization.md +197 -0
  268. package/dist/builtin/workflows/skills/workflow/references/context-engineering/evaluation.md +253 -0
  269. package/dist/builtin/workflows/skills/workflow/references/context-engineering/filesystem-context.md +289 -0
  270. package/dist/builtin/workflows/skills/workflow/references/context-engineering/hosted-agents.md +262 -0
  271. package/dist/builtin/workflows/skills/workflow/references/context-engineering/memory-systems.md +221 -0
  272. package/dist/builtin/workflows/skills/workflow/references/context-engineering/multi-agent-patterns.md +259 -0
  273. package/dist/builtin/workflows/skills/workflow/references/context-engineering/project-development.md +293 -0
  274. package/dist/builtin/workflows/skills/workflow/references/context-engineering/tool-design.md +273 -0
  275. package/dist/builtin/workflows/skills/workflow/references/context-engineering.md +23 -0
  276. package/dist/builtin/workflows/skills/workflow/references/design-checklist.md +79 -0
  277. package/dist/builtin/workflows/skills/workflow/references/running-workflows.md +107 -0
  278. package/dist/builtin/workflows/skills/workflow/references/sdk-authoring.md +140 -0
  279. package/dist/builtin/workflows/src/extension/background-ui-adapter.ts +168 -0
  280. package/dist/builtin/workflows/src/extension/companions.ts +210 -0
  281. package/dist/builtin/workflows/src/extension/config-loader.ts +493 -0
  282. package/dist/builtin/workflows/src/extension/discovery.ts +501 -0
  283. package/dist/builtin/workflows/src/extension/dispatcher.ts +173 -0
  284. package/dist/builtin/workflows/src/extension/index.ts +2143 -0
  285. package/dist/builtin/workflows/src/extension/mcp.ts +110 -0
  286. package/dist/builtin/workflows/src/extension/render-call.ts +39 -0
  287. package/dist/builtin/workflows/src/extension/render-result.ts +214 -0
  288. package/dist/builtin/workflows/src/extension/renderers.ts +87 -0
  289. package/dist/builtin/workflows/src/extension/runtime.ts +360 -0
  290. package/dist/builtin/workflows/src/extension/status-writer.ts +167 -0
  291. package/dist/builtin/workflows/src/extension/wiring.ts +555 -0
  292. package/dist/builtin/workflows/src/extension/workflow-schema.ts +102 -0
  293. package/dist/builtin/workflows/src/index.ts +25 -0
  294. package/dist/builtin/workflows/src/intercom/intercom-bridge.ts +93 -0
  295. package/dist/builtin/workflows/src/intercom/intercom-routing.ts +125 -0
  296. package/dist/builtin/workflows/src/intercom/result-intercom.ts +240 -0
  297. package/dist/builtin/workflows/src/runs/background/cancellation-registry.ts +113 -0
  298. package/dist/builtin/workflows/src/runs/background/job-tracker.ts +81 -0
  299. package/dist/builtin/workflows/src/runs/background/runner.ts +152 -0
  300. package/dist/builtin/workflows/src/runs/background/status.ts +354 -0
  301. package/dist/builtin/workflows/src/runs/foreground/executor.ts +1522 -0
  302. package/dist/builtin/workflows/src/runs/foreground/stage-control-registry.ts +233 -0
  303. package/dist/builtin/workflows/src/runs/foreground/stage-runner.ts +712 -0
  304. package/dist/builtin/workflows/src/runs/shared/concurrency.ts +76 -0
  305. package/dist/builtin/workflows/src/runs/shared/graph-inference.ts +69 -0
  306. package/dist/builtin/workflows/src/runs/shared/model-fallback.ts +293 -0
  307. package/dist/builtin/workflows/src/runs/shared/validate-inputs.ts +83 -0
  308. package/dist/builtin/workflows/src/runs/shared/workflow-runner.ts +170 -0
  309. package/dist/builtin/workflows/src/runs/shared/worktree.ts +577 -0
  310. package/dist/builtin/workflows/src/shared/persistence-compaction-policy.ts +72 -0
  311. package/dist/builtin/workflows/src/shared/persistence-restore.ts +257 -0
  312. package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +145 -0
  313. package/dist/builtin/workflows/src/shared/render-inputs-schema.ts +196 -0
  314. package/dist/builtin/workflows/src/shared/store-types.ts +160 -0
  315. package/dist/builtin/workflows/src/shared/store.ts +579 -0
  316. package/dist/builtin/workflows/src/shared/types.ts +566 -0
  317. package/dist/builtin/workflows/src/tui/chat-surface-message.ts +224 -0
  318. package/dist/builtin/workflows/src/tui/chat-surface.ts +511 -0
  319. package/dist/builtin/workflows/src/tui/color-utils.ts +64 -0
  320. package/dist/builtin/workflows/src/tui/connectors.ts +88 -0
  321. package/dist/builtin/workflows/src/tui/dispatch-confirm.ts +307 -0
  322. package/dist/builtin/workflows/src/tui/edge.ts +24 -0
  323. package/dist/builtin/workflows/src/tui/graph-canvas.ts +108 -0
  324. package/dist/builtin/workflows/src/tui/graph-theme.ts +283 -0
  325. package/dist/builtin/workflows/src/tui/graph-view.ts +1217 -0
  326. package/dist/builtin/workflows/src/tui/header.ts +172 -0
  327. package/dist/builtin/workflows/src/tui/inline-form-card.ts +421 -0
  328. package/dist/builtin/workflows/src/tui/inline-form-editor.ts +638 -0
  329. package/dist/builtin/workflows/src/tui/inline-form-overlay.ts +326 -0
  330. package/dist/builtin/workflows/src/tui/inline-form-store.ts +78 -0
  331. package/dist/builtin/workflows/src/tui/inputs-overlay.ts +163 -0
  332. package/dist/builtin/workflows/src/tui/inputs-picker.ts +888 -0
  333. package/dist/builtin/workflows/src/tui/keybindings-adapter.ts +154 -0
  334. package/dist/builtin/workflows/src/tui/layout.ts +153 -0
  335. package/dist/builtin/workflows/src/tui/node-card.ts +274 -0
  336. package/dist/builtin/workflows/src/tui/overlay-adapter.ts +277 -0
  337. package/dist/builtin/workflows/src/tui/prompt-card.ts +501 -0
  338. package/dist/builtin/workflows/src/tui/renderers.ts +15 -0
  339. package/dist/builtin/workflows/src/tui/run-detail.ts +339 -0
  340. package/dist/builtin/workflows/src/tui/session-confirm.ts +202 -0
  341. package/dist/builtin/workflows/src/tui/session-list.ts +32 -0
  342. package/dist/builtin/workflows/src/tui/session-overlays.ts +239 -0
  343. package/dist/builtin/workflows/src/tui/session-picker.ts +399 -0
  344. package/dist/builtin/workflows/src/tui/stage-chat-view.ts +1873 -0
  345. package/dist/builtin/workflows/src/tui/status-helpers.ts +73 -0
  346. package/dist/builtin/workflows/src/tui/status-list.ts +361 -0
  347. package/dist/builtin/workflows/src/tui/store-widget-installer.ts +206 -0
  348. package/dist/builtin/workflows/src/tui/switcher.ts +121 -0
  349. package/dist/builtin/workflows/src/tui/text-helpers.ts +31 -0
  350. package/dist/builtin/workflows/src/tui/toast.ts +106 -0
  351. package/dist/builtin/workflows/src/tui/widget.ts +348 -0
  352. package/dist/builtin/workflows/src/tui/workflow-attach-pane.ts +285 -0
  353. package/dist/builtin/workflows/src/tui/workflow-list.ts +224 -0
  354. package/dist/builtin/workflows/src/workflows/define-workflow.ts +150 -0
  355. package/dist/builtin/workflows/src/workflows/identity.ts +39 -0
  356. package/dist/builtin/workflows/src/workflows/registry.ts +113 -0
  357. package/dist/bun/cli.d.ts +3 -0
  358. package/dist/bun/cli.d.ts.map +1 -0
  359. package/dist/bun/cli.js +9 -0
  360. package/dist/bun/cli.js.map +1 -0
  361. package/dist/bun/register-bedrock.d.ts +2 -0
  362. package/dist/bun/register-bedrock.d.ts.map +1 -0
  363. package/dist/bun/register-bedrock.js +4 -0
  364. package/dist/bun/register-bedrock.js.map +1 -0
  365. package/dist/bun/restore-sandbox-env.d.ts +13 -0
  366. package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
  367. package/dist/bun/restore-sandbox-env.js +32 -0
  368. package/dist/bun/restore-sandbox-env.js.map +1 -0
  369. package/dist/cli/args.d.ts +53 -0
  370. package/dist/cli/args.d.ts.map +1 -0
  371. package/dist/cli/args.js +341 -0
  372. package/dist/cli/args.js.map +1 -0
  373. package/dist/cli/config-selector.d.ts +14 -0
  374. package/dist/cli/config-selector.d.ts.map +1 -0
  375. package/dist/cli/config-selector.js +31 -0
  376. package/dist/cli/config-selector.js.map +1 -0
  377. package/dist/cli/file-processor.d.ts +15 -0
  378. package/dist/cli/file-processor.d.ts.map +1 -0
  379. package/dist/cli/file-processor.js +83 -0
  380. package/dist/cli/file-processor.js.map +1 -0
  381. package/dist/cli/initial-message.d.ts +18 -0
  382. package/dist/cli/initial-message.d.ts.map +1 -0
  383. package/dist/cli/initial-message.js +22 -0
  384. package/dist/cli/initial-message.js.map +1 -0
  385. package/dist/cli/list-models.d.ts +9 -0
  386. package/dist/cli/list-models.d.ts.map +1 -0
  387. package/dist/cli/list-models.js +98 -0
  388. package/dist/cli/list-models.js.map +1 -0
  389. package/dist/cli/session-picker.d.ts +9 -0
  390. package/dist/cli/session-picker.d.ts.map +1 -0
  391. package/dist/cli/session-picker.js +35 -0
  392. package/dist/cli/session-picker.js.map +1 -0
  393. package/dist/cli.d.ts +3 -0
  394. package/dist/cli.d.ts.map +1 -0
  395. package/dist/cli.js +20 -0
  396. package/dist/cli.js.map +1 -0
  397. package/dist/config.d.ts +102 -0
  398. package/dist/config.d.ts.map +1 -0
  399. package/dist/config.js +411 -0
  400. package/dist/config.js.map +1 -0
  401. package/dist/core/agent-session-runtime.d.ts +117 -0
  402. package/dist/core/agent-session-runtime.d.ts.map +1 -0
  403. package/dist/core/agent-session-runtime.js +292 -0
  404. package/dist/core/agent-session-runtime.js.map +1 -0
  405. package/dist/core/agent-session-services.d.ts +86 -0
  406. package/dist/core/agent-session-services.d.ts.map +1 -0
  407. package/dist/core/agent-session-services.js +117 -0
  408. package/dist/core/agent-session-services.js.map +1 -0
  409. package/dist/core/agent-session.d.ts +595 -0
  410. package/dist/core/agent-session.d.ts.map +1 -0
  411. package/dist/core/agent-session.js +2518 -0
  412. package/dist/core/agent-session.js.map +1 -0
  413. package/dist/core/auth-guidance.d.ts +5 -0
  414. package/dist/core/auth-guidance.d.ts.map +1 -0
  415. package/dist/core/auth-guidance.js +21 -0
  416. package/dist/core/auth-guidance.js.map +1 -0
  417. package/dist/core/auth-storage.d.ts +141 -0
  418. package/dist/core/auth-storage.d.ts.map +1 -0
  419. package/dist/core/auth-storage.js +437 -0
  420. package/dist/core/auth-storage.js.map +1 -0
  421. package/dist/core/bash-executor.d.ts +32 -0
  422. package/dist/core/bash-executor.d.ts.map +1 -0
  423. package/dist/core/bash-executor.js +111 -0
  424. package/dist/core/bash-executor.js.map +1 -0
  425. package/dist/core/builtin-packages.d.ts +14 -0
  426. package/dist/core/builtin-packages.d.ts.map +1 -0
  427. package/dist/core/builtin-packages.js +113 -0
  428. package/dist/core/builtin-packages.js.map +1 -0
  429. package/dist/core/compaction/branch-summarization.d.ts +88 -0
  430. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  431. package/dist/core/compaction/branch-summarization.js +243 -0
  432. package/dist/core/compaction/branch-summarization.js.map +1 -0
  433. package/dist/core/compaction/compaction.d.ts +121 -0
  434. package/dist/core/compaction/compaction.d.ts.map +1 -0
  435. package/dist/core/compaction/compaction.js +615 -0
  436. package/dist/core/compaction/compaction.js.map +1 -0
  437. package/dist/core/compaction/index.d.ts +7 -0
  438. package/dist/core/compaction/index.d.ts.map +1 -0
  439. package/dist/core/compaction/index.js +7 -0
  440. package/dist/core/compaction/index.js.map +1 -0
  441. package/dist/core/compaction/utils.d.ts +38 -0
  442. package/dist/core/compaction/utils.d.ts.map +1 -0
  443. package/dist/core/compaction/utils.js +153 -0
  444. package/dist/core/compaction/utils.js.map +1 -0
  445. package/dist/core/defaults.d.ts +3 -0
  446. package/dist/core/defaults.d.ts.map +1 -0
  447. package/dist/core/defaults.js +2 -0
  448. package/dist/core/defaults.js.map +1 -0
  449. package/dist/core/diagnostics.d.ts +15 -0
  450. package/dist/core/diagnostics.d.ts.map +1 -0
  451. package/dist/core/diagnostics.js +2 -0
  452. package/dist/core/diagnostics.js.map +1 -0
  453. package/dist/core/event-bus.d.ts +9 -0
  454. package/dist/core/event-bus.d.ts.map +1 -0
  455. package/dist/core/event-bus.js +25 -0
  456. package/dist/core/event-bus.js.map +1 -0
  457. package/dist/core/exec.d.ts +29 -0
  458. package/dist/core/exec.d.ts.map +1 -0
  459. package/dist/core/exec.js +75 -0
  460. package/dist/core/exec.js.map +1 -0
  461. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  462. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  463. package/dist/core/export-html/ansi-to-html.js +249 -0
  464. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  465. package/dist/core/export-html/index.d.ts +37 -0
  466. package/dist/core/export-html/index.d.ts.map +1 -0
  467. package/dist/core/export-html/index.js +224 -0
  468. package/dist/core/export-html/index.js.map +1 -0
  469. package/dist/core/export-html/template.css +1066 -0
  470. package/dist/core/export-html/template.html +55 -0
  471. package/dist/core/export-html/template.js +1834 -0
  472. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  473. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  474. package/dist/core/export-html/tool-renderer.js +108 -0
  475. package/dist/core/export-html/tool-renderer.js.map +1 -0
  476. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  477. package/dist/core/export-html/vendor/marked.min.js +6 -0
  478. package/dist/core/extensions/index.d.ts +12 -0
  479. package/dist/core/extensions/index.d.ts.map +1 -0
  480. package/dist/core/extensions/index.js +9 -0
  481. package/dist/core/extensions/index.js.map +1 -0
  482. package/dist/core/extensions/loader.d.ts +24 -0
  483. package/dist/core/extensions/loader.d.ts.map +1 -0
  484. package/dist/core/extensions/loader.js +501 -0
  485. package/dist/core/extensions/loader.js.map +1 -0
  486. package/dist/core/extensions/runner.d.ts +159 -0
  487. package/dist/core/extensions/runner.d.ts.map +1 -0
  488. package/dist/core/extensions/runner.js +817 -0
  489. package/dist/core/extensions/runner.js.map +1 -0
  490. package/dist/core/extensions/types.d.ts +1173 -0
  491. package/dist/core/extensions/types.d.ts.map +1 -0
  492. package/dist/core/extensions/types.js +45 -0
  493. package/dist/core/extensions/types.js.map +1 -0
  494. package/dist/core/extensions/wrapper.d.ts +20 -0
  495. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  496. package/dist/core/extensions/wrapper.js +22 -0
  497. package/dist/core/extensions/wrapper.js.map +1 -0
  498. package/dist/core/footer-data-provider.d.ts +52 -0
  499. package/dist/core/footer-data-provider.d.ts.map +1 -0
  500. package/dist/core/footer-data-provider.js +309 -0
  501. package/dist/core/footer-data-provider.js.map +1 -0
  502. package/dist/core/index.d.ts +12 -0
  503. package/dist/core/index.d.ts.map +1 -0
  504. package/dist/core/index.js +12 -0
  505. package/dist/core/index.js.map +1 -0
  506. package/dist/core/keybindings.d.ts +353 -0
  507. package/dist/core/keybindings.d.ts.map +1 -0
  508. package/dist/core/keybindings.js +294 -0
  509. package/dist/core/keybindings.js.map +1 -0
  510. package/dist/core/messages.d.ts +77 -0
  511. package/dist/core/messages.d.ts.map +1 -0
  512. package/dist/core/messages.js +123 -0
  513. package/dist/core/messages.js.map +1 -0
  514. package/dist/core/model-registry.d.ts +150 -0
  515. package/dist/core/model-registry.d.ts.map +1 -0
  516. package/dist/core/model-registry.js +726 -0
  517. package/dist/core/model-registry.js.map +1 -0
  518. package/dist/core/model-resolver.d.ts +110 -0
  519. package/dist/core/model-resolver.d.ts.map +1 -0
  520. package/dist/core/model-resolver.js +493 -0
  521. package/dist/core/model-resolver.js.map +1 -0
  522. package/dist/core/output-guard.d.ts +6 -0
  523. package/dist/core/output-guard.d.ts.map +1 -0
  524. package/dist/core/output-guard.js +59 -0
  525. package/dist/core/output-guard.js.map +1 -0
  526. package/dist/core/package-manager.d.ts +198 -0
  527. package/dist/core/package-manager.d.ts.map +1 -0
  528. package/dist/core/package-manager.js +1970 -0
  529. package/dist/core/package-manager.js.map +1 -0
  530. package/dist/core/prompt-templates.d.ts +52 -0
  531. package/dist/core/prompt-templates.d.ts.map +1 -0
  532. package/dist/core/prompt-templates.js +250 -0
  533. package/dist/core/prompt-templates.js.map +1 -0
  534. package/dist/core/provider-display-names.d.ts +2 -0
  535. package/dist/core/provider-display-names.d.ts.map +1 -0
  536. package/dist/core/provider-display-names.js +33 -0
  537. package/dist/core/provider-display-names.js.map +1 -0
  538. package/dist/core/resolve-config-value.d.ts +23 -0
  539. package/dist/core/resolve-config-value.d.ts.map +1 -0
  540. package/dist/core/resolve-config-value.js +126 -0
  541. package/dist/core/resolve-config-value.js.map +1 -0
  542. package/dist/core/resource-loader.d.ts +196 -0
  543. package/dist/core/resource-loader.d.ts.map +1 -0
  544. package/dist/core/resource-loader.js +698 -0
  545. package/dist/core/resource-loader.js.map +1 -0
  546. package/dist/core/sdk.d.ts +107 -0
  547. package/dist/core/sdk.d.ts.map +1 -0
  548. package/dist/core/sdk.js +291 -0
  549. package/dist/core/sdk.js.map +1 -0
  550. package/dist/core/session-cwd.d.ts +19 -0
  551. package/dist/core/session-cwd.d.ts.map +1 -0
  552. package/dist/core/session-cwd.js +37 -0
  553. package/dist/core/session-cwd.js.map +1 -0
  554. package/dist/core/session-manager.d.ts +333 -0
  555. package/dist/core/session-manager.d.ts.map +1 -0
  556. package/dist/core/session-manager.js +1118 -0
  557. package/dist/core/session-manager.js.map +1 -0
  558. package/dist/core/settings-manager.d.ts +261 -0
  559. package/dist/core/settings-manager.d.ts.map +1 -0
  560. package/dist/core/settings-manager.js +773 -0
  561. package/dist/core/settings-manager.js.map +1 -0
  562. package/dist/core/skills.d.ts +60 -0
  563. package/dist/core/skills.d.ts.map +1 -0
  564. package/dist/core/skills.js +404 -0
  565. package/dist/core/skills.js.map +1 -0
  566. package/dist/core/slash-commands.d.ts +14 -0
  567. package/dist/core/slash-commands.d.ts.map +1 -0
  568. package/dist/core/slash-commands.js +25 -0
  569. package/dist/core/slash-commands.js.map +1 -0
  570. package/dist/core/source-info.d.ts +18 -0
  571. package/dist/core/source-info.d.ts.map +1 -0
  572. package/dist/core/source-info.js +19 -0
  573. package/dist/core/source-info.js.map +1 -0
  574. package/dist/core/system-prompt.d.ts +28 -0
  575. package/dist/core/system-prompt.d.ts.map +1 -0
  576. package/dist/core/system-prompt.js +120 -0
  577. package/dist/core/system-prompt.js.map +1 -0
  578. package/dist/core/telemetry.d.ts +3 -0
  579. package/dist/core/telemetry.d.ts.map +1 -0
  580. package/dist/core/telemetry.js +10 -0
  581. package/dist/core/telemetry.js.map +1 -0
  582. package/dist/core/timings.d.ts +8 -0
  583. package/dist/core/timings.d.ts.map +1 -0
  584. package/dist/core/timings.js +32 -0
  585. package/dist/core/timings.js.map +1 -0
  586. package/dist/core/tools/ask-user-question/ask-user-question.d.ts +10 -0
  587. package/dist/core/tools/ask-user-question/ask-user-question.d.ts.map +1 -0
  588. package/dist/core/tools/ask-user-question/ask-user-question.js +82 -0
  589. package/dist/core/tools/ask-user-question/ask-user-question.js.map +1 -0
  590. package/dist/core/tools/ask-user-question/config.d.ts +11 -0
  591. package/dist/core/tools/ask-user-question/config.d.ts.map +1 -0
  592. package/dist/core/tools/ask-user-question/config.js +34 -0
  593. package/dist/core/tools/ask-user-question/config.js.map +1 -0
  594. package/dist/core/tools/ask-user-question/index.d.ts +19 -0
  595. package/dist/core/tools/ask-user-question/index.d.ts.map +1 -0
  596. package/dist/core/tools/ask-user-question/index.js +19 -0
  597. package/dist/core/tools/ask-user-question/index.js.map +1 -0
  598. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts +36 -0
  599. package/dist/core/tools/ask-user-question/state/build-questionnaire.d.ts.map +1 -0
  600. package/dist/core/tools/ask-user-question/state/build-questionnaire.js +213 -0
  601. package/dist/core/tools/ask-user-question/state/build-questionnaire.js.map +1 -0
  602. package/dist/core/tools/ask-user-question/state/key-router.d.ts +53 -0
  603. package/dist/core/tools/ask-user-question/state/key-router.d.ts.map +1 -0
  604. package/dist/core/tools/ask-user-question/state/key-router.js +240 -0
  605. package/dist/core/tools/ask-user-question/state/key-router.js.map +1 -0
  606. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts +61 -0
  607. package/dist/core/tools/ask-user-question/state/questionnaire-session.d.ts.map +1 -0
  608. package/dist/core/tools/ask-user-question/state/questionnaire-session.js +147 -0
  609. package/dist/core/tools/ask-user-question/state/questionnaire-session.js.map +1 -0
  610. package/dist/core/tools/ask-user-question/state/row-intent.d.ts +91 -0
  611. package/dist/core/tools/ask-user-question/state/row-intent.d.ts.map +1 -0
  612. package/dist/core/tools/ask-user-question/state/row-intent.js +91 -0
  613. package/dist/core/tools/ask-user-question/state/row-intent.js.map +1 -0
  614. package/dist/core/tools/ask-user-question/state/selectors/contract.d.ts +21 -0
  615. package/dist/core/tools/ask-user-question/state/selectors/contract.d.ts.map +1 -0
  616. package/dist/core/tools/ask-user-question/state/selectors/contract.js +2 -0
  617. package/dist/core/tools/ask-user-question/state/selectors/contract.js.map +1 -0
  618. package/dist/core/tools/ask-user-question/state/selectors/derivations.d.ts +44 -0
  619. package/dist/core/tools/ask-user-question/state/selectors/derivations.d.ts.map +1 -0
  620. package/dist/core/tools/ask-user-question/state/selectors/derivations.js +76 -0
  621. package/dist/core/tools/ask-user-question/state/selectors/derivations.js.map +1 -0
  622. package/dist/core/tools/ask-user-question/state/selectors/focus.d.ts +15 -0
  623. package/dist/core/tools/ask-user-question/state/selectors/focus.d.ts.map +1 -0
  624. package/dist/core/tools/ask-user-question/state/selectors/focus.js +18 -0
  625. package/dist/core/tools/ask-user-question/state/selectors/focus.js.map +1 -0
  626. package/dist/core/tools/ask-user-question/state/selectors/projections.d.ts +16 -0
  627. package/dist/core/tools/ask-user-question/state/selectors/projections.d.ts.map +1 -0
  628. package/dist/core/tools/ask-user-question/state/selectors/projections.js +71 -0
  629. package/dist/core/tools/ask-user-question/state/selectors/projections.js.map +1 -0
  630. package/dist/core/tools/ask-user-question/state/state-reducer.d.ts +44 -0
  631. package/dist/core/tools/ask-user-question/state/state-reducer.d.ts.map +1 -0
  632. package/dist/core/tools/ask-user-question/state/state-reducer.js +239 -0
  633. package/dist/core/tools/ask-user-question/state/state-reducer.js.map +1 -0
  634. package/dist/core/tools/ask-user-question/state/state.d.ts +42 -0
  635. package/dist/core/tools/ask-user-question/state/state.d.ts.map +1 -0
  636. package/dist/core/tools/ask-user-question/state/state.js +2 -0
  637. package/dist/core/tools/ask-user-question/state/state.js.map +1 -0
  638. package/dist/core/tools/ask-user-question/tool/format-answer.d.ts +30 -0
  639. package/dist/core/tools/ask-user-question/tool/format-answer.d.ts.map +1 -0
  640. package/dist/core/tools/ask-user-question/tool/format-answer.js +39 -0
  641. package/dist/core/tools/ask-user-question/tool/format-answer.js.map +1 -0
  642. package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts +29 -0
  643. package/dist/core/tools/ask-user-question/tool/response-envelope.d.ts.map +1 -0
  644. package/dist/core/tools/ask-user-question/tool/response-envelope.js +46 -0
  645. package/dist/core/tools/ask-user-question/tool/response-envelope.js.map +1 -0
  646. package/dist/core/tools/ask-user-question/tool/types.d.ts +113 -0
  647. package/dist/core/tools/ask-user-question/tool/types.d.ts.map +1 -0
  648. package/dist/core/tools/ask-user-question/tool/types.js +81 -0
  649. package/dist/core/tools/ask-user-question/tool/types.js.map +1 -0
  650. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.d.ts +21 -0
  651. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.d.ts.map +1 -0
  652. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.js +49 -0
  653. package/dist/core/tools/ask-user-question/tool/validate-questionnaire.js.map +1 -0
  654. package/dist/core/tools/ask-user-question/view/body-residual-spacer.d.ts +18 -0
  655. package/dist/core/tools/ask-user-question/view/body-residual-spacer.d.ts.map +1 -0
  656. package/dist/core/tools/ask-user-question/view/body-residual-spacer.js +21 -0
  657. package/dist/core/tools/ask-user-question/view/body-residual-spacer.js.map +1 -0
  658. package/dist/core/tools/ask-user-question/view/component-binding.d.ts +23 -0
  659. package/dist/core/tools/ask-user-question/view/component-binding.d.ts.map +1 -0
  660. package/dist/core/tools/ask-user-question/view/component-binding.js +16 -0
  661. package/dist/core/tools/ask-user-question/view/component-binding.js.map +1 -0
  662. package/dist/core/tools/ask-user-question/view/components/chat-row-view.d.ts +40 -0
  663. package/dist/core/tools/ask-user-question/view/components/chat-row-view.d.ts.map +1 -0
  664. package/dist/core/tools/ask-user-question/view/components/chat-row-view.js +31 -0
  665. package/dist/core/tools/ask-user-question/view/components/chat-row-view.js.map +1 -0
  666. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts +35 -0
  667. package/dist/core/tools/ask-user-question/view/components/multi-select-view.d.ts.map +1 -0
  668. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js +91 -0
  669. package/dist/core/tools/ask-user-question/view/components/multi-select-view.js.map +1 -0
  670. package/dist/core/tools/ask-user-question/view/components/option-list-view.d.ts +43 -0
  671. package/dist/core/tools/ask-user-question/view/components/option-list-view.d.ts.map +1 -0
  672. package/dist/core/tools/ask-user-question/view/components/option-list-view.js +37 -0
  673. package/dist/core/tools/ask-user-question/view/components/option-list-view.js.map +1 -0
  674. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.d.ts +36 -0
  675. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.d.ts.map +1 -0
  676. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js +66 -0
  677. package/dist/core/tools/ask-user-question/view/components/preview/markdown-content-cache.js.map +1 -0
  678. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts +46 -0
  679. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.d.ts.map +1 -0
  680. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js +69 -0
  681. package/dist/core/tools/ask-user-question/view/components/preview/preview-block-renderer.js.map +1 -0
  682. package/dist/core/tools/ask-user-question/view/components/preview/preview-box-renderer.d.ts +39 -0
  683. package/dist/core/tools/ask-user-question/view/components/preview/preview-box-renderer.d.ts.map +1 -0
  684. package/dist/core/tools/ask-user-question/view/components/preview/preview-box-renderer.js +76 -0
  685. package/dist/core/tools/ask-user-question/view/components/preview/preview-box-renderer.js.map +1 -0
  686. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.d.ts +116 -0
  687. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.d.ts.map +1 -0
  688. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.js +173 -0
  689. package/dist/core/tools/ask-user-question/view/components/preview/preview-layout-decider.js.map +1 -0
  690. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts +66 -0
  691. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.d.ts.map +1 -0
  692. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js +124 -0
  693. package/dist/core/tools/ask-user-question/view/components/preview/preview-pane.js.map +1 -0
  694. package/dist/core/tools/ask-user-question/view/components/submit-picker.d.ts +37 -0
  695. package/dist/core/tools/ask-user-question/view/components/submit-picker.d.ts.map +1 -0
  696. package/dist/core/tools/ask-user-question/view/components/submit-picker.js +44 -0
  697. package/dist/core/tools/ask-user-question/view/components/submit-picker.js.map +1 -0
  698. package/dist/core/tools/ask-user-question/view/components/tab-bar.d.ts +32 -0
  699. package/dist/core/tools/ask-user-question/view/components/tab-bar.d.ts.map +1 -0
  700. package/dist/core/tools/ask-user-question/view/components/tab-bar.js +33 -0
  701. package/dist/core/tools/ask-user-question/view/components/tab-bar.js.map +1 -0
  702. package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts +122 -0
  703. package/dist/core/tools/ask-user-question/view/components/wrapping-select.d.ts.map +1 -0
  704. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js +161 -0
  705. package/dist/core/tools/ask-user-question/view/components/wrapping-select.js.map +1 -0
  706. package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts +66 -0
  707. package/dist/core/tools/ask-user-question/view/dialog-builder.d.ts.map +1 -0
  708. package/dist/core/tools/ask-user-question/view/dialog-builder.js +85 -0
  709. package/dist/core/tools/ask-user-question/view/dialog-builder.js.map +1 -0
  710. package/dist/core/tools/ask-user-question/view/props-adapter.d.ts +58 -0
  711. package/dist/core/tools/ask-user-question/view/props-adapter.d.ts.map +1 -0
  712. package/dist/core/tools/ask-user-question/view/props-adapter.js +67 -0
  713. package/dist/core/tools/ask-user-question/view/props-adapter.js.map +1 -0
  714. package/dist/core/tools/ask-user-question/view/stateful-view.d.ts +24 -0
  715. package/dist/core/tools/ask-user-question/view/stateful-view.d.ts.map +1 -0
  716. package/dist/core/tools/ask-user-question/view/stateful-view.js +2 -0
  717. package/dist/core/tools/ask-user-question/view/stateful-view.js.map +1 -0
  718. package/dist/core/tools/ask-user-question/view/tab-components.d.ts +15 -0
  719. package/dist/core/tools/ask-user-question/view/tab-components.d.ts.map +1 -0
  720. package/dist/core/tools/ask-user-question/view/tab-components.js +2 -0
  721. package/dist/core/tools/ask-user-question/view/tab-components.js.map +1 -0
  722. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts +71 -0
  723. package/dist/core/tools/ask-user-question/view/tab-content-strategy.d.ts.map +1 -0
  724. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js +129 -0
  725. package/dist/core/tools/ask-user-question/view/tab-content-strategy.js.map +1 -0
  726. package/dist/core/tools/bash.d.ts +68 -0
  727. package/dist/core/tools/bash.d.ts.map +1 -0
  728. package/dist/core/tools/bash.js +338 -0
  729. package/dist/core/tools/bash.js.map +1 -0
  730. package/dist/core/tools/edit-diff.d.ts +85 -0
  731. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  732. package/dist/core/tools/edit-diff.js +338 -0
  733. package/dist/core/tools/edit-diff.js.map +1 -0
  734. package/dist/core/tools/edit.d.ts +49 -0
  735. package/dist/core/tools/edit.d.ts.map +1 -0
  736. package/dist/core/tools/edit.js +324 -0
  737. package/dist/core/tools/edit.js.map +1 -0
  738. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  739. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  740. package/dist/core/tools/file-mutation-queue.js +37 -0
  741. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  742. package/dist/core/tools/find.d.ts +35 -0
  743. package/dist/core/tools/find.d.ts.map +1 -0
  744. package/dist/core/tools/find.js +298 -0
  745. package/dist/core/tools/find.js.map +1 -0
  746. package/dist/core/tools/grep.d.ts +37 -0
  747. package/dist/core/tools/grep.d.ts.map +1 -0
  748. package/dist/core/tools/grep.js +304 -0
  749. package/dist/core/tools/grep.js.map +1 -0
  750. package/dist/core/tools/index.d.ts +42 -0
  751. package/dist/core/tools/index.d.ts.map +1 -0
  752. package/dist/core/tools/index.js +139 -0
  753. package/dist/core/tools/index.js.map +1 -0
  754. package/dist/core/tools/ls.d.ts +37 -0
  755. package/dist/core/tools/ls.d.ts.map +1 -0
  756. package/dist/core/tools/ls.js +169 -0
  757. package/dist/core/tools/ls.js.map +1 -0
  758. package/dist/core/tools/output-accumulator.d.ts +50 -0
  759. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  760. package/dist/core/tools/output-accumulator.js +172 -0
  761. package/dist/core/tools/output-accumulator.js.map +1 -0
  762. package/dist/core/tools/path-utils.d.ts +8 -0
  763. package/dist/core/tools/path-utils.d.ts.map +1 -0
  764. package/dist/core/tools/path-utils.js +81 -0
  765. package/dist/core/tools/path-utils.js.map +1 -0
  766. package/dist/core/tools/read.d.ts +35 -0
  767. package/dist/core/tools/read.d.ts.map +1 -0
  768. package/dist/core/tools/read.js +289 -0
  769. package/dist/core/tools/read.js.map +1 -0
  770. package/dist/core/tools/render-utils.d.ts +21 -0
  771. package/dist/core/tools/render-utils.d.ts.map +1 -0
  772. package/dist/core/tools/render-utils.js +49 -0
  773. package/dist/core/tools/render-utils.js.map +1 -0
  774. package/dist/core/tools/todos.d.ts +35 -0
  775. package/dist/core/tools/todos.d.ts.map +1 -0
  776. package/dist/core/tools/todos.js +906 -0
  777. package/dist/core/tools/todos.js.map +1 -0
  778. package/dist/core/tools/tool-definition-wrapper.d.ts +14 -0
  779. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -0
  780. package/dist/core/tools/tool-definition-wrapper.js +34 -0
  781. package/dist/core/tools/tool-definition-wrapper.js.map +1 -0
  782. package/dist/core/tools/truncate.d.ts +70 -0
  783. package/dist/core/tools/truncate.d.ts.map +1 -0
  784. package/dist/core/tools/truncate.js +205 -0
  785. package/dist/core/tools/truncate.js.map +1 -0
  786. package/dist/core/tools/write.d.ts +26 -0
  787. package/dist/core/tools/write.d.ts.map +1 -0
  788. package/dist/core/tools/write.js +212 -0
  789. package/dist/core/tools/write.js.map +1 -0
  790. package/dist/index.d.ts +28 -0
  791. package/dist/index.d.ts.map +1 -0
  792. package/dist/index.js +41 -0
  793. package/dist/index.js.map +1 -0
  794. package/dist/main.d.ts +13 -0
  795. package/dist/main.d.ts.map +1 -0
  796. package/dist/main.js +586 -0
  797. package/dist/main.js.map +1 -0
  798. package/dist/migrations.d.ts +33 -0
  799. package/dist/migrations.d.ts.map +1 -0
  800. package/dist/migrations.js +281 -0
  801. package/dist/migrations.js.map +1 -0
  802. package/dist/modes/index.d.ts +9 -0
  803. package/dist/modes/index.d.ts.map +1 -0
  804. package/dist/modes/index.js +8 -0
  805. package/dist/modes/index.js.map +1 -0
  806. package/dist/modes/interactive/assets/clankolas.png +3 -0
  807. package/dist/modes/interactive/components/armin.d.ts +34 -0
  808. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  809. package/dist/modes/interactive/components/armin.js +329 -0
  810. package/dist/modes/interactive/components/armin.js.map +1 -0
  811. package/dist/modes/interactive/components/assistant-message.d.ts +20 -0
  812. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  813. package/dist/modes/interactive/components/assistant-message.js +116 -0
  814. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  815. package/dist/modes/interactive/components/bash-execution.d.ts +34 -0
  816. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  817. package/dist/modes/interactive/components/bash-execution.js +170 -0
  818. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  819. package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  820. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  821. package/dist/modes/interactive/components/bordered-loader.js +51 -0
  822. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  823. package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  824. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  825. package/dist/modes/interactive/components/branch-summary-message.js +42 -0
  826. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  827. package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  828. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  829. package/dist/modes/interactive/components/compaction-summary-message.js +43 -0
  830. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  831. package/dist/modes/interactive/components/config-selector.d.ts +71 -0
  832. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  833. package/dist/modes/interactive/components/config-selector.js +496 -0
  834. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  835. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  836. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  837. package/dist/modes/interactive/components/countdown-timer.js +28 -0
  838. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  839. package/dist/modes/interactive/components/custom-editor.d.ts +29 -0
  840. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  841. package/dist/modes/interactive/components/custom-editor.js +113 -0
  842. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  843. package/dist/modes/interactive/components/custom-message.d.ts +20 -0
  844. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  845. package/dist/modes/interactive/components/custom-message.js +74 -0
  846. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  847. package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  848. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
  849. package/dist/modes/interactive/components/daxnuts.js +138 -0
  850. package/dist/modes/interactive/components/daxnuts.js.map +1 -0
  851. package/dist/modes/interactive/components/diff.d.ts +12 -0
  852. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  853. package/dist/modes/interactive/components/diff.js +151 -0
  854. package/dist/modes/interactive/components/diff.js.map +1 -0
  855. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  856. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  857. package/dist/modes/interactive/components/dynamic-border.js +20 -0
  858. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  859. package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
  860. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
  861. package/dist/modes/interactive/components/earendil-announcement.js +40 -0
  862. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
  863. package/dist/modes/interactive/components/extension-editor.d.ts +20 -0
  864. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  865. package/dist/modes/interactive/components/extension-editor.js +106 -0
  866. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  867. package/dist/modes/interactive/components/extension-input.d.ts +23 -0
  868. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  869. package/dist/modes/interactive/components/extension-input.js +55 -0
  870. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  871. package/dist/modes/interactive/components/extension-selector.d.ts +26 -0
  872. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  873. package/dist/modes/interactive/components/extension-selector.js +75 -0
  874. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  875. package/dist/modes/interactive/components/footer.d.ts +27 -0
  876. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  877. package/dist/modes/interactive/components/footer.js +199 -0
  878. package/dist/modes/interactive/components/footer.js.map +1 -0
  879. package/dist/modes/interactive/components/index.d.ts +32 -0
  880. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  881. package/dist/modes/interactive/components/index.js +33 -0
  882. package/dist/modes/interactive/components/index.js.map +1 -0
  883. package/dist/modes/interactive/components/keybinding-hints.d.ts +13 -0
  884. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  885. package/dist/modes/interactive/components/keybinding-hints.js +36 -0
  886. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  887. package/dist/modes/interactive/components/login-dialog.d.ts +46 -0
  888. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  889. package/dist/modes/interactive/components/login-dialog.js +158 -0
  890. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  891. package/dist/modes/interactive/components/model-selector.d.ts +47 -0
  892. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  893. package/dist/modes/interactive/components/model-selector.js +266 -0
  894. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  895. package/dist/modes/interactive/components/oauth-selector.d.ts +31 -0
  896. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  897. package/dist/modes/interactive/components/oauth-selector.js +156 -0
  898. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  899. package/dist/modes/interactive/components/scoped-models-selector.d.ts +42 -0
  900. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  901. package/dist/modes/interactive/components/scoped-models-selector.js +286 -0
  902. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  903. package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  904. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  905. package/dist/modes/interactive/components/session-selector-search.js +155 -0
  906. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  907. package/dist/modes/interactive/components/session-selector.d.ts +96 -0
  908. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  909. package/dist/modes/interactive/components/session-selector.js +836 -0
  910. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  911. package/dist/modes/interactive/components/settings-selector.d.ts +67 -0
  912. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  913. package/dist/modes/interactive/components/settings-selector.js +371 -0
  914. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  915. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  916. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  917. package/dist/modes/interactive/components/show-images-selector.js +38 -0
  918. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  919. package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  920. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  921. package/dist/modes/interactive/components/skill-invocation-message.js +45 -0
  922. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  923. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  924. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  925. package/dist/modes/interactive/components/theme-selector.js +48 -0
  926. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  927. package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  928. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  929. package/dist/modes/interactive/components/thinking-selector.js +50 -0
  930. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  931. package/dist/modes/interactive/components/tool-execution.d.ts +63 -0
  932. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  933. package/dist/modes/interactive/components/tool-execution.js +280 -0
  934. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  935. package/dist/modes/interactive/components/tree-selector.d.ts +89 -0
  936. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  937. package/dist/modes/interactive/components/tree-selector.js +1079 -0
  938. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  939. package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  940. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  941. package/dist/modes/interactive/components/user-message-selector.js +111 -0
  942. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  943. package/dist/modes/interactive/components/user-message.d.ts +10 -0
  944. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  945. package/dist/modes/interactive/components/user-message.js +28 -0
  946. package/dist/modes/interactive/components/user-message.js.map +1 -0
  947. package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  948. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  949. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  950. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  951. package/dist/modes/interactive/interactive-mode.d.ts +369 -0
  952. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  953. package/dist/modes/interactive/interactive-mode.js +4709 -0
  954. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  955. package/dist/modes/interactive/theme/catppuccin-frappe.json +90 -0
  956. package/dist/modes/interactive/theme/catppuccin-latte.json +90 -0
  957. package/dist/modes/interactive/theme/catppuccin-macchiato.json +90 -0
  958. package/dist/modes/interactive/theme/catppuccin-mocha.json +90 -0
  959. package/dist/modes/interactive/theme/dark.json +85 -0
  960. package/dist/modes/interactive/theme/light.json +84 -0
  961. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  962. package/dist/modes/interactive/theme/theme.d.ts +81 -0
  963. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  964. package/dist/modes/interactive/theme/theme.js +970 -0
  965. package/dist/modes/interactive/theme/theme.js.map +1 -0
  966. package/dist/modes/interactive/whimsical-messages.d.ts +5 -0
  967. package/dist/modes/interactive/whimsical-messages.d.ts.map +1 -0
  968. package/dist/modes/interactive/whimsical-messages.js +464 -0
  969. package/dist/modes/interactive/whimsical-messages.js.map +1 -0
  970. package/dist/modes/print-mode.d.ts +28 -0
  971. package/dist/modes/print-mode.d.ts.map +1 -0
  972. package/dist/modes/print-mode.js +131 -0
  973. package/dist/modes/print-mode.js.map +1 -0
  974. package/dist/modes/rpc/jsonl.d.ts +17 -0
  975. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  976. package/dist/modes/rpc/jsonl.js +49 -0
  977. package/dist/modes/rpc/jsonl.js.map +1 -0
  978. package/dist/modes/rpc/rpc-client.d.ts +224 -0
  979. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  980. package/dist/modes/rpc/rpc-client.js +409 -0
  981. package/dist/modes/rpc/rpc-client.js.map +1 -0
  982. package/dist/modes/rpc/rpc-mode.d.ts +20 -0
  983. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  984. package/dist/modes/rpc/rpc-mode.js +601 -0
  985. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  986. package/dist/modes/rpc/rpc-types.d.ts +419 -0
  987. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  988. package/dist/modes/rpc/rpc-types.js +8 -0
  989. package/dist/modes/rpc/rpc-types.js.map +1 -0
  990. package/dist/package-manager-cli.d.ts +4 -0
  991. package/dist/package-manager-cli.d.ts.map +1 -0
  992. package/dist/package-manager-cli.js +460 -0
  993. package/dist/package-manager-cli.js.map +1 -0
  994. package/dist/utils/ansi.d.ts +2 -0
  995. package/dist/utils/ansi.d.ts.map +1 -0
  996. package/dist/utils/ansi.js +52 -0
  997. package/dist/utils/ansi.js.map +1 -0
  998. package/dist/utils/changelog.d.ts +21 -0
  999. package/dist/utils/changelog.d.ts.map +1 -0
  1000. package/dist/utils/changelog.js +87 -0
  1001. package/dist/utils/changelog.js.map +1 -0
  1002. package/dist/utils/child-process.d.ts +12 -0
  1003. package/dist/utils/child-process.d.ts.map +1 -0
  1004. package/dist/utils/child-process.js +86 -0
  1005. package/dist/utils/child-process.js.map +1 -0
  1006. package/dist/utils/clipboard-image.d.ts +11 -0
  1007. package/dist/utils/clipboard-image.d.ts.map +1 -0
  1008. package/dist/utils/clipboard-image.js +245 -0
  1009. package/dist/utils/clipboard-image.js.map +1 -0
  1010. package/dist/utils/clipboard-native.d.ts +8 -0
  1011. package/dist/utils/clipboard-native.d.ts.map +1 -0
  1012. package/dist/utils/clipboard-native.js +14 -0
  1013. package/dist/utils/clipboard-native.js.map +1 -0
  1014. package/dist/utils/clipboard.d.ts +2 -0
  1015. package/dist/utils/clipboard.d.ts.map +1 -0
  1016. package/dist/utils/clipboard.js +117 -0
  1017. package/dist/utils/clipboard.js.map +1 -0
  1018. package/dist/utils/exif-orientation.d.ts +5 -0
  1019. package/dist/utils/exif-orientation.d.ts.map +1 -0
  1020. package/dist/utils/exif-orientation.js +158 -0
  1021. package/dist/utils/exif-orientation.js.map +1 -0
  1022. package/dist/utils/frontmatter.d.ts +8 -0
  1023. package/dist/utils/frontmatter.d.ts.map +1 -0
  1024. package/dist/utils/frontmatter.js +26 -0
  1025. package/dist/utils/frontmatter.js.map +1 -0
  1026. package/dist/utils/fs-watch.d.ts +5 -0
  1027. package/dist/utils/fs-watch.d.ts.map +1 -0
  1028. package/dist/utils/fs-watch.js +25 -0
  1029. package/dist/utils/fs-watch.js.map +1 -0
  1030. package/dist/utils/git.d.ts +26 -0
  1031. package/dist/utils/git.d.ts.map +1 -0
  1032. package/dist/utils/git.js +163 -0
  1033. package/dist/utils/git.js.map +1 -0
  1034. package/dist/utils/html.d.ts +7 -0
  1035. package/dist/utils/html.d.ts.map +1 -0
  1036. package/dist/utils/html.js +40 -0
  1037. package/dist/utils/html.js.map +1 -0
  1038. package/dist/utils/image-convert.d.ts +9 -0
  1039. package/dist/utils/image-convert.d.ts.map +1 -0
  1040. package/dist/utils/image-convert.js +39 -0
  1041. package/dist/utils/image-convert.js.map +1 -0
  1042. package/dist/utils/image-resize.d.ts +36 -0
  1043. package/dist/utils/image-resize.d.ts.map +1 -0
  1044. package/dist/utils/image-resize.js +137 -0
  1045. package/dist/utils/image-resize.js.map +1 -0
  1046. package/dist/utils/mime.d.ts +3 -0
  1047. package/dist/utils/mime.d.ts.map +1 -0
  1048. package/dist/utils/mime.js +69 -0
  1049. package/dist/utils/mime.js.map +1 -0
  1050. package/dist/utils/paths.d.ts +16 -0
  1051. package/dist/utils/paths.d.ts.map +1 -0
  1052. package/dist/utils/paths.js +50 -0
  1053. package/dist/utils/paths.js.map +1 -0
  1054. package/dist/utils/photon.d.ts +21 -0
  1055. package/dist/utils/photon.d.ts.map +1 -0
  1056. package/dist/utils/photon.js +121 -0
  1057. package/dist/utils/photon.js.map +1 -0
  1058. package/dist/utils/pi-user-agent.d.ts +2 -0
  1059. package/dist/utils/pi-user-agent.d.ts.map +1 -0
  1060. package/dist/utils/pi-user-agent.js +5 -0
  1061. package/dist/utils/pi-user-agent.js.map +1 -0
  1062. package/dist/utils/shell.d.ts +30 -0
  1063. package/dist/utils/shell.d.ts.map +1 -0
  1064. package/dist/utils/shell.js +190 -0
  1065. package/dist/utils/shell.js.map +1 -0
  1066. package/dist/utils/sleep.d.ts +5 -0
  1067. package/dist/utils/sleep.d.ts.map +1 -0
  1068. package/dist/utils/sleep.js +17 -0
  1069. package/dist/utils/sleep.js.map +1 -0
  1070. package/dist/utils/syntax-highlight.d.ts +12 -0
  1071. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  1072. package/dist/utils/syntax-highlight.js +118 -0
  1073. package/dist/utils/syntax-highlight.js.map +1 -0
  1074. package/dist/utils/tools-manager.d.ts +3 -0
  1075. package/dist/utils/tools-manager.d.ts.map +1 -0
  1076. package/dist/utils/tools-manager.js +325 -0
  1077. package/dist/utils/tools-manager.js.map +1 -0
  1078. package/dist/utils/version-check.d.ts +14 -0
  1079. package/dist/utils/version-check.d.ts.map +1 -0
  1080. package/dist/utils/version-check.js +76 -0
  1081. package/dist/utils/version-check.js.map +1 -0
  1082. package/docs/compaction.md +394 -0
  1083. package/docs/custom-provider.md +646 -0
  1084. package/docs/development.md +71 -0
  1085. package/docs/docs.json +148 -0
  1086. package/docs/extensions.md +2596 -0
  1087. package/docs/images/doom-extension.png +0 -0
  1088. package/docs/images/exy.png +3 -0
  1089. package/docs/images/interactive-mode.png +0 -0
  1090. package/docs/images/tree-view.png +0 -0
  1091. package/docs/index.md +70 -0
  1092. package/docs/json.md +82 -0
  1093. package/docs/keybindings.md +197 -0
  1094. package/docs/models.md +474 -0
  1095. package/docs/packages.md +223 -0
  1096. package/docs/prompt-templates.md +88 -0
  1097. package/docs/providers.md +243 -0
  1098. package/docs/quickstart.md +142 -0
  1099. package/docs/rpc.md +1407 -0
  1100. package/docs/sdk.md +1129 -0
  1101. package/docs/session-format.md +412 -0
  1102. package/docs/sessions.md +137 -0
  1103. package/docs/settings.md +279 -0
  1104. package/docs/shell-aliases.md +13 -0
  1105. package/docs/skills.md +232 -0
  1106. package/docs/terminal-setup.md +106 -0
  1107. package/docs/termux.md +127 -0
  1108. package/docs/themes.md +299 -0
  1109. package/docs/tmux.md +61 -0
  1110. package/docs/tui.md +918 -0
  1111. package/docs/usage.md +277 -0
  1112. package/docs/windows.md +17 -0
  1113. package/examples/README.md +25 -0
  1114. package/examples/extensions/README.md +208 -0
  1115. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  1116. package/examples/extensions/bash-spawn-hook.ts +30 -0
  1117. package/examples/extensions/bookmark.ts +50 -0
  1118. package/examples/extensions/border-status-editor.ts +150 -0
  1119. package/examples/extensions/built-in-tool-renderer.ts +249 -0
  1120. package/examples/extensions/claude-rules.ts +86 -0
  1121. package/examples/extensions/commands.ts +72 -0
  1122. package/examples/extensions/confirm-destructive.ts +59 -0
  1123. package/examples/extensions/custom-compaction.ts +127 -0
  1124. package/examples/extensions/custom-footer.ts +64 -0
  1125. package/examples/extensions/custom-header.ts +73 -0
  1126. package/examples/extensions/custom-provider-anthropic/index.ts +604 -0
  1127. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  1128. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  1129. package/examples/extensions/custom-provider-gitlab-duo/index.ts +349 -0
  1130. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  1131. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  1132. package/examples/extensions/dirty-repo-guard.ts +56 -0
  1133. package/examples/extensions/doom-overlay/README.md +46 -0
  1134. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  1135. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  1136. package/examples/extensions/doom-overlay/doom-component.ts +132 -0
  1137. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  1138. package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
  1139. package/examples/extensions/doom-overlay/index.ts +74 -0
  1140. package/examples/extensions/doom-overlay/wad-finder.ts +51 -0
  1141. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  1142. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  1143. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  1144. package/examples/extensions/dynamic-resources/index.ts +15 -0
  1145. package/examples/extensions/dynamic-tools.ts +74 -0
  1146. package/examples/extensions/event-bus.ts +43 -0
  1147. package/examples/extensions/file-trigger.ts +41 -0
  1148. package/examples/extensions/git-checkpoint.ts +53 -0
  1149. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  1150. package/examples/extensions/handoff.ts +191 -0
  1151. package/examples/extensions/hello.ts +26 -0
  1152. package/examples/extensions/hidden-thinking-label.ts +53 -0
  1153. package/examples/extensions/inline-bash.ts +94 -0
  1154. package/examples/extensions/input-transform.ts +43 -0
  1155. package/examples/extensions/interactive-shell.ts +196 -0
  1156. package/examples/extensions/mac-system-theme.ts +47 -0
  1157. package/examples/extensions/message-renderer.ts +59 -0
  1158. package/examples/extensions/minimal-mode.ts +426 -0
  1159. package/examples/extensions/modal-editor.ts +85 -0
  1160. package/examples/extensions/model-status.ts +31 -0
  1161. package/examples/extensions/notify.ts +55 -0
  1162. package/examples/extensions/overlay-qa-tests.ts +1348 -0
  1163. package/examples/extensions/overlay-test.ts +150 -0
  1164. package/examples/extensions/permission-gate.ts +34 -0
  1165. package/examples/extensions/pirate.ts +47 -0
  1166. package/examples/extensions/plan-mode/README.md +65 -0
  1167. package/examples/extensions/plan-mode/index.ts +340 -0
  1168. package/examples/extensions/plan-mode/utils.ts +168 -0
  1169. package/examples/extensions/preset.ts +430 -0
  1170. package/examples/extensions/prompt-customizer.ts +97 -0
  1171. package/examples/extensions/protected-paths.ts +30 -0
  1172. package/examples/extensions/provider-payload.ts +18 -0
  1173. package/examples/extensions/qna.ts +122 -0
  1174. package/examples/extensions/question.ts +264 -0
  1175. package/examples/extensions/questionnaire.ts +427 -0
  1176. package/examples/extensions/rainbow-editor.ts +88 -0
  1177. package/examples/extensions/reload-runtime.ts +37 -0
  1178. package/examples/extensions/rpc-demo.ts +118 -0
  1179. package/examples/extensions/sandbox/index.ts +321 -0
  1180. package/examples/extensions/sandbox/package-lock.json +92 -0
  1181. package/examples/extensions/sandbox/package.json +19 -0
  1182. package/examples/extensions/send-user-message.ts +97 -0
  1183. package/examples/extensions/session-name.ts +27 -0
  1184. package/examples/extensions/shutdown-command.ts +63 -0
  1185. package/examples/extensions/snake.ts +343 -0
  1186. package/examples/extensions/space-invaders.ts +560 -0
  1187. package/examples/extensions/ssh.ts +220 -0
  1188. package/examples/extensions/status-line.ts +32 -0
  1189. package/examples/extensions/structured-output.ts +65 -0
  1190. package/examples/extensions/subagent/README.md +172 -0
  1191. package/examples/extensions/subagent/agents/planner.md +37 -0
  1192. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  1193. package/examples/extensions/subagent/agents/scout.md +50 -0
  1194. package/examples/extensions/subagent/agents/worker.md +24 -0
  1195. package/examples/extensions/subagent/agents.ts +126 -0
  1196. package/examples/extensions/subagent/index.ts +987 -0
  1197. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  1198. package/examples/extensions/subagent/prompts/implement.md +10 -0
  1199. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  1200. package/examples/extensions/summarize.ts +206 -0
  1201. package/examples/extensions/system-prompt-header.ts +17 -0
  1202. package/examples/extensions/tic-tac-toe.ts +1008 -0
  1203. package/examples/extensions/timed-confirm.ts +70 -0
  1204. package/examples/extensions/titlebar-spinner.ts +58 -0
  1205. package/examples/extensions/todo.ts +297 -0
  1206. package/examples/extensions/tool-override.ts +144 -0
  1207. package/examples/extensions/tools.ts +141 -0
  1208. package/examples/extensions/trigger-compact.ts +50 -0
  1209. package/examples/extensions/truncated-tool.ts +195 -0
  1210. package/examples/extensions/widget-placement.ts +9 -0
  1211. package/examples/extensions/with-deps/index.ts +32 -0
  1212. package/examples/extensions/with-deps/package-lock.json +31 -0
  1213. package/examples/extensions/with-deps/package.json +22 -0
  1214. package/examples/extensions/working-indicator.ts +123 -0
  1215. package/examples/extensions/working-message-test.ts +25 -0
  1216. package/examples/rpc-extension-ui.ts +632 -0
  1217. package/examples/sdk/01-minimal.ts +26 -0
  1218. package/examples/sdk/02-custom-model.ts +53 -0
  1219. package/examples/sdk/03-custom-prompt.ts +75 -0
  1220. package/examples/sdk/04-skills.ts +55 -0
  1221. package/examples/sdk/05-tools.ts +48 -0
  1222. package/examples/sdk/06-extensions.ts +99 -0
  1223. package/examples/sdk/07-context-files.ts +47 -0
  1224. package/examples/sdk/08-prompt-templates.ts +51 -0
  1225. package/examples/sdk/09-api-keys-and-oauth.ts +52 -0
  1226. package/examples/sdk/10-settings.ts +53 -0
  1227. package/examples/sdk/11-sessions.ts +52 -0
  1228. package/examples/sdk/12-full-control.ts +77 -0
  1229. package/examples/sdk/13-session-runtime.ts +67 -0
  1230. package/examples/sdk/README.md +144 -0
  1231. package/package.json +94 -19
  1232. package/bin/atomic +0 -82
  1233. /package/{LICENSE → dist/builtin/workflows/LICENSE} +0 -0
@@ -0,0 +1,4709 @@
1
+ /**
2
+ * Interactive mode for the coding agent.
3
+ * Handles TUI rendering and user interaction, delegating business logic to AgentSession.
4
+ */
5
+ import * as crypto from "node:crypto";
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import { getProviders, } from "@earendil-works/pi-ai";
10
+ import { CombinedAutocompleteProvider, Container, fuzzyFilter, getCapabilities, hyperlink, Loader, Markdown, matchesKey, ProcessTerminal, Spacer, setKeybindings, Text, TruncatedText, TUI, visibleWidth, } from "@earendil-works/pi-tui";
11
+ import { spawn, spawnSync } from "child_process";
12
+ import { APP_NAME, APP_TITLE, CHANGELOG_URL, ENV_OFFLINE, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, getShareViewerUrl, VERSION, } from "../../config.js";
13
+ import { parseSkillBlock, } from "../../core/agent-session.js";
14
+ import { pickWhimsicalWorkingMessage } from "./whimsical-messages.js";
15
+ import { SessionImportFileNotFoundError, } from "../../core/agent-session-runtime.js";
16
+ import { FooterDataProvider, } from "../../core/footer-data-provider.js";
17
+ import { KeybindingsManager, } from "../../core/keybindings.js";
18
+ import { createCompactionSummaryMessage } from "../../core/messages.js";
19
+ import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope, } from "../../core/model-resolver.js";
20
+ import { DefaultPackageManager } from "../../core/package-manager.js";
21
+ import { BUILT_IN_PROVIDER_DISPLAY_NAMES } from "../../core/provider-display-names.js";
22
+ import { formatMissingSessionCwdPrompt, MissingSessionCwdError, } from "../../core/session-cwd.js";
23
+ import { SessionManager, } from "../../core/session-manager.js";
24
+ import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js";
25
+ import { isInstallTelemetryEnabled } from "../../core/telemetry.js";
26
+ import { getChangelogPath, getNewEntries, parseChangelog, } from "../../utils/changelog.js";
27
+ import { copyToClipboard } from "../../utils/clipboard.js";
28
+ import { extensionForImageMimeType, readClipboardImage, } from "../../utils/clipboard-image.js";
29
+ import { parseGitUrl } from "../../utils/git.js";
30
+ import { getCwdRelativePath } from "../../utils/paths.js";
31
+ import { getPiUserAgent } from "../../utils/pi-user-agent.js";
32
+ import { killTrackedDetachedChildren } from "../../utils/shell.js";
33
+ import { ensureTool } from "../../utils/tools-manager.js";
34
+ import { checkForNewPiVersion } from "../../utils/version-check.js";
35
+ import { ArminComponent } from "./components/armin.js";
36
+ import { AssistantMessageComponent } from "./components/assistant-message.js";
37
+ import { BashExecutionComponent } from "./components/bash-execution.js";
38
+ import { BorderedLoader } from "./components/bordered-loader.js";
39
+ import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js";
40
+ import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
41
+ import { CountdownTimer } from "./components/countdown-timer.js";
42
+ import { CustomEditor } from "./components/custom-editor.js";
43
+ import { CustomMessageComponent } from "./components/custom-message.js";
44
+ import { DaxnutsComponent } from "./components/daxnuts.js";
45
+ import { DynamicBorder } from "./components/dynamic-border.js";
46
+ import { EarendilAnnouncementComponent } from "./components/earendil-announcement.js";
47
+ import { ExtensionEditorComponent } from "./components/extension-editor.js";
48
+ import { ExtensionInputComponent } from "./components/extension-input.js";
49
+ import { ExtensionSelectorComponent } from "./components/extension-selector.js";
50
+ import { FooterComponent } from "./components/footer.js";
51
+ import { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint, } from "./components/keybinding-hints.js";
52
+ import { LoginDialogComponent } from "./components/login-dialog.js";
53
+ import { ModelSelectorComponent } from "./components/model-selector.js";
54
+ import { OAuthSelectorComponent, } from "./components/oauth-selector.js";
55
+ import { ScopedModelsSelectorComponent } from "./components/scoped-models-selector.js";
56
+ import { SessionSelectorComponent } from "./components/session-selector.js";
57
+ import { SettingsSelectorComponent } from "./components/settings-selector.js";
58
+ import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
59
+ import { ToolExecutionComponent } from "./components/tool-execution.js";
60
+ import { TreeSelectorComponent } from "./components/tree-selector.js";
61
+ import { UserMessageComponent } from "./components/user-message.js";
62
+ import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
63
+ import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, initTheme, onThemeChange, setRegisteredThemes, setTheme, setThemeInstance, stopThemeWatcher, Theme, theme, } from "./theme/theme.js";
64
+ function isExpandable(obj) {
65
+ return (typeof obj === "object" &&
66
+ obj !== null &&
67
+ "setExpanded" in obj &&
68
+ typeof obj.setExpanded === "function");
69
+ }
70
+ class ExpandableText extends Text {
71
+ constructor(getCollapsedText, getExpandedText, expanded = false, paddingX = 0, paddingY = 0) {
72
+ super(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);
73
+ this.getCollapsedText = getCollapsedText;
74
+ this.getExpandedText = getExpandedText;
75
+ }
76
+ setExpanded(expanded) {
77
+ this.setText(expanded ? this.getExpandedText() : this.getCollapsedText());
78
+ }
79
+ }
80
+ const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN"]);
81
+ function isDeadTerminalError(error) {
82
+ if (!error || typeof error !== "object" || !("code" in error)) {
83
+ return false;
84
+ }
85
+ const code = error.code;
86
+ return code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);
87
+ }
88
+ const ANTHROPIC_SUBSCRIPTION_AUTH_WARNING = "Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage.";
89
+ function isAnthropicSubscriptionAuthKey(apiKey) {
90
+ return typeof apiKey === "string" && apiKey.startsWith("sk-ant-oat");
91
+ }
92
+ function isUnknownModel(model) {
93
+ return (!!model &&
94
+ model.provider === "unknown" &&
95
+ model.id === "unknown" &&
96
+ model.api === "unknown");
97
+ }
98
+ function hasDefaultModelProvider(providerId) {
99
+ return providerId in defaultModelPerProvider;
100
+ }
101
+ const BEDROCK_PROVIDER_ID = "amazon-bedrock";
102
+ const BUILT_IN_MODEL_PROVIDERS = new Set(getProviders());
103
+ export function isApiKeyLoginProvider(providerId, oauthProviderIds, builtInProviderIds = BUILT_IN_MODEL_PROVIDERS) {
104
+ if (BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]) {
105
+ return true;
106
+ }
107
+ if (builtInProviderIds.has(providerId)) {
108
+ return false;
109
+ }
110
+ return !oauthProviderIds.has(providerId);
111
+ }
112
+ export class InteractiveMode {
113
+ // Convenience accessors
114
+ get session() {
115
+ return this.runtimeHost.session;
116
+ }
117
+ get agent() {
118
+ return this.session.agent;
119
+ }
120
+ get sessionManager() {
121
+ return this.session.sessionManager;
122
+ }
123
+ get settingsManager() {
124
+ return this.session.settingsManager;
125
+ }
126
+ constructor(runtimeHost, options = {}) {
127
+ this.options = options;
128
+ this.autocompleteProviderWrappers = [];
129
+ this.isInitialized = false;
130
+ this.loadingAnimation = undefined;
131
+ this.workingMessage = undefined;
132
+ this.workingVisible = true;
133
+ this.workingIndicatorOptions = undefined;
134
+ this.defaultWorkingMessage = "Working...";
135
+ this.defaultHiddenThinkingLabel = "Thinking...";
136
+ this.hiddenThinkingLabel = this.defaultHiddenThinkingLabel;
137
+ this.lastSigintTime = 0;
138
+ this.lastEscapeTime = 0;
139
+ this.changelogMarkdown = undefined;
140
+ this.startupNoticesShown = false;
141
+ this.anthropicSubscriptionWarningShown = false;
142
+ // Status line tracking (for mutating immediately-sequential status updates)
143
+ this.lastStatusSpacer = undefined;
144
+ this.lastStatusText = undefined;
145
+ // Streaming message tracking
146
+ this.streamingComponent = undefined;
147
+ this.streamingMessage = undefined;
148
+ // Tool execution tracking: toolCallId -> component
149
+ this.pendingTools = new Map();
150
+ // Tool output expansion state
151
+ this.toolOutputExpanded = false;
152
+ // Thinking block visibility state
153
+ this.hideThinkingBlock = false;
154
+ // Skill commands: command name -> skill file path
155
+ this.skillCommands = new Map();
156
+ this.signalCleanupHandlers = [];
157
+ // Track if editor is in bash mode (text starts with !)
158
+ this.isBashMode = false;
159
+ // Track current bash execution component
160
+ this.bashComponent = undefined;
161
+ // Track pending bash components (shown in pending area, moved to chat on submit)
162
+ this.pendingBashComponents = [];
163
+ // Auto-compaction state
164
+ this.autoCompactionLoader = undefined;
165
+ // Auto-retry state
166
+ this.retryLoader = undefined;
167
+ this.retryCountdown = undefined;
168
+ // Messages queued while compaction is running
169
+ this.compactionQueuedMessages = [];
170
+ // Shutdown state
171
+ this.shutdownRequested = false;
172
+ // Extension UI state
173
+ this.extensionSelector = undefined;
174
+ this.extensionInput = undefined;
175
+ this.extensionEditor = undefined;
176
+ this.extensionTerminalInputUnsubscribers = new Set();
177
+ // Extension widgets (components rendered above/below the editor)
178
+ this.extensionWidgetsAbove = new Map();
179
+ this.extensionWidgetsBelow = new Map();
180
+ // Custom footer from extension (undefined = use built-in footer)
181
+ this.customFooter = undefined;
182
+ // Built-in header (logo + keybinding hints + changelog)
183
+ this.builtInHeader = undefined;
184
+ // Custom header from extension (undefined = use built-in header)
185
+ this.customHeader = undefined;
186
+ /**
187
+ * Gracefully shutdown the agent.
188
+ * Stops the TUI before emitting shutdown events so extension UI cleanup cannot
189
+ * repaint the final frame while the process is exiting.
190
+ */
191
+ this.isShuttingDown = false;
192
+ this.runtimeHost = runtimeHost;
193
+ this.runtimeHost.setBeforeSessionInvalidate(() => {
194
+ this.resetExtensionUI();
195
+ });
196
+ this.runtimeHost.setRebindSession(async () => {
197
+ await this.rebindCurrentSession();
198
+ });
199
+ this.version = VERSION;
200
+ this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor());
201
+ this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
202
+ this.headerContainer = new Container();
203
+ this.chatContainer = new Container();
204
+ this.pendingMessagesContainer = new Container();
205
+ this.statusContainer = new Container();
206
+ this.widgetContainerAbove = new Container();
207
+ this.widgetContainerBelow = new Container();
208
+ this.keybindings = KeybindingsManager.create();
209
+ setKeybindings(this.keybindings);
210
+ const editorPaddingX = this.settingsManager.getEditorPaddingX();
211
+ const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
212
+ this.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {
213
+ paddingX: editorPaddingX,
214
+ autocompleteMaxVisible,
215
+ });
216
+ this.editor = this.defaultEditor;
217
+ this.editorContainer = new Container();
218
+ this.editorContainer.addChild(this.editor);
219
+ this.footerDataProvider = new FooterDataProvider(this.sessionManager.getCwd());
220
+ this.footer = new FooterComponent(this.session, this.footerDataProvider);
221
+ this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);
222
+ // Load hide thinking block setting
223
+ this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
224
+ // Register themes from resource loader and initialize
225
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
226
+ initTheme(this.settingsManager.getTheme(), true);
227
+ }
228
+ getAutocompleteSourceTag(sourceInfo) {
229
+ if (!sourceInfo) {
230
+ return undefined;
231
+ }
232
+ const scopePrefix = sourceInfo.scope === "user"
233
+ ? "u"
234
+ : sourceInfo.scope === "project"
235
+ ? "p"
236
+ : "t";
237
+ const source = sourceInfo.source.trim();
238
+ if (source === "auto" || source === "local" || source === "cli") {
239
+ return scopePrefix;
240
+ }
241
+ if (source.startsWith("npm:")) {
242
+ return `${scopePrefix}:${source}`;
243
+ }
244
+ const gitSource = parseGitUrl(source);
245
+ if (gitSource) {
246
+ const ref = gitSource.ref ? `@${gitSource.ref}` : "";
247
+ return `${scopePrefix}:git:${gitSource.host}/${gitSource.path}${ref}`;
248
+ }
249
+ return scopePrefix;
250
+ }
251
+ prefixAutocompleteDescription(description, sourceInfo) {
252
+ const sourceTag = this.getAutocompleteSourceTag(sourceInfo);
253
+ if (!sourceTag) {
254
+ return description;
255
+ }
256
+ return description ? `[${sourceTag}] ${description}` : `[${sourceTag}]`;
257
+ }
258
+ getBuiltInCommandConflictDiagnostics(extensionRunner) {
259
+ const builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));
260
+ return extensionRunner
261
+ .getRegisteredCommands()
262
+ .filter((command) => builtinNames.has(command.name))
263
+ .map((command) => ({
264
+ type: "warning",
265
+ message: command.invocationName === command.name
266
+ ? `Extension command '/${command.name}' conflicts with built-in interactive command. Skipping in autocomplete.`
267
+ : `Extension command '/${command.name}' conflicts with built-in interactive command. Available as '/${command.invocationName}'.`,
268
+ path: command.sourceInfo.path,
269
+ }));
270
+ }
271
+ createBaseAutocompleteProvider() {
272
+ // Define commands for autocomplete
273
+ const slashCommands = BUILTIN_SLASH_COMMANDS.map((command) => ({
274
+ name: command.name,
275
+ description: command.description,
276
+ }));
277
+ const modelCommand = slashCommands.find((command) => command.name === "model");
278
+ if (modelCommand) {
279
+ modelCommand.getArgumentCompletions = (prefix) => {
280
+ // Get available models (scoped or from registry)
281
+ const models = this.session.scopedModels.length > 0
282
+ ? this.session.scopedModels.map((s) => s.model)
283
+ : this.session.modelRegistry.getAvailable();
284
+ if (models.length === 0)
285
+ return null;
286
+ // Create items with provider/id format
287
+ const items = models.map((m) => ({
288
+ id: m.id,
289
+ provider: m.provider,
290
+ label: `${m.provider}/${m.id}`,
291
+ }));
292
+ // Fuzzy filter by model ID + provider (allows "opus anthropic" to match)
293
+ const filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);
294
+ if (filtered.length === 0)
295
+ return null;
296
+ return filtered.map((item) => ({
297
+ value: item.label,
298
+ label: item.id,
299
+ description: item.provider,
300
+ }));
301
+ };
302
+ }
303
+ // Convert prompt templates to SlashCommand format for autocomplete
304
+ const templateCommands = this.session.promptTemplates.map((cmd) => ({
305
+ name: cmd.name,
306
+ description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
307
+ ...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),
308
+ }));
309
+ // Convert extension commands to SlashCommand format
310
+ const builtinCommandNames = new Set(slashCommands.map((c) => c.name));
311
+ const extensionCommands = this.session.extensionRunner
312
+ .getRegisteredCommands()
313
+ .filter((cmd) => !builtinCommandNames.has(cmd.name))
314
+ .map((cmd) => ({
315
+ name: cmd.invocationName,
316
+ description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
317
+ getArgumentCompletions: cmd.getArgumentCompletions,
318
+ }));
319
+ // Build skill commands from session.skills (if enabled)
320
+ this.skillCommands.clear();
321
+ const skillCommandList = [];
322
+ if (this.settingsManager.getEnableSkillCommands()) {
323
+ for (const skill of this.session.resourceLoader.getSkills().skills) {
324
+ const commandName = `skill:${skill.name}`;
325
+ this.skillCommands.set(commandName, skill.filePath);
326
+ skillCommandList.push({
327
+ name: commandName,
328
+ description: this.prefixAutocompleteDescription(skill.description, skill.sourceInfo),
329
+ });
330
+ }
331
+ }
332
+ return new CombinedAutocompleteProvider([
333
+ ...slashCommands,
334
+ ...templateCommands,
335
+ ...extensionCommands,
336
+ ...skillCommandList,
337
+ ], this.sessionManager.getCwd(), this.fdPath);
338
+ }
339
+ setupAutocompleteProvider() {
340
+ let provider = this.createBaseAutocompleteProvider();
341
+ for (const wrapProvider of this.autocompleteProviderWrappers) {
342
+ provider = wrapProvider(provider);
343
+ }
344
+ this.autocompleteProvider = provider;
345
+ this.defaultEditor.setAutocompleteProvider(provider);
346
+ if (this.editor !== this.defaultEditor) {
347
+ this.editor.setAutocompleteProvider?.(provider);
348
+ }
349
+ }
350
+ showStartupNoticesIfNeeded() {
351
+ if (this.startupNoticesShown) {
352
+ return;
353
+ }
354
+ this.startupNoticesShown = true;
355
+ if (!this.changelogMarkdown) {
356
+ return;
357
+ }
358
+ if (this.chatContainer.children.length > 0) {
359
+ this.chatContainer.addChild(new Spacer(1));
360
+ }
361
+ this.chatContainer.addChild(new DynamicBorder());
362
+ if (this.settingsManager.getCollapseChangelog()) {
363
+ const versionMatch = this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/);
364
+ const latestVersion = versionMatch ? versionMatch[1] : this.version;
365
+ const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`;
366
+ this.chatContainer.addChild(new Text(condensedText, 1, 0));
367
+ }
368
+ else {
369
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
370
+ this.chatContainer.addChild(new Spacer(1));
371
+ this.chatContainer.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()));
372
+ this.chatContainer.addChild(new Spacer(1));
373
+ }
374
+ this.chatContainer.addChild(new DynamicBorder());
375
+ }
376
+ async init() {
377
+ if (this.isInitialized)
378
+ return;
379
+ this.registerSignalHandlers();
380
+ // Load changelog (only show new entries, skip for resumed sessions)
381
+ this.changelogMarkdown = this.getChangelogForDisplay();
382
+ // Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)
383
+ // Both are needed: fd for autocomplete, rg for grep tool and bash commands
384
+ const [fdPath] = await Promise.all([ensureTool("fd"), ensureTool("rg")]);
385
+ this.fdPath = fdPath;
386
+ // Add header container as first child
387
+ this.ui.addChild(this.headerContainer);
388
+ // Add header with keybindings from config (unless silenced)
389
+ if (this.options.verbose || !this.settingsManager.getQuietStartup()) {
390
+ const logo = theme.bold(theme.fg("accent", APP_NAME)) +
391
+ theme.fg("dim", ` v${this.version}`);
392
+ // Build startup instructions using keybinding hint helpers
393
+ const hint = (keybinding, description) => keyHint(keybinding, description);
394
+ const expandedInstructions = [
395
+ hint("app.interrupt", "to interrupt"),
396
+ hint("app.clear", "to clear"),
397
+ rawKeyHint(`${keyText("app.clear")} twice`, "to exit"),
398
+ hint("app.exit", "to exit (empty)"),
399
+ hint("app.suspend", "to suspend"),
400
+ keyHint("tui.editor.deleteToLineEnd", "to delete to end"),
401
+ hint("app.thinking.cycle", "to cycle thinking level"),
402
+ rawKeyHint(`${keyText("app.model.cycleForward")}/${keyText("app.model.cycleBackward")}`, "to cycle models"),
403
+ hint("app.model.select", "to select model"),
404
+ hint("app.tools.expand", "to expand tools"),
405
+ hint("app.thinking.toggle", "to expand thinking"),
406
+ hint("app.editor.external", "for external editor"),
407
+ rawKeyHint("/", "for commands"),
408
+ rawKeyHint("!", "to run bash"),
409
+ rawKeyHint("!!", "to run bash (no context)"),
410
+ hint("app.message.followUp", "to queue follow-up"),
411
+ hint("app.message.dequeue", "to edit all queued messages"),
412
+ hint("app.clipboard.pasteImage", "to paste image"),
413
+ rawKeyHint("drop files", "to attach"),
414
+ ].join("\n");
415
+ const compactInstructions = [
416
+ hint("app.interrupt", "interrupt"),
417
+ rawKeyHint(`${keyText("app.clear")}/${keyText("app.exit")}`, "clear/exit"),
418
+ rawKeyHint("/", "commands"),
419
+ rawKeyHint("!", "bash"),
420
+ hint("app.tools.expand", "more"),
421
+ ].join(theme.fg("muted", " · "));
422
+ const compactOnboarding = theme.fg("dim", `Press ${keyText("app.tools.expand")} to show full startup help and loaded resources.`);
423
+ const onboarding = theme.fg("dim", `Atomic is built with Pi. Pi can explain its own features and look up its docs. Ask it how to use or extend Pi.`);
424
+ this.builtInHeader = new ExpandableText(() => `${logo}\n${compactInstructions}\n${compactOnboarding}\n\n${onboarding}`, () => `${logo}\n${expandedInstructions}\n\n${onboarding}`, this.getStartupExpansionState(), 1, 0);
425
+ // Setup UI layout
426
+ this.headerContainer.addChild(new Spacer(1));
427
+ this.headerContainer.addChild(this.builtInHeader);
428
+ this.headerContainer.addChild(new Spacer(1));
429
+ }
430
+ else {
431
+ // Minimal header when silenced
432
+ this.builtInHeader = new Text("", 0, 0);
433
+ this.headerContainer.addChild(this.builtInHeader);
434
+ }
435
+ this.ui.addChild(this.chatContainer);
436
+ this.ui.addChild(this.pendingMessagesContainer);
437
+ this.ui.addChild(this.statusContainer);
438
+ this.renderWidgets(); // Initialize with default spacer
439
+ this.ui.addChild(this.widgetContainerAbove);
440
+ this.ui.addChild(this.editorContainer);
441
+ this.ui.addChild(this.widgetContainerBelow);
442
+ this.ui.addChild(this.footer);
443
+ this.ui.setFocus(this.editor);
444
+ this.setupKeyHandlers();
445
+ this.setupEditorSubmitHandler();
446
+ // Start the UI before initializing extensions so session_start handlers can use interactive dialogs
447
+ this.ui.start();
448
+ this.isInitialized = true;
449
+ // Initialize extensions first so resources are shown before messages
450
+ await this.rebindCurrentSession();
451
+ // Render initial messages AFTER showing loaded resources
452
+ this.renderInitialMessages();
453
+ // Set up theme file watcher
454
+ onThemeChange(() => {
455
+ this.ui.invalidate();
456
+ this.updateEditorBorderColor();
457
+ this.ui.requestRender();
458
+ });
459
+ // Set up git branch watcher (uses provider instead of footer)
460
+ this.footerDataProvider.onBranchChange(() => {
461
+ this.ui.requestRender();
462
+ });
463
+ // Initialize available provider count for footer display
464
+ await this.updateAvailableProviderCount();
465
+ }
466
+ /**
467
+ * Update terminal title with session name and cwd.
468
+ */
469
+ updateTerminalTitle() {
470
+ const cwdBasename = path.basename(this.sessionManager.getCwd());
471
+ const sessionName = this.sessionManager.getSessionName();
472
+ if (sessionName) {
473
+ this.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);
474
+ }
475
+ else {
476
+ this.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);
477
+ }
478
+ }
479
+ /**
480
+ * Run the interactive mode. This is the main entry point.
481
+ * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.
482
+ */
483
+ async run() {
484
+ await this.init();
485
+ // Start version check asynchronously
486
+ checkForNewPiVersion(this.version).then((newVersion) => {
487
+ if (newVersion) {
488
+ this.showNewVersionNotification(newVersion);
489
+ }
490
+ });
491
+ // Start package update check asynchronously
492
+ this.checkForPackageUpdates().then((updates) => {
493
+ if (updates.length > 0) {
494
+ this.showPackageUpdateNotification(updates);
495
+ }
496
+ });
497
+ // Check tmux keyboard setup asynchronously
498
+ this.checkTmuxKeyboardSetup().then((warning) => {
499
+ if (warning) {
500
+ this.showWarning(warning);
501
+ }
502
+ });
503
+ // Show startup warnings
504
+ const { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages, } = this.options;
505
+ if (migratedProviders && migratedProviders.length > 0) {
506
+ this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
507
+ }
508
+ const modelsJsonError = this.session.modelRegistry.getError();
509
+ if (modelsJsonError) {
510
+ this.showError(`models.json error: ${modelsJsonError}`);
511
+ }
512
+ if (modelFallbackMessage) {
513
+ this.showWarning(modelFallbackMessage);
514
+ }
515
+ void this.maybeWarnAboutAnthropicSubscriptionAuth();
516
+ // Process initial messages
517
+ if (initialMessage) {
518
+ try {
519
+ await this.session.prompt(initialMessage, { images: initialImages });
520
+ }
521
+ catch (error) {
522
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
523
+ this.showError(errorMessage);
524
+ }
525
+ }
526
+ if (initialMessages) {
527
+ for (const message of initialMessages) {
528
+ try {
529
+ await this.session.prompt(message);
530
+ }
531
+ catch (error) {
532
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
533
+ this.showError(errorMessage);
534
+ }
535
+ }
536
+ }
537
+ // Main interactive loop
538
+ while (true) {
539
+ const userInput = await this.getUserInput();
540
+ try {
541
+ await this.session.prompt(userInput);
542
+ }
543
+ catch (error) {
544
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
545
+ this.showError(errorMessage);
546
+ }
547
+ }
548
+ }
549
+ async checkForPackageUpdates() {
550
+ if (process.env[ENV_OFFLINE]) {
551
+ return [];
552
+ }
553
+ try {
554
+ const packageManager = new DefaultPackageManager({
555
+ cwd: this.sessionManager.getCwd(),
556
+ agentDir: getAgentDir(),
557
+ settingsManager: this.settingsManager,
558
+ });
559
+ const updates = await packageManager.checkForAvailableUpdates();
560
+ return updates.map((update) => update.displayName);
561
+ }
562
+ catch {
563
+ return [];
564
+ }
565
+ }
566
+ async checkTmuxKeyboardSetup() {
567
+ if (!process.env.TMUX)
568
+ return undefined;
569
+ const runTmuxShow = (option) => {
570
+ return new Promise((resolve) => {
571
+ const proc = spawn("tmux", ["show", "-gv", option], {
572
+ stdio: ["ignore", "pipe", "ignore"],
573
+ });
574
+ let stdout = "";
575
+ const timer = setTimeout(() => {
576
+ proc.kill();
577
+ resolve(undefined);
578
+ }, 2000);
579
+ proc.stdout?.on("data", (data) => {
580
+ stdout += data.toString();
581
+ });
582
+ proc.on("error", () => {
583
+ clearTimeout(timer);
584
+ resolve(undefined);
585
+ });
586
+ proc.on("close", (code) => {
587
+ clearTimeout(timer);
588
+ resolve(code === 0 ? stdout.trim() : undefined);
589
+ });
590
+ });
591
+ };
592
+ const [extendedKeys, extendedKeysFormat] = await Promise.all([
593
+ runTmuxShow("extended-keys"),
594
+ runTmuxShow("extended-keys-format"),
595
+ ]);
596
+ // If we couldn't query tmux (timeout, sandbox, etc.), don't warn
597
+ if (extendedKeys === undefined)
598
+ return undefined;
599
+ if (extendedKeys !== "on" && extendedKeys !== "always") {
600
+ return "tmux extended-keys is off. Modified Enter keys may not work. Add `set -g extended-keys on` to ~/.tmux.conf and restart tmux.";
601
+ }
602
+ if (extendedKeysFormat === "xterm") {
603
+ return "tmux extended-keys-format is xterm. Pi works best with csi-u. Add `set -g extended-keys-format csi-u` to ~/.tmux.conf and restart tmux.";
604
+ }
605
+ return undefined;
606
+ }
607
+ /**
608
+ * Get changelog entries to display on startup.
609
+ * Only shows new entries since last seen version, skips for resumed sessions.
610
+ */
611
+ getChangelogForDisplay() {
612
+ // Skip changelog for resumed/continued sessions (already have messages)
613
+ if (this.session.state.messages.length > 0) {
614
+ return undefined;
615
+ }
616
+ const lastVersion = this.settingsManager.getLastChangelogVersion();
617
+ const changelogPath = getChangelogPath();
618
+ const entries = parseChangelog(changelogPath);
619
+ if (!lastVersion) {
620
+ // Fresh install - record the version, send telemetry, don't show changelog
621
+ this.settingsManager.setLastChangelogVersion(VERSION);
622
+ this.reportInstallTelemetry(VERSION);
623
+ return undefined;
624
+ }
625
+ const newEntries = getNewEntries(entries, lastVersion);
626
+ if (newEntries.length > 0) {
627
+ this.settingsManager.setLastChangelogVersion(VERSION);
628
+ this.reportInstallTelemetry(VERSION);
629
+ return newEntries.map((e) => e.content).join("\n\n");
630
+ }
631
+ return undefined;
632
+ }
633
+ reportInstallTelemetry(version) {
634
+ if (process.env[ENV_OFFLINE]) {
635
+ return;
636
+ }
637
+ if (!isInstallTelemetryEnabled(this.settingsManager)) {
638
+ return;
639
+ }
640
+ void fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {
641
+ headers: {
642
+ "User-Agent": getPiUserAgent(version),
643
+ },
644
+ signal: AbortSignal.timeout(5000),
645
+ })
646
+ .then(() => undefined)
647
+ .catch(() => undefined);
648
+ }
649
+ getMarkdownThemeWithSettings() {
650
+ return {
651
+ ...getMarkdownTheme(),
652
+ codeBlockIndent: this.settingsManager.getCodeBlockIndent(),
653
+ };
654
+ }
655
+ // =========================================================================
656
+ // Extension System
657
+ // =========================================================================
658
+ formatDisplayPath(p) {
659
+ const home = os.homedir();
660
+ let result = p;
661
+ // Replace home directory with ~
662
+ if (result.startsWith(home)) {
663
+ result = `~${result.slice(home.length)}`;
664
+ }
665
+ return result;
666
+ }
667
+ formatExtensionDisplayPath(path) {
668
+ let result = this.formatDisplayPath(path);
669
+ result = result.replace(/\/index\.ts$/, "").replace(/\/index\.js$/, "");
670
+ return result;
671
+ }
672
+ formatContextPath(p) {
673
+ const cwd = path.resolve(this.sessionManager.getCwd());
674
+ const absolutePath = path.isAbsolute(p)
675
+ ? path.resolve(p)
676
+ : path.resolve(cwd, p);
677
+ const relativePath = getCwdRelativePath(absolutePath, cwd);
678
+ if (relativePath !== undefined) {
679
+ return relativePath;
680
+ }
681
+ return this.formatDisplayPath(absolutePath);
682
+ }
683
+ getStartupExpansionState() {
684
+ return this.options.verbose || this.toolOutputExpanded;
685
+ }
686
+ /**
687
+ * Get a short path relative to the package root for display.
688
+ */
689
+ getShortPath(fullPath, sourceInfo) {
690
+ const baseDir = sourceInfo?.baseDir;
691
+ if (baseDir && this.isPackageSource(sourceInfo)) {
692
+ const relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));
693
+ if (relativePath &&
694
+ relativePath !== "." &&
695
+ !relativePath.startsWith("..") &&
696
+ !relativePath.startsWith(`..${path.sep}`) &&
697
+ !path.isAbsolute(relativePath)) {
698
+ return relativePath.replace(/\\/g, "/");
699
+ }
700
+ }
701
+ const source = sourceInfo?.source ?? "";
702
+ const npmMatch = fullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);
703
+ if (npmMatch && source.startsWith("npm:")) {
704
+ return npmMatch[2];
705
+ }
706
+ const gitMatch = fullPath.match(/git\/[^/]+\/[^/]+\/(.*)/);
707
+ if (gitMatch && source.startsWith("git:")) {
708
+ return gitMatch[1];
709
+ }
710
+ return this.formatDisplayPath(fullPath);
711
+ }
712
+ getCompactPathLabel(resourcePath, sourceInfo) {
713
+ const shortPath = this.getShortPath(resourcePath, sourceInfo);
714
+ const normalizedPath = shortPath.replace(/\\/g, "/");
715
+ const segments = normalizedPath
716
+ .split("/")
717
+ .filter((segment) => segment.length > 0 && segment !== "~");
718
+ if (segments.length > 0) {
719
+ return segments[segments.length - 1];
720
+ }
721
+ return shortPath;
722
+ }
723
+ getCompactPackageSourceLabel(sourceInfo) {
724
+ const source = sourceInfo?.source ?? "";
725
+ if (source.startsWith("npm:")) {
726
+ return source.slice("npm:".length) || source;
727
+ }
728
+ const gitSource = parseGitUrl(source);
729
+ if (gitSource) {
730
+ return gitSource.path || source;
731
+ }
732
+ return source;
733
+ }
734
+ getCompactExtensionLabel(resourcePath, sourceInfo) {
735
+ if (!this.isPackageSource(sourceInfo)) {
736
+ return this.getCompactPathLabel(resourcePath, sourceInfo);
737
+ }
738
+ const sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);
739
+ if (!sourceLabel) {
740
+ return this.getCompactPathLabel(resourcePath, sourceInfo);
741
+ }
742
+ const shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\/g, "/");
743
+ const packagePath = shortPath.startsWith("extensions/")
744
+ ? shortPath.slice("extensions/".length)
745
+ : shortPath;
746
+ const parsedPath = path.posix.parse(packagePath);
747
+ if (parsedPath.name === "index") {
748
+ return !parsedPath.dir || parsedPath.dir === "."
749
+ ? sourceLabel
750
+ : `${sourceLabel}:${parsedPath.dir}`;
751
+ }
752
+ return `${sourceLabel}:${packagePath}`;
753
+ }
754
+ getCompactDisplayPathSegments(resourcePath) {
755
+ return this.formatDisplayPath(resourcePath)
756
+ .replace(/\\/g, "/")
757
+ .split("/")
758
+ .filter((segment) => segment.length > 0 && segment !== "~");
759
+ }
760
+ getCompactNonPackageExtensionLabel(resourcePath, index, allPaths) {
761
+ const segments = allPaths[index]?.segments;
762
+ if (!segments || segments.length === 0) {
763
+ return this.getCompactPathLabel(resourcePath);
764
+ }
765
+ for (let segmentCount = 1; segmentCount <= segments.length; segmentCount += 1) {
766
+ const candidate = segments.slice(-segmentCount).join("/");
767
+ const isUnique = allPaths.every((item, itemIndex) => {
768
+ if (itemIndex === index) {
769
+ return true;
770
+ }
771
+ return item.segments.slice(-segmentCount).join("/") !== candidate;
772
+ });
773
+ if (isUnique) {
774
+ return candidate;
775
+ }
776
+ }
777
+ return segments.join("/");
778
+ }
779
+ getCompactExtensionLabels(extensions) {
780
+ const nonPackageExtensions = extensions
781
+ .map((extension) => {
782
+ const segments = this.getCompactDisplayPathSegments(extension.path);
783
+ const lastSegment = segments[segments.length - 1];
784
+ if (segments.length > 1 &&
785
+ (lastSegment === "index.ts" || lastSegment === "index.js")) {
786
+ segments.pop();
787
+ }
788
+ return {
789
+ path: extension.path,
790
+ sourceInfo: extension.sourceInfo,
791
+ segments,
792
+ };
793
+ })
794
+ .filter((extension) => !this.isPackageSource(extension.sourceInfo));
795
+ return extensions.map((extension) => {
796
+ if (this.isPackageSource(extension.sourceInfo)) {
797
+ return this.getCompactExtensionLabel(extension.path, extension.sourceInfo);
798
+ }
799
+ const nonPackageIndex = nonPackageExtensions.findIndex((item) => item.path === extension.path);
800
+ if (nonPackageIndex === -1) {
801
+ return this.getCompactPathLabel(extension.path, extension.sourceInfo);
802
+ }
803
+ return this.getCompactNonPackageExtensionLabel(extension.path, nonPackageIndex, nonPackageExtensions);
804
+ });
805
+ }
806
+ getDisplaySourceInfo(sourceInfo) {
807
+ const source = sourceInfo?.source ?? "local";
808
+ const scope = sourceInfo?.scope ?? "project";
809
+ if (source === "local") {
810
+ if (scope === "user") {
811
+ return { label: "user", color: "muted" };
812
+ }
813
+ if (scope === "project") {
814
+ return { label: "project", color: "muted" };
815
+ }
816
+ if (scope === "temporary") {
817
+ return { label: "path", scopeLabel: "temp", color: "muted" };
818
+ }
819
+ return { label: "path", color: "muted" };
820
+ }
821
+ if (source === "cli") {
822
+ return {
823
+ label: "path",
824
+ scopeLabel: scope === "temporary" ? "temp" : undefined,
825
+ color: "muted",
826
+ };
827
+ }
828
+ const scopeLabel = scope === "user"
829
+ ? "user"
830
+ : scope === "project"
831
+ ? "project"
832
+ : scope === "temporary"
833
+ ? "temp"
834
+ : undefined;
835
+ return { label: source, scopeLabel, color: "accent" };
836
+ }
837
+ getScopeGroup(sourceInfo) {
838
+ const source = sourceInfo?.source ?? "local";
839
+ const scope = sourceInfo?.scope ?? "project";
840
+ if (source === "cli" || scope === "temporary")
841
+ return "path";
842
+ if (scope === "user")
843
+ return "user";
844
+ if (scope === "project")
845
+ return "project";
846
+ return "path";
847
+ }
848
+ isPackageSource(sourceInfo) {
849
+ const source = sourceInfo?.source ?? "";
850
+ return source.startsWith("npm:") || source.startsWith("git:");
851
+ }
852
+ buildScopeGroups(items) {
853
+ const groups = {
854
+ user: { scope: "user", paths: [], packages: new Map() },
855
+ project: { scope: "project", paths: [], packages: new Map() },
856
+ path: { scope: "path", paths: [], packages: new Map() },
857
+ };
858
+ for (const item of items) {
859
+ const groupKey = this.getScopeGroup(item.sourceInfo);
860
+ const group = groups[groupKey];
861
+ const source = item.sourceInfo?.source ?? "local";
862
+ if (this.isPackageSource(item.sourceInfo)) {
863
+ const list = group.packages.get(source) ?? [];
864
+ list.push(item);
865
+ group.packages.set(source, list);
866
+ }
867
+ else {
868
+ group.paths.push(item);
869
+ }
870
+ }
871
+ return [groups.project, groups.user, groups.path].filter((group) => group.paths.length > 0 || group.packages.size > 0);
872
+ }
873
+ formatScopeGroups(groups, options) {
874
+ const lines = [];
875
+ for (const group of groups) {
876
+ lines.push(` ${theme.fg("accent", group.scope)}`);
877
+ const sortedPaths = [...group.paths].sort((a, b) => a.path.localeCompare(b.path));
878
+ for (const item of sortedPaths) {
879
+ lines.push(theme.fg("dim", ` ${options.formatPath(item)}`));
880
+ }
881
+ const sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));
882
+ for (const [source, items] of sortedPackages) {
883
+ lines.push(` ${theme.fg("mdLink", source)}`);
884
+ const sortedPackagePaths = [...items].sort((a, b) => a.path.localeCompare(b.path));
885
+ for (const item of sortedPackagePaths) {
886
+ lines.push(theme.fg("dim", ` ${options.formatPackagePath(item, source)}`));
887
+ }
888
+ }
889
+ }
890
+ return lines.join("\n");
891
+ }
892
+ findSourceInfoForPath(p, sourceInfos) {
893
+ const exact = sourceInfos.get(p);
894
+ if (exact)
895
+ return exact;
896
+ let current = p;
897
+ while (current.includes("/")) {
898
+ current = current.substring(0, current.lastIndexOf("/"));
899
+ const parent = sourceInfos.get(current);
900
+ if (parent)
901
+ return parent;
902
+ }
903
+ return undefined;
904
+ }
905
+ formatPathWithSource(p, sourceInfo) {
906
+ if (sourceInfo) {
907
+ const shortPath = this.getShortPath(p, sourceInfo);
908
+ const { label, scopeLabel } = this.getDisplaySourceInfo(sourceInfo);
909
+ const labelText = scopeLabel ? `${label} (${scopeLabel})` : label;
910
+ return `${labelText} ${shortPath}`;
911
+ }
912
+ return this.formatDisplayPath(p);
913
+ }
914
+ formatDiagnostics(diagnostics, sourceInfos) {
915
+ const lines = [];
916
+ // Group collision diagnostics by name
917
+ const collisions = new Map();
918
+ const otherDiagnostics = [];
919
+ for (const d of diagnostics) {
920
+ if (d.type === "collision" && d.collision) {
921
+ const list = collisions.get(d.collision.name) ?? [];
922
+ list.push(d);
923
+ collisions.set(d.collision.name, list);
924
+ }
925
+ else {
926
+ otherDiagnostics.push(d);
927
+ }
928
+ }
929
+ // Format collision diagnostics grouped by name
930
+ for (const [name, collisionList] of collisions) {
931
+ const first = collisionList[0]?.collision;
932
+ if (!first)
933
+ continue;
934
+ lines.push(theme.fg("warning", ` "${name}" collision:`));
935
+ lines.push(theme.fg("dim", ` ${theme.fg("success", "✓")} ${this.formatPathWithSource(first.winnerPath, this.findSourceInfoForPath(first.winnerPath, sourceInfos))}`));
936
+ for (const d of collisionList) {
937
+ if (d.collision) {
938
+ lines.push(theme.fg("dim", ` ${theme.fg("warning", "✗")} ${this.formatPathWithSource(d.collision.loserPath, this.findSourceInfoForPath(d.collision.loserPath, sourceInfos))} (skipped)`));
939
+ }
940
+ }
941
+ }
942
+ for (const d of otherDiagnostics) {
943
+ if (d.path) {
944
+ const formattedPath = this.formatPathWithSource(d.path, this.findSourceInfoForPath(d.path, sourceInfos));
945
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${formattedPath}`));
946
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));
947
+ }
948
+ else {
949
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));
950
+ }
951
+ }
952
+ return lines.join("\n");
953
+ }
954
+ showLoadedResources(options) {
955
+ const showListing = options?.force ||
956
+ this.options.verbose ||
957
+ !this.settingsManager.getQuietStartup();
958
+ const showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true;
959
+ if (!showListing && !showDiagnostics) {
960
+ return;
961
+ }
962
+ const sectionHeader = (name, color = "mdHeading") => theme.fg(color, `[${name}]`);
963
+ const formatCompactList = (items, options) => {
964
+ const labels = items
965
+ .map((item) => item.trim())
966
+ .filter((item) => item.length > 0);
967
+ if (options?.sort !== false) {
968
+ labels.sort((a, b) => a.localeCompare(b));
969
+ }
970
+ return theme.fg("dim", ` ${labels.join(", ")}`);
971
+ };
972
+ const addLoadedSection = (name, collapsedBody, expandedBody = collapsedBody, color = "mdHeading") => {
973
+ const section = new ExpandableText(() => `${sectionHeader(name, color)}\n${collapsedBody}`, () => `${sectionHeader(name, color)}\n${expandedBody}`, this.getStartupExpansionState(), 0, 0);
974
+ this.chatContainer.addChild(section);
975
+ this.chatContainer.addChild(new Spacer(1));
976
+ };
977
+ const skillsResult = this.session.resourceLoader.getSkills();
978
+ const promptsResult = this.session.resourceLoader.getPrompts();
979
+ const themesResult = this.session.resourceLoader.getThemes();
980
+ const extensions = options?.extensions ??
981
+ this.session.resourceLoader
982
+ .getExtensions()
983
+ .extensions.map((extension) => ({
984
+ path: extension.path,
985
+ sourceInfo: extension.sourceInfo,
986
+ }));
987
+ const sourceInfos = new Map();
988
+ for (const extension of extensions) {
989
+ if (extension.sourceInfo) {
990
+ sourceInfos.set(extension.path, extension.sourceInfo);
991
+ }
992
+ }
993
+ for (const skill of skillsResult.skills) {
994
+ if (skill.sourceInfo) {
995
+ sourceInfos.set(skill.filePath, skill.sourceInfo);
996
+ }
997
+ }
998
+ for (const prompt of promptsResult.prompts) {
999
+ if (prompt.sourceInfo) {
1000
+ sourceInfos.set(prompt.filePath, prompt.sourceInfo);
1001
+ }
1002
+ }
1003
+ for (const loadedTheme of themesResult.themes) {
1004
+ if (loadedTheme.sourcePath && loadedTheme.sourceInfo) {
1005
+ sourceInfos.set(loadedTheme.sourcePath, loadedTheme.sourceInfo);
1006
+ }
1007
+ }
1008
+ if (showListing) {
1009
+ const contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;
1010
+ if (contextFiles.length > 0) {
1011
+ this.chatContainer.addChild(new Spacer(1));
1012
+ const contextList = contextFiles
1013
+ .map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`))
1014
+ .join("\n");
1015
+ const contextCompactList = formatCompactList(contextFiles.map((contextFile) => this.formatContextPath(contextFile.path)), { sort: false });
1016
+ addLoadedSection("Context", contextCompactList, contextList);
1017
+ }
1018
+ const skills = skillsResult.skills;
1019
+ if (skills.length > 0) {
1020
+ const groups = this.buildScopeGroups(skills.map((skill) => ({
1021
+ path: skill.filePath,
1022
+ sourceInfo: skill.sourceInfo,
1023
+ })));
1024
+ const skillList = this.formatScopeGroups(groups, {
1025
+ formatPath: (item) => this.formatDisplayPath(item.path),
1026
+ formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
1027
+ });
1028
+ const skillCompactList = formatCompactList(skills.map((skill) => skill.name));
1029
+ addLoadedSection("Skills", skillCompactList, skillList);
1030
+ }
1031
+ const templates = this.session.promptTemplates;
1032
+ if (templates.length > 0) {
1033
+ const groups = this.buildScopeGroups(templates.map((template) => ({
1034
+ path: template.filePath,
1035
+ sourceInfo: template.sourceInfo,
1036
+ })));
1037
+ const templateByPath = new Map(templates.map((t) => [t.filePath, t]));
1038
+ const templateList = this.formatScopeGroups(groups, {
1039
+ formatPath: (item) => {
1040
+ const template = templateByPath.get(item.path);
1041
+ return template
1042
+ ? `/${template.name}`
1043
+ : this.formatDisplayPath(item.path);
1044
+ },
1045
+ formatPackagePath: (item) => {
1046
+ const template = templateByPath.get(item.path);
1047
+ return template
1048
+ ? `/${template.name}`
1049
+ : this.formatDisplayPath(item.path);
1050
+ },
1051
+ });
1052
+ const promptCompactList = formatCompactList(templates.map((template) => `/${template.name}`));
1053
+ addLoadedSection("Prompts", promptCompactList, templateList);
1054
+ }
1055
+ if (extensions.length > 0) {
1056
+ const groups = this.buildScopeGroups(extensions);
1057
+ const extList = this.formatScopeGroups(groups, {
1058
+ formatPath: (item) => this.formatExtensionDisplayPath(item.path),
1059
+ formatPackagePath: (item) => this.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),
1060
+ });
1061
+ const extensionCompactList = formatCompactList(this.getCompactExtensionLabels(extensions));
1062
+ addLoadedSection("Extensions", extensionCompactList, extList, "mdHeading");
1063
+ }
1064
+ // Show loaded themes (excluding built-in)
1065
+ const loadedThemes = themesResult.themes;
1066
+ const customThemes = loadedThemes.filter((t) => t.sourcePath);
1067
+ if (customThemes.length > 0) {
1068
+ const groups = this.buildScopeGroups(customThemes.map((loadedTheme) => ({
1069
+ path: loadedTheme.sourcePath,
1070
+ sourceInfo: loadedTheme.sourceInfo,
1071
+ })));
1072
+ const themeList = this.formatScopeGroups(groups, {
1073
+ formatPath: (item) => this.formatDisplayPath(item.path),
1074
+ formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
1075
+ });
1076
+ const themeCompactList = formatCompactList(customThemes.map((loadedTheme) => loadedTheme.name ??
1077
+ this.getCompactPathLabel(loadedTheme.sourcePath, loadedTheme.sourceInfo)));
1078
+ addLoadedSection("Themes", themeCompactList, themeList);
1079
+ }
1080
+ }
1081
+ if (showDiagnostics) {
1082
+ const skillDiagnostics = skillsResult.diagnostics;
1083
+ if (skillDiagnostics.length > 0) {
1084
+ const warningLines = this.formatDiagnostics(skillDiagnostics, sourceInfos);
1085
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Skill conflicts]")}\n${warningLines}`, 0, 0));
1086
+ this.chatContainer.addChild(new Spacer(1));
1087
+ }
1088
+ const promptDiagnostics = promptsResult.diagnostics;
1089
+ if (promptDiagnostics.length > 0) {
1090
+ const warningLines = this.formatDiagnostics(promptDiagnostics, sourceInfos);
1091
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Prompt conflicts]")}\n${warningLines}`, 0, 0));
1092
+ this.chatContainer.addChild(new Spacer(1));
1093
+ }
1094
+ const extensionDiagnostics = [];
1095
+ const extensionErrors = this.session.resourceLoader.getExtensions().errors;
1096
+ if (extensionErrors.length > 0) {
1097
+ for (const error of extensionErrors) {
1098
+ extensionDiagnostics.push({
1099
+ type: "error",
1100
+ message: error.error,
1101
+ path: error.path,
1102
+ });
1103
+ }
1104
+ }
1105
+ const commandDiagnostics = this.session.extensionRunner.getCommandDiagnostics();
1106
+ extensionDiagnostics.push(...commandDiagnostics);
1107
+ extensionDiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));
1108
+ const shortcutDiagnostics = this.session.extensionRunner.getShortcutDiagnostics();
1109
+ extensionDiagnostics.push(...shortcutDiagnostics);
1110
+ if (extensionDiagnostics.length > 0) {
1111
+ const warningLines = this.formatDiagnostics(extensionDiagnostics, sourceInfos);
1112
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Extension issues]")}\n${warningLines}`, 0, 0));
1113
+ this.chatContainer.addChild(new Spacer(1));
1114
+ }
1115
+ const themeDiagnostics = themesResult.diagnostics;
1116
+ if (themeDiagnostics.length > 0) {
1117
+ const warningLines = this.formatDiagnostics(themeDiagnostics, sourceInfos);
1118
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Theme conflicts]")}\n${warningLines}`, 0, 0));
1119
+ this.chatContainer.addChild(new Spacer(1));
1120
+ }
1121
+ }
1122
+ }
1123
+ /**
1124
+ * Initialize the extension system with TUI-based UI context.
1125
+ */
1126
+ async bindCurrentSessionExtensions() {
1127
+ const uiContext = this.createExtensionUIContext();
1128
+ await this.session.bindExtensions({
1129
+ uiContext,
1130
+ commandContextActions: {
1131
+ waitForIdle: () => this.session.agent.waitForIdle(),
1132
+ newSession: async (options) => {
1133
+ if (this.loadingAnimation) {
1134
+ this.loadingAnimation.stop();
1135
+ this.loadingAnimation = undefined;
1136
+ }
1137
+ this.statusContainer.clear();
1138
+ try {
1139
+ const result = await this.runtimeHost.newSession(options);
1140
+ if (!result.cancelled) {
1141
+ this.renderCurrentSessionState();
1142
+ this.ui.requestRender();
1143
+ }
1144
+ return result;
1145
+ }
1146
+ catch (error) {
1147
+ return this.handleFatalRuntimeError("Failed to create session", error);
1148
+ }
1149
+ },
1150
+ fork: async (entryId, options) => {
1151
+ try {
1152
+ const result = await this.runtimeHost.fork(entryId, options);
1153
+ if (!result.cancelled) {
1154
+ this.renderCurrentSessionState();
1155
+ this.editor.setText(result.selectedText ?? "");
1156
+ this.showStatus("Forked to new session");
1157
+ }
1158
+ return { cancelled: result.cancelled };
1159
+ }
1160
+ catch (error) {
1161
+ return this.handleFatalRuntimeError("Failed to fork session", error);
1162
+ }
1163
+ },
1164
+ navigateTree: async (targetId, options) => {
1165
+ const result = await this.session.navigateTree(targetId, {
1166
+ summarize: options?.summarize,
1167
+ customInstructions: options?.customInstructions,
1168
+ replaceInstructions: options?.replaceInstructions,
1169
+ label: options?.label,
1170
+ });
1171
+ if (result.cancelled) {
1172
+ return { cancelled: true };
1173
+ }
1174
+ this.chatContainer.clear();
1175
+ this.renderInitialMessages();
1176
+ if (result.editorText && !this.editor.getText().trim()) {
1177
+ this.editor.setText(result.editorText);
1178
+ }
1179
+ this.showStatus("Navigated to selected point");
1180
+ void this.flushCompactionQueue({ willRetry: false });
1181
+ return { cancelled: false };
1182
+ },
1183
+ switchSession: async (sessionPath, options) => {
1184
+ return this.handleResumeSession(sessionPath, options);
1185
+ },
1186
+ reload: async () => {
1187
+ await this.handleReloadCommand();
1188
+ },
1189
+ },
1190
+ shutdownHandler: () => {
1191
+ this.shutdownRequested = true;
1192
+ if (!this.session.isStreaming) {
1193
+ void this.shutdown();
1194
+ }
1195
+ },
1196
+ onError: (error) => {
1197
+ this.showExtensionError(error.extensionPath, error.error, error.stack);
1198
+ },
1199
+ });
1200
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
1201
+ this.setupAutocompleteProvider();
1202
+ const extensionRunner = this.session.extensionRunner;
1203
+ this.setupExtensionShortcuts(extensionRunner);
1204
+ this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });
1205
+ this.showStartupNoticesIfNeeded();
1206
+ }
1207
+ applyRuntimeSettings() {
1208
+ this.footer.setSession(this.session);
1209
+ this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);
1210
+ this.footerDataProvider.setCwd(this.sessionManager.getCwd());
1211
+ this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
1212
+ this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());
1213
+ this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
1214
+ const editorPaddingX = this.settingsManager.getEditorPaddingX();
1215
+ const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
1216
+ this.defaultEditor.setPaddingX(editorPaddingX);
1217
+ this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);
1218
+ if (this.editor !== this.defaultEditor) {
1219
+ this.editor.setPaddingX?.(editorPaddingX);
1220
+ this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);
1221
+ }
1222
+ }
1223
+ async rebindCurrentSession() {
1224
+ this.unsubscribe?.();
1225
+ this.unsubscribe = undefined;
1226
+ this.applyRuntimeSettings();
1227
+ await this.bindCurrentSessionExtensions();
1228
+ this.subscribeToAgent();
1229
+ await this.updateAvailableProviderCount();
1230
+ this.updateEditorBorderColor();
1231
+ this.updateTerminalTitle();
1232
+ }
1233
+ async handleFatalRuntimeError(prefix, error) {
1234
+ const message = error instanceof Error ? error.message : String(error);
1235
+ this.showError(`${prefix}: ${message}`);
1236
+ stopThemeWatcher();
1237
+ this.stop();
1238
+ process.exit(1);
1239
+ }
1240
+ renderCurrentSessionState() {
1241
+ this.chatContainer.clear();
1242
+ this.pendingMessagesContainer.clear();
1243
+ this.compactionQueuedMessages = [];
1244
+ this.streamingComponent = undefined;
1245
+ this.streamingMessage = undefined;
1246
+ this.pendingTools.clear();
1247
+ this.renderInitialMessages();
1248
+ }
1249
+ /**
1250
+ * Get a registered tool definition by name (for custom rendering).
1251
+ */
1252
+ getRegisteredToolDefinition(toolName) {
1253
+ return this.session.getToolDefinition(toolName);
1254
+ }
1255
+ /**
1256
+ * Set up keyboard shortcuts registered by extensions.
1257
+ */
1258
+ setupExtensionShortcuts(extensionRunner) {
1259
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
1260
+ if (shortcuts.size === 0)
1261
+ return;
1262
+ // Create a context for shortcut handlers
1263
+ const createContext = () => ({
1264
+ ui: this.createExtensionUIContext(),
1265
+ hasUI: true,
1266
+ cwd: this.sessionManager.getCwd(),
1267
+ sessionManager: this.sessionManager,
1268
+ modelRegistry: this.session.modelRegistry,
1269
+ model: this.session.model,
1270
+ isIdle: () => !this.session.isStreaming,
1271
+ signal: this.session.agent.signal,
1272
+ abort: () => this.session.abort(),
1273
+ hasPendingMessages: () => this.session.pendingMessageCount > 0,
1274
+ shutdown: () => {
1275
+ this.shutdownRequested = true;
1276
+ },
1277
+ getContextUsage: () => this.session.getContextUsage(),
1278
+ compact: (options) => {
1279
+ void (async () => {
1280
+ try {
1281
+ const result = await this.session.compact(options?.customInstructions);
1282
+ options?.onComplete?.(result);
1283
+ }
1284
+ catch (error) {
1285
+ const err = error instanceof Error ? error : new Error(String(error));
1286
+ options?.onError?.(err);
1287
+ }
1288
+ })();
1289
+ },
1290
+ getSystemPrompt: () => this.session.systemPrompt,
1291
+ });
1292
+ // Set up the extension shortcut handler on the default editor
1293
+ this.defaultEditor.onExtensionShortcut = (data) => {
1294
+ for (const [shortcutStr, shortcut] of shortcuts) {
1295
+ // Cast to KeyId - extension shortcuts use the same format
1296
+ if (matchesKey(data, shortcutStr)) {
1297
+ // Run handler async, don't block input
1298
+ Promise.resolve(shortcut.handler(createContext())).catch((err) => {
1299
+ this.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);
1300
+ });
1301
+ return true;
1302
+ }
1303
+ }
1304
+ return false;
1305
+ };
1306
+ }
1307
+ /**
1308
+ * Set extension status text in the footer.
1309
+ */
1310
+ setExtensionStatus(key, text) {
1311
+ this.footerDataProvider.setExtensionStatus(key, text);
1312
+ this.ui.requestRender();
1313
+ }
1314
+ getWorkingLoaderMessage() {
1315
+ return this.workingMessage ?? this.defaultWorkingMessage;
1316
+ }
1317
+ createWorkingLoader() {
1318
+ return new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), this.getWorkingLoaderMessage(), this.workingIndicatorOptions);
1319
+ }
1320
+ stopWorkingLoader() {
1321
+ if (this.loadingAnimation) {
1322
+ this.loadingAnimation.stop();
1323
+ this.loadingAnimation = undefined;
1324
+ }
1325
+ this.statusContainer.clear();
1326
+ }
1327
+ setWorkingVisible(visible) {
1328
+ this.workingVisible = visible;
1329
+ if (!visible) {
1330
+ this.stopWorkingLoader();
1331
+ this.ui.requestRender();
1332
+ return;
1333
+ }
1334
+ if (this.session.isStreaming && !this.loadingAnimation) {
1335
+ this.statusContainer.clear();
1336
+ this.loadingAnimation = this.createWorkingLoader();
1337
+ this.statusContainer.addChild(this.loadingAnimation);
1338
+ }
1339
+ this.ui.requestRender();
1340
+ }
1341
+ setWorkingIndicator(options) {
1342
+ this.workingIndicatorOptions = options;
1343
+ this.loadingAnimation?.setIndicator(options);
1344
+ this.ui.requestRender();
1345
+ }
1346
+ setHiddenThinkingLabel(label) {
1347
+ this.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;
1348
+ for (const child of this.chatContainer.children) {
1349
+ if (child instanceof AssistantMessageComponent) {
1350
+ child.setHiddenThinkingLabel(this.hiddenThinkingLabel);
1351
+ }
1352
+ }
1353
+ if (this.streamingComponent) {
1354
+ this.streamingComponent.setHiddenThinkingLabel(this.hiddenThinkingLabel);
1355
+ }
1356
+ this.ui.requestRender();
1357
+ }
1358
+ /**
1359
+ * Set an extension widget (string array or custom component).
1360
+ */
1361
+ setExtensionWidget(key, content, options) {
1362
+ const placement = options?.placement ?? "aboveEditor";
1363
+ const removeExisting = (map) => {
1364
+ const existing = map.get(key);
1365
+ if (existing?.dispose)
1366
+ existing.dispose();
1367
+ map.delete(key);
1368
+ };
1369
+ removeExisting(this.extensionWidgetsAbove);
1370
+ removeExisting(this.extensionWidgetsBelow);
1371
+ if (content === undefined) {
1372
+ this.renderWidgets();
1373
+ return;
1374
+ }
1375
+ let component;
1376
+ if (Array.isArray(content)) {
1377
+ // Wrap string array in a Container with Text components
1378
+ const container = new Container();
1379
+ for (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {
1380
+ container.addChild(new Text(line, 1, 0));
1381
+ }
1382
+ if (content.length > InteractiveMode.MAX_WIDGET_LINES) {
1383
+ container.addChild(new Text(theme.fg("muted", "... (widget truncated)"), 1, 0));
1384
+ }
1385
+ component = container;
1386
+ }
1387
+ else {
1388
+ // Factory function - create component
1389
+ component = content(this.ui, theme);
1390
+ }
1391
+ const targetMap = placement === "belowEditor"
1392
+ ? this.extensionWidgetsBelow
1393
+ : this.extensionWidgetsAbove;
1394
+ targetMap.set(key, component);
1395
+ this.renderWidgets();
1396
+ }
1397
+ clearExtensionWidgets() {
1398
+ for (const widget of this.extensionWidgetsAbove.values()) {
1399
+ widget.dispose?.();
1400
+ }
1401
+ for (const widget of this.extensionWidgetsBelow.values()) {
1402
+ widget.dispose?.();
1403
+ }
1404
+ this.extensionWidgetsAbove.clear();
1405
+ this.extensionWidgetsBelow.clear();
1406
+ this.renderWidgets();
1407
+ }
1408
+ resetExtensionUI() {
1409
+ if (this.extensionSelector) {
1410
+ this.hideExtensionSelector();
1411
+ }
1412
+ if (this.extensionInput) {
1413
+ this.hideExtensionInput();
1414
+ }
1415
+ if (this.extensionEditor) {
1416
+ this.hideExtensionEditor();
1417
+ }
1418
+ this.ui.hideOverlay();
1419
+ this.clearExtensionTerminalInputListeners();
1420
+ this.setExtensionFooter(undefined);
1421
+ this.setExtensionHeader(undefined);
1422
+ this.clearExtensionWidgets();
1423
+ this.footerDataProvider.clearExtensionStatuses();
1424
+ this.footer.invalidate();
1425
+ this.autocompleteProviderWrappers = [];
1426
+ this.setCustomEditorComponent(undefined);
1427
+ this.setupAutocompleteProvider();
1428
+ this.defaultEditor.onExtensionShortcut = undefined;
1429
+ this.updateTerminalTitle();
1430
+ this.workingMessage = undefined;
1431
+ this.workingVisible = true;
1432
+ this.setWorkingIndicator();
1433
+ if (this.loadingAnimation) {
1434
+ this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${keyText("app.interrupt")} to interrupt)`);
1435
+ }
1436
+ this.setHiddenThinkingLabel();
1437
+ }
1438
+ // Maximum total widget lines to prevent viewport overflow
1439
+ static { this.MAX_WIDGET_LINES = 10; }
1440
+ /**
1441
+ * Render all extension widgets to the widget container.
1442
+ */
1443
+ renderWidgets() {
1444
+ if (!this.widgetContainerAbove || !this.widgetContainerBelow)
1445
+ return;
1446
+ this.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);
1447
+ this.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);
1448
+ this.ui.requestRender();
1449
+ }
1450
+ renderWidgetContainer(container, widgets, spacerWhenEmpty, leadingSpacer) {
1451
+ container.clear();
1452
+ if (widgets.size === 0) {
1453
+ if (spacerWhenEmpty) {
1454
+ container.addChild(new Spacer(1));
1455
+ }
1456
+ return;
1457
+ }
1458
+ if (leadingSpacer) {
1459
+ container.addChild(new Spacer(1));
1460
+ }
1461
+ for (const component of widgets.values()) {
1462
+ container.addChild(component);
1463
+ }
1464
+ }
1465
+ /**
1466
+ * Set a custom footer component, or restore the built-in footer.
1467
+ */
1468
+ setExtensionFooter(factory) {
1469
+ // Dispose existing custom footer
1470
+ if (this.customFooter?.dispose) {
1471
+ this.customFooter.dispose();
1472
+ }
1473
+ // Remove current footer from UI
1474
+ if (this.customFooter) {
1475
+ this.ui.removeChild(this.customFooter);
1476
+ }
1477
+ else {
1478
+ this.ui.removeChild(this.footer);
1479
+ }
1480
+ if (factory) {
1481
+ // Create and add custom footer, passing the data provider
1482
+ this.customFooter = factory(this.ui, theme, this.footerDataProvider);
1483
+ this.ui.addChild(this.customFooter);
1484
+ }
1485
+ else {
1486
+ // Restore built-in footer
1487
+ this.customFooter = undefined;
1488
+ this.ui.addChild(this.footer);
1489
+ }
1490
+ this.ui.requestRender();
1491
+ }
1492
+ /**
1493
+ * Set a custom header component, or restore the built-in header.
1494
+ */
1495
+ setExtensionHeader(factory) {
1496
+ // Header may not be initialized yet if called during early initialization
1497
+ if (!this.builtInHeader) {
1498
+ return;
1499
+ }
1500
+ // Dispose existing custom header
1501
+ if (this.customHeader?.dispose) {
1502
+ this.customHeader.dispose();
1503
+ }
1504
+ // Find the index of the current header in the header container
1505
+ const currentHeader = this.customHeader || this.builtInHeader;
1506
+ const index = this.headerContainer.children.indexOf(currentHeader);
1507
+ if (factory) {
1508
+ // Create and add custom header
1509
+ this.customHeader = factory(this.ui, theme);
1510
+ if (isExpandable(this.customHeader)) {
1511
+ this.customHeader.setExpanded(this.toolOutputExpanded);
1512
+ }
1513
+ if (index !== -1) {
1514
+ this.headerContainer.children[index] = this.customHeader;
1515
+ }
1516
+ else {
1517
+ // If not found (e.g. builtInHeader was never added), add at the top
1518
+ this.headerContainer.children.unshift(this.customHeader);
1519
+ }
1520
+ }
1521
+ else {
1522
+ // Restore built-in header
1523
+ this.customHeader = undefined;
1524
+ if (isExpandable(this.builtInHeader)) {
1525
+ this.builtInHeader.setExpanded(this.toolOutputExpanded);
1526
+ }
1527
+ if (index !== -1) {
1528
+ this.headerContainer.children[index] = this.builtInHeader;
1529
+ }
1530
+ }
1531
+ this.ui.requestRender();
1532
+ }
1533
+ addExtensionTerminalInputListener(handler) {
1534
+ const unsubscribe = this.ui.addInputListener(handler);
1535
+ this.extensionTerminalInputUnsubscribers.add(unsubscribe);
1536
+ return () => {
1537
+ unsubscribe();
1538
+ this.extensionTerminalInputUnsubscribers.delete(unsubscribe);
1539
+ };
1540
+ }
1541
+ clearExtensionTerminalInputListeners() {
1542
+ for (const unsubscribe of this.extensionTerminalInputUnsubscribers) {
1543
+ unsubscribe();
1544
+ }
1545
+ this.extensionTerminalInputUnsubscribers.clear();
1546
+ }
1547
+ /**
1548
+ * Create the ExtensionUIContext for extensions.
1549
+ */
1550
+ createExtensionUIContext() {
1551
+ return {
1552
+ select: (title, options, opts) => this.showExtensionSelector(title, options, opts),
1553
+ confirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts),
1554
+ input: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts),
1555
+ notify: (message, type) => this.showExtensionNotify(message, type),
1556
+ onTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),
1557
+ setStatus: (key, text) => this.setExtensionStatus(key, text),
1558
+ setWorkingMessage: (message) => {
1559
+ this.workingMessage = message;
1560
+ if (this.loadingAnimation) {
1561
+ this.loadingAnimation.setMessage(message ?? this.defaultWorkingMessage);
1562
+ }
1563
+ },
1564
+ setWorkingVisible: (visible) => this.setWorkingVisible(visible),
1565
+ setWorkingIndicator: (options) => this.setWorkingIndicator(options),
1566
+ setHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label),
1567
+ setWidget: (key, content, options) => this.setExtensionWidget(key, content, options),
1568
+ setFooter: (factory) => this.setExtensionFooter(factory),
1569
+ setHeader: (factory) => this.setExtensionHeader(factory),
1570
+ setTitle: (title) => this.ui.terminal.setTitle(title),
1571
+ custom: (factory, options) => this.showExtensionCustom(factory, options),
1572
+ pasteToEditor: (text) => this.editor.handleInput(`\x1b[200~${text}\x1b[201~`),
1573
+ setEditorText: (text) => this.editor.setText(text),
1574
+ getEditorText: () => this.editor.getExpandedText?.() ?? this.editor.getText(),
1575
+ editor: (title, prefill) => this.showExtensionEditor(title, prefill),
1576
+ addAutocompleteProvider: (factory) => {
1577
+ this.autocompleteProviderWrappers.push(factory);
1578
+ this.setupAutocompleteProvider();
1579
+ },
1580
+ setEditorComponent: (factory) => this.setCustomEditorComponent(factory),
1581
+ getEditorComponent: () => this.editorComponentFactory,
1582
+ get theme() {
1583
+ return theme;
1584
+ },
1585
+ getAllThemes: () => getAvailableThemesWithPaths(),
1586
+ getTheme: (name) => getThemeByName(name),
1587
+ setTheme: (themeOrName) => {
1588
+ if (themeOrName instanceof Theme) {
1589
+ setThemeInstance(themeOrName);
1590
+ this.ui.requestRender();
1591
+ return { success: true };
1592
+ }
1593
+ const result = setTheme(themeOrName, true);
1594
+ if (result.success) {
1595
+ if (this.settingsManager.getTheme() !== themeOrName) {
1596
+ this.settingsManager.setTheme(themeOrName);
1597
+ }
1598
+ this.ui.requestRender();
1599
+ }
1600
+ return result;
1601
+ },
1602
+ getToolsExpanded: () => this.toolOutputExpanded,
1603
+ setToolsExpanded: (expanded) => this.setToolsExpanded(expanded),
1604
+ };
1605
+ }
1606
+ /**
1607
+ * Show a selector for extensions.
1608
+ */
1609
+ showExtensionSelector(title, options, opts) {
1610
+ return new Promise((resolve) => {
1611
+ if (opts?.signal?.aborted) {
1612
+ resolve(undefined);
1613
+ return;
1614
+ }
1615
+ const onAbort = () => {
1616
+ this.hideExtensionSelector();
1617
+ resolve(undefined);
1618
+ };
1619
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
1620
+ this.extensionSelector = new ExtensionSelectorComponent(title, options, (option) => {
1621
+ opts?.signal?.removeEventListener("abort", onAbort);
1622
+ this.hideExtensionSelector();
1623
+ resolve(option);
1624
+ }, () => {
1625
+ opts?.signal?.removeEventListener("abort", onAbort);
1626
+ this.hideExtensionSelector();
1627
+ resolve(undefined);
1628
+ }, {
1629
+ tui: this.ui,
1630
+ timeout: opts?.timeout,
1631
+ onToggleToolsExpanded: () => this.toggleToolOutputExpansion(),
1632
+ });
1633
+ this.editorContainer.clear();
1634
+ this.editorContainer.addChild(this.extensionSelector);
1635
+ this.ui.setFocus(this.extensionSelector);
1636
+ this.ui.requestRender();
1637
+ });
1638
+ }
1639
+ /**
1640
+ * Hide the extension selector.
1641
+ */
1642
+ hideExtensionSelector() {
1643
+ this.extensionSelector?.dispose();
1644
+ this.editorContainer.clear();
1645
+ this.editorContainer.addChild(this.editor);
1646
+ this.extensionSelector = undefined;
1647
+ this.ui.setFocus(this.editor);
1648
+ this.ui.requestRender();
1649
+ }
1650
+ /**
1651
+ * Show a confirmation dialog for extensions.
1652
+ */
1653
+ async showExtensionConfirm(title, message, opts) {
1654
+ const result = await this.showExtensionSelector(`${title}\n${message}`, ["Yes", "No"], opts);
1655
+ return result === "Yes";
1656
+ }
1657
+ async promptForMissingSessionCwd(error) {
1658
+ const confirmed = await this.showExtensionConfirm("Session cwd not found", formatMissingSessionCwdPrompt(error.issue));
1659
+ return confirmed ? error.issue.fallbackCwd : undefined;
1660
+ }
1661
+ /**
1662
+ * Show a text input for extensions.
1663
+ */
1664
+ showExtensionInput(title, placeholder, opts) {
1665
+ return new Promise((resolve) => {
1666
+ if (opts?.signal?.aborted) {
1667
+ resolve(undefined);
1668
+ return;
1669
+ }
1670
+ const onAbort = () => {
1671
+ this.hideExtensionInput();
1672
+ resolve(undefined);
1673
+ };
1674
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
1675
+ this.extensionInput = new ExtensionInputComponent(title, placeholder, (value) => {
1676
+ opts?.signal?.removeEventListener("abort", onAbort);
1677
+ this.hideExtensionInput();
1678
+ resolve(value);
1679
+ }, () => {
1680
+ opts?.signal?.removeEventListener("abort", onAbort);
1681
+ this.hideExtensionInput();
1682
+ resolve(undefined);
1683
+ }, { tui: this.ui, timeout: opts?.timeout });
1684
+ this.editorContainer.clear();
1685
+ this.editorContainer.addChild(this.extensionInput);
1686
+ this.ui.setFocus(this.extensionInput);
1687
+ this.ui.requestRender();
1688
+ });
1689
+ }
1690
+ /**
1691
+ * Hide the extension input.
1692
+ */
1693
+ hideExtensionInput() {
1694
+ this.extensionInput?.dispose();
1695
+ this.editorContainer.clear();
1696
+ this.editorContainer.addChild(this.editor);
1697
+ this.extensionInput = undefined;
1698
+ this.ui.setFocus(this.editor);
1699
+ this.ui.requestRender();
1700
+ }
1701
+ /**
1702
+ * Show a multi-line editor for extensions (with Ctrl+G support).
1703
+ */
1704
+ showExtensionEditor(title, prefill) {
1705
+ return new Promise((resolve) => {
1706
+ this.extensionEditor = new ExtensionEditorComponent(this.ui, this.keybindings, title, prefill, (value) => {
1707
+ this.hideExtensionEditor();
1708
+ resolve(value);
1709
+ }, () => {
1710
+ this.hideExtensionEditor();
1711
+ resolve(undefined);
1712
+ });
1713
+ this.editorContainer.clear();
1714
+ this.editorContainer.addChild(this.extensionEditor);
1715
+ this.ui.setFocus(this.extensionEditor);
1716
+ this.ui.requestRender();
1717
+ });
1718
+ }
1719
+ /**
1720
+ * Hide the extension editor.
1721
+ */
1722
+ hideExtensionEditor() {
1723
+ this.editorContainer.clear();
1724
+ this.editorContainer.addChild(this.editor);
1725
+ this.extensionEditor = undefined;
1726
+ this.ui.setFocus(this.editor);
1727
+ this.ui.requestRender();
1728
+ }
1729
+ /**
1730
+ * Set a custom editor component from an extension.
1731
+ * Pass undefined to restore the default editor.
1732
+ */
1733
+ setCustomEditorComponent(factory) {
1734
+ this.editorComponentFactory = factory;
1735
+ // Save text from current editor before switching
1736
+ const currentText = this.editor.getText();
1737
+ this.editorContainer.clear();
1738
+ if (factory) {
1739
+ // Create the custom editor with tui, theme, and keybindings
1740
+ const newEditor = factory(this.ui, getEditorTheme(), this.keybindings);
1741
+ // Wire up callbacks from the default editor
1742
+ newEditor.onSubmit = this.defaultEditor.onSubmit;
1743
+ newEditor.onChange = this.defaultEditor.onChange;
1744
+ // Copy text from previous editor
1745
+ newEditor.setText(currentText);
1746
+ // Copy appearance settings if supported
1747
+ if (newEditor.borderColor !== undefined) {
1748
+ newEditor.borderColor = this.defaultEditor.borderColor;
1749
+ }
1750
+ if (newEditor.setPaddingX !== undefined) {
1751
+ newEditor.setPaddingX(this.defaultEditor.getPaddingX());
1752
+ }
1753
+ // Set autocomplete if supported
1754
+ if (newEditor.setAutocompleteProvider && this.autocompleteProvider) {
1755
+ newEditor.setAutocompleteProvider(this.autocompleteProvider);
1756
+ }
1757
+ // If extending CustomEditor, copy app-level handlers
1758
+ // Use duck typing since instanceof fails across jiti module boundaries
1759
+ const customEditor = newEditor;
1760
+ if ("actionHandlers" in customEditor &&
1761
+ customEditor.actionHandlers instanceof Map) {
1762
+ if (!customEditor.onEscape) {
1763
+ customEditor.onEscape = () => this.defaultEditor.onEscape?.();
1764
+ }
1765
+ if (!customEditor.onCtrlD) {
1766
+ customEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.();
1767
+ }
1768
+ if (!customEditor.onPasteImage) {
1769
+ customEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.();
1770
+ }
1771
+ if (!customEditor.onExtensionShortcut) {
1772
+ customEditor.onExtensionShortcut = (data) => this.defaultEditor.onExtensionShortcut?.(data);
1773
+ }
1774
+ // Copy action handlers (clear, suspend, model switching, etc.)
1775
+ for (const [action, handler] of this.defaultEditor.actionHandlers) {
1776
+ customEditor.actionHandlers.set(action, handler);
1777
+ }
1778
+ }
1779
+ this.editor = newEditor;
1780
+ }
1781
+ else {
1782
+ // Restore default editor with text from custom editor
1783
+ this.defaultEditor.setText(currentText);
1784
+ this.editor = this.defaultEditor;
1785
+ }
1786
+ this.editorContainer.addChild(this.editor);
1787
+ this.ui.setFocus(this.editor);
1788
+ this.ui.requestRender();
1789
+ }
1790
+ /**
1791
+ * Show a notification for extensions.
1792
+ */
1793
+ showExtensionNotify(message, type) {
1794
+ if (type === "error") {
1795
+ this.showError(message);
1796
+ }
1797
+ else if (type === "warning") {
1798
+ this.showWarning(message);
1799
+ }
1800
+ else {
1801
+ this.showStatus(message);
1802
+ }
1803
+ }
1804
+ /** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */
1805
+ async showExtensionCustom(factory, options) {
1806
+ const savedText = this.editor.getText();
1807
+ const isOverlay = options?.overlay ?? false;
1808
+ const restoreEditor = () => {
1809
+ this.editorContainer.clear();
1810
+ this.editorContainer.addChild(this.editor);
1811
+ this.editor.setText(savedText);
1812
+ this.ui.setFocus(this.editor);
1813
+ this.ui.requestRender();
1814
+ };
1815
+ return new Promise((resolve, reject) => {
1816
+ let component;
1817
+ let closed = false;
1818
+ const close = (result) => {
1819
+ if (closed)
1820
+ return;
1821
+ closed = true;
1822
+ if (isOverlay)
1823
+ this.ui.hideOverlay();
1824
+ else
1825
+ restoreEditor();
1826
+ // Note: both branches above already call requestRender
1827
+ resolve(result);
1828
+ try {
1829
+ component?.dispose?.();
1830
+ }
1831
+ catch {
1832
+ /* ignore dispose errors */
1833
+ }
1834
+ };
1835
+ Promise.resolve(factory(this.ui, theme, this.keybindings, close))
1836
+ .then((c) => {
1837
+ if (closed)
1838
+ return;
1839
+ component = c;
1840
+ if (isOverlay) {
1841
+ // Resolve overlay options - can be static or dynamic function
1842
+ const resolveOptions = () => {
1843
+ if (options?.overlayOptions) {
1844
+ const opts = typeof options.overlayOptions === "function"
1845
+ ? options.overlayOptions()
1846
+ : options.overlayOptions;
1847
+ return opts;
1848
+ }
1849
+ // Fallback: use component's width property if available
1850
+ const w = component.width;
1851
+ return w ? { width: w } : undefined;
1852
+ };
1853
+ const handle = this.ui.showOverlay(component, resolveOptions());
1854
+ // Expose handle to caller for visibility control
1855
+ options?.onHandle?.(handle);
1856
+ }
1857
+ else {
1858
+ this.editorContainer.clear();
1859
+ this.editorContainer.addChild(component);
1860
+ this.ui.setFocus(component);
1861
+ this.ui.requestRender();
1862
+ }
1863
+ })
1864
+ .catch((err) => {
1865
+ if (closed)
1866
+ return;
1867
+ if (!isOverlay)
1868
+ restoreEditor();
1869
+ reject(err);
1870
+ });
1871
+ });
1872
+ }
1873
+ /**
1874
+ * Show an extension error in the UI.
1875
+ */
1876
+ showExtensionError(extensionPath, error, stack) {
1877
+ const errorMsg = `Extension "${extensionPath}" error: ${error}`;
1878
+ const errorText = new Text(theme.fg("error", errorMsg), 1, 0);
1879
+ this.chatContainer.addChild(errorText);
1880
+ if (stack) {
1881
+ // Show stack trace in dim color, indented
1882
+ const stackLines = stack
1883
+ .split("\n")
1884
+ .slice(1) // Skip first line (duplicates error message)
1885
+ .map((line) => theme.fg("dim", ` ${line.trim()}`))
1886
+ .join("\n");
1887
+ if (stackLines) {
1888
+ this.chatContainer.addChild(new Text(stackLines, 1, 0));
1889
+ }
1890
+ }
1891
+ this.ui.requestRender();
1892
+ }
1893
+ // =========================================================================
1894
+ // Key Handlers
1895
+ // =========================================================================
1896
+ setupKeyHandlers() {
1897
+ // Set up handlers on defaultEditor - they use this.editor for text access
1898
+ // so they work correctly regardless of which editor is active
1899
+ this.defaultEditor.onEscape = () => {
1900
+ if (this.session.isStreaming) {
1901
+ this.restoreQueuedMessagesToEditor({ abort: true });
1902
+ }
1903
+ else if (this.session.isBashRunning) {
1904
+ this.session.abortBash();
1905
+ }
1906
+ else if (this.isBashMode) {
1907
+ this.editor.setText("");
1908
+ this.isBashMode = false;
1909
+ this.updateEditorBorderColor();
1910
+ }
1911
+ else if (!this.editor.getText().trim()) {
1912
+ // Double-escape with empty editor triggers /tree, /fork, or nothing based on setting
1913
+ const action = this.settingsManager.getDoubleEscapeAction();
1914
+ if (action !== "none") {
1915
+ const now = Date.now();
1916
+ if (now - this.lastEscapeTime < 500) {
1917
+ if (action === "tree") {
1918
+ this.showTreeSelector();
1919
+ }
1920
+ else {
1921
+ this.showUserMessageSelector();
1922
+ }
1923
+ this.lastEscapeTime = 0;
1924
+ }
1925
+ else {
1926
+ this.lastEscapeTime = now;
1927
+ }
1928
+ }
1929
+ }
1930
+ };
1931
+ // Register app action handlers
1932
+ this.defaultEditor.onAction("app.clear", () => this.handleCtrlC());
1933
+ this.defaultEditor.onCtrlD = () => this.handleCtrlD();
1934
+ this.defaultEditor.onAction("app.suspend", () => this.handleCtrlZ());
1935
+ this.defaultEditor.onAction("app.thinking.cycle", () => this.cycleThinkingLevel());
1936
+ this.defaultEditor.onAction("app.model.cycleForward", () => this.cycleModel("forward"));
1937
+ this.defaultEditor.onAction("app.model.cycleBackward", () => this.cycleModel("backward"));
1938
+ // Global debug handler on TUI (works regardless of focus)
1939
+ this.ui.onDebug = () => this.handleDebugCommand();
1940
+ this.defaultEditor.onAction("app.model.select", () => this.showModelSelector());
1941
+ this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());
1942
+ this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());
1943
+ this.defaultEditor.onAction("app.editor.external", () => this.openExternalEditor());
1944
+ this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp());
1945
+ this.defaultEditor.onAction("app.message.dequeue", () => this.handleDequeue());
1946
+ this.defaultEditor.onAction("app.session.new", () => this.handleClearCommand());
1947
+ this.defaultEditor.onAction("app.session.tree", () => this.showTreeSelector());
1948
+ this.defaultEditor.onAction("app.session.fork", () => this.showUserMessageSelector());
1949
+ this.defaultEditor.onAction("app.session.resume", () => this.showSessionSelector());
1950
+ this.defaultEditor.onChange = (text) => {
1951
+ const wasBashMode = this.isBashMode;
1952
+ this.isBashMode = text.trimStart().startsWith("!");
1953
+ if (wasBashMode !== this.isBashMode) {
1954
+ this.updateEditorBorderColor();
1955
+ }
1956
+ };
1957
+ // Handle clipboard image paste (triggered on Ctrl+V)
1958
+ this.defaultEditor.onPasteImage = () => {
1959
+ this.handleClipboardImagePaste();
1960
+ };
1961
+ }
1962
+ async handleClipboardImagePaste() {
1963
+ try {
1964
+ const image = await readClipboardImage();
1965
+ if (!image) {
1966
+ return;
1967
+ }
1968
+ // Write to temp file
1969
+ const tmpDir = os.tmpdir();
1970
+ const ext = extensionForImageMimeType(image.mimeType) ?? "png";
1971
+ const fileName = `pi-clipboard-${crypto.randomUUID()}.${ext}`;
1972
+ const filePath = path.join(tmpDir, fileName);
1973
+ fs.writeFileSync(filePath, Buffer.from(image.bytes));
1974
+ // Insert file path directly
1975
+ this.editor.insertTextAtCursor?.(filePath);
1976
+ this.ui.requestRender();
1977
+ }
1978
+ catch {
1979
+ // Silently ignore clipboard errors (may not have permission, etc.)
1980
+ }
1981
+ }
1982
+ setupEditorSubmitHandler() {
1983
+ this.defaultEditor.onSubmit = async (text) => {
1984
+ text = text.trim();
1985
+ if (!text)
1986
+ return;
1987
+ // Handle commands
1988
+ if (text === "/settings") {
1989
+ this.showSettingsSelector();
1990
+ this.editor.setText("");
1991
+ return;
1992
+ }
1993
+ if (text === "/scoped-models") {
1994
+ this.editor.setText("");
1995
+ await this.showModelsSelector();
1996
+ return;
1997
+ }
1998
+ if (text === "/model" || text.startsWith("/model ")) {
1999
+ const searchTerm = text.startsWith("/model ")
2000
+ ? text.slice(7).trim()
2001
+ : undefined;
2002
+ this.editor.setText("");
2003
+ await this.handleModelCommand(searchTerm);
2004
+ return;
2005
+ }
2006
+ if (text === "/export" || text.startsWith("/export ")) {
2007
+ await this.handleExportCommand(text);
2008
+ this.editor.setText("");
2009
+ return;
2010
+ }
2011
+ if (text === "/import" || text.startsWith("/import ")) {
2012
+ await this.handleImportCommand(text);
2013
+ this.editor.setText("");
2014
+ return;
2015
+ }
2016
+ if (text === "/share") {
2017
+ await this.handleShareCommand();
2018
+ this.editor.setText("");
2019
+ return;
2020
+ }
2021
+ if (text === "/copy") {
2022
+ await this.handleCopyCommand();
2023
+ this.editor.setText("");
2024
+ return;
2025
+ }
2026
+ if (text === "/name" || text.startsWith("/name ")) {
2027
+ this.handleNameCommand(text);
2028
+ this.editor.setText("");
2029
+ return;
2030
+ }
2031
+ if (text === "/session") {
2032
+ this.handleSessionCommand();
2033
+ this.editor.setText("");
2034
+ return;
2035
+ }
2036
+ if (text === "/changelog") {
2037
+ this.handleChangelogCommand();
2038
+ this.editor.setText("");
2039
+ return;
2040
+ }
2041
+ if (text === "/hotkeys") {
2042
+ this.handleHotkeysCommand();
2043
+ this.editor.setText("");
2044
+ return;
2045
+ }
2046
+ if (text === "/fork") {
2047
+ this.showUserMessageSelector();
2048
+ this.editor.setText("");
2049
+ return;
2050
+ }
2051
+ if (text === "/clone") {
2052
+ this.editor.setText("");
2053
+ await this.handleCloneCommand();
2054
+ return;
2055
+ }
2056
+ if (text === "/tree") {
2057
+ this.showTreeSelector();
2058
+ this.editor.setText("");
2059
+ return;
2060
+ }
2061
+ if (text === "/login") {
2062
+ this.showOAuthSelector("login");
2063
+ this.editor.setText("");
2064
+ return;
2065
+ }
2066
+ if (text === "/logout") {
2067
+ this.showOAuthSelector("logout");
2068
+ this.editor.setText("");
2069
+ return;
2070
+ }
2071
+ if (text === "/new") {
2072
+ this.editor.setText("");
2073
+ await this.handleClearCommand();
2074
+ return;
2075
+ }
2076
+ if (text === "/compact" || text.startsWith("/compact ")) {
2077
+ const customInstructions = text.startsWith("/compact ")
2078
+ ? text.slice(9).trim()
2079
+ : undefined;
2080
+ this.editor.setText("");
2081
+ await this.handleCompactCommand(customInstructions);
2082
+ return;
2083
+ }
2084
+ if (text === "/reload") {
2085
+ this.editor.setText("");
2086
+ await this.handleReloadCommand();
2087
+ return;
2088
+ }
2089
+ if (text === "/debug") {
2090
+ this.handleDebugCommand();
2091
+ this.editor.setText("");
2092
+ return;
2093
+ }
2094
+ if (text === "/arminsayshi") {
2095
+ this.handleArminSaysHi();
2096
+ this.editor.setText("");
2097
+ return;
2098
+ }
2099
+ if (text === "/dementedelves") {
2100
+ this.handleDementedDelves();
2101
+ this.editor.setText("");
2102
+ return;
2103
+ }
2104
+ if (text === "/resume") {
2105
+ this.showSessionSelector();
2106
+ this.editor.setText("");
2107
+ return;
2108
+ }
2109
+ if (text === "/quit") {
2110
+ this.editor.setText("");
2111
+ await this.shutdown();
2112
+ return;
2113
+ }
2114
+ // Handle bash command (! for normal, !! for excluded from context)
2115
+ if (text.startsWith("!")) {
2116
+ const isExcluded = text.startsWith("!!");
2117
+ const command = isExcluded
2118
+ ? text.slice(2).trim()
2119
+ : text.slice(1).trim();
2120
+ if (command) {
2121
+ if (this.session.isBashRunning) {
2122
+ this.showWarning("A bash command is already running. Press Esc to cancel it first.");
2123
+ this.editor.setText(text);
2124
+ return;
2125
+ }
2126
+ this.editor.addToHistory?.(text);
2127
+ await this.handleBashCommand(command, isExcluded);
2128
+ this.isBashMode = false;
2129
+ this.updateEditorBorderColor();
2130
+ return;
2131
+ }
2132
+ }
2133
+ // Queue input during compaction (extension commands execute immediately)
2134
+ if (this.session.isCompacting) {
2135
+ if (this.isExtensionCommand(text)) {
2136
+ this.editor.addToHistory?.(text);
2137
+ this.editor.setText("");
2138
+ await this.session.prompt(text);
2139
+ }
2140
+ else {
2141
+ this.queueCompactionMessage(text, "steer");
2142
+ }
2143
+ return;
2144
+ }
2145
+ // If streaming, use prompt() with steer behavior
2146
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
2147
+ if (this.session.isStreaming) {
2148
+ this.editor.addToHistory?.(text);
2149
+ this.editor.setText("");
2150
+ await this.session.prompt(text, { streamingBehavior: "steer" });
2151
+ this.updatePendingMessagesDisplay();
2152
+ this.ui.requestRender();
2153
+ return;
2154
+ }
2155
+ // Normal message submission
2156
+ // First, move any pending bash components to chat
2157
+ this.flushPendingBashComponents();
2158
+ if (this.onInputCallback) {
2159
+ this.onInputCallback(text);
2160
+ }
2161
+ this.editor.addToHistory?.(text);
2162
+ };
2163
+ }
2164
+ subscribeToAgent() {
2165
+ this.unsubscribe = this.session.subscribe(async (event) => {
2166
+ await this.handleEvent(event);
2167
+ });
2168
+ }
2169
+ async handleEvent(event) {
2170
+ if (!this.isInitialized) {
2171
+ await this.init();
2172
+ }
2173
+ this.footer.invalidate();
2174
+ switch (event.type) {
2175
+ case "agent_start":
2176
+ this.pendingTools.clear();
2177
+ if (this.settingsManager.getShowTerminalProgress()) {
2178
+ this.ui.terminal.setProgress(true);
2179
+ }
2180
+ // Restore main escape handler if retry handler is still active
2181
+ // (retry success event fires later, but we need main handler now)
2182
+ if (this.retryEscapeHandler) {
2183
+ this.defaultEditor.onEscape = this.retryEscapeHandler;
2184
+ this.retryEscapeHandler = undefined;
2185
+ }
2186
+ if (this.retryCountdown) {
2187
+ this.retryCountdown.dispose();
2188
+ this.retryCountdown = undefined;
2189
+ }
2190
+ if (this.retryLoader) {
2191
+ this.retryLoader.stop();
2192
+ this.retryLoader = undefined;
2193
+ }
2194
+ this.stopWorkingLoader();
2195
+ if (this.workingVisible) {
2196
+ this.loadingAnimation = this.createWorkingLoader();
2197
+ this.statusContainer.addChild(this.loadingAnimation);
2198
+ }
2199
+ this.ui.requestRender();
2200
+ break;
2201
+ case "turn_start": {
2202
+ this.workingMessage = pickWhimsicalWorkingMessage();
2203
+ if (this.loadingAnimation) {
2204
+ this.loadingAnimation.setMessage(this.workingMessage);
2205
+ }
2206
+ break;
2207
+ }
2208
+ case "turn_end": {
2209
+ this.workingMessage = undefined;
2210
+ if (this.loadingAnimation) {
2211
+ this.loadingAnimation.setMessage(this.defaultWorkingMessage);
2212
+ }
2213
+ break;
2214
+ }
2215
+ case "queue_update":
2216
+ this.updatePendingMessagesDisplay();
2217
+ this.ui.requestRender();
2218
+ break;
2219
+ case "session_info_changed":
2220
+ this.updateTerminalTitle();
2221
+ this.footer.invalidate();
2222
+ this.ui.requestRender();
2223
+ break;
2224
+ case "thinking_level_changed":
2225
+ this.footer.invalidate();
2226
+ this.updateEditorBorderColor();
2227
+ break;
2228
+ case "message_start":
2229
+ if (event.message.role === "custom") {
2230
+ this.addMessageToChat(event.message);
2231
+ this.ui.requestRender();
2232
+ }
2233
+ else if (event.message.role === "user") {
2234
+ this.addMessageToChat(event.message);
2235
+ this.updatePendingMessagesDisplay();
2236
+ this.ui.requestRender();
2237
+ }
2238
+ else if (event.message.role === "assistant") {
2239
+ this.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel);
2240
+ this.streamingMessage = event.message;
2241
+ this.chatContainer.addChild(this.streamingComponent);
2242
+ this.streamingComponent.updateContent(this.streamingMessage);
2243
+ this.ui.requestRender();
2244
+ }
2245
+ break;
2246
+ case "message_update":
2247
+ if (this.streamingComponent && event.message.role === "assistant") {
2248
+ this.streamingMessage = event.message;
2249
+ this.streamingComponent.updateContent(this.streamingMessage);
2250
+ for (const content of this.streamingMessage.content) {
2251
+ if (content.type === "toolCall") {
2252
+ if (!this.pendingTools.has(content.id)) {
2253
+ const component = new ToolExecutionComponent(content.name, content.id, content.arguments, {
2254
+ showImages: this.settingsManager.getShowImages(),
2255
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
2256
+ }, this.getRegisteredToolDefinition(content.name), this.ui, this.sessionManager.getCwd());
2257
+ component.setExpanded(this.toolOutputExpanded);
2258
+ this.chatContainer.addChild(component);
2259
+ this.pendingTools.set(content.id, component);
2260
+ }
2261
+ else {
2262
+ const component = this.pendingTools.get(content.id);
2263
+ if (component) {
2264
+ component.updateArgs(content.arguments);
2265
+ }
2266
+ }
2267
+ }
2268
+ }
2269
+ this.ui.requestRender();
2270
+ }
2271
+ break;
2272
+ case "message_end":
2273
+ if (event.message.role === "user")
2274
+ break;
2275
+ if (this.streamingComponent && event.message.role === "assistant") {
2276
+ this.streamingMessage = event.message;
2277
+ let errorMessage;
2278
+ if (this.streamingMessage.stopReason === "aborted") {
2279
+ const retryAttempt = this.session.retryAttempt;
2280
+ errorMessage =
2281
+ retryAttempt > 0
2282
+ ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
2283
+ : "Operation aborted";
2284
+ this.streamingMessage.errorMessage = errorMessage;
2285
+ }
2286
+ this.streamingComponent.updateContent(this.streamingMessage);
2287
+ if (this.streamingMessage.stopReason === "aborted" ||
2288
+ this.streamingMessage.stopReason === "error") {
2289
+ if (!errorMessage) {
2290
+ errorMessage = this.streamingMessage.errorMessage || "Error";
2291
+ }
2292
+ for (const [, component] of this.pendingTools.entries()) {
2293
+ component.updateResult({
2294
+ content: [{ type: "text", text: errorMessage }],
2295
+ isError: true,
2296
+ });
2297
+ }
2298
+ this.pendingTools.clear();
2299
+ }
2300
+ else {
2301
+ // Args are now complete - trigger diff computation for edit tools
2302
+ for (const [, component] of this.pendingTools.entries()) {
2303
+ component.setArgsComplete();
2304
+ }
2305
+ }
2306
+ this.streamingComponent = undefined;
2307
+ this.streamingMessage = undefined;
2308
+ this.footer.invalidate();
2309
+ }
2310
+ this.ui.requestRender();
2311
+ break;
2312
+ case "tool_execution_start": {
2313
+ let component = this.pendingTools.get(event.toolCallId);
2314
+ if (!component) {
2315
+ component = new ToolExecutionComponent(event.toolName, event.toolCallId, event.args, {
2316
+ showImages: this.settingsManager.getShowImages(),
2317
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
2318
+ }, this.getRegisteredToolDefinition(event.toolName), this.ui, this.sessionManager.getCwd());
2319
+ component.setExpanded(this.toolOutputExpanded);
2320
+ this.chatContainer.addChild(component);
2321
+ this.pendingTools.set(event.toolCallId, component);
2322
+ }
2323
+ component.markExecutionStarted();
2324
+ this.ui.requestRender();
2325
+ break;
2326
+ }
2327
+ case "tool_execution_update": {
2328
+ const component = this.pendingTools.get(event.toolCallId);
2329
+ if (component) {
2330
+ component.updateResult({ ...event.partialResult, isError: false }, true);
2331
+ this.ui.requestRender();
2332
+ }
2333
+ break;
2334
+ }
2335
+ case "tool_execution_end": {
2336
+ const component = this.pendingTools.get(event.toolCallId);
2337
+ if (component) {
2338
+ component.updateResult({ ...event.result, isError: event.isError });
2339
+ this.pendingTools.delete(event.toolCallId);
2340
+ this.ui.requestRender();
2341
+ }
2342
+ break;
2343
+ }
2344
+ case "agent_end":
2345
+ if (this.settingsManager.getShowTerminalProgress()) {
2346
+ this.ui.terminal.setProgress(false);
2347
+ }
2348
+ if (this.loadingAnimation) {
2349
+ this.loadingAnimation.stop();
2350
+ this.loadingAnimation = undefined;
2351
+ this.statusContainer.clear();
2352
+ }
2353
+ if (this.streamingComponent) {
2354
+ this.chatContainer.removeChild(this.streamingComponent);
2355
+ this.streamingComponent = undefined;
2356
+ this.streamingMessage = undefined;
2357
+ }
2358
+ this.pendingTools.clear();
2359
+ await this.checkShutdownRequested();
2360
+ this.ui.requestRender();
2361
+ break;
2362
+ case "compaction_start": {
2363
+ if (this.settingsManager.getShowTerminalProgress()) {
2364
+ this.ui.terminal.setProgress(true);
2365
+ }
2366
+ // Keep editor active; submissions are queued during compaction.
2367
+ this.autoCompactionEscapeHandler = this.defaultEditor.onEscape;
2368
+ this.defaultEditor.onEscape = () => {
2369
+ this.session.abortCompaction();
2370
+ };
2371
+ this.statusContainer.clear();
2372
+ const cancelHint = `(${keyText("app.interrupt")} to cancel)`;
2373
+ const label = event.reason === "manual"
2374
+ ? `Compacting context... ${cancelHint}`
2375
+ : `${event.reason === "overflow" ? "Context overflow detected, " : ""}Auto-compacting... ${cancelHint}`;
2376
+ this.autoCompactionLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), label);
2377
+ this.statusContainer.addChild(this.autoCompactionLoader);
2378
+ this.ui.requestRender();
2379
+ break;
2380
+ }
2381
+ case "compaction_end": {
2382
+ if (this.settingsManager.getShowTerminalProgress()) {
2383
+ this.ui.terminal.setProgress(false);
2384
+ }
2385
+ if (this.autoCompactionEscapeHandler) {
2386
+ this.defaultEditor.onEscape = this.autoCompactionEscapeHandler;
2387
+ this.autoCompactionEscapeHandler = undefined;
2388
+ }
2389
+ if (this.autoCompactionLoader) {
2390
+ this.autoCompactionLoader.stop();
2391
+ this.autoCompactionLoader = undefined;
2392
+ this.statusContainer.clear();
2393
+ }
2394
+ if (event.aborted) {
2395
+ if (event.reason === "manual") {
2396
+ this.showError("Compaction cancelled");
2397
+ }
2398
+ else {
2399
+ this.showStatus("Auto-compaction cancelled");
2400
+ }
2401
+ }
2402
+ else if (event.result) {
2403
+ this.chatContainer.clear();
2404
+ this.rebuildChatFromMessages();
2405
+ this.addMessageToChat(createCompactionSummaryMessage(event.result.summary, event.result.tokensBefore, new Date().toISOString()));
2406
+ this.footer.invalidate();
2407
+ }
2408
+ else if (event.errorMessage) {
2409
+ if (event.reason === "manual") {
2410
+ this.showError(event.errorMessage);
2411
+ }
2412
+ else {
2413
+ this.chatContainer.addChild(new Spacer(1));
2414
+ this.chatContainer.addChild(new Text(theme.fg("error", event.errorMessage), 1, 0));
2415
+ }
2416
+ }
2417
+ void this.flushCompactionQueue({ willRetry: event.willRetry });
2418
+ this.ui.requestRender();
2419
+ break;
2420
+ }
2421
+ case "auto_retry_start": {
2422
+ // Set up escape to abort retry
2423
+ this.retryEscapeHandler = this.defaultEditor.onEscape;
2424
+ this.defaultEditor.onEscape = () => {
2425
+ this.session.abortRetry();
2426
+ };
2427
+ // Show retry indicator
2428
+ this.statusContainer.clear();
2429
+ this.retryCountdown?.dispose();
2430
+ const retryMessage = (seconds) => `Retrying (${event.attempt}/${event.maxAttempts}) in ${seconds}s... (${keyText("app.interrupt")} to cancel)`;
2431
+ this.retryLoader = new Loader(this.ui, (spinner) => theme.fg("warning", spinner), (text) => theme.fg("muted", text), retryMessage(Math.ceil(event.delayMs / 1000)));
2432
+ this.retryCountdown = new CountdownTimer(event.delayMs, this.ui, (seconds) => {
2433
+ this.retryLoader?.setMessage(retryMessage(seconds));
2434
+ }, () => {
2435
+ this.retryCountdown = undefined;
2436
+ });
2437
+ this.statusContainer.addChild(this.retryLoader);
2438
+ this.ui.requestRender();
2439
+ break;
2440
+ }
2441
+ case "auto_retry_end": {
2442
+ // Restore escape handler
2443
+ if (this.retryEscapeHandler) {
2444
+ this.defaultEditor.onEscape = this.retryEscapeHandler;
2445
+ this.retryEscapeHandler = undefined;
2446
+ }
2447
+ if (this.retryCountdown) {
2448
+ this.retryCountdown.dispose();
2449
+ this.retryCountdown = undefined;
2450
+ }
2451
+ // Stop loader
2452
+ if (this.retryLoader) {
2453
+ this.retryLoader.stop();
2454
+ this.retryLoader = undefined;
2455
+ this.statusContainer.clear();
2456
+ }
2457
+ // Show error only on final failure (success shows normal response)
2458
+ if (!event.success) {
2459
+ this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || "Unknown error"}`);
2460
+ }
2461
+ this.ui.requestRender();
2462
+ break;
2463
+ }
2464
+ }
2465
+ }
2466
+ /** Extract text content from a user message */
2467
+ getUserMessageText(message) {
2468
+ if (message.role !== "user")
2469
+ return "";
2470
+ const textBlocks = typeof message.content === "string"
2471
+ ? [{ type: "text", text: message.content }]
2472
+ : message.content.filter((c) => c.type === "text");
2473
+ return textBlocks.map((c) => c.text).join("");
2474
+ }
2475
+ /**
2476
+ * Show a status message in the chat.
2477
+ *
2478
+ * If multiple status messages are emitted back-to-back (without anything else being added to the chat),
2479
+ * we update the previous status line instead of appending new ones to avoid log spam.
2480
+ */
2481
+ showStatus(message) {
2482
+ const children = this.chatContainer.children;
2483
+ const last = children.length > 0 ? children[children.length - 1] : undefined;
2484
+ const secondLast = children.length > 1 ? children[children.length - 2] : undefined;
2485
+ if (last &&
2486
+ secondLast &&
2487
+ last === this.lastStatusText &&
2488
+ secondLast === this.lastStatusSpacer) {
2489
+ this.lastStatusText.setText(theme.fg("dim", message));
2490
+ this.ui.requestRender();
2491
+ return;
2492
+ }
2493
+ const spacer = new Spacer(1);
2494
+ const text = new Text(theme.fg("dim", message), 1, 0);
2495
+ this.chatContainer.addChild(spacer);
2496
+ this.chatContainer.addChild(text);
2497
+ this.lastStatusSpacer = spacer;
2498
+ this.lastStatusText = text;
2499
+ this.ui.requestRender();
2500
+ }
2501
+ addMessageToChat(message, options) {
2502
+ switch (message.role) {
2503
+ case "bashExecution": {
2504
+ const component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);
2505
+ if (message.output) {
2506
+ component.appendOutput(message.output);
2507
+ }
2508
+ component.setComplete(message.exitCode, message.cancelled, message.truncated
2509
+ ? { truncated: true }
2510
+ : undefined, message.fullOutputPath);
2511
+ this.chatContainer.addChild(component);
2512
+ break;
2513
+ }
2514
+ case "custom": {
2515
+ if (message.display) {
2516
+ const renderer = this.session.extensionRunner.getMessageRenderer(message.customType);
2517
+ const component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings());
2518
+ component.setExpanded(this.toolOutputExpanded);
2519
+ this.chatContainer.addChild(component);
2520
+ }
2521
+ break;
2522
+ }
2523
+ case "compactionSummary": {
2524
+ this.chatContainer.addChild(new Spacer(1));
2525
+ const component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
2526
+ component.setExpanded(this.toolOutputExpanded);
2527
+ this.chatContainer.addChild(component);
2528
+ break;
2529
+ }
2530
+ case "branchSummary": {
2531
+ this.chatContainer.addChild(new Spacer(1));
2532
+ const component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
2533
+ component.setExpanded(this.toolOutputExpanded);
2534
+ this.chatContainer.addChild(component);
2535
+ break;
2536
+ }
2537
+ case "user": {
2538
+ const textContent = this.getUserMessageText(message);
2539
+ if (textContent) {
2540
+ if (this.chatContainer.children.length > 0) {
2541
+ this.chatContainer.addChild(new Spacer(1));
2542
+ }
2543
+ const skillBlock = parseSkillBlock(textContent);
2544
+ if (skillBlock) {
2545
+ // Render skill block (collapsible)
2546
+ const component = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings());
2547
+ component.setExpanded(this.toolOutputExpanded);
2548
+ this.chatContainer.addChild(component);
2549
+ // Render user message separately if present
2550
+ if (skillBlock.userMessage) {
2551
+ const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings());
2552
+ this.chatContainer.addChild(userComponent);
2553
+ }
2554
+ }
2555
+ else {
2556
+ const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings());
2557
+ this.chatContainer.addChild(userComponent);
2558
+ }
2559
+ if (options?.populateHistory) {
2560
+ this.editor.addToHistory?.(textContent);
2561
+ }
2562
+ }
2563
+ break;
2564
+ }
2565
+ case "assistant": {
2566
+ const assistantComponent = new AssistantMessageComponent(message, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel);
2567
+ this.chatContainer.addChild(assistantComponent);
2568
+ break;
2569
+ }
2570
+ case "toolResult": {
2571
+ // Tool results are rendered inline with tool calls, handled separately
2572
+ break;
2573
+ }
2574
+ default: {
2575
+ const _exhaustive = message;
2576
+ }
2577
+ }
2578
+ }
2579
+ /**
2580
+ * Render session context to chat. Used for initial load and rebuild after compaction.
2581
+ * @param sessionContext Session context to render
2582
+ * @param options.updateFooter Update footer state
2583
+ * @param options.populateHistory Add user messages to editor history
2584
+ */
2585
+ renderSessionContext(sessionContext, options = {}) {
2586
+ this.pendingTools.clear();
2587
+ const renderedPendingTools = new Map();
2588
+ if (options.updateFooter) {
2589
+ this.footer.invalidate();
2590
+ this.updateEditorBorderColor();
2591
+ }
2592
+ for (const message of sessionContext.messages) {
2593
+ // Assistant messages need special handling for tool calls
2594
+ if (message.role === "assistant") {
2595
+ this.addMessageToChat(message);
2596
+ // Render tool call components
2597
+ for (const content of message.content) {
2598
+ if (content.type === "toolCall") {
2599
+ const component = new ToolExecutionComponent(content.name, content.id, content.arguments, {
2600
+ showImages: this.settingsManager.getShowImages(),
2601
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
2602
+ }, this.getRegisteredToolDefinition(content.name), this.ui, this.sessionManager.getCwd());
2603
+ component.setExpanded(this.toolOutputExpanded);
2604
+ this.chatContainer.addChild(component);
2605
+ if (message.stopReason === "aborted" ||
2606
+ message.stopReason === "error") {
2607
+ let errorMessage;
2608
+ if (message.stopReason === "aborted") {
2609
+ const retryAttempt = this.session.retryAttempt;
2610
+ errorMessage =
2611
+ retryAttempt > 0
2612
+ ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
2613
+ : "Operation aborted";
2614
+ }
2615
+ else {
2616
+ errorMessage = message.errorMessage || "Error";
2617
+ }
2618
+ component.updateResult({
2619
+ content: [{ type: "text", text: errorMessage }],
2620
+ isError: true,
2621
+ });
2622
+ }
2623
+ else {
2624
+ renderedPendingTools.set(content.id, component);
2625
+ }
2626
+ }
2627
+ }
2628
+ }
2629
+ else if (message.role === "toolResult") {
2630
+ // Match tool results to pending tool components
2631
+ const component = renderedPendingTools.get(message.toolCallId);
2632
+ if (component) {
2633
+ component.updateResult(message);
2634
+ renderedPendingTools.delete(message.toolCallId);
2635
+ }
2636
+ }
2637
+ else {
2638
+ // All other messages use standard rendering
2639
+ this.addMessageToChat(message, options);
2640
+ }
2641
+ }
2642
+ for (const [toolCallId, component] of renderedPendingTools) {
2643
+ this.pendingTools.set(toolCallId, component);
2644
+ }
2645
+ this.ui.requestRender();
2646
+ }
2647
+ renderInitialMessages() {
2648
+ // Get aligned messages and entries from session context
2649
+ const context = this.sessionManager.buildSessionContext();
2650
+ this.renderSessionContext(context, {
2651
+ updateFooter: true,
2652
+ populateHistory: true,
2653
+ });
2654
+ // Show compaction info if session was compacted
2655
+ const allEntries = this.sessionManager.getEntries();
2656
+ const compactionCount = allEntries.filter((e) => e.type === "compaction").length;
2657
+ if (compactionCount > 0) {
2658
+ const times = compactionCount === 1 ? "1 time" : `${compactionCount} times`;
2659
+ this.showStatus(`Session compacted ${times}`);
2660
+ }
2661
+ }
2662
+ async getUserInput() {
2663
+ return new Promise((resolve) => {
2664
+ this.onInputCallback = (text) => {
2665
+ this.onInputCallback = undefined;
2666
+ resolve(text);
2667
+ };
2668
+ });
2669
+ }
2670
+ rebuildChatFromMessages() {
2671
+ this.chatContainer.clear();
2672
+ const context = this.sessionManager.buildSessionContext();
2673
+ this.renderSessionContext(context);
2674
+ }
2675
+ // =========================================================================
2676
+ // Key handlers
2677
+ // =========================================================================
2678
+ handleCtrlC() {
2679
+ const now = Date.now();
2680
+ if (now - this.lastSigintTime < 500) {
2681
+ void this.shutdown();
2682
+ }
2683
+ else {
2684
+ this.clearEditor();
2685
+ this.lastSigintTime = now;
2686
+ }
2687
+ }
2688
+ handleCtrlD() {
2689
+ // Only called when editor is empty (enforced by CustomEditor)
2690
+ void this.shutdown();
2691
+ }
2692
+ async shutdown() {
2693
+ if (this.isShuttingDown)
2694
+ return;
2695
+ this.isShuttingDown = true;
2696
+ this.unregisterSignalHandlers();
2697
+ // Drain any in-flight Kitty key release events before stopping.
2698
+ // This prevents escape sequences from leaking to the parent shell over slow SSH.
2699
+ await this.ui.terminal.drainInput(1000);
2700
+ this.stop();
2701
+ await this.runtimeHost.dispose();
2702
+ process.exit(0);
2703
+ }
2704
+ emergencyTerminalExit() {
2705
+ this.isShuttingDown = true;
2706
+ this.unregisterSignalHandlers();
2707
+ killTrackedDetachedChildren();
2708
+ // The terminal is gone. Do not run normal shutdown because TUI and
2709
+ // extension cleanup can write restore sequences and re-trigger EIO.
2710
+ process.exit(129);
2711
+ }
2712
+ /**
2713
+ * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw
2714
+ * mode and hides the cursor; without this handler, an uncaught throw from
2715
+ * anywhere (e.g. an extension's async `ChildProcess.on("exit")` callback)
2716
+ * tears down the process while leaving the terminal in raw mode with no
2717
+ * cursor, requiring `stty sane && reset` to recover.
2718
+ *
2719
+ * Unlike emergencyTerminalExit, the terminal is still alive here, so we
2720
+ * call ui.stop() to restore cooked mode, the cursor, and disable bracketed
2721
+ * paste / Kitty / modifyOtherKeys sequences.
2722
+ */
2723
+ uncaughtCrash(error) {
2724
+ if (this.isShuttingDown) {
2725
+ process.exit(1);
2726
+ }
2727
+ this.isShuttingDown = true;
2728
+ try {
2729
+ this.unregisterSignalHandlers();
2730
+ }
2731
+ catch { }
2732
+ try {
2733
+ killTrackedDetachedChildren();
2734
+ }
2735
+ catch { }
2736
+ try {
2737
+ this.ui.stop();
2738
+ }
2739
+ catch { }
2740
+ console.error("pi exiting due to uncaughtException:");
2741
+ console.error(error);
2742
+ process.exit(1);
2743
+ }
2744
+ /**
2745
+ * Check if shutdown was requested and perform shutdown if so.
2746
+ */
2747
+ async checkShutdownRequested() {
2748
+ if (!this.shutdownRequested)
2749
+ return;
2750
+ await this.shutdown();
2751
+ }
2752
+ registerSignalHandlers() {
2753
+ this.unregisterSignalHandlers();
2754
+ const signals = ["SIGTERM"];
2755
+ if (process.platform !== "win32") {
2756
+ signals.push("SIGHUP");
2757
+ }
2758
+ for (const signal of signals) {
2759
+ const handler = () => {
2760
+ if (signal === "SIGHUP") {
2761
+ this.emergencyTerminalExit();
2762
+ }
2763
+ killTrackedDetachedChildren();
2764
+ void this.shutdown();
2765
+ };
2766
+ process.prependListener(signal, handler);
2767
+ this.signalCleanupHandlers.push(() => process.off(signal, handler));
2768
+ }
2769
+ const terminalErrorHandler = (error) => {
2770
+ if (isDeadTerminalError(error)) {
2771
+ this.emergencyTerminalExit();
2772
+ }
2773
+ throw error;
2774
+ };
2775
+ process.stdout.on("error", terminalErrorHandler);
2776
+ process.stderr.on("error", terminalErrorHandler);
2777
+ this.signalCleanupHandlers.push(() => process.stdout.off("error", terminalErrorHandler));
2778
+ this.signalCleanupHandlers.push(() => process.stderr.off("error", terminalErrorHandler));
2779
+ // Restore the terminal before the process dies on any uncaught throw.
2780
+ // Without this, an unhandled exception from extension code (or anywhere
2781
+ // in pi) leaves the terminal in raw mode with no cursor.
2782
+ const uncaughtExceptionHandler = (error) => this.uncaughtCrash(error);
2783
+ process.prependListener("uncaughtException", uncaughtExceptionHandler);
2784
+ this.signalCleanupHandlers.push(() => process.off("uncaughtException", uncaughtExceptionHandler));
2785
+ }
2786
+ unregisterSignalHandlers() {
2787
+ for (const cleanup of this.signalCleanupHandlers) {
2788
+ cleanup();
2789
+ }
2790
+ this.signalCleanupHandlers = [];
2791
+ }
2792
+ handleCtrlZ() {
2793
+ if (process.platform === "win32") {
2794
+ this.showStatus("Suspend to background is not supported on Windows");
2795
+ return;
2796
+ }
2797
+ // Keep the event loop alive while suspended. Without this, stopping the TUI
2798
+ // can leave Node with no ref'ed handles, causing the process to exit on fg
2799
+ // before the SIGCONT handler gets a chance to restore the terminal.
2800
+ const suspendKeepAlive = setInterval(() => { }, 2 ** 30);
2801
+ // Ignore SIGINT while suspended so Ctrl+C in the terminal does not
2802
+ // kill the backgrounded process. The handler is removed on resume.
2803
+ const ignoreSigint = () => { };
2804
+ process.on("SIGINT", ignoreSigint);
2805
+ // Set up handler to restore TUI when resumed
2806
+ process.once("SIGCONT", () => {
2807
+ clearInterval(suspendKeepAlive);
2808
+ process.removeListener("SIGINT", ignoreSigint);
2809
+ this.ui.start();
2810
+ this.ui.requestRender(true);
2811
+ });
2812
+ try {
2813
+ // Stop the TUI (restore terminal to normal mode)
2814
+ this.ui.stop();
2815
+ // Send SIGTSTP to process group (pid=0 means all processes in group)
2816
+ process.kill(0, "SIGTSTP");
2817
+ }
2818
+ catch (error) {
2819
+ clearInterval(suspendKeepAlive);
2820
+ process.removeListener("SIGINT", ignoreSigint);
2821
+ throw error;
2822
+ }
2823
+ }
2824
+ async handleFollowUp() {
2825
+ const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();
2826
+ if (!text)
2827
+ return;
2828
+ // Queue input during compaction (extension commands execute immediately)
2829
+ if (this.session.isCompacting) {
2830
+ if (this.isExtensionCommand(text)) {
2831
+ this.editor.addToHistory?.(text);
2832
+ this.editor.setText("");
2833
+ await this.session.prompt(text);
2834
+ }
2835
+ else {
2836
+ this.queueCompactionMessage(text, "followUp");
2837
+ }
2838
+ return;
2839
+ }
2840
+ // Alt+Enter queues a follow-up message (waits until agent finishes)
2841
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
2842
+ if (this.session.isStreaming) {
2843
+ this.editor.addToHistory?.(text);
2844
+ this.editor.setText("");
2845
+ await this.session.prompt(text, { streamingBehavior: "followUp" });
2846
+ this.updatePendingMessagesDisplay();
2847
+ this.ui.requestRender();
2848
+ }
2849
+ // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
2850
+ else if (this.editor.onSubmit) {
2851
+ this.editor.setText("");
2852
+ this.editor.onSubmit(text);
2853
+ }
2854
+ }
2855
+ handleDequeue() {
2856
+ const restored = this.restoreQueuedMessagesToEditor();
2857
+ if (restored === 0) {
2858
+ this.showStatus("No queued messages to restore");
2859
+ }
2860
+ else {
2861
+ this.showStatus(`Restored ${restored} queued message${restored > 1 ? "s" : ""} to editor`);
2862
+ }
2863
+ }
2864
+ updateEditorBorderColor() {
2865
+ if (this.isBashMode) {
2866
+ this.editor.borderColor = theme.getBashModeBorderColor();
2867
+ }
2868
+ else {
2869
+ const level = this.session.thinkingLevel || "off";
2870
+ this.editor.borderColor = theme.getThinkingBorderColor(level);
2871
+ }
2872
+ this.ui.requestRender();
2873
+ }
2874
+ cycleThinkingLevel() {
2875
+ const newLevel = this.session.cycleThinkingLevel();
2876
+ if (newLevel === undefined) {
2877
+ this.showStatus("Current model does not support thinking");
2878
+ }
2879
+ else {
2880
+ this.footer.invalidate();
2881
+ this.updateEditorBorderColor();
2882
+ this.showStatus(`Thinking level: ${newLevel}`);
2883
+ }
2884
+ }
2885
+ async cycleModel(direction) {
2886
+ try {
2887
+ const result = await this.session.cycleModel(direction);
2888
+ if (result === undefined) {
2889
+ const msg = this.session.scopedModels.length > 0
2890
+ ? "Only one model in scope"
2891
+ : "Only one model available";
2892
+ this.showStatus(msg);
2893
+ }
2894
+ else {
2895
+ this.footer.invalidate();
2896
+ this.updateEditorBorderColor();
2897
+ const thinkingStr = result.model.reasoning && result.thinkingLevel !== "off"
2898
+ ? ` (thinking: ${result.thinkingLevel})`
2899
+ : "";
2900
+ this.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);
2901
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(result.model);
2902
+ }
2903
+ }
2904
+ catch (error) {
2905
+ this.showError(error instanceof Error ? error.message : String(error));
2906
+ }
2907
+ }
2908
+ toggleToolOutputExpansion() {
2909
+ this.setToolsExpanded(!this.toolOutputExpanded);
2910
+ }
2911
+ setToolsExpanded(expanded) {
2912
+ this.toolOutputExpanded = expanded;
2913
+ const activeHeader = this.customHeader ?? this.builtInHeader;
2914
+ if (isExpandable(activeHeader)) {
2915
+ activeHeader.setExpanded(expanded);
2916
+ }
2917
+ for (const child of this.chatContainer.children) {
2918
+ if (isExpandable(child)) {
2919
+ child.setExpanded(expanded);
2920
+ }
2921
+ }
2922
+ this.ui.requestRender();
2923
+ }
2924
+ toggleThinkingBlockVisibility() {
2925
+ this.hideThinkingBlock = !this.hideThinkingBlock;
2926
+ this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);
2927
+ // Rebuild chat from session messages
2928
+ this.chatContainer.clear();
2929
+ this.rebuildChatFromMessages();
2930
+ // If streaming, re-add the streaming component with updated visibility and re-render
2931
+ if (this.streamingComponent && this.streamingMessage) {
2932
+ this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);
2933
+ this.streamingComponent.updateContent(this.streamingMessage);
2934
+ this.chatContainer.addChild(this.streamingComponent);
2935
+ }
2936
+ this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
2937
+ }
2938
+ openExternalEditor() {
2939
+ // Determine editor (respect $VISUAL, then $EDITOR)
2940
+ const editorCmd = process.env.VISUAL || process.env.EDITOR;
2941
+ if (!editorCmd) {
2942
+ this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");
2943
+ return;
2944
+ }
2945
+ const currentText = this.editor.getExpandedText?.() ?? this.editor.getText();
2946
+ const tmpFile = path.join(os.tmpdir(), `pi-editor-${Date.now()}.pi.md`);
2947
+ try {
2948
+ // Write current content to temp file
2949
+ fs.writeFileSync(tmpFile, currentText, "utf-8");
2950
+ // Stop TUI to release terminal
2951
+ this.ui.stop();
2952
+ // Split by space to support editor arguments (e.g., "code --wait")
2953
+ const [editor, ...editorArgs] = editorCmd.split(" ");
2954
+ // Spawn editor synchronously with inherited stdio for interactive editing
2955
+ const result = spawnSync(editor, [...editorArgs, tmpFile], {
2956
+ stdio: "inherit",
2957
+ shell: process.platform === "win32",
2958
+ });
2959
+ // On successful exit (status 0), replace editor content
2960
+ if (result.status === 0) {
2961
+ const newContent = fs.readFileSync(tmpFile, "utf-8").replace(/\n$/, "");
2962
+ this.editor.setText(newContent);
2963
+ }
2964
+ // On non-zero exit, keep original text (no action needed)
2965
+ }
2966
+ finally {
2967
+ // Clean up temp file
2968
+ try {
2969
+ fs.unlinkSync(tmpFile);
2970
+ }
2971
+ catch {
2972
+ // Ignore cleanup errors
2973
+ }
2974
+ // Restart TUI
2975
+ this.ui.start();
2976
+ // Force full re-render since external editor uses alternate screen
2977
+ this.ui.requestRender(true);
2978
+ }
2979
+ }
2980
+ // =========================================================================
2981
+ // UI helpers
2982
+ // =========================================================================
2983
+ clearEditor() {
2984
+ this.editor.setText("");
2985
+ this.ui.requestRender();
2986
+ }
2987
+ showError(errorMessage) {
2988
+ this.chatContainer.addChild(new Spacer(1));
2989
+ this.chatContainer.addChild(new Text(theme.fg("error", `Error: ${errorMessage}`), 1, 0));
2990
+ this.chatContainer.addChild(new Spacer(1));
2991
+ this.ui.requestRender();
2992
+ }
2993
+ showWarning(warningMessage) {
2994
+ this.chatContainer.addChild(new Spacer(1));
2995
+ this.chatContainer.addChild(new Text(theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
2996
+ this.ui.requestRender();
2997
+ }
2998
+ showNewVersionNotification(newVersion) {
2999
+ const action = theme.fg("accent", `${APP_NAME} update`);
3000
+ const updateInstruction = theme.fg("muted", `New version ${newVersion} is available. Run `) +
3001
+ action;
3002
+ const changelogLine = CHANGELOG_URL
3003
+ ? `\n${theme.fg("muted", "Changelog: ")}${getCapabilities().hyperlinks
3004
+ ? hyperlink(theme.fg("accent", "open changelog"), CHANGELOG_URL)
3005
+ : theme.fg("accent", CHANGELOG_URL)}`
3006
+ : "";
3007
+ this.chatContainer.addChild(new Spacer(1));
3008
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3009
+ this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}${changelogLine}`, 1, 0));
3010
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3011
+ this.ui.requestRender();
3012
+ }
3013
+ showPackageUpdateNotification(packages) {
3014
+ const action = theme.fg("accent", `${APP_NAME} update`);
3015
+ const updateInstruction = theme.fg("muted", "Package updates are available. Run ") + action;
3016
+ const packageLines = packages.map((pkg) => `- ${pkg}`).join("\n");
3017
+ this.chatContainer.addChild(new Spacer(1));
3018
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3019
+ this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Package Updates Available"))}\n${updateInstruction}\n${theme.fg("muted", "Packages:")}\n${packageLines}`, 1, 0));
3020
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3021
+ this.ui.requestRender();
3022
+ }
3023
+ /**
3024
+ * Get all queued messages (read-only).
3025
+ * Combines session queue and compaction queue.
3026
+ */
3027
+ getAllQueuedMessages() {
3028
+ return {
3029
+ steering: [
3030
+ ...this.session.getSteeringMessages(),
3031
+ ...this.compactionQueuedMessages
3032
+ .filter((msg) => msg.mode === "steer")
3033
+ .map((msg) => msg.text),
3034
+ ],
3035
+ followUp: [
3036
+ ...this.session.getFollowUpMessages(),
3037
+ ...this.compactionQueuedMessages
3038
+ .filter((msg) => msg.mode === "followUp")
3039
+ .map((msg) => msg.text),
3040
+ ],
3041
+ };
3042
+ }
3043
+ /**
3044
+ * Clear all queued messages and return their contents.
3045
+ * Clears both session queue and compaction queue.
3046
+ */
3047
+ clearAllQueues() {
3048
+ const { steering, followUp } = this.session.clearQueue();
3049
+ const compactionSteering = this.compactionQueuedMessages
3050
+ .filter((msg) => msg.mode === "steer")
3051
+ .map((msg) => msg.text);
3052
+ const compactionFollowUp = this.compactionQueuedMessages
3053
+ .filter((msg) => msg.mode === "followUp")
3054
+ .map((msg) => msg.text);
3055
+ this.compactionQueuedMessages = [];
3056
+ return {
3057
+ steering: [...steering, ...compactionSteering],
3058
+ followUp: [...followUp, ...compactionFollowUp],
3059
+ };
3060
+ }
3061
+ updatePendingMessagesDisplay() {
3062
+ this.pendingMessagesContainer.clear();
3063
+ const { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();
3064
+ if (steeringMessages.length > 0 || followUpMessages.length > 0) {
3065
+ this.pendingMessagesContainer.addChild(new Spacer(1));
3066
+ for (const message of steeringMessages) {
3067
+ const text = theme.fg("dim", `Steering: ${message}`);
3068
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
3069
+ }
3070
+ for (const message of followUpMessages) {
3071
+ const text = theme.fg("dim", `Follow-up: ${message}`);
3072
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
3073
+ }
3074
+ const dequeueHint = this.getAppKeyDisplay("app.message.dequeue");
3075
+ const hintText = theme.fg("dim", `↳ ${dequeueHint} to edit all queued messages`);
3076
+ this.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));
3077
+ }
3078
+ }
3079
+ restoreQueuedMessagesToEditor(options) {
3080
+ const { steering, followUp } = this.clearAllQueues();
3081
+ const allQueued = [...steering, ...followUp];
3082
+ if (allQueued.length === 0) {
3083
+ this.updatePendingMessagesDisplay();
3084
+ if (options?.abort) {
3085
+ this.agent.abort();
3086
+ }
3087
+ return 0;
3088
+ }
3089
+ const queuedText = allQueued.join("\n\n");
3090
+ const currentText = options?.currentText ?? this.editor.getText();
3091
+ const combinedText = [queuedText, currentText]
3092
+ .filter((t) => t.trim())
3093
+ .join("\n\n");
3094
+ this.editor.setText(combinedText);
3095
+ this.updatePendingMessagesDisplay();
3096
+ if (options?.abort) {
3097
+ this.agent.abort();
3098
+ }
3099
+ return allQueued.length;
3100
+ }
3101
+ queueCompactionMessage(text, mode) {
3102
+ this.compactionQueuedMessages.push({ text, mode });
3103
+ this.editor.addToHistory?.(text);
3104
+ this.editor.setText("");
3105
+ this.updatePendingMessagesDisplay();
3106
+ this.showStatus("Queued message for after compaction");
3107
+ }
3108
+ isExtensionCommand(text) {
3109
+ if (!text.startsWith("/"))
3110
+ return false;
3111
+ const extensionRunner = this.session.extensionRunner;
3112
+ const spaceIndex = text.indexOf(" ");
3113
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
3114
+ return !!extensionRunner.getCommand(commandName);
3115
+ }
3116
+ async flushCompactionQueue(options) {
3117
+ if (this.compactionQueuedMessages.length === 0) {
3118
+ return;
3119
+ }
3120
+ const queuedMessages = [...this.compactionQueuedMessages];
3121
+ this.compactionQueuedMessages = [];
3122
+ this.updatePendingMessagesDisplay();
3123
+ const restoreQueue = (error) => {
3124
+ this.session.clearQueue();
3125
+ this.compactionQueuedMessages = queuedMessages;
3126
+ this.updatePendingMessagesDisplay();
3127
+ this.showError(`Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${error instanceof Error ? error.message : String(error)}`);
3128
+ };
3129
+ try {
3130
+ if (options?.willRetry) {
3131
+ // When retry is pending, queue messages for the retry turn
3132
+ for (const message of queuedMessages) {
3133
+ if (this.isExtensionCommand(message.text)) {
3134
+ await this.session.prompt(message.text);
3135
+ }
3136
+ else if (message.mode === "followUp") {
3137
+ await this.session.followUp(message.text);
3138
+ }
3139
+ else {
3140
+ await this.session.steer(message.text);
3141
+ }
3142
+ }
3143
+ this.updatePendingMessagesDisplay();
3144
+ return;
3145
+ }
3146
+ // Find first non-extension-command message to use as prompt
3147
+ const firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));
3148
+ if (firstPromptIndex === -1) {
3149
+ // All extension commands - execute them all
3150
+ for (const message of queuedMessages) {
3151
+ await this.session.prompt(message.text);
3152
+ }
3153
+ return;
3154
+ }
3155
+ // Execute any extension commands before the first prompt
3156
+ const preCommands = queuedMessages.slice(0, firstPromptIndex);
3157
+ const firstPrompt = queuedMessages[firstPromptIndex];
3158
+ const rest = queuedMessages.slice(firstPromptIndex + 1);
3159
+ for (const message of preCommands) {
3160
+ await this.session.prompt(message.text);
3161
+ }
3162
+ // Send first prompt (starts streaming)
3163
+ const promptPromise = this.session
3164
+ .prompt(firstPrompt.text)
3165
+ .catch((error) => {
3166
+ restoreQueue(error);
3167
+ });
3168
+ // Queue remaining messages
3169
+ for (const message of rest) {
3170
+ if (this.isExtensionCommand(message.text)) {
3171
+ await this.session.prompt(message.text);
3172
+ }
3173
+ else if (message.mode === "followUp") {
3174
+ await this.session.followUp(message.text);
3175
+ }
3176
+ else {
3177
+ await this.session.steer(message.text);
3178
+ }
3179
+ }
3180
+ this.updatePendingMessagesDisplay();
3181
+ void promptPromise;
3182
+ }
3183
+ catch (error) {
3184
+ restoreQueue(error);
3185
+ }
3186
+ }
3187
+ /** Move pending bash components from pending area to chat */
3188
+ flushPendingBashComponents() {
3189
+ for (const component of this.pendingBashComponents) {
3190
+ this.pendingMessagesContainer.removeChild(component);
3191
+ this.chatContainer.addChild(component);
3192
+ }
3193
+ this.pendingBashComponents = [];
3194
+ }
3195
+ // =========================================================================
3196
+ // Selectors
3197
+ // =========================================================================
3198
+ /**
3199
+ * Shows a selector component in place of the editor.
3200
+ * @param create Factory that receives a `done` callback and returns the component and focus target
3201
+ */
3202
+ showSelector(create) {
3203
+ const done = () => {
3204
+ this.editorContainer.clear();
3205
+ this.editorContainer.addChild(this.editor);
3206
+ this.ui.setFocus(this.editor);
3207
+ };
3208
+ const { component, focus } = create(done);
3209
+ this.editorContainer.clear();
3210
+ this.editorContainer.addChild(component);
3211
+ this.ui.setFocus(focus);
3212
+ this.ui.requestRender();
3213
+ }
3214
+ showSettingsSelector() {
3215
+ this.showSelector((done) => {
3216
+ const selector = new SettingsSelectorComponent({
3217
+ autoCompact: this.session.autoCompactionEnabled,
3218
+ showImages: this.settingsManager.getShowImages(),
3219
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
3220
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
3221
+ blockImages: this.settingsManager.getBlockImages(),
3222
+ enableSkillCommands: this.settingsManager.getEnableSkillCommands(),
3223
+ steeringMode: this.session.steeringMode,
3224
+ followUpMode: this.session.followUpMode,
3225
+ transport: this.settingsManager.getTransport(),
3226
+ thinkingLevel: this.session.thinkingLevel,
3227
+ availableThinkingLevels: this.session.getAvailableThinkingLevels(),
3228
+ currentTheme: this.settingsManager.getTheme() || "dark",
3229
+ availableThemes: getAvailableThemes(),
3230
+ hideThinkingBlock: this.hideThinkingBlock,
3231
+ collapseChangelog: this.settingsManager.getCollapseChangelog(),
3232
+ enableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),
3233
+ doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),
3234
+ treeFilterMode: this.settingsManager.getTreeFilterMode(),
3235
+ showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
3236
+ editorPaddingX: this.settingsManager.getEditorPaddingX(),
3237
+ autocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),
3238
+ quietStartup: this.settingsManager.getQuietStartup(),
3239
+ clearOnShrink: this.settingsManager.getClearOnShrink(),
3240
+ showTerminalProgress: this.settingsManager.getShowTerminalProgress(),
3241
+ warnings: this.settingsManager.getWarnings(),
3242
+ }, {
3243
+ onAutoCompactChange: (enabled) => {
3244
+ this.session.setAutoCompactionEnabled(enabled);
3245
+ this.footer.setAutoCompactEnabled(enabled);
3246
+ },
3247
+ onShowImagesChange: (enabled) => {
3248
+ this.settingsManager.setShowImages(enabled);
3249
+ for (const child of this.chatContainer.children) {
3250
+ if (child instanceof ToolExecutionComponent) {
3251
+ child.setShowImages(enabled);
3252
+ }
3253
+ }
3254
+ },
3255
+ onImageWidthCellsChange: (width) => {
3256
+ this.settingsManager.setImageWidthCells(width);
3257
+ for (const child of this.chatContainer.children) {
3258
+ if (child instanceof ToolExecutionComponent) {
3259
+ child.setImageWidthCells(width);
3260
+ }
3261
+ }
3262
+ },
3263
+ onAutoResizeImagesChange: (enabled) => {
3264
+ this.settingsManager.setImageAutoResize(enabled);
3265
+ },
3266
+ onBlockImagesChange: (blocked) => {
3267
+ this.settingsManager.setBlockImages(blocked);
3268
+ },
3269
+ onEnableSkillCommandsChange: (enabled) => {
3270
+ this.settingsManager.setEnableSkillCommands(enabled);
3271
+ this.setupAutocompleteProvider();
3272
+ },
3273
+ onSteeringModeChange: (mode) => {
3274
+ this.session.setSteeringMode(mode);
3275
+ },
3276
+ onFollowUpModeChange: (mode) => {
3277
+ this.session.setFollowUpMode(mode);
3278
+ },
3279
+ onTransportChange: (transport) => {
3280
+ this.settingsManager.setTransport(transport);
3281
+ this.session.agent.transport = transport;
3282
+ },
3283
+ onThinkingLevelChange: (level) => {
3284
+ this.session.setThinkingLevel(level);
3285
+ this.footer.invalidate();
3286
+ this.updateEditorBorderColor();
3287
+ },
3288
+ onThemeChange: (themeName) => {
3289
+ const result = setTheme(themeName, true);
3290
+ this.settingsManager.setTheme(themeName);
3291
+ this.ui.invalidate();
3292
+ if (!result.success) {
3293
+ this.showError(`Failed to load theme "${themeName}": ${result.error}\nFell back to dark theme.`);
3294
+ }
3295
+ },
3296
+ onThemePreview: (themeName) => {
3297
+ const result = setTheme(themeName, true);
3298
+ if (result.success) {
3299
+ this.ui.invalidate();
3300
+ this.ui.requestRender();
3301
+ }
3302
+ },
3303
+ onHideThinkingBlockChange: (hidden) => {
3304
+ this.hideThinkingBlock = hidden;
3305
+ this.settingsManager.setHideThinkingBlock(hidden);
3306
+ for (const child of this.chatContainer.children) {
3307
+ if (child instanceof AssistantMessageComponent) {
3308
+ child.setHideThinkingBlock(hidden);
3309
+ }
3310
+ }
3311
+ this.chatContainer.clear();
3312
+ this.rebuildChatFromMessages();
3313
+ },
3314
+ onCollapseChangelogChange: (collapsed) => {
3315
+ this.settingsManager.setCollapseChangelog(collapsed);
3316
+ },
3317
+ onEnableInstallTelemetryChange: (enabled) => {
3318
+ this.settingsManager.setEnableInstallTelemetry(enabled);
3319
+ },
3320
+ onQuietStartupChange: (enabled) => {
3321
+ this.settingsManager.setQuietStartup(enabled);
3322
+ },
3323
+ onDoubleEscapeActionChange: (action) => {
3324
+ this.settingsManager.setDoubleEscapeAction(action);
3325
+ },
3326
+ onTreeFilterModeChange: (mode) => {
3327
+ this.settingsManager.setTreeFilterMode(mode);
3328
+ },
3329
+ onShowHardwareCursorChange: (enabled) => {
3330
+ this.settingsManager.setShowHardwareCursor(enabled);
3331
+ this.ui.setShowHardwareCursor(enabled);
3332
+ },
3333
+ onEditorPaddingXChange: (padding) => {
3334
+ this.settingsManager.setEditorPaddingX(padding);
3335
+ this.defaultEditor.setPaddingX(padding);
3336
+ if (this.editor !== this.defaultEditor &&
3337
+ this.editor.setPaddingX !== undefined) {
3338
+ this.editor.setPaddingX(padding);
3339
+ }
3340
+ },
3341
+ onAutocompleteMaxVisibleChange: (maxVisible) => {
3342
+ this.settingsManager.setAutocompleteMaxVisible(maxVisible);
3343
+ this.defaultEditor.setAutocompleteMaxVisible(maxVisible);
3344
+ if (this.editor !== this.defaultEditor &&
3345
+ this.editor.setAutocompleteMaxVisible !== undefined) {
3346
+ this.editor.setAutocompleteMaxVisible(maxVisible);
3347
+ }
3348
+ },
3349
+ onClearOnShrinkChange: (enabled) => {
3350
+ this.settingsManager.setClearOnShrink(enabled);
3351
+ this.ui.setClearOnShrink(enabled);
3352
+ },
3353
+ onShowTerminalProgressChange: (enabled) => {
3354
+ this.settingsManager.setShowTerminalProgress(enabled);
3355
+ },
3356
+ onWarningsChange: (warnings) => {
3357
+ this.settingsManager.setWarnings(warnings);
3358
+ },
3359
+ onCancel: () => {
3360
+ done();
3361
+ this.ui.requestRender();
3362
+ },
3363
+ });
3364
+ return { component: selector, focus: selector.getSettingsList() };
3365
+ });
3366
+ }
3367
+ async handleModelCommand(searchTerm) {
3368
+ if (!searchTerm) {
3369
+ this.showModelSelector();
3370
+ return;
3371
+ }
3372
+ const model = await this.findExactModelMatch(searchTerm);
3373
+ if (model) {
3374
+ try {
3375
+ await this.session.setModel(model);
3376
+ this.footer.invalidate();
3377
+ this.updateEditorBorderColor();
3378
+ this.showStatus(`Model: ${model.id}`);
3379
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
3380
+ this.checkDaxnutsEasterEgg(model);
3381
+ }
3382
+ catch (error) {
3383
+ this.showError(error instanceof Error ? error.message : String(error));
3384
+ }
3385
+ return;
3386
+ }
3387
+ this.showModelSelector(searchTerm);
3388
+ }
3389
+ async findExactModelMatch(searchTerm) {
3390
+ const models = await this.getModelCandidates();
3391
+ return findExactModelReferenceMatch(searchTerm, models);
3392
+ }
3393
+ async getModelCandidates() {
3394
+ if (this.session.scopedModels.length > 0) {
3395
+ return this.session.scopedModels.map((scoped) => scoped.model);
3396
+ }
3397
+ this.session.modelRegistry.refresh();
3398
+ try {
3399
+ return await this.session.modelRegistry.getAvailable();
3400
+ }
3401
+ catch {
3402
+ return [];
3403
+ }
3404
+ }
3405
+ /** Update the footer's available provider count from current model candidates */
3406
+ async updateAvailableProviderCount() {
3407
+ const models = await this.getModelCandidates();
3408
+ const uniqueProviders = new Set(models.map((m) => m.provider));
3409
+ this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);
3410
+ }
3411
+ async maybeWarnAboutAnthropicSubscriptionAuth(model = this.session.model) {
3412
+ if (this.settingsManager.getWarnings().anthropicExtraUsage === false) {
3413
+ return;
3414
+ }
3415
+ if (this.anthropicSubscriptionWarningShown) {
3416
+ return;
3417
+ }
3418
+ if (!model || model.provider !== "anthropic") {
3419
+ return;
3420
+ }
3421
+ const storedCredential = this.session.modelRegistry.authStorage.get("anthropic");
3422
+ if (storedCredential?.type === "oauth") {
3423
+ this.anthropicSubscriptionWarningShown = true;
3424
+ this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);
3425
+ return;
3426
+ }
3427
+ try {
3428
+ const apiKey = await this.session.modelRegistry.getApiKeyForProvider(model.provider);
3429
+ if (!isAnthropicSubscriptionAuthKey(apiKey)) {
3430
+ return;
3431
+ }
3432
+ this.anthropicSubscriptionWarningShown = true;
3433
+ this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);
3434
+ }
3435
+ catch {
3436
+ // Ignore auth lookup failures for warning-only checks.
3437
+ }
3438
+ }
3439
+ showModelSelector(initialSearchInput) {
3440
+ this.showSelector((done) => {
3441
+ const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRegistry, this.session.scopedModels, async (model) => {
3442
+ try {
3443
+ await this.session.setModel(model);
3444
+ this.footer.invalidate();
3445
+ this.updateEditorBorderColor();
3446
+ done();
3447
+ this.showStatus(`Model: ${model.id}`);
3448
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
3449
+ this.checkDaxnutsEasterEgg(model);
3450
+ }
3451
+ catch (error) {
3452
+ done();
3453
+ this.showError(error instanceof Error ? error.message : String(error));
3454
+ }
3455
+ }, () => {
3456
+ done();
3457
+ this.ui.requestRender();
3458
+ }, initialSearchInput);
3459
+ return { component: selector, focus: selector };
3460
+ });
3461
+ }
3462
+ async showModelsSelector() {
3463
+ // Get all available models
3464
+ this.session.modelRegistry.refresh();
3465
+ const allModels = this.session.modelRegistry.getAvailable();
3466
+ if (allModels.length === 0) {
3467
+ this.showStatus("No models available");
3468
+ return;
3469
+ }
3470
+ // Check if session has scoped models (from previous session-only changes or CLI --models)
3471
+ const sessionScopedModels = this.session.scopedModels;
3472
+ const hasSessionScope = sessionScopedModels.length > 0;
3473
+ // Build enabled model IDs from session state or settings
3474
+ let currentEnabledIds = null;
3475
+ if (hasSessionScope) {
3476
+ // Use current session's scoped models
3477
+ currentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3478
+ }
3479
+ else {
3480
+ // Fall back to settings
3481
+ const patterns = this.settingsManager.getEnabledModels();
3482
+ if (patterns !== undefined && patterns.length > 0) {
3483
+ const scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);
3484
+ currentEnabledIds = scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3485
+ }
3486
+ }
3487
+ // Helper to update session's scoped models (session-only, no persist)
3488
+ const updateSessionModels = async (enabledIds) => {
3489
+ currentEnabledIds = enabledIds === null ? null : [...enabledIds];
3490
+ if (enabledIds &&
3491
+ enabledIds.length > 0 &&
3492
+ enabledIds.length < allModels.length) {
3493
+ const newScopedModels = await resolveModelScope(enabledIds, this.session.modelRegistry);
3494
+ this.session.setScopedModels(newScopedModels.map((sm) => ({
3495
+ model: sm.model,
3496
+ thinkingLevel: sm.thinkingLevel,
3497
+ })));
3498
+ }
3499
+ else {
3500
+ // All enabled or none enabled = no filter
3501
+ this.session.setScopedModels([]);
3502
+ }
3503
+ await this.updateAvailableProviderCount();
3504
+ this.ui.requestRender();
3505
+ };
3506
+ this.showSelector((done) => {
3507
+ const selector = new ScopedModelsSelectorComponent({
3508
+ allModels,
3509
+ enabledModelIds: currentEnabledIds,
3510
+ }, {
3511
+ onChange: async (enabledIds) => {
3512
+ await updateSessionModels(enabledIds);
3513
+ },
3514
+ onPersist: (enabledIds) => {
3515
+ // Persist to settings
3516
+ const newPatterns = enabledIds === null || enabledIds.length === allModels.length
3517
+ ? undefined // All enabled = clear filter
3518
+ : enabledIds;
3519
+ this.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);
3520
+ this.showStatus("Model selection saved to settings");
3521
+ },
3522
+ onCancel: () => {
3523
+ done();
3524
+ this.ui.requestRender();
3525
+ },
3526
+ });
3527
+ return { component: selector, focus: selector };
3528
+ });
3529
+ }
3530
+ showUserMessageSelector() {
3531
+ const userMessages = this.session.getUserMessagesForForking();
3532
+ if (userMessages.length === 0) {
3533
+ this.showStatus("No messages to fork from");
3534
+ return;
3535
+ }
3536
+ const initialSelectedId = userMessages[userMessages.length - 1]?.entryId;
3537
+ this.showSelector((done) => {
3538
+ const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => {
3539
+ try {
3540
+ const result = await this.runtimeHost.fork(entryId);
3541
+ if (result.cancelled) {
3542
+ done();
3543
+ this.ui.requestRender();
3544
+ return;
3545
+ }
3546
+ this.renderCurrentSessionState();
3547
+ this.editor.setText(result.selectedText ?? "");
3548
+ done();
3549
+ this.showStatus("Forked to new session");
3550
+ }
3551
+ catch (error) {
3552
+ done();
3553
+ this.showError(error instanceof Error ? error.message : String(error));
3554
+ }
3555
+ }, () => {
3556
+ done();
3557
+ this.ui.requestRender();
3558
+ }, initialSelectedId);
3559
+ return { component: selector, focus: selector.getMessageList() };
3560
+ });
3561
+ }
3562
+ async handleCloneCommand() {
3563
+ const leafId = this.sessionManager.getLeafId();
3564
+ if (!leafId) {
3565
+ this.showStatus("Nothing to clone yet");
3566
+ return;
3567
+ }
3568
+ try {
3569
+ const result = await this.runtimeHost.fork(leafId, { position: "at" });
3570
+ if (result.cancelled) {
3571
+ this.ui.requestRender();
3572
+ return;
3573
+ }
3574
+ this.renderCurrentSessionState();
3575
+ this.editor.setText("");
3576
+ this.showStatus("Cloned to new session");
3577
+ }
3578
+ catch (error) {
3579
+ this.showError(error instanceof Error ? error.message : String(error));
3580
+ }
3581
+ }
3582
+ showTreeSelector(initialSelectedId) {
3583
+ const tree = this.sessionManager.getTree();
3584
+ const realLeafId = this.sessionManager.getLeafId();
3585
+ const initialFilterMode = this.settingsManager.getTreeFilterMode();
3586
+ if (tree.length === 0) {
3587
+ this.showStatus("No entries in session");
3588
+ return;
3589
+ }
3590
+ this.showSelector((done) => {
3591
+ const selector = new TreeSelectorComponent(tree, realLeafId, this.ui.terminal.rows, async (entryId) => {
3592
+ // Selecting the current leaf is a no-op (already there)
3593
+ if (entryId === realLeafId) {
3594
+ done();
3595
+ this.showStatus("Already at this point");
3596
+ return;
3597
+ }
3598
+ // Ask about summarization
3599
+ done(); // Close selector first
3600
+ // Loop until user makes a complete choice or cancels to tree
3601
+ let wantsSummary = false;
3602
+ let customInstructions;
3603
+ // Check if we should skip the prompt (user preference to always default to no summary)
3604
+ if (!this.settingsManager.getBranchSummarySkipPrompt()) {
3605
+ while (true) {
3606
+ const summaryChoice = await this.showExtensionSelector("Summarize branch?", ["No summary", "Summarize", "Summarize with custom prompt"]);
3607
+ if (summaryChoice === undefined) {
3608
+ // User pressed escape - re-show tree selector with same selection
3609
+ this.showTreeSelector(entryId);
3610
+ return;
3611
+ }
3612
+ wantsSummary = summaryChoice !== "No summary";
3613
+ if (summaryChoice === "Summarize with custom prompt") {
3614
+ customInstructions = await this.showExtensionEditor("Custom summarization instructions");
3615
+ if (customInstructions === undefined) {
3616
+ // User cancelled - loop back to summary selector
3617
+ continue;
3618
+ }
3619
+ }
3620
+ // User made a complete choice
3621
+ break;
3622
+ }
3623
+ }
3624
+ // Set up escape handler and loader if summarizing
3625
+ let summaryLoader;
3626
+ const originalOnEscape = this.defaultEditor.onEscape;
3627
+ if (wantsSummary) {
3628
+ this.defaultEditor.onEscape = () => {
3629
+ this.session.abortBranchSummary();
3630
+ };
3631
+ this.chatContainer.addChild(new Spacer(1));
3632
+ summaryLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), `Summarizing branch... (${keyText("app.interrupt")} to cancel)`);
3633
+ this.statusContainer.addChild(summaryLoader);
3634
+ this.ui.requestRender();
3635
+ }
3636
+ try {
3637
+ const result = await this.session.navigateTree(entryId, {
3638
+ summarize: wantsSummary,
3639
+ customInstructions,
3640
+ });
3641
+ if (result.aborted) {
3642
+ // Summarization aborted - re-show tree selector with same selection
3643
+ this.showStatus("Branch summarization cancelled");
3644
+ this.showTreeSelector(entryId);
3645
+ return;
3646
+ }
3647
+ if (result.cancelled) {
3648
+ this.showStatus("Navigation cancelled");
3649
+ return;
3650
+ }
3651
+ // Update UI
3652
+ this.chatContainer.clear();
3653
+ this.renderInitialMessages();
3654
+ if (result.editorText && !this.editor.getText().trim()) {
3655
+ this.editor.setText(result.editorText);
3656
+ }
3657
+ this.showStatus("Navigated to selected point");
3658
+ void this.flushCompactionQueue({ willRetry: false });
3659
+ }
3660
+ catch (error) {
3661
+ this.showError(error instanceof Error ? error.message : String(error));
3662
+ }
3663
+ finally {
3664
+ if (summaryLoader) {
3665
+ summaryLoader.stop();
3666
+ this.statusContainer.clear();
3667
+ }
3668
+ this.defaultEditor.onEscape = originalOnEscape;
3669
+ }
3670
+ }, () => {
3671
+ done();
3672
+ this.ui.requestRender();
3673
+ }, (entryId, label) => {
3674
+ this.sessionManager.appendLabelChange(entryId, label);
3675
+ this.ui.requestRender();
3676
+ }, initialSelectedId, initialFilterMode);
3677
+ return { component: selector, focus: selector };
3678
+ });
3679
+ }
3680
+ showSessionSelector() {
3681
+ this.showSelector((done) => {
3682
+ const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), SessionManager.listAll, async (sessionPath) => {
3683
+ done();
3684
+ await this.handleResumeSession(sessionPath);
3685
+ }, () => {
3686
+ done();
3687
+ this.ui.requestRender();
3688
+ }, () => {
3689
+ void this.shutdown();
3690
+ }, () => this.ui.requestRender(), {
3691
+ renameSession: async (sessionFilePath, nextName) => {
3692
+ const next = (nextName ?? "").trim();
3693
+ if (!next)
3694
+ return;
3695
+ const mgr = SessionManager.open(sessionFilePath);
3696
+ mgr.appendSessionInfo(next);
3697
+ },
3698
+ showRenameHint: true,
3699
+ keybindings: this.keybindings,
3700
+ }, this.sessionManager.getSessionFile());
3701
+ return { component: selector, focus: selector };
3702
+ });
3703
+ }
3704
+ async handleResumeSession(sessionPath, options) {
3705
+ if (this.loadingAnimation) {
3706
+ this.loadingAnimation.stop();
3707
+ this.loadingAnimation = undefined;
3708
+ }
3709
+ this.statusContainer.clear();
3710
+ try {
3711
+ const result = await this.runtimeHost.switchSession(sessionPath, {
3712
+ withSession: options?.withSession,
3713
+ });
3714
+ if (result.cancelled) {
3715
+ return result;
3716
+ }
3717
+ this.renderCurrentSessionState();
3718
+ this.showStatus("Resumed session");
3719
+ return result;
3720
+ }
3721
+ catch (error) {
3722
+ if (error instanceof MissingSessionCwdError) {
3723
+ const selectedCwd = await this.promptForMissingSessionCwd(error);
3724
+ if (!selectedCwd) {
3725
+ this.showStatus("Resume cancelled");
3726
+ return { cancelled: true };
3727
+ }
3728
+ const result = await this.runtimeHost.switchSession(sessionPath, {
3729
+ cwdOverride: selectedCwd,
3730
+ withSession: options?.withSession,
3731
+ });
3732
+ if (result.cancelled) {
3733
+ return result;
3734
+ }
3735
+ this.renderCurrentSessionState();
3736
+ this.showStatus("Resumed session in current cwd");
3737
+ return result;
3738
+ }
3739
+ return this.handleFatalRuntimeError("Failed to resume session", error);
3740
+ }
3741
+ }
3742
+ getLoginProviderOptions(authType) {
3743
+ const authStorage = this.session.modelRegistry.authStorage;
3744
+ const oauthProviders = authStorage.getOAuthProviders();
3745
+ const oauthProviderIds = new Set(oauthProviders.map((provider) => provider.id));
3746
+ const options = oauthProviders.map((provider) => ({
3747
+ id: provider.id,
3748
+ name: provider.name,
3749
+ authType: "oauth",
3750
+ }));
3751
+ const modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));
3752
+ for (const providerId of modelProviders) {
3753
+ if (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {
3754
+ continue;
3755
+ }
3756
+ options.push({
3757
+ id: providerId,
3758
+ name: this.session.modelRegistry.getProviderDisplayName(providerId),
3759
+ authType: "api_key",
3760
+ });
3761
+ }
3762
+ const filteredOptions = authType
3763
+ ? options.filter((option) => option.authType === authType)
3764
+ : options;
3765
+ return filteredOptions.sort((a, b) => a.name.localeCompare(b.name));
3766
+ }
3767
+ getLogoutProviderOptions() {
3768
+ const authStorage = this.session.modelRegistry.authStorage;
3769
+ const options = [];
3770
+ for (const providerId of authStorage.list()) {
3771
+ const credential = authStorage.get(providerId);
3772
+ if (!credential) {
3773
+ continue;
3774
+ }
3775
+ options.push({
3776
+ id: providerId,
3777
+ name: this.session.modelRegistry.getProviderDisplayName(providerId),
3778
+ authType: credential.type,
3779
+ });
3780
+ }
3781
+ return options.sort((a, b) => a.name.localeCompare(b.name));
3782
+ }
3783
+ showLoginAuthTypeSelector() {
3784
+ const subscriptionLabel = "Use a subscription";
3785
+ const apiKeyLabel = "Use an API key";
3786
+ this.showSelector((done) => {
3787
+ const selector = new ExtensionSelectorComponent("Select authentication method:", [subscriptionLabel, apiKeyLabel], (option) => {
3788
+ done();
3789
+ const authType = option === subscriptionLabel ? "oauth" : "api_key";
3790
+ this.showLoginProviderSelector(authType);
3791
+ }, () => {
3792
+ done();
3793
+ this.ui.requestRender();
3794
+ });
3795
+ return { component: selector, focus: selector };
3796
+ });
3797
+ }
3798
+ showLoginProviderSelector(authType) {
3799
+ const providerOptions = this.getLoginProviderOptions(authType);
3800
+ if (providerOptions.length === 0) {
3801
+ this.showStatus(authType === "oauth"
3802
+ ? "No subscription providers available."
3803
+ : "No API key providers available.");
3804
+ return;
3805
+ }
3806
+ this.showSelector((done) => {
3807
+ const selector = new OAuthSelectorComponent("login", this.session.modelRegistry.authStorage, providerOptions, async (providerId) => {
3808
+ done();
3809
+ const providerOption = providerOptions.find((provider) => provider.id === providerId);
3810
+ if (!providerOption) {
3811
+ return;
3812
+ }
3813
+ if (providerOption.authType === "oauth") {
3814
+ await this.showLoginDialog(providerOption.id, providerOption.name);
3815
+ }
3816
+ else if (providerOption.id === BEDROCK_PROVIDER_ID) {
3817
+ this.showBedrockSetupDialog(providerOption.id, providerOption.name);
3818
+ }
3819
+ else {
3820
+ await this.showApiKeyLoginDialog(providerOption.id, providerOption.name);
3821
+ }
3822
+ }, () => {
3823
+ done();
3824
+ this.showLoginAuthTypeSelector();
3825
+ }, (providerId) => this.session.modelRegistry.getProviderAuthStatus(providerId));
3826
+ return { component: selector, focus: selector };
3827
+ });
3828
+ }
3829
+ async showOAuthSelector(mode) {
3830
+ if (mode === "login") {
3831
+ this.showLoginAuthTypeSelector();
3832
+ return;
3833
+ }
3834
+ const providerOptions = this.getLogoutProviderOptions();
3835
+ if (providerOptions.length === 0) {
3836
+ this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");
3837
+ return;
3838
+ }
3839
+ this.showSelector((done) => {
3840
+ const selector = new OAuthSelectorComponent(mode, this.session.modelRegistry.authStorage, providerOptions, async (providerId) => {
3841
+ done();
3842
+ const providerOption = providerOptions.find((provider) => provider.id === providerId);
3843
+ if (!providerOption) {
3844
+ return;
3845
+ }
3846
+ try {
3847
+ this.session.modelRegistry.authStorage.logout(providerOption.id);
3848
+ this.session.modelRegistry.refresh();
3849
+ await this.updateAvailableProviderCount();
3850
+ const message = providerOption.authType === "oauth"
3851
+ ? `Logged out of ${providerOption.name}`
3852
+ : `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;
3853
+ this.showStatus(message);
3854
+ }
3855
+ catch (error) {
3856
+ this.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);
3857
+ }
3858
+ }, () => {
3859
+ done();
3860
+ this.ui.requestRender();
3861
+ });
3862
+ return { component: selector, focus: selector };
3863
+ });
3864
+ }
3865
+ async completeProviderAuthentication(providerId, providerName, authType, previousModel) {
3866
+ this.session.modelRegistry.refresh();
3867
+ const actionLabel = authType === "oauth"
3868
+ ? `Logged in to ${providerName}`
3869
+ : `Saved API key for ${providerName}`;
3870
+ let selectedModel;
3871
+ let selectionError;
3872
+ if (isUnknownModel(previousModel)) {
3873
+ const availableModels = this.session.modelRegistry.getAvailable();
3874
+ const providerModels = availableModels.filter((model) => model.provider === providerId);
3875
+ if (!hasDefaultModelProvider(providerId)) {
3876
+ selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;
3877
+ }
3878
+ else if (providerModels.length === 0) {
3879
+ selectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;
3880
+ }
3881
+ else {
3882
+ const defaultModelId = defaultModelPerProvider[providerId];
3883
+ selectedModel = providerModels.find((model) => model.id === defaultModelId);
3884
+ if (!selectedModel) {
3885
+ selectionError = `${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;
3886
+ }
3887
+ else {
3888
+ try {
3889
+ await this.session.setModel(selectedModel);
3890
+ }
3891
+ catch (error) {
3892
+ selectedModel = undefined;
3893
+ const errorMessage = error instanceof Error ? error.message : String(error);
3894
+ selectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;
3895
+ }
3896
+ }
3897
+ }
3898
+ }
3899
+ await this.updateAvailableProviderCount();
3900
+ this.footer.invalidate();
3901
+ this.updateEditorBorderColor();
3902
+ if (selectedModel) {
3903
+ this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);
3904
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);
3905
+ this.checkDaxnutsEasterEgg(selectedModel);
3906
+ }
3907
+ else {
3908
+ this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);
3909
+ if (selectionError) {
3910
+ this.showError(selectionError);
3911
+ }
3912
+ else {
3913
+ void this.maybeWarnAboutAnthropicSubscriptionAuth();
3914
+ }
3915
+ }
3916
+ }
3917
+ showBedrockSetupDialog(providerId, providerName) {
3918
+ const restoreEditor = () => {
3919
+ this.editorContainer.clear();
3920
+ this.editorContainer.addChild(this.editor);
3921
+ this.ui.setFocus(this.editor);
3922
+ this.ui.requestRender();
3923
+ };
3924
+ const dialog = new LoginDialogComponent(this.ui, providerId, () => restoreEditor(), providerName, "Amazon Bedrock setup");
3925
+ dialog.showInfo([
3926
+ theme.fg("text", "Amazon Bedrock uses AWS credentials instead of a single API key."),
3927
+ theme.fg("text", "Configure an AWS profile, IAM keys, bearer token, or role-based credentials."),
3928
+ theme.fg("muted", "See:"),
3929
+ theme.fg("accent", ` ${path.join(getDocsPath(), "providers.md")}`),
3930
+ ]);
3931
+ this.editorContainer.clear();
3932
+ this.editorContainer.addChild(dialog);
3933
+ this.ui.setFocus(dialog);
3934
+ this.ui.requestRender();
3935
+ }
3936
+ async showApiKeyLoginDialog(providerId, providerName) {
3937
+ const previousModel = this.session.model;
3938
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
3939
+ // Completion handled below
3940
+ }, providerName);
3941
+ this.editorContainer.clear();
3942
+ this.editorContainer.addChild(dialog);
3943
+ this.ui.setFocus(dialog);
3944
+ this.ui.requestRender();
3945
+ const restoreEditor = () => {
3946
+ this.editorContainer.clear();
3947
+ this.editorContainer.addChild(this.editor);
3948
+ this.ui.setFocus(this.editor);
3949
+ this.ui.requestRender();
3950
+ };
3951
+ try {
3952
+ const apiKey = (await dialog.showPrompt("Enter API key:")).trim();
3953
+ if (!apiKey) {
3954
+ throw new Error("API key cannot be empty.");
3955
+ }
3956
+ this.session.modelRegistry.authStorage.set(providerId, {
3957
+ type: "api_key",
3958
+ key: apiKey,
3959
+ });
3960
+ restoreEditor();
3961
+ await this.completeProviderAuthentication(providerId, providerName, "api_key", previousModel);
3962
+ }
3963
+ catch (error) {
3964
+ restoreEditor();
3965
+ const errorMsg = error instanceof Error ? error.message : String(error);
3966
+ if (errorMsg !== "Login cancelled") {
3967
+ this.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);
3968
+ }
3969
+ }
3970
+ }
3971
+ showOAuthLoginSelect(dialog, prompt) {
3972
+ return new Promise((resolve) => {
3973
+ const restoreDialog = () => {
3974
+ this.editorContainer.clear();
3975
+ this.editorContainer.addChild(dialog);
3976
+ this.ui.setFocus(dialog);
3977
+ this.ui.requestRender();
3978
+ };
3979
+ const labels = prompt.options.map((option) => option.label);
3980
+ const selector = new ExtensionSelectorComponent(prompt.message, labels, (optionLabel) => {
3981
+ restoreDialog();
3982
+ resolve(prompt.options.find((option) => option.label === optionLabel)?.id);
3983
+ }, () => {
3984
+ restoreDialog();
3985
+ resolve(undefined);
3986
+ });
3987
+ this.editorContainer.clear();
3988
+ this.editorContainer.addChild(selector);
3989
+ this.ui.setFocus(selector);
3990
+ this.ui.requestRender();
3991
+ });
3992
+ }
3993
+ async showLoginDialog(providerId, providerName) {
3994
+ const providerInfo = this.session.modelRegistry.authStorage
3995
+ .getOAuthProviders()
3996
+ .find((provider) => provider.id === providerId);
3997
+ const previousModel = this.session.model;
3998
+ // Providers that use callback servers (can paste redirect URL)
3999
+ const usesCallbackServer = providerInfo?.usesCallbackServer ?? false;
4000
+ // Create login dialog component
4001
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
4002
+ // Completion handled below
4003
+ }, providerName);
4004
+ // Show dialog in editor container
4005
+ this.editorContainer.clear();
4006
+ this.editorContainer.addChild(dialog);
4007
+ this.ui.setFocus(dialog);
4008
+ this.ui.requestRender();
4009
+ // Promise for manual code input (racing with callback server)
4010
+ let manualCodeResolve;
4011
+ let manualCodeReject;
4012
+ const manualCodePromise = new Promise((resolve, reject) => {
4013
+ manualCodeResolve = resolve;
4014
+ manualCodeReject = reject;
4015
+ });
4016
+ // Restore editor helper
4017
+ const restoreEditor = () => {
4018
+ this.editorContainer.clear();
4019
+ this.editorContainer.addChild(this.editor);
4020
+ this.ui.setFocus(this.editor);
4021
+ this.ui.requestRender();
4022
+ };
4023
+ try {
4024
+ await this.session.modelRegistry.authStorage.login(providerId, {
4025
+ onAuth: (info) => {
4026
+ dialog.showAuth(info.url, info.instructions);
4027
+ if (usesCallbackServer) {
4028
+ // Show input for manual paste, racing with callback
4029
+ dialog
4030
+ .showManualInput("Paste redirect URL below, or complete login in browser:")
4031
+ .then((value) => {
4032
+ if (value && manualCodeResolve) {
4033
+ manualCodeResolve(value);
4034
+ manualCodeResolve = undefined;
4035
+ }
4036
+ })
4037
+ .catch(() => {
4038
+ if (manualCodeReject) {
4039
+ manualCodeReject(new Error("Login cancelled"));
4040
+ manualCodeReject = undefined;
4041
+ }
4042
+ });
4043
+ }
4044
+ else if (providerId === "github-copilot") {
4045
+ // GitHub Copilot polls after onAuth
4046
+ dialog.showWaiting("Waiting for browser authentication...");
4047
+ }
4048
+ // For Anthropic: onPrompt is called immediately after
4049
+ },
4050
+ onPrompt: async (prompt) => {
4051
+ return dialog.showPrompt(prompt.message, prompt.placeholder);
4052
+ },
4053
+ onProgress: (message) => {
4054
+ dialog.showProgress(message);
4055
+ },
4056
+ onSelect: (prompt) => this.showOAuthLoginSelect(dialog, prompt),
4057
+ onManualCodeInput: () => manualCodePromise,
4058
+ signal: dialog.signal,
4059
+ });
4060
+ // Success
4061
+ restoreEditor();
4062
+ await this.completeProviderAuthentication(providerId, providerName, "oauth", previousModel);
4063
+ }
4064
+ catch (error) {
4065
+ restoreEditor();
4066
+ const errorMsg = error instanceof Error ? error.message : String(error);
4067
+ if (errorMsg !== "Login cancelled") {
4068
+ this.showError(`Failed to login to ${providerName}: ${errorMsg}`);
4069
+ }
4070
+ }
4071
+ }
4072
+ // =========================================================================
4073
+ // Command handlers
4074
+ // =========================================================================
4075
+ async handleReloadCommand() {
4076
+ if (this.session.isStreaming) {
4077
+ this.showWarning("Wait for the current response to finish before reloading.");
4078
+ return;
4079
+ }
4080
+ if (this.session.isCompacting) {
4081
+ this.showWarning("Wait for compaction to finish before reloading.");
4082
+ return;
4083
+ }
4084
+ this.resetExtensionUI();
4085
+ const reloadBox = new Container();
4086
+ const borderColor = (s) => theme.fg("border", s);
4087
+ reloadBox.addChild(new DynamicBorder(borderColor));
4088
+ reloadBox.addChild(new Spacer(1));
4089
+ reloadBox.addChild(new Text(theme.fg("muted", "Reloading keybindings, extensions, skills, prompts, themes..."), 1, 0));
4090
+ reloadBox.addChild(new Spacer(1));
4091
+ reloadBox.addChild(new DynamicBorder(borderColor));
4092
+ const previousEditor = this.editor;
4093
+ this.editorContainer.clear();
4094
+ this.editorContainer.addChild(reloadBox);
4095
+ this.ui.setFocus(reloadBox);
4096
+ this.ui.requestRender(true);
4097
+ await new Promise((resolve) => process.nextTick(resolve));
4098
+ const dismissReloadBox = (editor) => {
4099
+ this.editorContainer.clear();
4100
+ this.editorContainer.addChild(editor);
4101
+ this.ui.setFocus(editor);
4102
+ this.ui.requestRender();
4103
+ };
4104
+ try {
4105
+ await this.session.reload();
4106
+ this.keybindings.reload();
4107
+ const activeHeader = this.customHeader ?? this.builtInHeader;
4108
+ if (isExpandable(activeHeader)) {
4109
+ activeHeader.setExpanded(this.toolOutputExpanded);
4110
+ }
4111
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
4112
+ this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
4113
+ const themeName = this.settingsManager.getTheme();
4114
+ const themeResult = themeName
4115
+ ? setTheme(themeName, true)
4116
+ : { success: true };
4117
+ if (!themeResult.success) {
4118
+ this.showError(`Failed to load theme "${themeName}": ${themeResult.error}\nFell back to dark theme.`);
4119
+ }
4120
+ const editorPaddingX = this.settingsManager.getEditorPaddingX();
4121
+ const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
4122
+ this.defaultEditor.setPaddingX(editorPaddingX);
4123
+ this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);
4124
+ if (this.editor !== this.defaultEditor) {
4125
+ this.editor.setPaddingX?.(editorPaddingX);
4126
+ this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);
4127
+ }
4128
+ this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());
4129
+ this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
4130
+ this.setupAutocompleteProvider();
4131
+ const runner = this.session.extensionRunner;
4132
+ this.setupExtensionShortcuts(runner);
4133
+ this.rebuildChatFromMessages();
4134
+ dismissReloadBox(this.editor);
4135
+ this.showLoadedResources({
4136
+ force: false,
4137
+ showDiagnosticsWhenQuiet: true,
4138
+ });
4139
+ const modelsJsonError = this.session.modelRegistry.getError();
4140
+ if (modelsJsonError) {
4141
+ this.showError(`models.json error: ${modelsJsonError}`);
4142
+ }
4143
+ this.showStatus("Reloaded keybindings, extensions, skills, prompts, themes");
4144
+ }
4145
+ catch (error) {
4146
+ dismissReloadBox(previousEditor);
4147
+ this.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);
4148
+ }
4149
+ }
4150
+ async handleExportCommand(text) {
4151
+ const outputPath = this.getPathCommandArgument(text, "/export");
4152
+ try {
4153
+ if (outputPath?.endsWith(".jsonl")) {
4154
+ const filePath = this.session.exportToJsonl(outputPath);
4155
+ this.showStatus(`Session exported to: ${filePath}`);
4156
+ }
4157
+ else {
4158
+ const filePath = await this.session.exportToHtml(outputPath);
4159
+ this.showStatus(`Session exported to: ${filePath}`);
4160
+ }
4161
+ }
4162
+ catch (error) {
4163
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
4164
+ }
4165
+ }
4166
+ getPathCommandArgument(text, command) {
4167
+ if (text === command) {
4168
+ return undefined;
4169
+ }
4170
+ if (!text.startsWith(`${command} `)) {
4171
+ return undefined;
4172
+ }
4173
+ const argsString = text.slice(command.length + 1).trimStart();
4174
+ if (!argsString) {
4175
+ return undefined;
4176
+ }
4177
+ const firstChar = argsString[0];
4178
+ if (firstChar === '"' || firstChar === "'") {
4179
+ const closingQuoteIndex = argsString.indexOf(firstChar, 1);
4180
+ if (closingQuoteIndex < 0) {
4181
+ return undefined;
4182
+ }
4183
+ return argsString.slice(1, closingQuoteIndex);
4184
+ }
4185
+ const firstWhitespaceIndex = argsString.search(/\s/);
4186
+ if (firstWhitespaceIndex < 0) {
4187
+ return argsString;
4188
+ }
4189
+ return argsString.slice(0, firstWhitespaceIndex);
4190
+ }
4191
+ async handleImportCommand(text) {
4192
+ const inputPath = this.getPathCommandArgument(text, "/import");
4193
+ if (!inputPath) {
4194
+ this.showError("Usage: /import <path.jsonl>");
4195
+ return;
4196
+ }
4197
+ const confirmed = await this.showExtensionConfirm("Import session", `Replace current session with ${inputPath}?`);
4198
+ if (!confirmed) {
4199
+ this.showStatus("Import cancelled");
4200
+ return;
4201
+ }
4202
+ try {
4203
+ if (this.loadingAnimation) {
4204
+ this.loadingAnimation.stop();
4205
+ this.loadingAnimation = undefined;
4206
+ }
4207
+ this.statusContainer.clear();
4208
+ const result = await this.runtimeHost.importFromJsonl(inputPath);
4209
+ if (result.cancelled) {
4210
+ this.showStatus("Import cancelled");
4211
+ return;
4212
+ }
4213
+ this.renderCurrentSessionState();
4214
+ this.showStatus(`Session imported from: ${inputPath}`);
4215
+ }
4216
+ catch (error) {
4217
+ if (error instanceof MissingSessionCwdError) {
4218
+ const selectedCwd = await this.promptForMissingSessionCwd(error);
4219
+ if (!selectedCwd) {
4220
+ this.showStatus("Import cancelled");
4221
+ return;
4222
+ }
4223
+ const result = await this.runtimeHost.importFromJsonl(inputPath, selectedCwd);
4224
+ if (result.cancelled) {
4225
+ this.showStatus("Import cancelled");
4226
+ return;
4227
+ }
4228
+ this.renderCurrentSessionState();
4229
+ this.showStatus(`Session imported from: ${inputPath}`);
4230
+ return;
4231
+ }
4232
+ if (error instanceof SessionImportFileNotFoundError) {
4233
+ this.showError(`Failed to import session: ${error.message}`);
4234
+ return;
4235
+ }
4236
+ await this.handleFatalRuntimeError("Failed to import session", error);
4237
+ }
4238
+ }
4239
+ async handleShareCommand() {
4240
+ // Check if gh is available and logged in
4241
+ try {
4242
+ const authResult = spawnSync("gh", ["auth", "status"], {
4243
+ encoding: "utf-8",
4244
+ });
4245
+ if (authResult.status !== 0) {
4246
+ this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");
4247
+ return;
4248
+ }
4249
+ }
4250
+ catch {
4251
+ this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");
4252
+ return;
4253
+ }
4254
+ // Export to a temp file
4255
+ const tmpFile = path.join(os.tmpdir(), "session.html");
4256
+ try {
4257
+ await this.session.exportToHtml(tmpFile);
4258
+ }
4259
+ catch (error) {
4260
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
4261
+ return;
4262
+ }
4263
+ // Show cancellable loader, replacing the editor
4264
+ const loader = new BorderedLoader(this.ui, theme, "Creating gist...");
4265
+ this.editorContainer.clear();
4266
+ this.editorContainer.addChild(loader);
4267
+ this.ui.setFocus(loader);
4268
+ this.ui.requestRender();
4269
+ const restoreEditor = () => {
4270
+ loader.dispose();
4271
+ this.editorContainer.clear();
4272
+ this.editorContainer.addChild(this.editor);
4273
+ this.ui.setFocus(this.editor);
4274
+ try {
4275
+ fs.unlinkSync(tmpFile);
4276
+ }
4277
+ catch {
4278
+ // Ignore cleanup errors
4279
+ }
4280
+ };
4281
+ // Create a secret gist asynchronously
4282
+ let proc = null;
4283
+ loader.onAbort = () => {
4284
+ proc?.kill();
4285
+ restoreEditor();
4286
+ this.showStatus("Share cancelled");
4287
+ };
4288
+ try {
4289
+ const result = await new Promise((resolve) => {
4290
+ proc = spawn("gh", ["gist", "create", "--public=false", tmpFile]);
4291
+ let stdout = "";
4292
+ let stderr = "";
4293
+ proc.stdout?.on("data", (data) => {
4294
+ stdout += data.toString();
4295
+ });
4296
+ proc.stderr?.on("data", (data) => {
4297
+ stderr += data.toString();
4298
+ });
4299
+ proc.on("close", (code) => resolve({ stdout, stderr, code }));
4300
+ });
4301
+ if (loader.signal.aborted)
4302
+ return;
4303
+ restoreEditor();
4304
+ if (result.code !== 0) {
4305
+ const errorMsg = result.stderr?.trim() || "Unknown error";
4306
+ this.showError(`Failed to create gist: ${errorMsg}`);
4307
+ return;
4308
+ }
4309
+ // Extract gist ID from the URL returned by gh
4310
+ // gh returns something like: https://gist.github.com/username/GIST_ID
4311
+ const gistUrl = result.stdout?.trim();
4312
+ const gistId = gistUrl?.split("/").pop();
4313
+ if (!gistId) {
4314
+ this.showError("Failed to parse gist ID from gh output");
4315
+ return;
4316
+ }
4317
+ // Create the preview URL
4318
+ const previewUrl = getShareViewerUrl(gistId);
4319
+ this.showStatus(`Share URL: ${previewUrl}\nGist: ${gistUrl}`);
4320
+ }
4321
+ catch (error) {
4322
+ if (!loader.signal.aborted) {
4323
+ restoreEditor();
4324
+ this.showError(`Failed to create gist: ${error instanceof Error ? error.message : "Unknown error"}`);
4325
+ }
4326
+ }
4327
+ }
4328
+ async handleCopyCommand() {
4329
+ const text = this.session.getLastAssistantText();
4330
+ if (!text) {
4331
+ this.showError("No agent messages to copy yet.");
4332
+ return;
4333
+ }
4334
+ try {
4335
+ await copyToClipboard(text);
4336
+ this.showStatus("Copied last agent message to clipboard");
4337
+ }
4338
+ catch (error) {
4339
+ this.showError(error instanceof Error ? error.message : String(error));
4340
+ }
4341
+ }
4342
+ handleNameCommand(text) {
4343
+ const name = text.replace(/^\/name\s*/, "").trim();
4344
+ if (!name) {
4345
+ const currentName = this.sessionManager.getSessionName();
4346
+ if (currentName) {
4347
+ this.chatContainer.addChild(new Spacer(1));
4348
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name: ${currentName}`), 1, 0));
4349
+ }
4350
+ else {
4351
+ this.showWarning("Usage: /name <name>");
4352
+ }
4353
+ this.ui.requestRender();
4354
+ return;
4355
+ }
4356
+ this.session.setSessionName(name);
4357
+ this.chatContainer.addChild(new Spacer(1));
4358
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name set: ${name}`), 1, 0));
4359
+ this.ui.requestRender();
4360
+ }
4361
+ handleSessionCommand() {
4362
+ const stats = this.session.getSessionStats();
4363
+ const sessionName = this.sessionManager.getSessionName();
4364
+ let info = `${theme.bold("Session Info")}\n\n`;
4365
+ if (sessionName) {
4366
+ info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
4367
+ }
4368
+ info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
4369
+ info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
4370
+ info += `${theme.bold("Messages")}\n`;
4371
+ info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
4372
+ info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
4373
+ info += `${theme.fg("dim", "Tool Calls:")} ${stats.toolCalls}\n`;
4374
+ info += `${theme.fg("dim", "Tool Results:")} ${stats.toolResults}\n`;
4375
+ info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n\n`;
4376
+ info += `${theme.bold("Tokens")}\n`;
4377
+ info += `${theme.fg("dim", "Input:")} ${stats.tokens.input.toLocaleString()}\n`;
4378
+ info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`;
4379
+ if (stats.tokens.cacheRead > 0) {
4380
+ info += `${theme.fg("dim", "Cache Read:")} ${stats.tokens.cacheRead.toLocaleString()}\n`;
4381
+ }
4382
+ if (stats.tokens.cacheWrite > 0) {
4383
+ info += `${theme.fg("dim", "Cache Write:")} ${stats.tokens.cacheWrite.toLocaleString()}\n`;
4384
+ }
4385
+ info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`;
4386
+ if (stats.cost > 0) {
4387
+ info += `\n${theme.bold("Cost")}\n`;
4388
+ info += `${theme.fg("dim", "Total:")} ${stats.cost.toFixed(4)}`;
4389
+ }
4390
+ this.chatContainer.addChild(new Spacer(1));
4391
+ this.chatContainer.addChild(new Text(info, 1, 0));
4392
+ this.ui.requestRender();
4393
+ }
4394
+ handleChangelogCommand() {
4395
+ const changelogPath = getChangelogPath();
4396
+ const allEntries = parseChangelog(changelogPath);
4397
+ const changelogMarkdown = allEntries.length > 0
4398
+ ? allEntries
4399
+ .reverse()
4400
+ .map((e) => e.content)
4401
+ .join("\n\n")
4402
+ : "No changelog entries found.";
4403
+ this.chatContainer.addChild(new Spacer(1));
4404
+ this.chatContainer.addChild(new DynamicBorder());
4405
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
4406
+ this.chatContainer.addChild(new Spacer(1));
4407
+ this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));
4408
+ this.chatContainer.addChild(new DynamicBorder());
4409
+ this.ui.requestRender();
4410
+ }
4411
+ /**
4412
+ * Get capitalized display string for an app keybinding action.
4413
+ */
4414
+ getAppKeyDisplay(action) {
4415
+ return keyDisplayText(action);
4416
+ }
4417
+ /**
4418
+ * Get capitalized display string for an editor keybinding action.
4419
+ */
4420
+ getEditorKeyDisplay(action) {
4421
+ return keyDisplayText(action);
4422
+ }
4423
+ handleHotkeysCommand() {
4424
+ // Navigation keybindings
4425
+ const cursorUp = this.getEditorKeyDisplay("tui.editor.cursorUp");
4426
+ const cursorDown = this.getEditorKeyDisplay("tui.editor.cursorDown");
4427
+ const cursorLeft = this.getEditorKeyDisplay("tui.editor.cursorLeft");
4428
+ const cursorRight = this.getEditorKeyDisplay("tui.editor.cursorRight");
4429
+ const cursorWordLeft = this.getEditorKeyDisplay("tui.editor.cursorWordLeft");
4430
+ const cursorWordRight = this.getEditorKeyDisplay("tui.editor.cursorWordRight");
4431
+ const cursorLineStart = this.getEditorKeyDisplay("tui.editor.cursorLineStart");
4432
+ const cursorLineEnd = this.getEditorKeyDisplay("tui.editor.cursorLineEnd");
4433
+ const jumpForward = this.getEditorKeyDisplay("tui.editor.jumpForward");
4434
+ const jumpBackward = this.getEditorKeyDisplay("tui.editor.jumpBackward");
4435
+ const pageUp = this.getEditorKeyDisplay("tui.editor.pageUp");
4436
+ const pageDown = this.getEditorKeyDisplay("tui.editor.pageDown");
4437
+ // Editing keybindings
4438
+ const submit = this.getEditorKeyDisplay("tui.input.submit");
4439
+ const newLine = this.getEditorKeyDisplay("tui.input.newLine");
4440
+ const deleteWordBackward = this.getEditorKeyDisplay("tui.editor.deleteWordBackward");
4441
+ const deleteWordForward = this.getEditorKeyDisplay("tui.editor.deleteWordForward");
4442
+ const deleteToLineStart = this.getEditorKeyDisplay("tui.editor.deleteToLineStart");
4443
+ const deleteToLineEnd = this.getEditorKeyDisplay("tui.editor.deleteToLineEnd");
4444
+ const yank = this.getEditorKeyDisplay("tui.editor.yank");
4445
+ const yankPop = this.getEditorKeyDisplay("tui.editor.yankPop");
4446
+ const undo = this.getEditorKeyDisplay("tui.editor.undo");
4447
+ const tab = this.getEditorKeyDisplay("tui.input.tab");
4448
+ // App keybindings
4449
+ const interrupt = this.getAppKeyDisplay("app.interrupt");
4450
+ const clear = this.getAppKeyDisplay("app.clear");
4451
+ const exit = this.getAppKeyDisplay("app.exit");
4452
+ const suspend = this.getAppKeyDisplay("app.suspend");
4453
+ const cycleThinkingLevel = this.getAppKeyDisplay("app.thinking.cycle");
4454
+ const cycleModelForward = this.getAppKeyDisplay("app.model.cycleForward");
4455
+ const selectModel = this.getAppKeyDisplay("app.model.select");
4456
+ const expandTools = this.getAppKeyDisplay("app.tools.expand");
4457
+ const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");
4458
+ const externalEditor = this.getAppKeyDisplay("app.editor.external");
4459
+ const cycleModelBackward = this.getAppKeyDisplay("app.model.cycleBackward");
4460
+ const followUp = this.getAppKeyDisplay("app.message.followUp");
4461
+ const dequeue = this.getAppKeyDisplay("app.message.dequeue");
4462
+ const pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage");
4463
+ let hotkeys = `
4464
+ **Navigation**
4465
+ | Key | Action |
4466
+ |-----|--------|
4467
+ | \`${cursorUp}\` / \`${cursorDown}\` / \`${cursorLeft}\` / \`${cursorRight}\` | Move cursor / browse history (Up when empty) |
4468
+ | \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word |
4469
+ | \`${cursorLineStart}\` | Start of line |
4470
+ | \`${cursorLineEnd}\` | End of line |
4471
+ | \`${jumpForward}\` | Jump forward to character |
4472
+ | \`${jumpBackward}\` | Jump backward to character |
4473
+ | \`${pageUp}\` / \`${pageDown}\` | Scroll by page |
4474
+
4475
+ **Editing**
4476
+ | Key | Action |
4477
+ |-----|--------|
4478
+ | \`${submit}\` | Send message |
4479
+ | \`${newLine}\` | New line${process.platform === "win32" ? " (Ctrl+Enter on Windows Terminal)" : ""} |
4480
+ | \`${deleteWordBackward}\` | Delete word backwards |
4481
+ | \`${deleteWordForward}\` | Delete word forwards |
4482
+ | \`${deleteToLineStart}\` | Delete to start of line |
4483
+ | \`${deleteToLineEnd}\` | Delete to end of line |
4484
+ | \`${yank}\` | Paste the most-recently-deleted text |
4485
+ | \`${yankPop}\` | Cycle through the deleted text after pasting |
4486
+ | \`${undo}\` | Undo |
4487
+
4488
+ **Other**
4489
+ | Key | Action |
4490
+ |-----|--------|
4491
+ | \`${tab}\` | Path completion / accept autocomplete |
4492
+ | \`${interrupt}\` | Cancel autocomplete / abort streaming |
4493
+ | \`${clear}\` | Clear editor (first) / exit (second) |
4494
+ | \`${exit}\` | Exit (when editor is empty) |
4495
+ | \`${suspend}\` | Suspend to background |
4496
+ | \`${cycleThinkingLevel}\` | Cycle thinking level |
4497
+ | \`${cycleModelForward}\` / \`${cycleModelBackward}\` | Cycle models |
4498
+ | \`${selectModel}\` | Open model selector |
4499
+ | \`${expandTools}\` | Toggle tool output expansion |
4500
+ | \`${toggleThinking}\` | Toggle thinking block visibility |
4501
+ | \`${externalEditor}\` | Edit message in external editor |
4502
+ | \`${followUp}\` | Queue follow-up message |
4503
+ | \`${dequeue}\` | Restore queued messages |
4504
+ | \`${pasteImage}\` | Paste image from clipboard |
4505
+ | \`/\` | Slash commands |
4506
+ | \`!\` | Run bash command |
4507
+ | \`!!\` | Run bash command (excluded from context) |
4508
+ `;
4509
+ // Add extension-registered shortcuts
4510
+ const extensionRunner = this.session.extensionRunner;
4511
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
4512
+ if (shortcuts.size > 0) {
4513
+ hotkeys += `
4514
+ **Extensions**
4515
+ | Key | Action |
4516
+ |-----|--------|
4517
+ `;
4518
+ for (const [key, shortcut] of shortcuts) {
4519
+ const description = shortcut.description ?? shortcut.extensionPath;
4520
+ const keyDisplay = formatKeyText(key, { capitalize: true });
4521
+ hotkeys += `| \`${keyDisplay}\` | ${description} |\n`;
4522
+ }
4523
+ }
4524
+ this.chatContainer.addChild(new Spacer(1));
4525
+ this.chatContainer.addChild(new DynamicBorder());
4526
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0));
4527
+ this.chatContainer.addChild(new Spacer(1));
4528
+ this.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));
4529
+ this.chatContainer.addChild(new DynamicBorder());
4530
+ this.ui.requestRender();
4531
+ }
4532
+ async handleClearCommand() {
4533
+ if (this.loadingAnimation) {
4534
+ this.loadingAnimation.stop();
4535
+ this.loadingAnimation = undefined;
4536
+ }
4537
+ this.statusContainer.clear();
4538
+ try {
4539
+ const result = await this.runtimeHost.newSession();
4540
+ if (result.cancelled) {
4541
+ return;
4542
+ }
4543
+ this.renderCurrentSessionState();
4544
+ this.chatContainer.addChild(new Spacer(1));
4545
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));
4546
+ this.ui.requestRender();
4547
+ }
4548
+ catch (error) {
4549
+ await this.handleFatalRuntimeError("Failed to create session", error);
4550
+ }
4551
+ }
4552
+ handleDebugCommand() {
4553
+ const width = this.ui.terminal.columns;
4554
+ const height = this.ui.terminal.rows;
4555
+ const allLines = this.ui.render(width);
4556
+ const debugLogPath = getDebugLogPath();
4557
+ const debugData = [
4558
+ `Debug output at ${new Date().toISOString()}`,
4559
+ `Terminal: ${width}x${height}`,
4560
+ `Total lines: ${allLines.length}`,
4561
+ "",
4562
+ "=== All rendered lines with visible widths ===",
4563
+ ...allLines.map((line, idx) => {
4564
+ const vw = visibleWidth(line);
4565
+ const escaped = JSON.stringify(line);
4566
+ return `[${idx}] (w=${vw}) ${escaped}`;
4567
+ }),
4568
+ "",
4569
+ "=== Agent messages (JSONL) ===",
4570
+ ...this.session.messages.map((msg) => JSON.stringify(msg)),
4571
+ "",
4572
+ ].join("\n");
4573
+ fs.mkdirSync(path.dirname(debugLogPath), { recursive: true });
4574
+ fs.writeFileSync(debugLogPath, debugData);
4575
+ this.chatContainer.addChild(new Spacer(1));
4576
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ Debug log written")}\n${theme.fg("muted", debugLogPath)}`, 1, 1));
4577
+ this.ui.requestRender();
4578
+ }
4579
+ handleArminSaysHi() {
4580
+ this.chatContainer.addChild(new Spacer(1));
4581
+ this.chatContainer.addChild(new ArminComponent(this.ui));
4582
+ this.ui.requestRender();
4583
+ }
4584
+ handleDementedDelves() {
4585
+ this.chatContainer.addChild(new Spacer(1));
4586
+ this.chatContainer.addChild(new EarendilAnnouncementComponent());
4587
+ this.ui.requestRender();
4588
+ }
4589
+ handleDaxnuts() {
4590
+ this.chatContainer.addChild(new Spacer(1));
4591
+ this.chatContainer.addChild(new DaxnutsComponent(this.ui));
4592
+ this.ui.requestRender();
4593
+ }
4594
+ checkDaxnutsEasterEgg(model) {
4595
+ if (model.provider === "opencode" &&
4596
+ model.id.toLowerCase().includes("kimi-k2.5")) {
4597
+ this.handleDaxnuts();
4598
+ }
4599
+ }
4600
+ async handleBashCommand(command, excludeFromContext = false) {
4601
+ const extensionRunner = this.session.extensionRunner;
4602
+ // Emit user_bash event to let extensions intercept
4603
+ const eventResult = await extensionRunner.emitUserBash({
4604
+ type: "user_bash",
4605
+ command,
4606
+ excludeFromContext,
4607
+ cwd: this.sessionManager.getCwd(),
4608
+ });
4609
+ // If extension returned a full result, use it directly
4610
+ if (eventResult?.result) {
4611
+ const result = eventResult.result;
4612
+ // Create UI component for display
4613
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
4614
+ if (this.session.isStreaming) {
4615
+ this.pendingMessagesContainer.addChild(this.bashComponent);
4616
+ this.pendingBashComponents.push(this.bashComponent);
4617
+ }
4618
+ else {
4619
+ this.chatContainer.addChild(this.bashComponent);
4620
+ }
4621
+ // Show output and complete
4622
+ if (result.output) {
4623
+ this.bashComponent.appendOutput(result.output);
4624
+ }
4625
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated
4626
+ ? { truncated: true, content: result.output }
4627
+ : undefined, result.fullOutputPath);
4628
+ // Record the result in session
4629
+ this.session.recordBashResult(command, result, { excludeFromContext });
4630
+ this.bashComponent = undefined;
4631
+ this.ui.requestRender();
4632
+ return;
4633
+ }
4634
+ // Normal execution path (possibly with custom operations)
4635
+ const isDeferred = this.session.isStreaming;
4636
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
4637
+ if (isDeferred) {
4638
+ // Show in pending area when agent is streaming
4639
+ this.pendingMessagesContainer.addChild(this.bashComponent);
4640
+ this.pendingBashComponents.push(this.bashComponent);
4641
+ }
4642
+ else {
4643
+ // Show in chat immediately when agent is idle
4644
+ this.chatContainer.addChild(this.bashComponent);
4645
+ }
4646
+ this.ui.requestRender();
4647
+ try {
4648
+ const result = await this.session.executeBash(command, (chunk) => {
4649
+ if (this.bashComponent) {
4650
+ this.bashComponent.appendOutput(chunk);
4651
+ this.ui.requestRender();
4652
+ }
4653
+ }, { excludeFromContext, operations: eventResult?.operations });
4654
+ if (this.bashComponent) {
4655
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated
4656
+ ? { truncated: true, content: result.output }
4657
+ : undefined, result.fullOutputPath);
4658
+ }
4659
+ }
4660
+ catch (error) {
4661
+ if (this.bashComponent) {
4662
+ this.bashComponent.setComplete(undefined, false);
4663
+ }
4664
+ this.showError(`Bash command failed: ${error instanceof Error ? error.message : "Unknown error"}`);
4665
+ }
4666
+ this.bashComponent = undefined;
4667
+ this.ui.requestRender();
4668
+ }
4669
+ async handleCompactCommand(customInstructions) {
4670
+ const entries = this.sessionManager.getEntries();
4671
+ const messageCount = entries.filter((e) => e.type === "message").length;
4672
+ if (messageCount < 2) {
4673
+ this.showWarning("Nothing to compact (no messages yet)");
4674
+ return;
4675
+ }
4676
+ if (this.loadingAnimation) {
4677
+ this.loadingAnimation.stop();
4678
+ this.loadingAnimation = undefined;
4679
+ }
4680
+ this.statusContainer.clear();
4681
+ try {
4682
+ await this.session.compact(customInstructions);
4683
+ }
4684
+ catch {
4685
+ // Ignore, will be emitted as an event
4686
+ }
4687
+ }
4688
+ stop() {
4689
+ this.unregisterSignalHandlers();
4690
+ if (this.settingsManager.getShowTerminalProgress()) {
4691
+ this.ui.terminal.setProgress(false);
4692
+ }
4693
+ if (this.loadingAnimation) {
4694
+ this.loadingAnimation.stop();
4695
+ this.loadingAnimation = undefined;
4696
+ }
4697
+ this.clearExtensionTerminalInputListeners();
4698
+ this.footer.dispose();
4699
+ this.footerDataProvider.dispose();
4700
+ if (this.unsubscribe) {
4701
+ this.unsubscribe();
4702
+ }
4703
+ if (this.isInitialized) {
4704
+ this.ui.stop();
4705
+ this.isInitialized = false;
4706
+ }
4707
+ }
4708
+ }
4709
+ //# sourceMappingURL=interactive-mode.js.map