@code-yeongyu/senpi 0.74.0

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