@dyyz1993/pi-coding-agent 0.69.5

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