@tuan_son.dinh/gsd 2.6.2 → 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 +6 -6
  959. package/pkg/dist/modes/interactive/theme/light.json +6 -5
  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 +2 -2
  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 -78
  1024. package/patches/@mariozechner+pi-tui+0.57.1.patch +0 -47
@@ -0,0 +1,3050 @@
1
+ /**
2
+ * AgentSession - Core abstraction for agent lifecycle and session management.
3
+ *
4
+ * This class is shared between all run modes (interactive, print, rpc).
5
+ * It encapsulates:
6
+ * - Agent state access
7
+ * - Event subscription with automatic session persistence
8
+ * - Model and thinking level management
9
+ * - Compaction (manual and auto)
10
+ * - Bash execution
11
+ * - Session switching and branching
12
+ *
13
+ * Modes use this class and add their own I/O layer on top.
14
+ */
15
+
16
+ import { readFileSync } from "node:fs";
17
+ import { basename, dirname, join } from "node:path";
18
+ import type {
19
+ Agent,
20
+ AgentEvent,
21
+ AgentMessage,
22
+ AgentState,
23
+ AgentTool,
24
+ ThinkingLevel,
25
+ } from "@gsd/pi-agent-core";
26
+ import type { AssistantMessage, ImageContent, Message, Model, TextContent } from "@gsd/pi-ai";
27
+ import { isContextOverflow, modelsAreEqual, resetApiProviders, supportsXhigh } from "@gsd/pi-ai";
28
+ import { getDocsPath } from "../config.js";
29
+ import { theme } from "../modes/interactive/theme/theme.js";
30
+ import { stripFrontmatter } from "../utils/frontmatter.js";
31
+ import { sleep } from "../utils/sleep.js";
32
+ import { type BashResult, executeBash as executeBashCommand, executeBashWithOperations } from "./bash-executor.js";
33
+ import {
34
+ type CompactionResult,
35
+ calculateContextTokens,
36
+ collectEntriesForBranchSummary,
37
+ compact,
38
+ estimateContextTokens,
39
+ generateBranchSummary,
40
+ prepareCompaction,
41
+ shouldCompact,
42
+ } from "./compaction/index.js";
43
+ import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
44
+ import { exportSessionToHtml, type ToolHtmlRenderer } from "./export-html/index.js";
45
+ import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
46
+ import {
47
+ type ContextUsage,
48
+ type ExtensionCommandContextActions,
49
+ type ExtensionErrorListener,
50
+ ExtensionRunner,
51
+ type ExtensionUIContext,
52
+ type InputSource,
53
+ type MessageEndEvent,
54
+ type MessageStartEvent,
55
+ type MessageUpdateEvent,
56
+ type SessionBeforeCompactResult,
57
+ type SessionBeforeForkResult,
58
+ type SessionBeforeSwitchResult,
59
+ type SessionBeforeTreeResult,
60
+ type ShutdownHandler,
61
+ type ToolDefinition,
62
+ type ToolExecutionEndEvent,
63
+ type ToolExecutionStartEvent,
64
+ type ToolExecutionUpdateEvent,
65
+ type ToolInfo,
66
+ type TreePreparation,
67
+ type TurnEndEvent,
68
+ type TurnStartEvent,
69
+ wrapRegisteredTools,
70
+ wrapToolsWithExtensions,
71
+ } from "./extensions/index.js";
72
+ import type { BashExecutionMessage, CustomMessage } from "./messages.js";
73
+ import type { ModelRegistry } from "./model-registry.js";
74
+ import { expandPromptTemplate, type PromptTemplate } from "./prompt-templates.js";
75
+ import type { ResourceExtensionPaths, ResourceLoader } from "./resource-loader.js";
76
+ import type { BranchSummaryEntry, CompactionEntry, SessionManager } from "./session-manager.js";
77
+ import { getLatestCompactionEntry } from "./session-manager.js";
78
+ import type { SettingsManager } from "./settings-manager.js";
79
+ import { BUILTIN_SLASH_COMMANDS, type SlashCommandInfo, type SlashCommandLocation } from "./slash-commands.js";
80
+ import { buildSystemPrompt } from "./system-prompt.js";
81
+ import type { BashOperations } from "./tools/bash.js";
82
+ import { createAllTools } from "./tools/index.js";
83
+
84
+ // ============================================================================
85
+ // Skill Block Parsing
86
+ // ============================================================================
87
+
88
+ /** Parsed skill block from a user message */
89
+ export interface ParsedSkillBlock {
90
+ name: string;
91
+ location: string;
92
+ content: string;
93
+ userMessage: string | undefined;
94
+ }
95
+
96
+ /**
97
+ * Parse a skill block from message text.
98
+ * Returns null if the text doesn't contain a skill block.
99
+ */
100
+ export function parseSkillBlock(text: string): ParsedSkillBlock | null {
101
+ const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
102
+ if (!match) return null;
103
+ return {
104
+ name: match[1],
105
+ location: match[2],
106
+ content: match[3],
107
+ userMessage: match[4]?.trim() || undefined,
108
+ };
109
+ }
110
+
111
+ /** Session-specific events that extend the core AgentEvent */
112
+ export type AgentSessionEvent =
113
+ | AgentEvent
114
+ | { type: "auto_compaction_start"; reason: "threshold" | "overflow" }
115
+ | {
116
+ type: "auto_compaction_end";
117
+ result: CompactionResult | undefined;
118
+ aborted: boolean;
119
+ willRetry: boolean;
120
+ errorMessage?: string;
121
+ }
122
+ | { type: "auto_retry_start"; attempt: number; maxAttempts: number; delayMs: number; errorMessage: string }
123
+ | { type: "auto_retry_end"; success: boolean; attempt: number; finalError?: string };
124
+
125
+ /** Listener function for agent session events */
126
+ export type AgentSessionEventListener = (event: AgentSessionEvent) => void;
127
+
128
+ // ============================================================================
129
+ // Types
130
+ // ============================================================================
131
+
132
+ export interface AgentSessionConfig {
133
+ agent: Agent;
134
+ sessionManager: SessionManager;
135
+ settingsManager: SettingsManager;
136
+ cwd: string;
137
+ /** Models to cycle through with Ctrl+P (from --models flag) */
138
+ scopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
139
+ /** Resource loader for skills, prompts, themes, context files, system prompt */
140
+ resourceLoader: ResourceLoader;
141
+ /** SDK custom tools registered outside extensions */
142
+ customTools?: ToolDefinition[];
143
+ /** Model registry for API key resolution and model discovery */
144
+ modelRegistry: ModelRegistry;
145
+ /** Initial active built-in tool names. Default: [read, bash, edit, write] */
146
+ initialActiveToolNames?: string[];
147
+ /** Override base tools (useful for custom runtimes). */
148
+ baseToolsOverride?: Record<string, AgentTool>;
149
+ /** Mutable ref used by Agent to access the current ExtensionRunner */
150
+ extensionRunnerRef?: { current?: ExtensionRunner };
151
+ }
152
+
153
+ export interface ExtensionBindings {
154
+ uiContext?: ExtensionUIContext;
155
+ commandContextActions?: ExtensionCommandContextActions;
156
+ shutdownHandler?: ShutdownHandler;
157
+ onError?: ExtensionErrorListener;
158
+ }
159
+
160
+ /** Options for AgentSession.prompt() */
161
+ export interface PromptOptions {
162
+ /** Whether to expand file-based prompt templates (default: true) */
163
+ expandPromptTemplates?: boolean;
164
+ /** Image attachments */
165
+ images?: ImageContent[];
166
+ /** When streaming, how to queue the message: "steer" (interrupt) or "followUp" (wait). Required if streaming. */
167
+ streamingBehavior?: "steer" | "followUp";
168
+ /** Source of input for extension input event handlers. Defaults to "interactive". */
169
+ source?: InputSource;
170
+ }
171
+
172
+ /** Result from cycleModel() */
173
+ export interface ModelCycleResult {
174
+ model: Model<any>;
175
+ thinkingLevel: ThinkingLevel;
176
+ /** Whether cycling through scoped models (--models flag) or all available */
177
+ isScoped: boolean;
178
+ }
179
+
180
+ /** Session statistics for /session command */
181
+ export interface SessionStats {
182
+ sessionFile: string | undefined;
183
+ sessionId: string;
184
+ userMessages: number;
185
+ assistantMessages: number;
186
+ toolCalls: number;
187
+ toolResults: number;
188
+ totalMessages: number;
189
+ tokens: {
190
+ input: number;
191
+ output: number;
192
+ cacheRead: number;
193
+ cacheWrite: number;
194
+ total: number;
195
+ };
196
+ cost: number;
197
+ }
198
+
199
+ // ============================================================================
200
+ // Constants
201
+ // ============================================================================
202
+
203
+ /** Standard thinking levels */
204
+ const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high"];
205
+
206
+ /** Thinking levels including xhigh (for supported models) */
207
+ const THINKING_LEVELS_WITH_XHIGH: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh"];
208
+
209
+ // ============================================================================
210
+ // AgentSession Class
211
+ // ============================================================================
212
+
213
+ export class AgentSession {
214
+ readonly agent: Agent;
215
+ readonly sessionManager: SessionManager;
216
+ readonly settingsManager: SettingsManager;
217
+
218
+ private _scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;
219
+
220
+ // Event subscription state
221
+ private _unsubscribeAgent?: () => void;
222
+ private _eventListeners: AgentSessionEventListener[] = [];
223
+ private _agentEventQueue: Promise<void> = Promise.resolve();
224
+
225
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
226
+ private _steeringMessages: string[] = [];
227
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
228
+ private _followUpMessages: string[] = [];
229
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
230
+ private _pendingNextTurnMessages: CustomMessage[] = [];
231
+
232
+ // Compaction state
233
+ private _compactionAbortController: AbortController | undefined = undefined;
234
+ private _autoCompactionAbortController: AbortController | undefined = undefined;
235
+ private _overflowRecoveryAttempted = false;
236
+
237
+ // Branch summarization state
238
+ private _branchSummaryAbortController: AbortController | undefined = undefined;
239
+
240
+ // Retry state
241
+ private _retryAbortController: AbortController | undefined = undefined;
242
+ private _retryAttempt = 0;
243
+ private _retryPromise: Promise<void> | undefined = undefined;
244
+ private _retryResolve: (() => void) | undefined = undefined;
245
+
246
+ // Bash execution state
247
+ private _bashAbortController: AbortController | undefined = undefined;
248
+ private _pendingBashMessages: BashExecutionMessage[] = [];
249
+
250
+ // Extension system
251
+ private _extensionRunner: ExtensionRunner | undefined = undefined;
252
+ private _turnIndex = 0;
253
+
254
+ private _resourceLoader: ResourceLoader;
255
+ private _customTools: ToolDefinition[];
256
+ private _baseToolRegistry: Map<string, AgentTool> = new Map();
257
+ private _cwd: string;
258
+ private _extensionRunnerRef?: { current?: ExtensionRunner };
259
+ private _initialActiveToolNames?: string[];
260
+ private _baseToolsOverride?: Record<string, AgentTool>;
261
+ private _extensionUIContext?: ExtensionUIContext;
262
+ private _extensionCommandContextActions?: ExtensionCommandContextActions;
263
+ private _extensionShutdownHandler?: ShutdownHandler;
264
+ private _extensionErrorListener?: ExtensionErrorListener;
265
+ private _extensionErrorUnsubscriber?: () => void;
266
+
267
+ // Model registry for API key resolution
268
+ private _modelRegistry: ModelRegistry;
269
+
270
+ // Tool registry for extension getTools/setTools
271
+ private _toolRegistry: Map<string, AgentTool> = new Map();
272
+ private _toolPromptSnippets: Map<string, string> = new Map();
273
+ private _toolPromptGuidelines: Map<string, string[]> = new Map();
274
+
275
+ // Base system prompt (without extension appends) - used to apply fresh appends each turn
276
+ private _baseSystemPrompt = "";
277
+
278
+ constructor(config: AgentSessionConfig) {
279
+ this.agent = config.agent;
280
+ this.sessionManager = config.sessionManager;
281
+ this.settingsManager = config.settingsManager;
282
+ this._scopedModels = config.scopedModels ?? [];
283
+ this._resourceLoader = config.resourceLoader;
284
+ this._customTools = config.customTools ?? [];
285
+ this._cwd = config.cwd;
286
+ this._modelRegistry = config.modelRegistry;
287
+ this._extensionRunnerRef = config.extensionRunnerRef;
288
+ this._initialActiveToolNames = config.initialActiveToolNames;
289
+ this._baseToolsOverride = config.baseToolsOverride;
290
+
291
+ // Always subscribe to agent events for internal handling
292
+ // (session persistence, extensions, auto-compaction, retry logic)
293
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
294
+
295
+ this._buildRuntime({
296
+ activeToolNames: this._initialActiveToolNames,
297
+ includeAllExtensionTools: true,
298
+ });
299
+ }
300
+
301
+ /** Model registry for API key resolution and model discovery */
302
+ get modelRegistry(): ModelRegistry {
303
+ return this._modelRegistry;
304
+ }
305
+
306
+ // =========================================================================
307
+ // Event Subscription
308
+ // =========================================================================
309
+
310
+ /** Emit an event to all listeners */
311
+ private _emit(event: AgentSessionEvent): void {
312
+ for (const l of this._eventListeners) {
313
+ l(event);
314
+ }
315
+ }
316
+
317
+ // Track last assistant message for auto-compaction check
318
+ private _lastAssistantMessage: AssistantMessage | undefined = undefined;
319
+
320
+ /** Internal handler for agent events - shared by subscribe and reconnect */
321
+ private _handleAgentEvent = (event: AgentEvent): void => {
322
+ // Create retry promise synchronously before queueing async processing.
323
+ // Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()
324
+ // as soon as agent.prompt() resolves. If _retryPromise is created only inside
325
+ // _processAgentEvent, slow earlier queued events can delay agent_end processing
326
+ // and waitForRetry() can miss the in-flight retry.
327
+ this._createRetryPromiseForAgentEnd(event);
328
+
329
+ this._agentEventQueue = this._agentEventQueue.then(
330
+ () => this._processAgentEvent(event),
331
+ () => this._processAgentEvent(event),
332
+ );
333
+
334
+ // Keep queue alive if an event handler fails
335
+ this._agentEventQueue.catch(() => {});
336
+ };
337
+
338
+ private _createRetryPromiseForAgentEnd(event: AgentEvent): void {
339
+ if (event.type !== "agent_end" || this._retryPromise) {
340
+ return;
341
+ }
342
+
343
+ const settings = this.settingsManager.getRetrySettings();
344
+ if (!settings.enabled) {
345
+ return;
346
+ }
347
+
348
+ const lastAssistant = this._findLastAssistantInMessages(event.messages);
349
+ if (!lastAssistant || !this._isRetryableError(lastAssistant)) {
350
+ return;
351
+ }
352
+
353
+ this._retryPromise = new Promise((resolve) => {
354
+ this._retryResolve = resolve;
355
+ });
356
+ }
357
+
358
+ private _findLastAssistantInMessages(messages: AgentMessage[]): AssistantMessage | undefined {
359
+ for (let i = messages.length - 1; i >= 0; i--) {
360
+ const message = messages[i];
361
+ if (message.role === "assistant") {
362
+ return message as AssistantMessage;
363
+ }
364
+ }
365
+ return undefined;
366
+ }
367
+
368
+ private async _processAgentEvent(event: AgentEvent): Promise<void> {
369
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
370
+ // This ensures the UI sees the updated queue state
371
+ if (event.type === "message_start" && event.message.role === "user") {
372
+ this._overflowRecoveryAttempted = false;
373
+ const messageText = this._getUserMessageText(event.message);
374
+ if (messageText) {
375
+ // Check steering queue first
376
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
377
+ if (steeringIndex !== -1) {
378
+ this._steeringMessages.splice(steeringIndex, 1);
379
+ } else {
380
+ // Check follow-up queue
381
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
382
+ if (followUpIndex !== -1) {
383
+ this._followUpMessages.splice(followUpIndex, 1);
384
+ }
385
+ }
386
+ }
387
+ }
388
+
389
+ // Emit to extensions first
390
+ await this._emitExtensionEvent(event);
391
+
392
+ // Notify all listeners
393
+ this._emit(event);
394
+
395
+ // Handle session persistence
396
+ if (event.type === "message_end") {
397
+ // Check if this is a custom message from extensions
398
+ if (event.message.role === "custom") {
399
+ // Persist as CustomMessageEntry
400
+ this.sessionManager.appendCustomMessageEntry(
401
+ event.message.customType,
402
+ event.message.content,
403
+ event.message.display,
404
+ event.message.details,
405
+ );
406
+ } else if (
407
+ event.message.role === "user" ||
408
+ event.message.role === "assistant" ||
409
+ event.message.role === "toolResult"
410
+ ) {
411
+ // Regular LLM message - persist as SessionMessageEntry
412
+ this.sessionManager.appendMessage(event.message);
413
+ }
414
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
415
+
416
+ // Track assistant message for auto-compaction (checked on agent_end)
417
+ if (event.message.role === "assistant") {
418
+ this._lastAssistantMessage = event.message;
419
+
420
+ const assistantMsg = event.message as AssistantMessage;
421
+ if (assistantMsg.stopReason !== "error") {
422
+ this._overflowRecoveryAttempted = false;
423
+ }
424
+
425
+ // Reset retry counter immediately on successful assistant response
426
+ // This prevents accumulation across multiple LLM calls within a turn
427
+ if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
428
+ this._emit({
429
+ type: "auto_retry_end",
430
+ success: true,
431
+ attempt: this._retryAttempt,
432
+ });
433
+ this._retryAttempt = 0;
434
+ this._resolveRetry();
435
+ }
436
+ }
437
+ }
438
+
439
+ // Check auto-retry and auto-compaction after agent completes
440
+ if (event.type === "agent_end" && this._lastAssistantMessage) {
441
+ const msg = this._lastAssistantMessage;
442
+ this._lastAssistantMessage = undefined;
443
+
444
+ // Check for retryable errors first (overloaded, rate limit, server errors)
445
+ if (this._isRetryableError(msg)) {
446
+ const didRetry = await this._handleRetryableError(msg);
447
+ if (didRetry) return; // Retry was initiated, don't proceed to compaction
448
+ }
449
+
450
+ await this._checkCompaction(msg);
451
+ }
452
+ }
453
+
454
+ /** Resolve the pending retry promise */
455
+ private _resolveRetry(): void {
456
+ if (this._retryResolve) {
457
+ this._retryResolve();
458
+ this._retryResolve = undefined;
459
+ this._retryPromise = undefined;
460
+ }
461
+ }
462
+
463
+ /** Extract text content from a message */
464
+ private _getUserMessageText(message: Message): string {
465
+ if (message.role !== "user") return "";
466
+ const content = message.content;
467
+ if (typeof content === "string") return content;
468
+ const textBlocks = content.filter((c) => c.type === "text");
469
+ return textBlocks.map((c) => (c as TextContent).text).join("");
470
+ }
471
+
472
+ /** Find the last assistant message in agent state (including aborted ones) */
473
+ private _findLastAssistantMessage(): AssistantMessage | undefined {
474
+ const messages = this.agent.state.messages;
475
+ for (let i = messages.length - 1; i >= 0; i--) {
476
+ const msg = messages[i];
477
+ if (msg.role === "assistant") {
478
+ return msg as AssistantMessage;
479
+ }
480
+ }
481
+ return undefined;
482
+ }
483
+
484
+ /** Emit extension events based on agent events */
485
+ private async _emitExtensionEvent(event: AgentEvent): Promise<void> {
486
+ if (!this._extensionRunner) return;
487
+
488
+ if (event.type === "agent_start") {
489
+ this._turnIndex = 0;
490
+ await this._extensionRunner.emit({ type: "agent_start" });
491
+ } else if (event.type === "agent_end") {
492
+ await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
493
+ } else if (event.type === "turn_start") {
494
+ const extensionEvent: TurnStartEvent = {
495
+ type: "turn_start",
496
+ turnIndex: this._turnIndex,
497
+ timestamp: Date.now(),
498
+ };
499
+ await this._extensionRunner.emit(extensionEvent);
500
+ } else if (event.type === "turn_end") {
501
+ const extensionEvent: TurnEndEvent = {
502
+ type: "turn_end",
503
+ turnIndex: this._turnIndex,
504
+ message: event.message,
505
+ toolResults: event.toolResults,
506
+ };
507
+ await this._extensionRunner.emit(extensionEvent);
508
+ this._turnIndex++;
509
+ } else if (event.type === "message_start") {
510
+ const extensionEvent: MessageStartEvent = {
511
+ type: "message_start",
512
+ message: event.message,
513
+ };
514
+ await this._extensionRunner.emit(extensionEvent);
515
+ } else if (event.type === "message_update") {
516
+ const extensionEvent: MessageUpdateEvent = {
517
+ type: "message_update",
518
+ message: event.message,
519
+ assistantMessageEvent: event.assistantMessageEvent,
520
+ };
521
+ await this._extensionRunner.emit(extensionEvent);
522
+ } else if (event.type === "message_end") {
523
+ const extensionEvent: MessageEndEvent = {
524
+ type: "message_end",
525
+ message: event.message,
526
+ };
527
+ await this._extensionRunner.emit(extensionEvent);
528
+ } else if (event.type === "tool_execution_start") {
529
+ const extensionEvent: ToolExecutionStartEvent = {
530
+ type: "tool_execution_start",
531
+ toolCallId: event.toolCallId,
532
+ toolName: event.toolName,
533
+ args: event.args,
534
+ };
535
+ await this._extensionRunner.emit(extensionEvent);
536
+ } else if (event.type === "tool_execution_update") {
537
+ const extensionEvent: ToolExecutionUpdateEvent = {
538
+ type: "tool_execution_update",
539
+ toolCallId: event.toolCallId,
540
+ toolName: event.toolName,
541
+ args: event.args,
542
+ partialResult: event.partialResult,
543
+ };
544
+ await this._extensionRunner.emit(extensionEvent);
545
+ } else if (event.type === "tool_execution_end") {
546
+ const extensionEvent: ToolExecutionEndEvent = {
547
+ type: "tool_execution_end",
548
+ toolCallId: event.toolCallId,
549
+ toolName: event.toolName,
550
+ result: event.result,
551
+ isError: event.isError,
552
+ };
553
+ await this._extensionRunner.emit(extensionEvent);
554
+ }
555
+ }
556
+
557
+ /**
558
+ * Subscribe to agent events.
559
+ * Session persistence is handled internally (saves messages on message_end).
560
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
561
+ */
562
+ subscribe(listener: AgentSessionEventListener): () => void {
563
+ this._eventListeners.push(listener);
564
+
565
+ // Return unsubscribe function for this specific listener
566
+ return () => {
567
+ const index = this._eventListeners.indexOf(listener);
568
+ if (index !== -1) {
569
+ this._eventListeners.splice(index, 1);
570
+ }
571
+ };
572
+ }
573
+
574
+ /**
575
+ * Temporarily disconnect from agent events.
576
+ * User listeners are preserved and will receive events again after resubscribe().
577
+ * Used internally during operations that need to pause event processing.
578
+ */
579
+ private _disconnectFromAgent(): void {
580
+ if (this._unsubscribeAgent) {
581
+ this._unsubscribeAgent();
582
+ this._unsubscribeAgent = undefined;
583
+ }
584
+ }
585
+
586
+ /**
587
+ * Reconnect to agent events after _disconnectFromAgent().
588
+ * Preserves all existing listeners.
589
+ */
590
+ private _reconnectToAgent(): void {
591
+ if (this._unsubscribeAgent) return; // Already connected
592
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
593
+ }
594
+
595
+ /**
596
+ * Remove all listeners and disconnect from agent.
597
+ * Call this when completely done with the session.
598
+ */
599
+ dispose(): void {
600
+ this._disconnectFromAgent();
601
+ this._eventListeners = [];
602
+ }
603
+
604
+ // =========================================================================
605
+ // Read-only State Access
606
+ // =========================================================================
607
+
608
+ /** Full agent state */
609
+ get state(): AgentState {
610
+ return this.agent.state;
611
+ }
612
+
613
+ /** Current model (may be undefined if not yet selected) */
614
+ get model(): Model<any> | undefined {
615
+ return this.agent.state.model;
616
+ }
617
+
618
+ /** Current thinking level */
619
+ get thinkingLevel(): ThinkingLevel {
620
+ return this.agent.state.thinkingLevel;
621
+ }
622
+
623
+ /** Whether agent is currently streaming a response */
624
+ get isStreaming(): boolean {
625
+ return this.agent.state.isStreaming;
626
+ }
627
+
628
+ /** Current effective system prompt (includes any per-turn extension modifications) */
629
+ get systemPrompt(): string {
630
+ return this.agent.state.systemPrompt;
631
+ }
632
+
633
+ /** Current retry attempt (0 if not retrying) */
634
+ get retryAttempt(): number {
635
+ return this._retryAttempt;
636
+ }
637
+
638
+ /**
639
+ * Get the names of currently active tools.
640
+ * Returns the names of tools currently set on the agent.
641
+ */
642
+ getActiveToolNames(): string[] {
643
+ return this.agent.state.tools.map((t) => t.name);
644
+ }
645
+
646
+ /**
647
+ * Get all configured tools with name, description, and parameter schema.
648
+ */
649
+ getAllTools(): ToolInfo[] {
650
+ return Array.from(this._toolRegistry.values()).map((t) => ({
651
+ name: t.name,
652
+ description: t.description,
653
+ parameters: t.parameters,
654
+ }));
655
+ }
656
+
657
+ /**
658
+ * Set active tools by name.
659
+ * Only tools in the registry can be enabled. Unknown tool names are ignored.
660
+ * Also rebuilds the system prompt to reflect the new tool set.
661
+ * Changes take effect on the next agent turn.
662
+ */
663
+ setActiveToolsByName(toolNames: string[]): void {
664
+ const tools: AgentTool[] = [];
665
+ const validToolNames: string[] = [];
666
+ for (const name of toolNames) {
667
+ const tool = this._toolRegistry.get(name);
668
+ if (tool) {
669
+ tools.push(tool);
670
+ validToolNames.push(name);
671
+ }
672
+ }
673
+ this.agent.setTools(tools);
674
+
675
+ // Rebuild base system prompt with new tool set
676
+ this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
677
+ this.agent.setSystemPrompt(this._baseSystemPrompt);
678
+ }
679
+
680
+ /** Whether compaction or branch summarization is currently running */
681
+ get isCompacting(): boolean {
682
+ return (
683
+ this._autoCompactionAbortController !== undefined ||
684
+ this._compactionAbortController !== undefined ||
685
+ this._branchSummaryAbortController !== undefined
686
+ );
687
+ }
688
+
689
+ /** All messages including custom types like BashExecutionMessage */
690
+ get messages(): AgentMessage[] {
691
+ return this.agent.state.messages;
692
+ }
693
+
694
+ /** Current steering mode */
695
+ get steeringMode(): "all" | "one-at-a-time" {
696
+ return this.agent.getSteeringMode();
697
+ }
698
+
699
+ /** Current follow-up mode */
700
+ get followUpMode(): "all" | "one-at-a-time" {
701
+ return this.agent.getFollowUpMode();
702
+ }
703
+
704
+ /** Current session file path, or undefined if sessions are disabled */
705
+ get sessionFile(): string | undefined {
706
+ return this.sessionManager.getSessionFile();
707
+ }
708
+
709
+ /** Current session ID */
710
+ get sessionId(): string {
711
+ return this.sessionManager.getSessionId();
712
+ }
713
+
714
+ /** Current session display name, if set */
715
+ get sessionName(): string | undefined {
716
+ return this.sessionManager.getSessionName();
717
+ }
718
+
719
+ /** Scoped models for cycling (from --models flag) */
720
+ get scopedModels(): ReadonlyArray<{ model: Model<any>; thinkingLevel?: ThinkingLevel }> {
721
+ return this._scopedModels;
722
+ }
723
+
724
+ /** Update scoped models for cycling */
725
+ setScopedModels(scopedModels: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>): void {
726
+ this._scopedModels = scopedModels;
727
+ }
728
+
729
+ /** File-based prompt templates */
730
+ get promptTemplates(): ReadonlyArray<PromptTemplate> {
731
+ return this._resourceLoader.getPrompts().prompts;
732
+ }
733
+
734
+ private _normalizePromptSnippet(text: string | undefined): string | undefined {
735
+ if (!text) return undefined;
736
+ const oneLine = text
737
+ .replace(/[\r\n]+/g, " ")
738
+ .replace(/\s+/g, " ")
739
+ .trim();
740
+ return oneLine.length > 0 ? oneLine : undefined;
741
+ }
742
+
743
+ private _normalizePromptGuidelines(guidelines: string[] | undefined): string[] {
744
+ if (!guidelines || guidelines.length === 0) {
745
+ return [];
746
+ }
747
+
748
+ const unique = new Set<string>();
749
+ for (const guideline of guidelines) {
750
+ const normalized = guideline.trim();
751
+ if (normalized.length > 0) {
752
+ unique.add(normalized);
753
+ }
754
+ }
755
+ return Array.from(unique);
756
+ }
757
+
758
+ private _rebuildSystemPrompt(toolNames: string[]): string {
759
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
760
+ const toolSnippets: Record<string, string> = {};
761
+ const promptGuidelines: string[] = [];
762
+ for (const name of validToolNames) {
763
+ const snippet = this._toolPromptSnippets.get(name);
764
+ if (snippet) {
765
+ toolSnippets[name] = snippet;
766
+ }
767
+
768
+ const toolGuidelines = this._toolPromptGuidelines.get(name);
769
+ if (toolGuidelines) {
770
+ promptGuidelines.push(...toolGuidelines);
771
+ }
772
+ }
773
+
774
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
775
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
776
+ const appendSystemPrompt =
777
+ loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
778
+ const loadedSkills = this._resourceLoader.getSkills().skills;
779
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
780
+
781
+ return buildSystemPrompt({
782
+ cwd: this._cwd,
783
+ skills: loadedSkills,
784
+ contextFiles: loadedContextFiles,
785
+ customPrompt: loaderSystemPrompt,
786
+ appendSystemPrompt,
787
+ selectedTools: validToolNames,
788
+ toolSnippets,
789
+ promptGuidelines,
790
+ });
791
+ }
792
+
793
+ // =========================================================================
794
+ // Prompting
795
+ // =========================================================================
796
+
797
+ /**
798
+ * Send a prompt to the agent.
799
+ * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
800
+ * - Expands file-based prompt templates by default
801
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
802
+ * - Validates model and API key before sending (when not streaming)
803
+ * @throws Error if streaming and no streamingBehavior specified
804
+ * @throws Error if no model selected or no API key available (when not streaming)
805
+ */
806
+ async prompt(text: string, options?: PromptOptions): Promise<void> {
807
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
808
+
809
+ // Handle extension commands first (execute immediately, even during streaming)
810
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
811
+ if (expandPromptTemplates && text.startsWith("/")) {
812
+ const handled = await this._tryExecuteExtensionCommand(text);
813
+ if (handled) {
814
+ // Extension command executed, no prompt to send
815
+ return;
816
+ }
817
+ }
818
+
819
+ // Emit input event for extension interception (before skill/template expansion)
820
+ let currentText = text;
821
+ let currentImages = options?.images;
822
+ if (this._extensionRunner?.hasHandlers("input")) {
823
+ const inputResult = await this._extensionRunner.emitInput(
824
+ currentText,
825
+ currentImages,
826
+ options?.source ?? "interactive",
827
+ );
828
+ if (inputResult.action === "handled") {
829
+ return;
830
+ }
831
+ if (inputResult.action === "transform") {
832
+ currentText = inputResult.text;
833
+ currentImages = inputResult.images ?? currentImages;
834
+ }
835
+ }
836
+
837
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
838
+ let expandedText = currentText;
839
+ if (expandPromptTemplates) {
840
+ expandedText = this._expandSkillCommand(expandedText);
841
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
842
+ }
843
+
844
+ // If streaming, queue via steer() or followUp() based on option
845
+ if (this.isStreaming) {
846
+ if (!options?.streamingBehavior) {
847
+ throw new Error(
848
+ "Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.",
849
+ );
850
+ }
851
+ if (options.streamingBehavior === "followUp") {
852
+ await this._queueFollowUp(expandedText, currentImages);
853
+ } else {
854
+ await this._queueSteer(expandedText, currentImages);
855
+ }
856
+ return;
857
+ }
858
+
859
+ // Flush any pending bash messages before the new prompt
860
+ this._flushPendingBashMessages();
861
+
862
+ // Validate model
863
+ if (!this.model) {
864
+ throw new Error(
865
+ "No model selected.\n\n" +
866
+ `Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}\n\n` +
867
+ "Then use /model to select a model.",
868
+ );
869
+ }
870
+
871
+ // Validate API key
872
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
873
+ if (!apiKey) {
874
+ const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
875
+ if (isOAuth) {
876
+ throw new Error(
877
+ `Authentication failed for "${this.model.provider}". ` +
878
+ `Credentials may have expired or network is unavailable. ` +
879
+ `Run '/login ${this.model.provider}' to re-authenticate.`,
880
+ );
881
+ }
882
+ throw new Error(
883
+ `No API key found for ${this.model.provider}.\n\n` +
884
+ `Use /login or set an API key environment variable. See ${join(getDocsPath(), "providers.md")}`,
885
+ );
886
+ }
887
+
888
+ // Check if we need to compact before sending (catches aborted responses)
889
+ const lastAssistant = this._findLastAssistantMessage();
890
+ if (lastAssistant) {
891
+ await this._checkCompaction(lastAssistant, false);
892
+ }
893
+
894
+ // Build messages array (custom message if any, then user message)
895
+ const messages: AgentMessage[] = [];
896
+
897
+ // Add user message
898
+ const userContent: (TextContent | ImageContent)[] = [{ type: "text", text: expandedText }];
899
+ if (currentImages) {
900
+ userContent.push(...currentImages);
901
+ }
902
+ messages.push({
903
+ role: "user",
904
+ content: userContent,
905
+ timestamp: Date.now(),
906
+ });
907
+
908
+ // Inject any pending "nextTurn" messages as context alongside the user message
909
+ for (const msg of this._pendingNextTurnMessages) {
910
+ messages.push(msg);
911
+ }
912
+ this._pendingNextTurnMessages = [];
913
+
914
+ // Emit before_agent_start extension event
915
+ if (this._extensionRunner) {
916
+ const result = await this._extensionRunner.emitBeforeAgentStart(
917
+ expandedText,
918
+ currentImages,
919
+ this._baseSystemPrompt,
920
+ );
921
+ // Add all custom messages from extensions
922
+ if (result?.messages) {
923
+ for (const msg of result.messages) {
924
+ messages.push({
925
+ role: "custom",
926
+ customType: msg.customType,
927
+ content: msg.content,
928
+ display: msg.display,
929
+ details: msg.details,
930
+ timestamp: Date.now(),
931
+ });
932
+ }
933
+ }
934
+ // Apply extension-modified system prompt, or reset to base
935
+ if (result?.systemPrompt) {
936
+ this.agent.setSystemPrompt(result.systemPrompt);
937
+ } else {
938
+ // Ensure we're using the base prompt (in case previous turn had modifications)
939
+ this.agent.setSystemPrompt(this._baseSystemPrompt);
940
+ }
941
+ }
942
+
943
+ await this.agent.prompt(messages);
944
+ await this.waitForRetry();
945
+ }
946
+
947
+ /**
948
+ * Try to execute an extension command. Returns true if command was found and executed.
949
+ */
950
+ private async _tryExecuteExtensionCommand(text: string): Promise<boolean> {
951
+ if (!this._extensionRunner) return false;
952
+
953
+ // Parse command name and args
954
+ const spaceIndex = text.indexOf(" ");
955
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
956
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
957
+
958
+ const command = this._extensionRunner.getCommand(commandName);
959
+ if (!command) return false;
960
+
961
+ // Get command context from extension runner (includes session control methods)
962
+ const ctx = this._extensionRunner.createCommandContext();
963
+
964
+ try {
965
+ await command.handler(args, ctx);
966
+ return true;
967
+ } catch (err) {
968
+ // Emit error via extension runner
969
+ this._extensionRunner.emitError({
970
+ extensionPath: `command:${commandName}`,
971
+ event: "command",
972
+ error: err instanceof Error ? err.message : String(err),
973
+ });
974
+ return true;
975
+ }
976
+ }
977
+
978
+ /**
979
+ * Expand skill commands (/skill:name args) to their full content.
980
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
981
+ * Emits errors via extension runner if file read fails.
982
+ */
983
+ private _expandSkillCommand(text: string): string {
984
+ if (!text.startsWith("/skill:")) return text;
985
+
986
+ const spaceIndex = text.indexOf(" ");
987
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
988
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
989
+
990
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
991
+ if (!skill) return text; // Unknown skill, pass through
992
+
993
+ try {
994
+ const content = readFileSync(skill.filePath, "utf-8");
995
+ const body = stripFrontmatter(content).trim();
996
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
997
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
998
+ } catch (err) {
999
+ // Emit error like extension commands do
1000
+ this._extensionRunner?.emitError({
1001
+ extensionPath: skill.filePath,
1002
+ event: "skill_expansion",
1003
+ error: err instanceof Error ? err.message : String(err),
1004
+ });
1005
+ return text; // Return original on error
1006
+ }
1007
+ }
1008
+
1009
+ /**
1010
+ * Queue a steering message to interrupt the agent mid-run.
1011
+ * Delivered after current tool execution, skips remaining tools.
1012
+ * Expands skill commands and prompt templates. Errors on extension commands.
1013
+ * @param images Optional image attachments to include with the message
1014
+ * @throws Error if text is an extension command
1015
+ */
1016
+ async steer(text: string, images?: ImageContent[]): Promise<void> {
1017
+ // Check for extension commands (cannot be queued)
1018
+ if (text.startsWith("/")) {
1019
+ this._throwIfExtensionCommand(text);
1020
+ }
1021
+
1022
+ // Expand skill commands and prompt templates
1023
+ let expandedText = this._expandSkillCommand(text);
1024
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1025
+
1026
+ await this._queueSteer(expandedText, images);
1027
+ }
1028
+
1029
+ /**
1030
+ * Queue a follow-up message to be processed after the agent finishes.
1031
+ * Delivered only when agent has no more tool calls or steering messages.
1032
+ * Expands skill commands and prompt templates. Errors on extension commands.
1033
+ * @param images Optional image attachments to include with the message
1034
+ * @throws Error if text is an extension command
1035
+ */
1036
+ async followUp(text: string, images?: ImageContent[]): Promise<void> {
1037
+ // Check for extension commands (cannot be queued)
1038
+ if (text.startsWith("/")) {
1039
+ this._throwIfExtensionCommand(text);
1040
+ }
1041
+
1042
+ // Expand skill commands and prompt templates
1043
+ let expandedText = this._expandSkillCommand(text);
1044
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1045
+
1046
+ await this._queueFollowUp(expandedText, images);
1047
+ }
1048
+
1049
+ /**
1050
+ * Internal: Queue a steering message (already expanded, no extension command check).
1051
+ */
1052
+ private async _queueSteer(text: string, images?: ImageContent[]): Promise<void> {
1053
+ this._steeringMessages.push(text);
1054
+ const content: (TextContent | ImageContent)[] = [{ type: "text", text }];
1055
+ if (images) {
1056
+ content.push(...images);
1057
+ }
1058
+ this.agent.steer({
1059
+ role: "user",
1060
+ content,
1061
+ timestamp: Date.now(),
1062
+ });
1063
+ }
1064
+
1065
+ /**
1066
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
1067
+ */
1068
+ private async _queueFollowUp(text: string, images?: ImageContent[]): Promise<void> {
1069
+ this._followUpMessages.push(text);
1070
+ const content: (TextContent | ImageContent)[] = [{ type: "text", text }];
1071
+ if (images) {
1072
+ content.push(...images);
1073
+ }
1074
+ this.agent.followUp({
1075
+ role: "user",
1076
+ content,
1077
+ timestamp: Date.now(),
1078
+ });
1079
+ }
1080
+
1081
+ /**
1082
+ * Throw an error if the text is an extension command.
1083
+ */
1084
+ private _throwIfExtensionCommand(text: string): void {
1085
+ if (!this._extensionRunner) return;
1086
+
1087
+ const spaceIndex = text.indexOf(" ");
1088
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1089
+ const command = this._extensionRunner.getCommand(commandName);
1090
+
1091
+ if (command) {
1092
+ throw new Error(
1093
+ `Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`,
1094
+ );
1095
+ }
1096
+ }
1097
+
1098
+ /**
1099
+ * Send a custom message to the session. Creates a CustomMessageEntry.
1100
+ *
1101
+ * Handles three cases:
1102
+ * - Streaming: queues message, processed when loop pulls from queue
1103
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
1104
+ * - Not streaming + no trigger: appends to state/session, no turn
1105
+ *
1106
+ * @param message Custom message with customType, content, display, details
1107
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
1108
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
1109
+ */
1110
+ async sendCustomMessage<T = unknown>(
1111
+ message: Pick<CustomMessage<T>, "customType" | "content" | "display" | "details">,
1112
+ options?: { triggerTurn?: boolean; deliverAs?: "steer" | "followUp" | "nextTurn" },
1113
+ ): Promise<void> {
1114
+ const appMessage = {
1115
+ role: "custom" as const,
1116
+ customType: message.customType,
1117
+ content: message.content,
1118
+ display: message.display,
1119
+ details: message.details,
1120
+ timestamp: Date.now(),
1121
+ } satisfies CustomMessage<T>;
1122
+ if (options?.deliverAs === "nextTurn") {
1123
+ this._pendingNextTurnMessages.push(appMessage);
1124
+ } else if (this.isStreaming) {
1125
+ if (options?.deliverAs === "followUp") {
1126
+ this.agent.followUp(appMessage);
1127
+ } else {
1128
+ this.agent.steer(appMessage);
1129
+ }
1130
+ } else if (options?.triggerTurn) {
1131
+ await this.agent.prompt(appMessage);
1132
+ } else {
1133
+ this.agent.appendMessage(appMessage);
1134
+ this.sessionManager.appendCustomMessageEntry(
1135
+ message.customType,
1136
+ message.content,
1137
+ message.display,
1138
+ message.details,
1139
+ );
1140
+ this._emit({ type: "message_start", message: appMessage });
1141
+ this._emit({ type: "message_end", message: appMessage });
1142
+ }
1143
+ }
1144
+
1145
+ /**
1146
+ * Send a user message to the agent. Always triggers a turn.
1147
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
1148
+ *
1149
+ * @param content User message content (string or content array)
1150
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
1151
+ */
1152
+ async sendUserMessage(
1153
+ content: string | (TextContent | ImageContent)[],
1154
+ options?: { deliverAs?: "steer" | "followUp" },
1155
+ ): Promise<void> {
1156
+ // Normalize content to text string + optional images
1157
+ let text: string;
1158
+ let images: ImageContent[] | undefined;
1159
+
1160
+ if (typeof content === "string") {
1161
+ text = content;
1162
+ } else {
1163
+ const textParts: string[] = [];
1164
+ images = [];
1165
+ for (const part of content) {
1166
+ if (part.type === "text") {
1167
+ textParts.push(part.text);
1168
+ } else {
1169
+ images.push(part);
1170
+ }
1171
+ }
1172
+ text = textParts.join("\n");
1173
+ if (images.length === 0) images = undefined;
1174
+ }
1175
+
1176
+ // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
1177
+ await this.prompt(text, {
1178
+ expandPromptTemplates: false,
1179
+ streamingBehavior: options?.deliverAs,
1180
+ images,
1181
+ source: "extension",
1182
+ });
1183
+ }
1184
+
1185
+ /**
1186
+ * Clear all queued messages and return them.
1187
+ * Useful for restoring to editor when user aborts.
1188
+ * @returns Object with steering and followUp arrays
1189
+ */
1190
+ clearQueue(): { steering: string[]; followUp: string[] } {
1191
+ const steering = [...this._steeringMessages];
1192
+ const followUp = [...this._followUpMessages];
1193
+ this._steeringMessages = [];
1194
+ this._followUpMessages = [];
1195
+ this.agent.clearAllQueues();
1196
+ return { steering, followUp };
1197
+ }
1198
+
1199
+ /** Number of pending messages (includes both steering and follow-up) */
1200
+ get pendingMessageCount(): number {
1201
+ return this._steeringMessages.length + this._followUpMessages.length;
1202
+ }
1203
+
1204
+ /** Get pending steering messages (read-only) */
1205
+ getSteeringMessages(): readonly string[] {
1206
+ return this._steeringMessages;
1207
+ }
1208
+
1209
+ /** Get pending follow-up messages (read-only) */
1210
+ getFollowUpMessages(): readonly string[] {
1211
+ return this._followUpMessages;
1212
+ }
1213
+
1214
+ get resourceLoader(): ResourceLoader {
1215
+ return this._resourceLoader;
1216
+ }
1217
+
1218
+ /**
1219
+ * Abort current operation and wait for agent to become idle.
1220
+ */
1221
+ async abort(): Promise<void> {
1222
+ this.abortRetry();
1223
+ this.agent.abort();
1224
+ await this.agent.waitForIdle();
1225
+ }
1226
+
1227
+ /**
1228
+ * Start a new session, optionally with initial messages and parent tracking.
1229
+ * Clears all messages and starts a new session.
1230
+ * Listeners are preserved and will continue receiving events.
1231
+ * @param options.parentSession - Optional parent session path for tracking
1232
+ * @param options.setup - Optional callback to initialize session (e.g., append messages)
1233
+ * @returns true if completed, false if cancelled by extension
1234
+ */
1235
+ async newSession(options?: {
1236
+ parentSession?: string;
1237
+ setup?: (sessionManager: SessionManager) => Promise<void>;
1238
+ }): Promise<boolean> {
1239
+ const previousSessionFile = this.sessionFile;
1240
+
1241
+ // Emit session_before_switch event with reason "new" (can be cancelled)
1242
+ if (this._extensionRunner?.hasHandlers("session_before_switch")) {
1243
+ const result = (await this._extensionRunner.emit({
1244
+ type: "session_before_switch",
1245
+ reason: "new",
1246
+ })) as SessionBeforeSwitchResult | undefined;
1247
+
1248
+ if (result?.cancel) {
1249
+ return false;
1250
+ }
1251
+ }
1252
+
1253
+ this._disconnectFromAgent();
1254
+ await this.abort();
1255
+ this.agent.reset();
1256
+ this.sessionManager.newSession({ parentSession: options?.parentSession });
1257
+ this.agent.sessionId = this.sessionManager.getSessionId();
1258
+ this._steeringMessages = [];
1259
+ this._followUpMessages = [];
1260
+ this._pendingNextTurnMessages = [];
1261
+
1262
+ this.sessionManager.appendThinkingLevelChange(this.thinkingLevel);
1263
+
1264
+ // Run setup callback if provided (e.g., to append initial messages)
1265
+ if (options?.setup) {
1266
+ await options.setup(this.sessionManager);
1267
+ // Sync agent state with session manager after setup
1268
+ const sessionContext = this.sessionManager.buildSessionContext();
1269
+ this.agent.replaceMessages(sessionContext.messages);
1270
+ }
1271
+
1272
+ this._reconnectToAgent();
1273
+
1274
+ // Emit session_switch event with reason "new" to extensions
1275
+ if (this._extensionRunner) {
1276
+ await this._extensionRunner.emit({
1277
+ type: "session_switch",
1278
+ reason: "new",
1279
+ previousSessionFile,
1280
+ });
1281
+ }
1282
+
1283
+ // Emit session event to custom tools
1284
+ return true;
1285
+ }
1286
+
1287
+ // =========================================================================
1288
+ // Model Management
1289
+ // =========================================================================
1290
+
1291
+ private async _emitModelSelect(
1292
+ nextModel: Model<any>,
1293
+ previousModel: Model<any> | undefined,
1294
+ source: "set" | "cycle" | "restore",
1295
+ ): Promise<void> {
1296
+ if (!this._extensionRunner) return;
1297
+ if (modelsAreEqual(previousModel, nextModel)) return;
1298
+ await this._extensionRunner.emit({
1299
+ type: "model_select",
1300
+ model: nextModel,
1301
+ previousModel,
1302
+ source,
1303
+ });
1304
+ }
1305
+
1306
+ /**
1307
+ * Set model directly.
1308
+ * Validates API key, saves to session and settings.
1309
+ * @throws Error if no API key available for the model
1310
+ */
1311
+ async setModel(model: Model<any>, options?: { persist?: boolean }): Promise<void> {
1312
+ const apiKey = await this._modelRegistry.getApiKey(model);
1313
+ if (!apiKey) {
1314
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
1315
+ }
1316
+
1317
+ const previousModel = this.model;
1318
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1319
+ this.agent.setModel(model);
1320
+ this.sessionManager.appendModelChange(model.provider, model.id);
1321
+ if (options?.persist !== false) {
1322
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1323
+ }
1324
+
1325
+ // Re-clamp thinking level for new model's capabilities
1326
+ this.setThinkingLevel(thinkingLevel);
1327
+
1328
+ await this._emitModelSelect(model, previousModel, "set");
1329
+ }
1330
+
1331
+ /**
1332
+ * Cycle to next/previous model.
1333
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
1334
+ * @param direction - "forward" (default) or "backward"
1335
+ * @returns The new model info, or undefined if only one model available
1336
+ */
1337
+ async cycleModel(direction: "forward" | "backward" = "forward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined> {
1338
+ if (this._scopedModels.length > 0) {
1339
+ return this._cycleScopedModel(direction, options);
1340
+ }
1341
+ return this._cycleAvailableModel(direction, options);
1342
+ }
1343
+
1344
+ private async _getScopedModelsWithApiKey(): Promise<Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>> {
1345
+ const apiKeysByProvider = new Map<string, string | undefined>();
1346
+ const result: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }> = [];
1347
+
1348
+ for (const scoped of this._scopedModels) {
1349
+ const provider = scoped.model.provider;
1350
+ let apiKey: string | undefined;
1351
+ if (apiKeysByProvider.has(provider)) {
1352
+ apiKey = apiKeysByProvider.get(provider);
1353
+ } else {
1354
+ apiKey = await this._modelRegistry.getApiKeyForProvider(provider);
1355
+ apiKeysByProvider.set(provider, apiKey);
1356
+ }
1357
+
1358
+ if (apiKey) {
1359
+ result.push(scoped);
1360
+ }
1361
+ }
1362
+
1363
+ return result;
1364
+ }
1365
+
1366
+ private async _cycleScopedModel(direction: "forward" | "backward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined> {
1367
+ const scopedModels = await this._getScopedModelsWithApiKey();
1368
+ if (scopedModels.length <= 1) return undefined;
1369
+
1370
+ const currentModel = this.model;
1371
+ let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
1372
+
1373
+ if (currentIndex === -1) currentIndex = 0;
1374
+ const len = scopedModels.length;
1375
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1376
+ const next = scopedModels[nextIndex];
1377
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1378
+
1379
+ // Apply model
1380
+ this.agent.setModel(next.model);
1381
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id);
1382
+ if (options?.persist !== false) {
1383
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1384
+ }
1385
+
1386
+ // Apply thinking level.
1387
+ // - Explicit scoped model thinking level overrides current session level
1388
+ // - Undefined scoped model thinking level inherits the current session preference
1389
+ // setThinkingLevel clamps to model capabilities.
1390
+ this.setThinkingLevel(thinkingLevel);
1391
+
1392
+ await this._emitModelSelect(next.model, currentModel, "cycle");
1393
+
1394
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1395
+ }
1396
+
1397
+ private async _cycleAvailableModel(direction: "forward" | "backward", options?: { persist?: boolean }): Promise<ModelCycleResult | undefined> {
1398
+ const availableModels = await this._modelRegistry.getAvailable();
1399
+ if (availableModels.length <= 1) return undefined;
1400
+
1401
+ const currentModel = this.model;
1402
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
1403
+
1404
+ if (currentIndex === -1) currentIndex = 0;
1405
+ const len = availableModels.length;
1406
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1407
+ const nextModel = availableModels[nextIndex];
1408
+
1409
+ const apiKey = await this._modelRegistry.getApiKey(nextModel);
1410
+ if (!apiKey) {
1411
+ throw new Error(`No API key for ${nextModel.provider}/${nextModel.id}`);
1412
+ }
1413
+
1414
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1415
+ this.agent.setModel(nextModel);
1416
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
1417
+ if (options?.persist !== false) {
1418
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1419
+ }
1420
+
1421
+ // Re-clamp thinking level for new model's capabilities
1422
+ this.setThinkingLevel(thinkingLevel);
1423
+
1424
+ await this._emitModelSelect(nextModel, currentModel, "cycle");
1425
+
1426
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
1427
+ }
1428
+
1429
+ // =========================================================================
1430
+ // Thinking Level Management
1431
+ // =========================================================================
1432
+
1433
+ /**
1434
+ * Set thinking level.
1435
+ * Clamps to model capabilities based on available thinking levels.
1436
+ * Saves to session and settings only if the level actually changes.
1437
+ */
1438
+ setThinkingLevel(level: ThinkingLevel): void {
1439
+ const availableLevels = this.getAvailableThinkingLevels();
1440
+ const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1441
+
1442
+ // Only persist if actually changing
1443
+ const isChanging = effectiveLevel !== this.agent.state.thinkingLevel;
1444
+
1445
+ this.agent.setThinkingLevel(effectiveLevel);
1446
+
1447
+ if (isChanging) {
1448
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1449
+ if (this.supportsThinking() || effectiveLevel !== "off") {
1450
+ this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1451
+ }
1452
+ }
1453
+ }
1454
+
1455
+ /**
1456
+ * Cycle to next thinking level.
1457
+ * @returns New level, or undefined if model doesn't support thinking
1458
+ */
1459
+ cycleThinkingLevel(): ThinkingLevel | undefined {
1460
+ if (!this.supportsThinking()) return undefined;
1461
+
1462
+ const levels = this.getAvailableThinkingLevels();
1463
+ const currentIndex = levels.indexOf(this.thinkingLevel);
1464
+ const nextIndex = (currentIndex + 1) % levels.length;
1465
+ const nextLevel = levels[nextIndex];
1466
+
1467
+ this.setThinkingLevel(nextLevel);
1468
+ return nextLevel;
1469
+ }
1470
+
1471
+ /**
1472
+ * Get available thinking levels for current model.
1473
+ * The provider will clamp to what the specific model supports internally.
1474
+ */
1475
+ getAvailableThinkingLevels(): ThinkingLevel[] {
1476
+ if (!this.supportsThinking()) return ["off"];
1477
+ return this.supportsXhighThinking() ? THINKING_LEVELS_WITH_XHIGH : THINKING_LEVELS;
1478
+ }
1479
+
1480
+ /**
1481
+ * Check if current model supports xhigh thinking level.
1482
+ */
1483
+ supportsXhighThinking(): boolean {
1484
+ return this.model ? supportsXhigh(this.model) : false;
1485
+ }
1486
+
1487
+ /**
1488
+ * Check if current model supports thinking/reasoning.
1489
+ */
1490
+ supportsThinking(): boolean {
1491
+ return !!this.model?.reasoning;
1492
+ }
1493
+
1494
+ private _getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel {
1495
+ if (explicitLevel !== undefined) {
1496
+ return explicitLevel;
1497
+ }
1498
+ if (!this.supportsThinking()) {
1499
+ return this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
1500
+ }
1501
+ return this.thinkingLevel;
1502
+ }
1503
+
1504
+ private _clampThinkingLevel(level: ThinkingLevel, availableLevels: ThinkingLevel[]): ThinkingLevel {
1505
+ const ordered = THINKING_LEVELS_WITH_XHIGH;
1506
+ const available = new Set(availableLevels);
1507
+ const requestedIndex = ordered.indexOf(level);
1508
+ if (requestedIndex === -1) {
1509
+ return availableLevels[0] ?? "off";
1510
+ }
1511
+ for (let i = requestedIndex; i < ordered.length; i++) {
1512
+ const candidate = ordered[i];
1513
+ if (available.has(candidate)) return candidate;
1514
+ }
1515
+ for (let i = requestedIndex - 1; i >= 0; i--) {
1516
+ const candidate = ordered[i];
1517
+ if (available.has(candidate)) return candidate;
1518
+ }
1519
+ return availableLevels[0] ?? "off";
1520
+ }
1521
+
1522
+ // =========================================================================
1523
+ // Queue Mode Management
1524
+ // =========================================================================
1525
+
1526
+ /**
1527
+ * Set steering message mode.
1528
+ * Saves to settings.
1529
+ */
1530
+ setSteeringMode(mode: "all" | "one-at-a-time"): void {
1531
+ this.agent.setSteeringMode(mode);
1532
+ this.settingsManager.setSteeringMode(mode);
1533
+ }
1534
+
1535
+ /**
1536
+ * Set follow-up message mode.
1537
+ * Saves to settings.
1538
+ */
1539
+ setFollowUpMode(mode: "all" | "one-at-a-time"): void {
1540
+ this.agent.setFollowUpMode(mode);
1541
+ this.settingsManager.setFollowUpMode(mode);
1542
+ }
1543
+
1544
+ // =========================================================================
1545
+ // Compaction
1546
+ // =========================================================================
1547
+
1548
+ /**
1549
+ * Manually compact the session context.
1550
+ * Aborts current agent operation first.
1551
+ * @param customInstructions Optional instructions for the compaction summary
1552
+ */
1553
+ async compact(customInstructions?: string): Promise<CompactionResult> {
1554
+ this._disconnectFromAgent();
1555
+ await this.abort();
1556
+ this._compactionAbortController = new AbortController();
1557
+
1558
+ try {
1559
+ if (!this.model) {
1560
+ throw new Error("No model selected");
1561
+ }
1562
+
1563
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
1564
+ if (!apiKey) {
1565
+ throw new Error(`No API key for ${this.model.provider}`);
1566
+ }
1567
+
1568
+ const pathEntries = this.sessionManager.getBranch();
1569
+ const settings = this.settingsManager.getCompactionSettings();
1570
+
1571
+ const preparation = prepareCompaction(pathEntries, settings);
1572
+ if (!preparation) {
1573
+ // Check why we can't compact
1574
+ const lastEntry = pathEntries[pathEntries.length - 1];
1575
+ if (lastEntry?.type === "compaction") {
1576
+ throw new Error("Already compacted");
1577
+ }
1578
+ throw new Error("Nothing to compact (session too small)");
1579
+ }
1580
+
1581
+ let extensionCompaction: CompactionResult | undefined;
1582
+ let fromExtension = false;
1583
+
1584
+ if (this._extensionRunner?.hasHandlers("session_before_compact")) {
1585
+ const result = (await this._extensionRunner.emit({
1586
+ type: "session_before_compact",
1587
+ preparation,
1588
+ branchEntries: pathEntries,
1589
+ customInstructions,
1590
+ signal: this._compactionAbortController.signal,
1591
+ })) as SessionBeforeCompactResult | undefined;
1592
+
1593
+ if (result?.cancel) {
1594
+ throw new Error("Compaction cancelled");
1595
+ }
1596
+
1597
+ if (result?.compaction) {
1598
+ extensionCompaction = result.compaction;
1599
+ fromExtension = true;
1600
+ }
1601
+ }
1602
+
1603
+ let summary: string;
1604
+ let firstKeptEntryId: string;
1605
+ let tokensBefore: number;
1606
+ let details: unknown;
1607
+
1608
+ if (extensionCompaction) {
1609
+ // Extension provided compaction content
1610
+ summary = extensionCompaction.summary;
1611
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1612
+ tokensBefore = extensionCompaction.tokensBefore;
1613
+ details = extensionCompaction.details;
1614
+ } else {
1615
+ // Generate compaction result
1616
+ const result = await compact(
1617
+ preparation,
1618
+ this.model,
1619
+ apiKey,
1620
+ customInstructions,
1621
+ this._compactionAbortController.signal,
1622
+ );
1623
+ summary = result.summary;
1624
+ firstKeptEntryId = result.firstKeptEntryId;
1625
+ tokensBefore = result.tokensBefore;
1626
+ details = result.details;
1627
+ }
1628
+
1629
+ if (this._compactionAbortController.signal.aborted) {
1630
+ throw new Error("Compaction cancelled");
1631
+ }
1632
+
1633
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1634
+ const newEntries = this.sessionManager.getEntries();
1635
+ const sessionContext = this.sessionManager.buildSessionContext();
1636
+ this.agent.replaceMessages(sessionContext.messages);
1637
+
1638
+ // Get the saved compaction entry for the extension event
1639
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
1640
+ | CompactionEntry
1641
+ | undefined;
1642
+
1643
+ if (this._extensionRunner && savedCompactionEntry) {
1644
+ await this._extensionRunner.emit({
1645
+ type: "session_compact",
1646
+ compactionEntry: savedCompactionEntry,
1647
+ fromExtension,
1648
+ });
1649
+ }
1650
+
1651
+ return {
1652
+ summary,
1653
+ firstKeptEntryId,
1654
+ tokensBefore,
1655
+ details,
1656
+ };
1657
+ } finally {
1658
+ this._compactionAbortController = undefined;
1659
+ this._reconnectToAgent();
1660
+ }
1661
+ }
1662
+
1663
+ /**
1664
+ * Cancel in-progress compaction (manual or auto).
1665
+ */
1666
+ abortCompaction(): void {
1667
+ this._compactionAbortController?.abort();
1668
+ this._autoCompactionAbortController?.abort();
1669
+ }
1670
+
1671
+ /**
1672
+ * Cancel in-progress branch summarization.
1673
+ */
1674
+ abortBranchSummary(): void {
1675
+ this._branchSummaryAbortController?.abort();
1676
+ }
1677
+
1678
+ /**
1679
+ * Check if compaction is needed and run it.
1680
+ * Called after agent_end and before prompt submission.
1681
+ *
1682
+ * Two cases:
1683
+ * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
1684
+ * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
1685
+ *
1686
+ * @param assistantMessage The assistant message to check
1687
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
1688
+ */
1689
+ private async _checkCompaction(assistantMessage: AssistantMessage, skipAbortedCheck = true): Promise<void> {
1690
+ const settings = this.settingsManager.getCompactionSettings();
1691
+ if (!settings.enabled) return;
1692
+
1693
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1694
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted") return;
1695
+
1696
+ const contextWindow = this.model?.contextWindow ?? 0;
1697
+
1698
+ // Skip overflow check if the message came from a different model.
1699
+ // This handles the case where user switched from a smaller-context model (e.g. opus)
1700
+ // to a larger-context model (e.g. codex) - the overflow error from the old model
1701
+ // shouldn't trigger compaction for the new model.
1702
+ const sameModel =
1703
+ this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
1704
+
1705
+ // Skip compaction checks if this assistant message is older than the latest
1706
+ // compaction boundary. This prevents a stale pre-compaction usage/error
1707
+ // from retriggering compaction on the first prompt after compaction.
1708
+ const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
1709
+ const assistantIsFromBeforeCompaction =
1710
+ compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
1711
+ if (assistantIsFromBeforeCompaction) {
1712
+ return;
1713
+ }
1714
+
1715
+ // Case 1: Overflow - LLM returned context overflow error
1716
+ if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
1717
+ if (this._overflowRecoveryAttempted) {
1718
+ this._emit({
1719
+ type: "auto_compaction_end",
1720
+ result: undefined,
1721
+ aborted: false,
1722
+ willRetry: false,
1723
+ errorMessage:
1724
+ "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
1725
+ });
1726
+ return;
1727
+ }
1728
+
1729
+ this._overflowRecoveryAttempted = true;
1730
+ // Remove the error message from agent state (it IS saved to session for history,
1731
+ // but we don't want it in context for the retry)
1732
+ const messages = this.agent.state.messages;
1733
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1734
+ this.agent.replaceMessages(messages.slice(0, -1));
1735
+ }
1736
+ await this._runAutoCompaction("overflow", true);
1737
+ return;
1738
+ }
1739
+
1740
+ // Case 2: Threshold - context is getting large
1741
+ // For error messages (no usage data), estimate from last successful response.
1742
+ // This ensures sessions that hit persistent API errors (e.g. 529) can still compact.
1743
+ let contextTokens: number;
1744
+ if (assistantMessage.stopReason === "error") {
1745
+ const messages = this.agent.state.messages;
1746
+ const estimate = estimateContextTokens(messages);
1747
+ if (estimate.lastUsageIndex === null) return; // No usage data at all
1748
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
1749
+ // have stale usage reflecting the old (larger) context and would falsely
1750
+ // trigger compaction right after one just finished.
1751
+ const usageMsg = messages[estimate.lastUsageIndex];
1752
+ if (
1753
+ compactionEntry &&
1754
+ usageMsg.role === "assistant" &&
1755
+ (usageMsg as AssistantMessage).timestamp <= new Date(compactionEntry.timestamp).getTime()
1756
+ ) {
1757
+ return;
1758
+ }
1759
+ contextTokens = estimate.tokens;
1760
+ } else {
1761
+ contextTokens = calculateContextTokens(assistantMessage.usage);
1762
+ }
1763
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
1764
+ await this._runAutoCompaction("threshold", false);
1765
+ }
1766
+ }
1767
+
1768
+ /**
1769
+ * Internal: Run auto-compaction with events.
1770
+ */
1771
+ private async _runAutoCompaction(reason: "overflow" | "threshold", willRetry: boolean): Promise<void> {
1772
+ const settings = this.settingsManager.getCompactionSettings();
1773
+
1774
+ this._emit({ type: "auto_compaction_start", reason });
1775
+ this._autoCompactionAbortController = new AbortController();
1776
+
1777
+ try {
1778
+ if (!this.model) {
1779
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
1780
+ return;
1781
+ }
1782
+
1783
+ const apiKey = await this._modelRegistry.getApiKey(this.model);
1784
+ if (!apiKey) {
1785
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
1786
+ return;
1787
+ }
1788
+
1789
+ const pathEntries = this.sessionManager.getBranch();
1790
+
1791
+ const preparation = prepareCompaction(pathEntries, settings);
1792
+ if (!preparation) {
1793
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: false, willRetry: false });
1794
+ return;
1795
+ }
1796
+
1797
+ let extensionCompaction: CompactionResult | undefined;
1798
+ let fromExtension = false;
1799
+
1800
+ if (this._extensionRunner?.hasHandlers("session_before_compact")) {
1801
+ const extensionResult = (await this._extensionRunner.emit({
1802
+ type: "session_before_compact",
1803
+ preparation,
1804
+ branchEntries: pathEntries,
1805
+ customInstructions: undefined,
1806
+ signal: this._autoCompactionAbortController.signal,
1807
+ })) as SessionBeforeCompactResult | undefined;
1808
+
1809
+ if (extensionResult?.cancel) {
1810
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: true, willRetry: false });
1811
+ return;
1812
+ }
1813
+
1814
+ if (extensionResult?.compaction) {
1815
+ extensionCompaction = extensionResult.compaction;
1816
+ fromExtension = true;
1817
+ }
1818
+ }
1819
+
1820
+ let summary: string;
1821
+ let firstKeptEntryId: string;
1822
+ let tokensBefore: number;
1823
+ let details: unknown;
1824
+
1825
+ if (extensionCompaction) {
1826
+ // Extension provided compaction content
1827
+ summary = extensionCompaction.summary;
1828
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1829
+ tokensBefore = extensionCompaction.tokensBefore;
1830
+ details = extensionCompaction.details;
1831
+ } else {
1832
+ // Generate compaction result
1833
+ const compactResult = await compact(
1834
+ preparation,
1835
+ this.model,
1836
+ apiKey,
1837
+ undefined,
1838
+ this._autoCompactionAbortController.signal,
1839
+ );
1840
+ summary = compactResult.summary;
1841
+ firstKeptEntryId = compactResult.firstKeptEntryId;
1842
+ tokensBefore = compactResult.tokensBefore;
1843
+ details = compactResult.details;
1844
+ }
1845
+
1846
+ if (this._autoCompactionAbortController.signal.aborted) {
1847
+ this._emit({ type: "auto_compaction_end", result: undefined, aborted: true, willRetry: false });
1848
+ return;
1849
+ }
1850
+
1851
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1852
+ const newEntries = this.sessionManager.getEntries();
1853
+ const sessionContext = this.sessionManager.buildSessionContext();
1854
+ this.agent.replaceMessages(sessionContext.messages);
1855
+
1856
+ // Get the saved compaction entry for the extension event
1857
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary) as
1858
+ | CompactionEntry
1859
+ | undefined;
1860
+
1861
+ if (this._extensionRunner && savedCompactionEntry) {
1862
+ await this._extensionRunner.emit({
1863
+ type: "session_compact",
1864
+ compactionEntry: savedCompactionEntry,
1865
+ fromExtension,
1866
+ });
1867
+ }
1868
+
1869
+ const result: CompactionResult = {
1870
+ summary,
1871
+ firstKeptEntryId,
1872
+ tokensBefore,
1873
+ details,
1874
+ };
1875
+ this._emit({ type: "auto_compaction_end", result, aborted: false, willRetry });
1876
+
1877
+ if (willRetry) {
1878
+ const messages = this.agent.state.messages;
1879
+ const lastMsg = messages[messages.length - 1];
1880
+ if (lastMsg?.role === "assistant" && (lastMsg as AssistantMessage).stopReason === "error") {
1881
+ this.agent.replaceMessages(messages.slice(0, -1));
1882
+ }
1883
+
1884
+ setTimeout(() => {
1885
+ this.agent.continue().catch(() => {});
1886
+ }, 100);
1887
+ } else if (this.agent.hasQueuedMessages()) {
1888
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1889
+ // Kick the loop so queued messages are actually delivered.
1890
+ setTimeout(() => {
1891
+ this.agent.continue().catch(() => {});
1892
+ }, 100);
1893
+ }
1894
+ } catch (error) {
1895
+ const errorMessage = error instanceof Error ? error.message : "compaction failed";
1896
+ this._emit({
1897
+ type: "auto_compaction_end",
1898
+ result: undefined,
1899
+ aborted: false,
1900
+ willRetry: false,
1901
+ errorMessage:
1902
+ reason === "overflow"
1903
+ ? `Context overflow recovery failed: ${errorMessage}`
1904
+ : `Auto-compaction failed: ${errorMessage}`,
1905
+ });
1906
+ } finally {
1907
+ this._autoCompactionAbortController = undefined;
1908
+ }
1909
+ }
1910
+
1911
+ /**
1912
+ * Toggle auto-compaction setting.
1913
+ */
1914
+ setAutoCompactionEnabled(enabled: boolean): void {
1915
+ this.settingsManager.setCompactionEnabled(enabled);
1916
+ }
1917
+
1918
+ /** Whether auto-compaction is enabled */
1919
+ get autoCompactionEnabled(): boolean {
1920
+ return this.settingsManager.getCompactionEnabled();
1921
+ }
1922
+
1923
+ async bindExtensions(bindings: ExtensionBindings): Promise<void> {
1924
+ if (bindings.uiContext !== undefined) {
1925
+ this._extensionUIContext = bindings.uiContext;
1926
+ }
1927
+ if (bindings.commandContextActions !== undefined) {
1928
+ this._extensionCommandContextActions = bindings.commandContextActions;
1929
+ }
1930
+ if (bindings.shutdownHandler !== undefined) {
1931
+ this._extensionShutdownHandler = bindings.shutdownHandler;
1932
+ }
1933
+ if (bindings.onError !== undefined) {
1934
+ this._extensionErrorListener = bindings.onError;
1935
+ }
1936
+
1937
+ if (this._extensionRunner) {
1938
+ this._applyExtensionBindings(this._extensionRunner);
1939
+ await this._extensionRunner.emit({ type: "session_start" });
1940
+ await this.extendResourcesFromExtensions("startup");
1941
+ }
1942
+ }
1943
+
1944
+ private async extendResourcesFromExtensions(reason: "startup" | "reload"): Promise<void> {
1945
+ if (!this._extensionRunner?.hasHandlers("resources_discover")) {
1946
+ return;
1947
+ }
1948
+
1949
+ const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(
1950
+ this._cwd,
1951
+ reason,
1952
+ );
1953
+
1954
+ if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
1955
+ return;
1956
+ }
1957
+
1958
+ const extensionPaths: ResourceExtensionPaths = {
1959
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
1960
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
1961
+ themePaths: this.buildExtensionResourcePaths(themePaths),
1962
+ };
1963
+
1964
+ this._resourceLoader.extendResources(extensionPaths);
1965
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
1966
+ this.agent.setSystemPrompt(this._baseSystemPrompt);
1967
+ }
1968
+
1969
+ private buildExtensionResourcePaths(entries: Array<{ path: string; extensionPath: string }>): Array<{
1970
+ path: string;
1971
+ metadata: { source: string; scope: "temporary"; origin: "top-level"; baseDir?: string };
1972
+ }> {
1973
+ return entries.map((entry) => {
1974
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
1975
+ const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
1976
+ return {
1977
+ path: entry.path,
1978
+ metadata: {
1979
+ source,
1980
+ scope: "temporary",
1981
+ origin: "top-level",
1982
+ baseDir,
1983
+ },
1984
+ };
1985
+ });
1986
+ }
1987
+
1988
+ private getExtensionSourceLabel(extensionPath: string): string {
1989
+ if (extensionPath.startsWith("<")) {
1990
+ return `extension:${extensionPath.replace(/[<>]/g, "")}`;
1991
+ }
1992
+ const base = basename(extensionPath);
1993
+ const name = base.replace(/\.(ts|js)$/, "");
1994
+ return `extension:${name}`;
1995
+ }
1996
+
1997
+ private _applyExtensionBindings(runner: ExtensionRunner): void {
1998
+ runner.setUIContext(this._extensionUIContext);
1999
+ runner.bindCommandContext(this._extensionCommandContextActions);
2000
+
2001
+ this._extensionErrorUnsubscriber?.();
2002
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
2003
+ ? runner.onError(this._extensionErrorListener)
2004
+ : undefined;
2005
+ }
2006
+
2007
+ private _bindExtensionCore(runner: ExtensionRunner): void {
2008
+ const normalizeLocation = (source: string): SlashCommandLocation | undefined => {
2009
+ if (source === "user" || source === "project" || source === "path") {
2010
+ return source;
2011
+ }
2012
+ return undefined;
2013
+ };
2014
+
2015
+ const reservedBuiltins = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));
2016
+
2017
+ const getCommands = (): SlashCommandInfo[] => {
2018
+ const extensionCommands: SlashCommandInfo[] = runner
2019
+ .getRegisteredCommandsWithPaths()
2020
+ .filter(({ command }) => !reservedBuiltins.has(command.name))
2021
+ .map(({ command, extensionPath }) => ({
2022
+ name: command.name,
2023
+ description: command.description,
2024
+ source: "extension",
2025
+ path: extensionPath,
2026
+ }));
2027
+
2028
+ const templates: SlashCommandInfo[] = this.promptTemplates.map((template) => ({
2029
+ name: template.name,
2030
+ description: template.description,
2031
+ source: "prompt",
2032
+ location: normalizeLocation(template.source),
2033
+ path: template.filePath,
2034
+ }));
2035
+
2036
+ const skills: SlashCommandInfo[] = this._resourceLoader.getSkills().skills.map((skill) => ({
2037
+ name: `skill:${skill.name}`,
2038
+ description: skill.description,
2039
+ source: "skill",
2040
+ location: normalizeLocation(skill.source),
2041
+ path: skill.filePath,
2042
+ }));
2043
+
2044
+ return [...extensionCommands, ...templates, ...skills];
2045
+ };
2046
+
2047
+ runner.bindCore(
2048
+ {
2049
+ sendMessage: (message, options) => {
2050
+ this.sendCustomMessage(message, options).catch((err) => {
2051
+ runner.emitError({
2052
+ extensionPath: "<runtime>",
2053
+ event: "send_message",
2054
+ error: err instanceof Error ? err.message : String(err),
2055
+ });
2056
+ });
2057
+ },
2058
+ sendUserMessage: (content, options) => {
2059
+ this.sendUserMessage(content, options).catch((err) => {
2060
+ runner.emitError({
2061
+ extensionPath: "<runtime>",
2062
+ event: "send_user_message",
2063
+ error: err instanceof Error ? err.message : String(err),
2064
+ });
2065
+ });
2066
+ },
2067
+ appendEntry: (customType, data) => {
2068
+ this.sessionManager.appendCustomEntry(customType, data);
2069
+ },
2070
+ setSessionName: (name) => {
2071
+ this.sessionManager.appendSessionInfo(name);
2072
+ },
2073
+ getSessionName: () => {
2074
+ return this.sessionManager.getSessionName();
2075
+ },
2076
+ setLabel: (entryId, label) => {
2077
+ this.sessionManager.appendLabelChange(entryId, label);
2078
+ },
2079
+ getActiveTools: () => this.getActiveToolNames(),
2080
+ getAllTools: () => this.getAllTools(),
2081
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
2082
+ refreshTools: () => this._refreshToolRegistry(),
2083
+ getCommands,
2084
+ setModel: async (model, options) => {
2085
+ const key = await this.modelRegistry.getApiKey(model);
2086
+ if (!key) return false;
2087
+ await this.setModel(model, options);
2088
+ return true;
2089
+ },
2090
+ getThinkingLevel: () => this.thinkingLevel,
2091
+ setThinkingLevel: (level) => this.setThinkingLevel(level),
2092
+ },
2093
+ {
2094
+ getModel: () => this.model,
2095
+ isIdle: () => !this.isStreaming,
2096
+ abort: () => this.abort(),
2097
+ hasPendingMessages: () => this.pendingMessageCount > 0,
2098
+ shutdown: () => {
2099
+ this._extensionShutdownHandler?.();
2100
+ },
2101
+ getContextUsage: () => this.getContextUsage(),
2102
+ compact: (options) => {
2103
+ void (async () => {
2104
+ try {
2105
+ const result = await this.compact(options?.customInstructions);
2106
+ options?.onComplete?.(result);
2107
+ } catch (error) {
2108
+ const err = error instanceof Error ? error : new Error(String(error));
2109
+ options?.onError?.(err);
2110
+ }
2111
+ })();
2112
+ },
2113
+ getSystemPrompt: () => this.systemPrompt,
2114
+ },
2115
+ );
2116
+ }
2117
+
2118
+ private _refreshToolRegistry(options?: { activeToolNames?: string[]; includeAllExtensionTools?: boolean }): void {
2119
+ const previousRegistryNames = new Set(this._toolRegistry.keys());
2120
+ const previousActiveToolNames = this.getActiveToolNames();
2121
+
2122
+ const registeredTools = this._extensionRunner?.getAllRegisteredTools() ?? [];
2123
+ const allCustomTools = [
2124
+ ...registeredTools,
2125
+ ...this._customTools.map((def) => ({ definition: def, extensionPath: "<sdk>" })),
2126
+ ];
2127
+ this._toolPromptSnippets = new Map(
2128
+ allCustomTools
2129
+ .map((registeredTool) => {
2130
+ const snippet = this._normalizePromptSnippet(
2131
+ registeredTool.definition.promptSnippet ?? registeredTool.definition.description,
2132
+ );
2133
+ return snippet ? ([registeredTool.definition.name, snippet] as const) : undefined;
2134
+ })
2135
+ .filter((entry): entry is readonly [string, string] => entry !== undefined),
2136
+ );
2137
+ this._toolPromptGuidelines = new Map(
2138
+ allCustomTools
2139
+ .map((registeredTool) => {
2140
+ const guidelines = this._normalizePromptGuidelines(registeredTool.definition.promptGuidelines);
2141
+ return guidelines.length > 0 ? ([registeredTool.definition.name, guidelines] as const) : undefined;
2142
+ })
2143
+ .filter((entry): entry is readonly [string, string[]] => entry !== undefined),
2144
+ );
2145
+ const wrappedExtensionTools = this._extensionRunner
2146
+ ? wrapRegisteredTools(allCustomTools, this._extensionRunner)
2147
+ : [];
2148
+
2149
+ const toolRegistry = new Map(this._baseToolRegistry);
2150
+ for (const tool of wrappedExtensionTools as AgentTool[]) {
2151
+ toolRegistry.set(tool.name, tool);
2152
+ }
2153
+
2154
+ if (this._extensionRunner) {
2155
+ const wrappedAllTools = wrapToolsWithExtensions(Array.from(toolRegistry.values()), this._extensionRunner);
2156
+ this._toolRegistry = new Map(wrappedAllTools.map((tool) => [tool.name, tool]));
2157
+ } else {
2158
+ this._toolRegistry = toolRegistry;
2159
+ }
2160
+
2161
+ const nextActiveToolNames = options?.activeToolNames
2162
+ ? [...options.activeToolNames]
2163
+ : [...previousActiveToolNames];
2164
+
2165
+ if (options?.includeAllExtensionTools) {
2166
+ for (const tool of wrappedExtensionTools) {
2167
+ nextActiveToolNames.push(tool.name);
2168
+ }
2169
+ } else if (!options?.activeToolNames) {
2170
+ for (const toolName of this._toolRegistry.keys()) {
2171
+ if (!previousRegistryNames.has(toolName)) {
2172
+ nextActiveToolNames.push(toolName);
2173
+ }
2174
+ }
2175
+ }
2176
+
2177
+ this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
2178
+ }
2179
+
2180
+ private _buildRuntime(options: {
2181
+ activeToolNames?: string[];
2182
+ flagValues?: Map<string, boolean | string>;
2183
+ includeAllExtensionTools?: boolean;
2184
+ }): void {
2185
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
2186
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
2187
+ const baseTools = this._baseToolsOverride
2188
+ ? this._baseToolsOverride
2189
+ : createAllTools(this._cwd, {
2190
+ read: { autoResizeImages },
2191
+ bash: { commandPrefix: shellCommandPrefix },
2192
+ });
2193
+
2194
+ this._baseToolRegistry = new Map(Object.entries(baseTools).map(([name, tool]) => [name, tool as AgentTool]));
2195
+
2196
+ const extensionsResult = this._resourceLoader.getExtensions();
2197
+ if (options.flagValues) {
2198
+ for (const [name, value] of options.flagValues) {
2199
+ extensionsResult.runtime.flagValues.set(name, value);
2200
+ }
2201
+ }
2202
+
2203
+ const hasExtensions = extensionsResult.extensions.length > 0;
2204
+ const hasCustomTools = this._customTools.length > 0;
2205
+ this._extensionRunner =
2206
+ hasExtensions || hasCustomTools
2207
+ ? new ExtensionRunner(
2208
+ extensionsResult.extensions,
2209
+ extensionsResult.runtime,
2210
+ this._cwd,
2211
+ this.sessionManager,
2212
+ this._modelRegistry,
2213
+ )
2214
+ : undefined;
2215
+ if (this._extensionRunnerRef) {
2216
+ this._extensionRunnerRef.current = this._extensionRunner;
2217
+ }
2218
+ if (this._extensionRunner) {
2219
+ this._bindExtensionCore(this._extensionRunner);
2220
+ this._applyExtensionBindings(this._extensionRunner);
2221
+ }
2222
+
2223
+ const defaultActiveToolNames = this._baseToolsOverride
2224
+ ? Object.keys(this._baseToolsOverride)
2225
+ : ["read", "bash", "edit", "write"];
2226
+ const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
2227
+ this._refreshToolRegistry({
2228
+ activeToolNames: baseActiveToolNames,
2229
+ includeAllExtensionTools: options.includeAllExtensionTools,
2230
+ });
2231
+ }
2232
+
2233
+ async reload(): Promise<void> {
2234
+ const previousFlagValues = this._extensionRunner?.getFlagValues();
2235
+ await this._extensionRunner?.emit({ type: "session_shutdown" });
2236
+ this.settingsManager.reload();
2237
+ resetApiProviders();
2238
+ await this._resourceLoader.reload();
2239
+ this._buildRuntime({
2240
+ activeToolNames: this.getActiveToolNames(),
2241
+ flagValues: previousFlagValues,
2242
+ includeAllExtensionTools: true,
2243
+ });
2244
+
2245
+ const hasBindings =
2246
+ this._extensionUIContext ||
2247
+ this._extensionCommandContextActions ||
2248
+ this._extensionShutdownHandler ||
2249
+ this._extensionErrorListener;
2250
+ if (this._extensionRunner && hasBindings) {
2251
+ await this._extensionRunner.emit({ type: "session_start" });
2252
+ await this.extendResourcesFromExtensions("reload");
2253
+ }
2254
+ }
2255
+
2256
+ // =========================================================================
2257
+ // Auto-Retry
2258
+ // =========================================================================
2259
+
2260
+ /**
2261
+ * Check if an error is retryable (overloaded, rate limit, server errors).
2262
+ * Context overflow errors are NOT retryable (handled by compaction instead).
2263
+ */
2264
+ private _isRetryableError(message: AssistantMessage): boolean {
2265
+ if (message.stopReason !== "error" || !message.errorMessage) return false;
2266
+
2267
+ // Context overflow is handled by compaction, not retry
2268
+ const contextWindow = this.model?.contextWindow ?? 0;
2269
+ if (isContextOverflow(message, contextWindow)) return false;
2270
+
2271
+ const err = message.errorMessage;
2272
+ // Match: overloaded_error, rate limit, 429, 500, 502, 503, 504, service unavailable, connection errors, fetch failed, terminated, retry delay exceeded
2273
+ return /overloaded|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server error|internal error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|terminated|retry delay/i.test(
2274
+ err,
2275
+ );
2276
+ }
2277
+
2278
+ /**
2279
+ * Handle retryable errors with exponential backoff.
2280
+ * @returns true if retry was initiated, false if max retries exceeded or disabled
2281
+ */
2282
+ private async _handleRetryableError(message: AssistantMessage): Promise<boolean> {
2283
+ const settings = this.settingsManager.getRetrySettings();
2284
+ if (!settings.enabled) {
2285
+ this._resolveRetry();
2286
+ return false;
2287
+ }
2288
+
2289
+ // Retry promise is created synchronously in _handleAgentEvent for agent_end.
2290
+ // Keep a defensive fallback here in case a future refactor bypasses that path.
2291
+ if (!this._retryPromise) {
2292
+ this._retryPromise = new Promise((resolve) => {
2293
+ this._retryResolve = resolve;
2294
+ });
2295
+ }
2296
+
2297
+ this._retryAttempt++;
2298
+
2299
+ if (this._retryAttempt > settings.maxRetries) {
2300
+ // Max retries exceeded, emit final failure and reset
2301
+ this._emit({
2302
+ type: "auto_retry_end",
2303
+ success: false,
2304
+ attempt: this._retryAttempt - 1,
2305
+ finalError: message.errorMessage,
2306
+ });
2307
+ this._retryAttempt = 0;
2308
+ this._resolveRetry(); // Resolve so waitForRetry() completes
2309
+ return false;
2310
+ }
2311
+
2312
+ const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
2313
+
2314
+ this._emit({
2315
+ type: "auto_retry_start",
2316
+ attempt: this._retryAttempt,
2317
+ maxAttempts: settings.maxRetries,
2318
+ delayMs,
2319
+ errorMessage: message.errorMessage || "Unknown error",
2320
+ });
2321
+
2322
+ // Remove error message from agent state (keep in session for history)
2323
+ const messages = this.agent.state.messages;
2324
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2325
+ this.agent.replaceMessages(messages.slice(0, -1));
2326
+ }
2327
+
2328
+ // Wait with exponential backoff (abortable)
2329
+ this._retryAbortController = new AbortController();
2330
+ try {
2331
+ await sleep(delayMs, this._retryAbortController.signal);
2332
+ } catch {
2333
+ // Aborted during sleep - emit end event so UI can clean up
2334
+ const attempt = this._retryAttempt;
2335
+ this._retryAttempt = 0;
2336
+ this._retryAbortController = undefined;
2337
+ this._emit({
2338
+ type: "auto_retry_end",
2339
+ success: false,
2340
+ attempt,
2341
+ finalError: "Retry cancelled",
2342
+ });
2343
+ this._resolveRetry();
2344
+ return false;
2345
+ }
2346
+ this._retryAbortController = undefined;
2347
+
2348
+ // Retry via continue() - use setTimeout to break out of event handler chain
2349
+ setTimeout(() => {
2350
+ this.agent.continue().catch(() => {
2351
+ // Retry failed - will be caught by next agent_end
2352
+ });
2353
+ }, 0);
2354
+
2355
+ return true;
2356
+ }
2357
+
2358
+ /**
2359
+ * Cancel in-progress retry.
2360
+ */
2361
+ abortRetry(): void {
2362
+ this._retryAbortController?.abort();
2363
+ // Note: _retryAttempt is reset in the catch block of _autoRetry
2364
+ this._resolveRetry();
2365
+ }
2366
+
2367
+ /**
2368
+ * Wait for any in-progress retry to complete.
2369
+ * Returns immediately if no retry is in progress.
2370
+ */
2371
+ private async waitForRetry(): Promise<void> {
2372
+ if (this._retryPromise) {
2373
+ await this._retryPromise;
2374
+ }
2375
+ }
2376
+
2377
+ /** Whether auto-retry is currently in progress */
2378
+ get isRetrying(): boolean {
2379
+ return this._retryPromise !== undefined;
2380
+ }
2381
+
2382
+ /** Whether auto-retry is enabled */
2383
+ get autoRetryEnabled(): boolean {
2384
+ return this.settingsManager.getRetryEnabled();
2385
+ }
2386
+
2387
+ /**
2388
+ * Toggle auto-retry setting.
2389
+ */
2390
+ setAutoRetryEnabled(enabled: boolean): void {
2391
+ this.settingsManager.setRetryEnabled(enabled);
2392
+ }
2393
+
2394
+ // =========================================================================
2395
+ // Bash Execution
2396
+ // =========================================================================
2397
+
2398
+ /**
2399
+ * Execute a bash command.
2400
+ * Adds result to agent context and session.
2401
+ * @param command The bash command to execute
2402
+ * @param onChunk Optional streaming callback for output
2403
+ * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
2404
+ * @param options.operations Custom BashOperations for remote execution
2405
+ */
2406
+ async executeBash(
2407
+ command: string,
2408
+ onChunk?: (chunk: string) => void,
2409
+ options?: { excludeFromContext?: boolean; operations?: BashOperations },
2410
+ ): Promise<BashResult> {
2411
+ this._bashAbortController = new AbortController();
2412
+
2413
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2414
+ const prefix = this.settingsManager.getShellCommandPrefix();
2415
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2416
+
2417
+ try {
2418
+ const result = options?.operations
2419
+ ? await executeBashWithOperations(resolvedCommand, process.cwd(), options.operations, {
2420
+ onChunk,
2421
+ signal: this._bashAbortController.signal,
2422
+ })
2423
+ : await executeBashCommand(resolvedCommand, {
2424
+ onChunk,
2425
+ signal: this._bashAbortController.signal,
2426
+ });
2427
+
2428
+ this.recordBashResult(command, result, options);
2429
+ return result;
2430
+ } finally {
2431
+ this._bashAbortController = undefined;
2432
+ }
2433
+ }
2434
+
2435
+ /**
2436
+ * Record a bash execution result in session history.
2437
+ * Used by executeBash and by extensions that handle bash execution themselves.
2438
+ */
2439
+ recordBashResult(command: string, result: BashResult, options?: { excludeFromContext?: boolean }): void {
2440
+ const bashMessage: BashExecutionMessage = {
2441
+ role: "bashExecution",
2442
+ command,
2443
+ output: result.output,
2444
+ exitCode: result.exitCode,
2445
+ cancelled: result.cancelled,
2446
+ truncated: result.truncated,
2447
+ fullOutputPath: result.fullOutputPath,
2448
+ timestamp: Date.now(),
2449
+ excludeFromContext: options?.excludeFromContext,
2450
+ };
2451
+
2452
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
2453
+ if (this.isStreaming) {
2454
+ // Queue for later - will be flushed on agent_end
2455
+ this._pendingBashMessages.push(bashMessage);
2456
+ } else {
2457
+ // Add to agent state immediately
2458
+ this.agent.appendMessage(bashMessage);
2459
+
2460
+ // Save to session
2461
+ this.sessionManager.appendMessage(bashMessage);
2462
+ }
2463
+ }
2464
+
2465
+ /**
2466
+ * Cancel running bash command.
2467
+ */
2468
+ abortBash(): void {
2469
+ this._bashAbortController?.abort();
2470
+ }
2471
+
2472
+ /** Whether a bash command is currently running */
2473
+ get isBashRunning(): boolean {
2474
+ return this._bashAbortController !== undefined;
2475
+ }
2476
+
2477
+ /** Whether there are pending bash messages waiting to be flushed */
2478
+ get hasPendingBashMessages(): boolean {
2479
+ return this._pendingBashMessages.length > 0;
2480
+ }
2481
+
2482
+ /**
2483
+ * Flush pending bash messages to agent state and session.
2484
+ * Called after agent turn completes to maintain proper message ordering.
2485
+ */
2486
+ private _flushPendingBashMessages(): void {
2487
+ if (this._pendingBashMessages.length === 0) return;
2488
+
2489
+ for (const bashMessage of this._pendingBashMessages) {
2490
+ // Add to agent state
2491
+ this.agent.appendMessage(bashMessage);
2492
+
2493
+ // Save to session
2494
+ this.sessionManager.appendMessage(bashMessage);
2495
+ }
2496
+
2497
+ this._pendingBashMessages = [];
2498
+ }
2499
+
2500
+ // =========================================================================
2501
+ // Session Management
2502
+ // =========================================================================
2503
+
2504
+ /**
2505
+ * Switch to a different session file.
2506
+ * Aborts current operation, loads messages, restores model/thinking.
2507
+ * Listeners are preserved and will continue receiving events.
2508
+ * @returns true if switch completed, false if cancelled by extension
2509
+ */
2510
+ async switchSession(sessionPath: string): Promise<boolean> {
2511
+ const previousSessionFile = this.sessionManager.getSessionFile();
2512
+
2513
+ // Emit session_before_switch event (can be cancelled)
2514
+ if (this._extensionRunner?.hasHandlers("session_before_switch")) {
2515
+ const result = (await this._extensionRunner.emit({
2516
+ type: "session_before_switch",
2517
+ reason: "resume",
2518
+ targetSessionFile: sessionPath,
2519
+ })) as SessionBeforeSwitchResult | undefined;
2520
+
2521
+ if (result?.cancel) {
2522
+ return false;
2523
+ }
2524
+ }
2525
+
2526
+ this._disconnectFromAgent();
2527
+ await this.abort();
2528
+ this._steeringMessages = [];
2529
+ this._followUpMessages = [];
2530
+ this._pendingNextTurnMessages = [];
2531
+
2532
+ // Set new session
2533
+ this.sessionManager.setSessionFile(sessionPath);
2534
+ this.agent.sessionId = this.sessionManager.getSessionId();
2535
+
2536
+ // Reload messages
2537
+ const sessionContext = this.sessionManager.buildSessionContext();
2538
+
2539
+ // Emit session_switch event to extensions
2540
+ if (this._extensionRunner) {
2541
+ await this._extensionRunner.emit({
2542
+ type: "session_switch",
2543
+ reason: "resume",
2544
+ previousSessionFile,
2545
+ });
2546
+ }
2547
+
2548
+ // Emit session event to custom tools
2549
+
2550
+ this.agent.replaceMessages(sessionContext.messages);
2551
+
2552
+ // Restore model if saved
2553
+ if (sessionContext.model) {
2554
+ const previousModel = this.model;
2555
+ const availableModels = await this._modelRegistry.getAvailable();
2556
+ const match = availableModels.find(
2557
+ (m) => m.provider === sessionContext.model!.provider && m.id === sessionContext.model!.modelId,
2558
+ );
2559
+ if (match) {
2560
+ this.agent.setModel(match);
2561
+ await this._emitModelSelect(match, previousModel, "restore");
2562
+ }
2563
+ }
2564
+
2565
+ const hasThinkingEntry = this.sessionManager.getBranch().some((entry) => entry.type === "thinking_level_change");
2566
+ const defaultThinkingLevel = this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
2567
+
2568
+ if (hasThinkingEntry) {
2569
+ // Restore thinking level if saved (setThinkingLevel clamps to model capabilities)
2570
+ this.setThinkingLevel(sessionContext.thinkingLevel as ThinkingLevel);
2571
+ } else {
2572
+ const availableLevels = this.getAvailableThinkingLevels();
2573
+ const effectiveLevel = availableLevels.includes(defaultThinkingLevel)
2574
+ ? defaultThinkingLevel
2575
+ : this._clampThinkingLevel(defaultThinkingLevel, availableLevels);
2576
+ this.agent.setThinkingLevel(effectiveLevel);
2577
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
2578
+ }
2579
+
2580
+ this._reconnectToAgent();
2581
+ return true;
2582
+ }
2583
+
2584
+ /**
2585
+ * Set a display name for the current session.
2586
+ */
2587
+ setSessionName(name: string): void {
2588
+ this.sessionManager.appendSessionInfo(name);
2589
+ }
2590
+
2591
+ /**
2592
+ * Create a fork from a specific entry.
2593
+ * Emits before_fork/fork session events to extensions.
2594
+ *
2595
+ * @param entryId ID of the entry to fork from
2596
+ * @returns Object with:
2597
+ * - selectedText: The text of the selected user message (for editor pre-fill)
2598
+ * - cancelled: True if an extension cancelled the fork
2599
+ */
2600
+ async fork(entryId: string): Promise<{ selectedText: string; cancelled: boolean }> {
2601
+ const previousSessionFile = this.sessionFile;
2602
+ const selectedEntry = this.sessionManager.getEntry(entryId);
2603
+
2604
+ if (!selectedEntry || selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
2605
+ throw new Error("Invalid entry ID for forking");
2606
+ }
2607
+
2608
+ const selectedText = this._extractUserMessageText(selectedEntry.message.content);
2609
+
2610
+ let skipConversationRestore = false;
2611
+
2612
+ // Emit session_before_fork event (can be cancelled)
2613
+ if (this._extensionRunner?.hasHandlers("session_before_fork")) {
2614
+ const result = (await this._extensionRunner.emit({
2615
+ type: "session_before_fork",
2616
+ entryId,
2617
+ })) as SessionBeforeForkResult | undefined;
2618
+
2619
+ if (result?.cancel) {
2620
+ return { selectedText, cancelled: true };
2621
+ }
2622
+ skipConversationRestore = result?.skipConversationRestore ?? false;
2623
+ }
2624
+
2625
+ // Clear pending messages (bound to old session state)
2626
+ this._pendingNextTurnMessages = [];
2627
+
2628
+ if (!selectedEntry.parentId) {
2629
+ this.sessionManager.newSession({ parentSession: previousSessionFile });
2630
+ } else {
2631
+ this.sessionManager.createBranchedSession(selectedEntry.parentId);
2632
+ }
2633
+ this.agent.sessionId = this.sessionManager.getSessionId();
2634
+
2635
+ // Reload messages from entries (works for both file and in-memory mode)
2636
+ const sessionContext = this.sessionManager.buildSessionContext();
2637
+
2638
+ // Emit session_fork event to extensions (after fork completes)
2639
+ if (this._extensionRunner) {
2640
+ await this._extensionRunner.emit({
2641
+ type: "session_fork",
2642
+ previousSessionFile,
2643
+ });
2644
+ }
2645
+
2646
+ // Emit session event to custom tools (with reason "fork")
2647
+
2648
+ if (!skipConversationRestore) {
2649
+ this.agent.replaceMessages(sessionContext.messages);
2650
+ }
2651
+
2652
+ return { selectedText, cancelled: false };
2653
+ }
2654
+
2655
+ // =========================================================================
2656
+ // Tree Navigation
2657
+ // =========================================================================
2658
+
2659
+ /**
2660
+ * Navigate to a different node in the session tree.
2661
+ * Unlike fork() which creates a new session file, this stays in the same file.
2662
+ *
2663
+ * @param targetId The entry ID to navigate to
2664
+ * @param options.summarize Whether user wants to summarize abandoned branch
2665
+ * @param options.customInstructions Custom instructions for summarizer
2666
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
2667
+ * @param options.label Label to attach to the branch summary entry
2668
+ * @returns Result with editorText (if user message) and cancelled status
2669
+ */
2670
+ async navigateTree(
2671
+ targetId: string,
2672
+ options: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string } = {},
2673
+ ): Promise<{ editorText?: string; cancelled: boolean; aborted?: boolean; summaryEntry?: BranchSummaryEntry }> {
2674
+ const oldLeafId = this.sessionManager.getLeafId();
2675
+
2676
+ // No-op if already at target
2677
+ if (targetId === oldLeafId) {
2678
+ return { cancelled: false };
2679
+ }
2680
+
2681
+ // Model required for summarization
2682
+ if (options.summarize && !this.model) {
2683
+ throw new Error("No model available for summarization");
2684
+ }
2685
+
2686
+ const targetEntry = this.sessionManager.getEntry(targetId);
2687
+ if (!targetEntry) {
2688
+ throw new Error(`Entry ${targetId} not found`);
2689
+ }
2690
+
2691
+ // Collect entries to summarize (from old leaf to common ancestor)
2692
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(
2693
+ this.sessionManager,
2694
+ oldLeafId,
2695
+ targetId,
2696
+ );
2697
+
2698
+ // Prepare event data - mutable so extensions can override
2699
+ let customInstructions = options.customInstructions;
2700
+ let replaceInstructions = options.replaceInstructions;
2701
+ let label = options.label;
2702
+
2703
+ const preparation: TreePreparation = {
2704
+ targetId,
2705
+ oldLeafId,
2706
+ commonAncestorId,
2707
+ entriesToSummarize,
2708
+ userWantsSummary: options.summarize ?? false,
2709
+ customInstructions,
2710
+ replaceInstructions,
2711
+ label,
2712
+ };
2713
+
2714
+ // Set up abort controller for summarization
2715
+ this._branchSummaryAbortController = new AbortController();
2716
+ let extensionSummary: { summary: string; details?: unknown } | undefined;
2717
+ let fromExtension = false;
2718
+
2719
+ // Emit session_before_tree event
2720
+ if (this._extensionRunner?.hasHandlers("session_before_tree")) {
2721
+ const result = (await this._extensionRunner.emit({
2722
+ type: "session_before_tree",
2723
+ preparation,
2724
+ signal: this._branchSummaryAbortController.signal,
2725
+ })) as SessionBeforeTreeResult | undefined;
2726
+
2727
+ if (result?.cancel) {
2728
+ return { cancelled: true };
2729
+ }
2730
+
2731
+ if (result?.summary && options.summarize) {
2732
+ extensionSummary = result.summary;
2733
+ fromExtension = true;
2734
+ }
2735
+
2736
+ // Allow extensions to override instructions and label
2737
+ if (result?.customInstructions !== undefined) {
2738
+ customInstructions = result.customInstructions;
2739
+ }
2740
+ if (result?.replaceInstructions !== undefined) {
2741
+ replaceInstructions = result.replaceInstructions;
2742
+ }
2743
+ if (result?.label !== undefined) {
2744
+ label = result.label;
2745
+ }
2746
+ }
2747
+
2748
+ // Run default summarizer if needed
2749
+ let summaryText: string | undefined;
2750
+ let summaryDetails: unknown;
2751
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2752
+ const model = this.model!;
2753
+ const apiKey = await this._modelRegistry.getApiKey(model);
2754
+ if (!apiKey) {
2755
+ throw new Error(`No API key for ${model.provider}`);
2756
+ }
2757
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2758
+ const result = await generateBranchSummary(entriesToSummarize, {
2759
+ model,
2760
+ apiKey,
2761
+ signal: this._branchSummaryAbortController.signal,
2762
+ customInstructions,
2763
+ replaceInstructions,
2764
+ reserveTokens: branchSummarySettings.reserveTokens,
2765
+ });
2766
+ this._branchSummaryAbortController = undefined;
2767
+ if (result.aborted) {
2768
+ return { cancelled: true, aborted: true };
2769
+ }
2770
+ if (result.error) {
2771
+ throw new Error(result.error);
2772
+ }
2773
+ summaryText = result.summary;
2774
+ summaryDetails = {
2775
+ readFiles: result.readFiles || [],
2776
+ modifiedFiles: result.modifiedFiles || [],
2777
+ };
2778
+ } else if (extensionSummary) {
2779
+ summaryText = extensionSummary.summary;
2780
+ summaryDetails = extensionSummary.details;
2781
+ }
2782
+
2783
+ // Determine the new leaf position based on target type
2784
+ let newLeafId: string | null;
2785
+ let editorText: string | undefined;
2786
+
2787
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2788
+ // User message: leaf = parent (null if root), text goes to editor
2789
+ newLeafId = targetEntry.parentId;
2790
+ editorText = this._extractUserMessageText(targetEntry.message.content);
2791
+ } else if (targetEntry.type === "custom_message") {
2792
+ // Custom message: leaf = parent (null if root), text goes to editor
2793
+ newLeafId = targetEntry.parentId;
2794
+ editorText =
2795
+ typeof targetEntry.content === "string"
2796
+ ? targetEntry.content
2797
+ : targetEntry.content
2798
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
2799
+ .map((c) => c.text)
2800
+ .join("");
2801
+ } else {
2802
+ // Non-user message: leaf = selected node
2803
+ newLeafId = targetId;
2804
+ }
2805
+
2806
+ // Switch leaf (with or without summary)
2807
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
2808
+ let summaryEntry: BranchSummaryEntry | undefined;
2809
+ if (summaryText) {
2810
+ // Create summary at target position (can be null for root)
2811
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
2812
+ summaryEntry = this.sessionManager.getEntry(summaryId) as BranchSummaryEntry;
2813
+
2814
+ // Attach label to the summary entry
2815
+ if (label) {
2816
+ this.sessionManager.appendLabelChange(summaryId, label);
2817
+ }
2818
+ } else if (newLeafId === null) {
2819
+ // No summary, navigating to root - reset leaf
2820
+ this.sessionManager.resetLeaf();
2821
+ } else {
2822
+ // No summary, navigating to non-root
2823
+ this.sessionManager.branch(newLeafId);
2824
+ }
2825
+
2826
+ // Attach label to target entry when not summarizing (no summary entry to label)
2827
+ if (label && !summaryText) {
2828
+ this.sessionManager.appendLabelChange(targetId, label);
2829
+ }
2830
+
2831
+ // Update agent state
2832
+ const sessionContext = this.sessionManager.buildSessionContext();
2833
+ this.agent.replaceMessages(sessionContext.messages);
2834
+
2835
+ // Emit session_tree event
2836
+ if (this._extensionRunner) {
2837
+ await this._extensionRunner.emit({
2838
+ type: "session_tree",
2839
+ newLeafId: this.sessionManager.getLeafId(),
2840
+ oldLeafId,
2841
+ summaryEntry,
2842
+ fromExtension: summaryText ? fromExtension : undefined,
2843
+ });
2844
+ }
2845
+
2846
+ // Emit to custom tools
2847
+
2848
+ this._branchSummaryAbortController = undefined;
2849
+ return { editorText, cancelled: false, summaryEntry };
2850
+ }
2851
+
2852
+ /**
2853
+ * Get all user messages from session for fork selector.
2854
+ */
2855
+ getUserMessagesForForking(): Array<{ entryId: string; text: string }> {
2856
+ const entries = this.sessionManager.getEntries();
2857
+ const result: Array<{ entryId: string; text: string }> = [];
2858
+
2859
+ for (const entry of entries) {
2860
+ if (entry.type !== "message") continue;
2861
+ if (entry.message.role !== "user") continue;
2862
+
2863
+ const text = this._extractUserMessageText(entry.message.content);
2864
+ if (text) {
2865
+ result.push({ entryId: entry.id, text });
2866
+ }
2867
+ }
2868
+
2869
+ return result;
2870
+ }
2871
+
2872
+ private _extractUserMessageText(content: string | Array<{ type: string; text?: string }>): string {
2873
+ if (typeof content === "string") return content;
2874
+ if (Array.isArray(content)) {
2875
+ return content
2876
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
2877
+ .map((c) => c.text)
2878
+ .join("");
2879
+ }
2880
+ return "";
2881
+ }
2882
+
2883
+ /**
2884
+ * Get session statistics.
2885
+ */
2886
+ getSessionStats(): SessionStats {
2887
+ const state = this.state;
2888
+ const userMessages = state.messages.filter((m) => m.role === "user").length;
2889
+ const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
2890
+ const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
2891
+
2892
+ let toolCalls = 0;
2893
+ let totalInput = 0;
2894
+ let totalOutput = 0;
2895
+ let totalCacheRead = 0;
2896
+ let totalCacheWrite = 0;
2897
+ let totalCost = 0;
2898
+
2899
+ for (const message of state.messages) {
2900
+ if (message.role === "assistant") {
2901
+ const assistantMsg = message as AssistantMessage;
2902
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
2903
+ totalInput += assistantMsg.usage.input;
2904
+ totalOutput += assistantMsg.usage.output;
2905
+ totalCacheRead += assistantMsg.usage.cacheRead;
2906
+ totalCacheWrite += assistantMsg.usage.cacheWrite;
2907
+ totalCost += assistantMsg.usage.cost.total;
2908
+ }
2909
+ }
2910
+
2911
+ return {
2912
+ sessionFile: this.sessionFile,
2913
+ sessionId: this.sessionId,
2914
+ userMessages,
2915
+ assistantMessages,
2916
+ toolCalls,
2917
+ toolResults,
2918
+ totalMessages: state.messages.length,
2919
+ tokens: {
2920
+ input: totalInput,
2921
+ output: totalOutput,
2922
+ cacheRead: totalCacheRead,
2923
+ cacheWrite: totalCacheWrite,
2924
+ total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
2925
+ },
2926
+ cost: totalCost,
2927
+ };
2928
+ }
2929
+
2930
+ getContextUsage(): ContextUsage | undefined {
2931
+ const model = this.model;
2932
+ if (!model) return undefined;
2933
+
2934
+ const contextWindow = model.contextWindow ?? 0;
2935
+ if (contextWindow <= 0) return undefined;
2936
+
2937
+ // After compaction, the last assistant usage reflects pre-compaction context size.
2938
+ // We can only trust usage from an assistant that responded after the latest compaction.
2939
+ // If no such assistant exists, context token count is unknown until the next LLM response.
2940
+ const branchEntries = this.sessionManager.getBranch();
2941
+ const latestCompaction = getLatestCompactionEntry(branchEntries);
2942
+
2943
+ if (latestCompaction) {
2944
+ // Check if there's a valid assistant usage after the compaction boundary
2945
+ const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
2946
+ let hasPostCompactionUsage = false;
2947
+ for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
2948
+ const entry = branchEntries[i];
2949
+ if (entry.type === "message" && entry.message.role === "assistant") {
2950
+ const assistant = entry.message;
2951
+ if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
2952
+ const contextTokens = calculateContextTokens(assistant.usage);
2953
+ if (contextTokens > 0) {
2954
+ hasPostCompactionUsage = true;
2955
+ }
2956
+ break;
2957
+ }
2958
+ }
2959
+ }
2960
+
2961
+ if (!hasPostCompactionUsage) {
2962
+ return { tokens: null, contextWindow, percent: null };
2963
+ }
2964
+ }
2965
+
2966
+ const estimate = estimateContextTokens(this.messages);
2967
+ const percent = (estimate.tokens / contextWindow) * 100;
2968
+
2969
+ return {
2970
+ tokens: estimate.tokens,
2971
+ contextWindow,
2972
+ percent,
2973
+ };
2974
+ }
2975
+
2976
+ /**
2977
+ * Export session to HTML.
2978
+ * @param outputPath Optional output path (defaults to session directory)
2979
+ * @returns Path to exported file
2980
+ */
2981
+ async exportToHtml(outputPath?: string): Promise<string> {
2982
+ const themeName = this.settingsManager.getTheme();
2983
+
2984
+ // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
2985
+ let toolRenderer: ToolHtmlRenderer | undefined;
2986
+ if (this._extensionRunner) {
2987
+ toolRenderer = createToolHtmlRenderer({
2988
+ getToolDefinition: (name) => this._extensionRunner!.getToolDefinition(name),
2989
+ theme,
2990
+ });
2991
+ }
2992
+
2993
+ return await exportSessionToHtml(this.sessionManager, this.state, {
2994
+ outputPath,
2995
+ themeName,
2996
+ toolRenderer,
2997
+ });
2998
+ }
2999
+
3000
+ // =========================================================================
3001
+ // Utilities
3002
+ // =========================================================================
3003
+
3004
+ /**
3005
+ * Get text content of last assistant message.
3006
+ * Useful for /copy command.
3007
+ * @returns Text content, or undefined if no assistant message exists
3008
+ */
3009
+ getLastAssistantText(): string | undefined {
3010
+ const lastAssistant = this.messages
3011
+ .slice()
3012
+ .reverse()
3013
+ .find((m) => {
3014
+ if (m.role !== "assistant") return false;
3015
+ const msg = m as AssistantMessage;
3016
+ // Skip aborted messages with no content
3017
+ if (msg.stopReason === "aborted" && msg.content.length === 0) return false;
3018
+ return true;
3019
+ });
3020
+
3021
+ if (!lastAssistant) return undefined;
3022
+
3023
+ let text = "";
3024
+ for (const content of (lastAssistant as AssistantMessage).content) {
3025
+ if (content.type === "text") {
3026
+ text += content.text;
3027
+ }
3028
+ }
3029
+
3030
+ return text.trim() || undefined;
3031
+ }
3032
+
3033
+ // =========================================================================
3034
+ // Extension System
3035
+ // =========================================================================
3036
+
3037
+ /**
3038
+ * Check if extensions have handlers for a specific event type.
3039
+ */
3040
+ hasExtensionHandlers(eventType: string): boolean {
3041
+ return this._extensionRunner?.hasHandlers(eventType) ?? false;
3042
+ }
3043
+
3044
+ /**
3045
+ * Get the extension runner (for setting UI context and error handlers).
3046
+ */
3047
+ get extensionRunner(): ExtensionRunner | undefined {
3048
+ return this._extensionRunner;
3049
+ }
3050
+ }