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