@mars_ai/marscli 2.0.12 → 2.0.14

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 (1187) hide show
  1. package/CHANGELOG.md +6515 -0
  2. package/README.md +71 -22
  3. package/dist/bun/cli.d.ts +5 -0
  4. package/dist/bun/cli.d.ts.map +1 -0
  5. package/dist/bun/cli.js +5 -0
  6. package/dist/bun/cli.js.map +1 -0
  7. package/dist/bun/restore-sandbox-env.d.ts +17 -0
  8. package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
  9. package/dist/bun/restore-sandbox-env.js +36 -0
  10. package/dist/bun/restore-sandbox-env.js.map +1 -0
  11. package/dist/bun/runtime-setup.d.ts +2 -0
  12. package/dist/bun/runtime-setup.d.ts.map +1 -0
  13. package/dist/bun/runtime-setup.js +12 -0
  14. package/dist/bun/runtime-setup.js.map +1 -0
  15. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  16. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  17. package/dist/bun/sandbox-env-setup.js +4 -0
  18. package/dist/bun/sandbox-env-setup.js.map +1 -0
  19. package/dist/bundle/chunks/anthropic-messages-QCK7M7VG.js +6 -0
  20. package/dist/bundle/chunks/anthropic.js +75 -0
  21. package/dist/bundle/chunks/azure-openai-responses-LMBPTTDE.js +2 -0
  22. package/dist/bundle/chunks/bedrock-converse-stream.js +89 -0
  23. package/dist/bundle/chunks/chunk-45GGYWI5.js +2 -0
  24. package/dist/bundle/chunks/chunk-5AGIVGSV.js +6 -0
  25. package/dist/bundle/chunks/chunk-5ZIVIB55.js +8 -0
  26. package/dist/bundle/chunks/chunk-6QGV3IWD.js +6 -0
  27. package/dist/bundle/chunks/chunk-7CBJINYJ.js +20 -0
  28. package/dist/bundle/chunks/chunk-7DDKXS2Q.js +2 -0
  29. package/dist/bundle/chunks/chunk-7ZC4UXSL.js +2 -0
  30. package/dist/bundle/chunks/chunk-AZEKCFSR.js +82 -0
  31. package/dist/bundle/chunks/chunk-BUEFMMN7.js +1261 -0
  32. package/dist/bundle/chunks/chunk-CF5GWZHW.js +31 -0
  33. package/dist/bundle/chunks/chunk-FFMDRXC4.js +10 -0
  34. package/dist/bundle/chunks/chunk-FR2OJIAF.js +2 -0
  35. package/dist/bundle/chunks/chunk-G4QXDUQL.js +30 -0
  36. package/dist/bundle/chunks/chunk-GFUN2N5K.js +2 -0
  37. package/dist/bundle/chunks/chunk-GXW3X65X.js +4 -0
  38. package/dist/bundle/chunks/chunk-ICLDQMTM.js +129 -0
  39. package/dist/bundle/chunks/chunk-IEBK4HQA.js +2 -0
  40. package/dist/bundle/chunks/chunk-JEIXS66U.js +2 -0
  41. package/dist/bundle/chunks/chunk-JK44MIUX.js +44 -0
  42. package/dist/bundle/chunks/chunk-JXUDILQJ.js +16 -0
  43. package/dist/bundle/chunks/chunk-JXWJOIH4.js +2 -0
  44. package/dist/bundle/chunks/chunk-K5TQM7UY.js +2 -0
  45. package/dist/bundle/chunks/chunk-L2ZPNLYD.js +2 -0
  46. package/dist/bundle/chunks/chunk-LPXNMA2W.js +2 -0
  47. package/dist/bundle/chunks/chunk-LVVZS2NO.js +12 -0
  48. package/dist/bundle/chunks/chunk-MTY47RPT.js +19 -0
  49. package/dist/bundle/chunks/chunk-OLNSR6Z3.js +13 -0
  50. package/dist/bundle/chunks/chunk-P7FPUEYA.js +2 -0
  51. package/dist/bundle/chunks/chunk-PGXDEOVV.js +2 -0
  52. package/dist/bundle/chunks/chunk-PJACZCIR.js +2 -0
  53. package/dist/bundle/chunks/chunk-PMRZO46Y.js +2 -0
  54. package/dist/bundle/chunks/chunk-PRRNXB7S.js +2 -0
  55. package/dist/bundle/chunks/chunk-RDZVAGPR.js +2 -0
  56. package/dist/bundle/chunks/chunk-TVDA4NZP.js +55 -0
  57. package/dist/bundle/chunks/chunk-UNAPBUIX.js +2 -0
  58. package/dist/bundle/chunks/chunk-UTB4DTYQ.js +2 -0
  59. package/dist/bundle/chunks/chunk-V6KH5QG4.js +9 -0
  60. package/dist/bundle/chunks/chunk-ZG74NES2.js +2 -0
  61. package/dist/bundle/chunks/cli-CI7EFTTK.js +53 -0
  62. package/dist/bundle/chunks/codemode-worker.js +478 -0
  63. package/dist/bundle/chunks/easter-egg-3d-P2D4BQR7.js +2 -0
  64. package/dist/bundle/chunks/execute-PRYDOFWM.js +505 -0
  65. package/dist/bundle/chunks/github-copilot.js +2 -0
  66. package/dist/bundle/chunks/google-generative-ai-WFLFMJYT.js +2 -0
  67. package/dist/bundle/chunks/google-vertex-3VJ5WJYY.js +2 -0
  68. package/dist/bundle/chunks/https-proxy-agent-LVOO5TPL.js +13 -0
  69. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  70. package/dist/bundle/chunks/jiti-loader-GL4HJFAD.js +21 -0
  71. package/dist/bundle/chunks/jiti-static-loader-2RCDI6B4.js +2 -0
  72. package/dist/bundle/chunks/kimi-coding.js +2 -0
  73. package/dist/bundle/chunks/lib-4AVRLBHM.js +9 -0
  74. package/dist/bundle/chunks/meta.js +2 -0
  75. package/dist/bundle/chunks/mistral-conversations-G22LGLWM.js +5 -0
  76. package/dist/bundle/chunks/multipart-parser-FMGQ7342.js +3 -0
  77. package/dist/bundle/chunks/node-AUOGOBCN.js +2 -0
  78. package/dist/bundle/chunks/node-KCMANYC2.js +16 -0
  79. package/dist/bundle/chunks/openai-chatgpt.js +75 -0
  80. package/dist/bundle/chunks/openai-codex-responses-CDQVKDUO.js +10 -0
  81. package/dist/bundle/chunks/openai-codex.js +75 -0
  82. package/dist/bundle/chunks/openai-completions-RAU4DJDG.js +7 -0
  83. package/dist/bundle/chunks/openai-responses-4IZEGS2C.js +4 -0
  84. package/dist/bundle/chunks/openrouter-images-EXXX2XDD.js +2 -0
  85. package/dist/bundle/chunks/openrouter.js +75 -0
  86. package/dist/bundle/chunks/pi-messages-YPAWD2FK.js +8 -0
  87. package/dist/bundle/chunks/radius.js +75 -0
  88. package/dist/bundle/chunks/runtime-4K2RC6HQ.js +2 -0
  89. package/dist/bundle/chunks/src-QKGKDFSU.js +4 -0
  90. package/dist/bundle/chunks/typesafe-system-one-2F7KHMWD.js +2 -0
  91. package/dist/bundle/chunks/virtual-modules-XDTMJGCH.js +2 -0
  92. package/dist/bundle/chunks/xai.js +2 -0
  93. package/dist/bundle/cli-runtime.js +3 -0
  94. package/dist/bundle/cli.js +5 -0
  95. package/dist/bundle/index.js +2 -0
  96. package/dist/bundle/rpc-entry.js +3 -0
  97. package/dist/cli/args.d.ts +62 -0
  98. package/dist/cli/args.d.ts.map +1 -0
  99. package/dist/cli/args.js +474 -0
  100. package/dist/cli/args.js.map +1 -0
  101. package/dist/cli/auth-check.d.ts +19 -0
  102. package/dist/cli/auth-check.d.ts.map +1 -0
  103. package/dist/cli/auth-check.js +50 -0
  104. package/dist/cli/auth-check.js.map +1 -0
  105. package/dist/cli/auth-command.d.ts +24 -0
  106. package/dist/cli/auth-command.d.ts.map +1 -0
  107. package/dist/cli/auth-command.js +103 -0
  108. package/dist/cli/auth-command.js.map +1 -0
  109. package/dist/cli/config-selector.d.ts +16 -0
  110. package/dist/cli/config-selector.d.ts.map +1 -0
  111. package/dist/cli/config-selector.js +34 -0
  112. package/dist/cli/config-selector.js.map +1 -0
  113. package/dist/cli/credential-print.d.ts +13 -0
  114. package/dist/cli/credential-print.d.ts.map +1 -0
  115. package/dist/cli/credential-print.js +76 -0
  116. package/dist/cli/credential-print.js.map +1 -0
  117. package/dist/cli/file-processor.d.ts +15 -0
  118. package/dist/cli/file-processor.d.ts.map +1 -0
  119. package/dist/cli/file-processor.js +71 -0
  120. package/dist/cli/file-processor.js.map +1 -0
  121. package/dist/cli/initial-message.d.ts +18 -0
  122. package/dist/cli/initial-message.d.ts.map +1 -0
  123. package/dist/cli/initial-message.js +22 -0
  124. package/dist/cli/initial-message.js.map +1 -0
  125. package/dist/cli/list-models.d.ts +9 -0
  126. package/dist/cli/list-models.d.ts.map +1 -0
  127. package/dist/cli/list-models.js +98 -0
  128. package/dist/cli/list-models.js.map +1 -0
  129. package/dist/cli/project-trust.d.ts +10 -0
  130. package/dist/cli/project-trust.d.ts.map +1 -0
  131. package/dist/cli/project-trust.js +48 -0
  132. package/dist/cli/project-trust.js.map +1 -0
  133. package/dist/cli/session-picker.d.ts +10 -0
  134. package/dist/cli/session-picker.d.ts.map +1 -0
  135. package/dist/cli/session-picker.js +36 -0
  136. package/dist/cli/session-picker.js.map +1 -0
  137. package/dist/cli/setup.d.ts +2 -0
  138. package/dist/cli/setup.d.ts.map +1 -0
  139. package/dist/cli/setup.js +12 -0
  140. package/dist/cli/setup.js.map +1 -0
  141. package/dist/cli/startup-ui.d.ts +20 -0
  142. package/dist/cli/startup-ui.d.ts.map +1 -0
  143. package/dist/cli/startup-ui.js +175 -0
  144. package/dist/cli/startup-ui.js.map +1 -0
  145. package/dist/cli.d.ts +3 -0
  146. package/dist/cli.d.ts.map +1 -0
  147. package/dist/cli.js +6 -0
  148. package/dist/cli.js.map +1 -0
  149. package/dist/config.d.ts +136 -0
  150. package/dist/config.d.ts.map +1 -0
  151. package/dist/config.js +554 -0
  152. package/dist/config.js.map +1 -0
  153. package/dist/core/agent-session-runtime.d.ts +124 -0
  154. package/dist/core/agent-session-runtime.d.ts.map +1 -0
  155. package/dist/core/agent-session-runtime.js +324 -0
  156. package/dist/core/agent-session-runtime.js.map +1 -0
  157. package/dist/core/agent-session-services.d.ts +86 -0
  158. package/dist/core/agent-session-services.d.ts.map +1 -0
  159. package/dist/core/agent-session-services.js +147 -0
  160. package/dist/core/agent-session-services.js.map +1 -0
  161. package/dist/core/agent-session.d.ts +950 -0
  162. package/dist/core/agent-session.d.ts.map +1 -0
  163. package/dist/core/agent-session.js +3710 -0
  164. package/dist/core/agent-session.js.map +1 -0
  165. package/dist/core/auth-guidance.d.ts +5 -0
  166. package/dist/core/auth-guidance.d.ts.map +1 -0
  167. package/dist/core/auth-guidance.js +21 -0
  168. package/dist/core/auth-guidance.js.map +1 -0
  169. package/dist/core/auth-storage.d.ts +72 -0
  170. package/dist/core/auth-storage.d.ts.map +1 -0
  171. package/dist/core/auth-storage.js +434 -0
  172. package/dist/core/auth-storage.js.map +1 -0
  173. package/dist/core/bash-executor.d.ts +32 -0
  174. package/dist/core/bash-executor.d.ts.map +1 -0
  175. package/dist/core/bash-executor.js +103 -0
  176. package/dist/core/bash-executor.js.map +1 -0
  177. package/dist/core/bug-report-upload.d.ts +12 -0
  178. package/dist/core/bug-report-upload.d.ts.map +1 -0
  179. package/dist/core/bug-report-upload.js +22 -0
  180. package/dist/core/bug-report-upload.js.map +1 -0
  181. package/dist/core/bug-report.d.ts +184 -0
  182. package/dist/core/bug-report.d.ts.map +1 -0
  183. package/dist/core/bug-report.js +292 -0
  184. package/dist/core/bug-report.js.map +1 -0
  185. package/dist/core/cache-stats.d.ts +49 -0
  186. package/dist/core/cache-stats.d.ts.map +1 -0
  187. package/dist/core/cache-stats.js +112 -0
  188. package/dist/core/cache-stats.js.map +1 -0
  189. package/dist/core/cache-warmer.d.ts +103 -0
  190. package/dist/core/cache-warmer.d.ts.map +1 -0
  191. package/dist/core/cache-warmer.js +358 -0
  192. package/dist/core/cache-warmer.js.map +1 -0
  193. package/dist/core/client-identity.d.ts +8 -0
  194. package/dist/core/client-identity.d.ts.map +1 -0
  195. package/dist/core/client-identity.js +15 -0
  196. package/dist/core/client-identity.js.map +1 -0
  197. package/dist/core/compaction/branch-summarization.d.ts +100 -0
  198. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  199. package/dist/core/compaction/branch-summarization.js +262 -0
  200. package/dist/core/compaction/branch-summarization.js.map +1 -0
  201. package/dist/core/compaction/compaction.d.ts +145 -0
  202. package/dist/core/compaction/compaction.d.ts.map +1 -0
  203. package/dist/core/compaction/compaction.js +749 -0
  204. package/dist/core/compaction/compaction.js.map +1 -0
  205. package/dist/core/compaction/index.d.ts +7 -0
  206. package/dist/core/compaction/index.d.ts.map +1 -0
  207. package/dist/core/compaction/index.js +7 -0
  208. package/dist/core/compaction/index.js.map +1 -0
  209. package/dist/core/compaction/utils.d.ts +45 -0
  210. package/dist/core/compaction/utils.d.ts.map +1 -0
  211. package/dist/core/compaction/utils.js +149 -0
  212. package/dist/core/compaction/utils.js.map +1 -0
  213. package/dist/core/crash-log.d.ts +27 -0
  214. package/dist/core/crash-log.d.ts.map +1 -0
  215. package/dist/core/crash-log.js +140 -0
  216. package/dist/core/crash-log.js.map +1 -0
  217. package/dist/core/defaults.d.ts +4 -0
  218. package/dist/core/defaults.d.ts.map +1 -0
  219. package/dist/core/defaults.js +11 -0
  220. package/dist/core/defaults.js.map +1 -0
  221. package/dist/core/diagnostics.d.ts +15 -0
  222. package/dist/core/diagnostics.d.ts.map +1 -0
  223. package/dist/core/diagnostics.js +2 -0
  224. package/dist/core/diagnostics.js.map +1 -0
  225. package/dist/core/event-bus.d.ts +9 -0
  226. package/dist/core/event-bus.d.ts.map +1 -0
  227. package/dist/core/event-bus.js +25 -0
  228. package/dist/core/event-bus.js.map +1 -0
  229. package/dist/core/exec.d.ts +37 -0
  230. package/dist/core/exec.d.ts.map +1 -0
  231. package/dist/core/exec.js +119 -0
  232. package/dist/core/exec.js.map +1 -0
  233. package/dist/core/experimental.d.ts +2 -0
  234. package/dist/core/experimental.d.ts.map +1 -0
  235. package/dist/core/experimental.js +4 -0
  236. package/dist/core/experimental.js.map +1 -0
  237. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  238. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  239. package/dist/core/export-html/ansi-to-html.js +249 -0
  240. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  241. package/dist/core/export-html/index.d.ts +37 -0
  242. package/dist/core/export-html/index.d.ts.map +1 -0
  243. package/dist/core/export-html/index.js +228 -0
  244. package/dist/core/export-html/index.js.map +1 -0
  245. package/dist/core/export-html/template.css +1085 -0
  246. package/dist/core/export-html/template.html +56 -0
  247. package/dist/core/export-html/template.js +2044 -0
  248. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  249. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  250. package/dist/core/export-html/tool-renderer.js +113 -0
  251. package/dist/core/export-html/tool-renderer.js.map +1 -0
  252. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  253. package/dist/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
  254. package/dist/core/export-html/vendor/marked.min.js +79 -0
  255. package/dist/core/extensions/index.d.ts +12 -0
  256. package/dist/core/extensions/index.d.ts.map +1 -0
  257. package/dist/core/extensions/index.js +9 -0
  258. package/dist/core/extensions/index.js.map +1 -0
  259. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  260. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  261. package/dist/core/extensions/jiti-loader.js +4 -0
  262. package/dist/core/extensions/jiti-loader.js.map +1 -0
  263. package/dist/core/extensions/jiti-static-loader.d.ts +2 -0
  264. package/dist/core/extensions/jiti-static-loader.d.ts.map +1 -0
  265. package/dist/core/extensions/jiti-static-loader.js +4 -0
  266. package/dist/core/extensions/jiti-static-loader.js.map +1 -0
  267. package/dist/core/extensions/loader.d.ts +23 -0
  268. package/dist/core/extensions/loader.d.ts.map +1 -0
  269. package/dist/core/extensions/loader.js +710 -0
  270. package/dist/core/extensions/loader.js.map +1 -0
  271. package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
  272. package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
  273. package/dist/core/extensions/pi-ai-extension-view.js +22 -0
  274. package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
  275. package/dist/core/extensions/runner.d.ts +216 -0
  276. package/dist/core/extensions/runner.d.ts.map +1 -0
  277. package/dist/core/extensions/runner.js +1246 -0
  278. package/dist/core/extensions/runner.js.map +1 -0
  279. package/dist/core/extensions/types.d.ts +1801 -0
  280. package/dist/core/extensions/types.d.ts.map +1 -0
  281. package/dist/core/extensions/types.js +48 -0
  282. package/dist/core/extensions/types.js.map +1 -0
  283. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  284. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  285. package/dist/core/extensions/virtual-modules.js +42 -0
  286. package/dist/core/extensions/virtual-modules.js.map +1 -0
  287. package/dist/core/extensions/wrapper.d.ts +20 -0
  288. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  289. package/dist/core/extensions/wrapper.js +22 -0
  290. package/dist/core/extensions/wrapper.js.map +1 -0
  291. package/dist/core/footer-data-provider.d.ts +64 -0
  292. package/dist/core/footer-data-provider.d.ts.map +1 -0
  293. package/dist/core/footer-data-provider.js +338 -0
  294. package/dist/core/footer-data-provider.js.map +1 -0
  295. package/dist/core/http-dispatcher.d.ts +22 -0
  296. package/dist/core/http-dispatcher.d.ts.map +1 -0
  297. package/dist/core/http-dispatcher.js +98 -0
  298. package/dist/core/http-dispatcher.js.map +1 -0
  299. package/dist/core/index.d.ts +14 -0
  300. package/dist/core/index.d.ts.map +1 -0
  301. package/dist/core/index.js +13 -0
  302. package/dist/core/index.js.map +1 -0
  303. package/dist/core/key-id-schema.d.ts +6 -0
  304. package/dist/core/key-id-schema.d.ts.map +1 -0
  305. package/dist/core/key-id-schema.js +16 -0
  306. package/dist/core/key-id-schema.js.map +1 -0
  307. package/dist/core/keybindings-schema.d.ts +4 -0
  308. package/dist/core/keybindings-schema.d.ts.map +1 -0
  309. package/dist/core/keybindings-schema.js +16 -0
  310. package/dist/core/keybindings-schema.js.map +1 -0
  311. package/dist/core/keybindings.d.ts +560 -0
  312. package/dist/core/keybindings.d.ts.map +1 -0
  313. package/dist/core/keybindings.js +324 -0
  314. package/dist/core/keybindings.js.map +1 -0
  315. package/dist/core/mcp-servers.d.ts +121 -0
  316. package/dist/core/mcp-servers.d.ts.map +1 -0
  317. package/dist/core/mcp-servers.js +163 -0
  318. package/dist/core/mcp-servers.js.map +1 -0
  319. package/dist/core/messages.d.ts +77 -0
  320. package/dist/core/messages.d.ts.map +1 -0
  321. package/dist/core/messages.js +124 -0
  322. package/dist/core/messages.js.map +1 -0
  323. package/dist/core/model-config.d.ts +2000 -0
  324. package/dist/core/model-config.d.ts.map +1 -0
  325. package/dist/core/model-config.js +167 -0
  326. package/dist/core/model-config.js.map +1 -0
  327. package/dist/core/model-registry.d.ts +63 -0
  328. package/dist/core/model-registry.d.ts.map +1 -0
  329. package/dist/core/model-registry.js +144 -0
  330. package/dist/core/model-registry.js.map +1 -0
  331. package/dist/core/model-resolver.d.ts +139 -0
  332. package/dist/core/model-resolver.d.ts.map +1 -0
  333. package/dist/core/model-resolver.js +495 -0
  334. package/dist/core/model-resolver.js.map +1 -0
  335. package/dist/core/model-runtime.d.ts +150 -0
  336. package/dist/core/model-runtime.d.ts.map +1 -0
  337. package/dist/core/model-runtime.js +774 -0
  338. package/dist/core/model-runtime.js.map +1 -0
  339. package/dist/core/models-store.d.ts +22 -0
  340. package/dist/core/models-store.d.ts.map +1 -0
  341. package/dist/core/models-store.js +115 -0
  342. package/dist/core/models-store.js.map +1 -0
  343. package/dist/core/nested-tool-calls.d.ts +103 -0
  344. package/dist/core/nested-tool-calls.d.ts.map +1 -0
  345. package/dist/core/nested-tool-calls.js +179 -0
  346. package/dist/core/nested-tool-calls.js.map +1 -0
  347. package/dist/core/output-guard.d.ts +7 -0
  348. package/dist/core/output-guard.d.ts.map +1 -0
  349. package/dist/core/output-guard.js +89 -0
  350. package/dist/core/output-guard.js.map +1 -0
  351. package/dist/core/package-manager.d.ts +240 -0
  352. package/dist/core/package-manager.d.ts.map +1 -0
  353. package/dist/core/package-manager.js +2383 -0
  354. package/dist/core/package-manager.js.map +1 -0
  355. package/dist/core/pi-ai-schemas.d.ts +166 -0
  356. package/dist/core/pi-ai-schemas.d.ts.map +1 -0
  357. package/dist/core/pi-ai-schemas.js +21 -0
  358. package/dist/core/pi-ai-schemas.js.map +1 -0
  359. package/dist/core/pi-manifest.d.ts +9 -0
  360. package/dist/core/pi-manifest.d.ts.map +1 -0
  361. package/dist/core/pi-manifest.js +30 -0
  362. package/dist/core/pi-manifest.js.map +1 -0
  363. package/dist/core/project-trust.d.ts +15 -0
  364. package/dist/core/project-trust.d.ts.map +1 -0
  365. package/dist/core/project-trust.js +60 -0
  366. package/dist/core/project-trust.js.map +1 -0
  367. package/dist/core/prompt-templates.d.ts +59 -0
  368. package/dist/core/prompt-templates.d.ts.map +1 -0
  369. package/dist/core/prompt-templates.js +267 -0
  370. package/dist/core/prompt-templates.js.map +1 -0
  371. package/dist/core/provider-composer.d.ts +81 -0
  372. package/dist/core/provider-composer.d.ts.map +1 -0
  373. package/dist/core/provider-composer.js +492 -0
  374. package/dist/core/provider-composer.js.map +1 -0
  375. package/dist/core/radius.d.ts +7 -0
  376. package/dist/core/radius.d.ts.map +1 -0
  377. package/dist/core/radius.js +10 -0
  378. package/dist/core/radius.js.map +1 -0
  379. package/dist/core/remote-catalog-provider.d.ts +23 -0
  380. package/dist/core/remote-catalog-provider.d.ts.map +1 -0
  381. package/dist/core/remote-catalog-provider.js +190 -0
  382. package/dist/core/remote-catalog-provider.js.map +1 -0
  383. package/dist/core/resolve-config-value.d.ts +30 -0
  384. package/dist/core/resolve-config-value.d.ts.map +1 -0
  385. package/dist/core/resolve-config-value.js +247 -0
  386. package/dist/core/resolve-config-value.js.map +1 -0
  387. package/dist/core/resource-loader.d.ts +233 -0
  388. package/dist/core/resource-loader.d.ts.map +1 -0
  389. package/dist/core/resource-loader.js +1025 -0
  390. package/dist/core/resource-loader.js.map +1 -0
  391. package/dist/core/runtime-credentials.d.ts +23 -0
  392. package/dist/core/runtime-credentials.d.ts.map +1 -0
  393. package/dist/core/runtime-credentials.js +53 -0
  394. package/dist/core/runtime-credentials.js.map +1 -0
  395. package/dist/core/sdk.d.ts +117 -0
  396. package/dist/core/sdk.d.ts.map +1 -0
  397. package/dist/core/sdk.js +329 -0
  398. package/dist/core/sdk.js.map +1 -0
  399. package/dist/core/session-cwd.d.ts +19 -0
  400. package/dist/core/session-cwd.d.ts.map +1 -0
  401. package/dist/core/session-cwd.js +38 -0
  402. package/dist/core/session-cwd.js.map +1 -0
  403. package/dist/core/session-export.d.ts +8 -0
  404. package/dist/core/session-export.d.ts.map +1 -0
  405. package/dist/core/session-export.js +33 -0
  406. package/dist/core/session-export.js.map +1 -0
  407. package/dist/core/session-manager.d.ts +423 -0
  408. package/dist/core/session-manager.d.ts.map +1 -0
  409. package/dist/core/session-manager.js +1542 -0
  410. package/dist/core/session-manager.js.map +1 -0
  411. package/dist/core/settings-defaults.d.ts +66 -0
  412. package/dist/core/settings-defaults.d.ts.map +1 -0
  413. package/dist/core/settings-defaults.js +69 -0
  414. package/dist/core/settings-defaults.js.map +1 -0
  415. package/dist/core/settings-diagnostics.d.ts +9 -0
  416. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  417. package/dist/core/settings-diagnostics.js +21 -0
  418. package/dist/core/settings-diagnostics.js.map +1 -0
  419. package/dist/core/settings-manager.d.ts +253 -0
  420. package/dist/core/settings-manager.d.ts.map +1 -0
  421. package/dist/core/settings-manager.js +1154 -0
  422. package/dist/core/settings-manager.js.map +1 -0
  423. package/dist/core/settings-schema.d.ts +232 -0
  424. package/dist/core/settings-schema.d.ts.map +1 -0
  425. package/dist/core/settings-schema.js +301 -0
  426. package/dist/core/settings-schema.js.map +1 -0
  427. package/dist/core/skills.d.ts +63 -0
  428. package/dist/core/skills.d.ts.map +1 -0
  429. package/dist/core/skills.js +404 -0
  430. package/dist/core/skills.js.map +1 -0
  431. package/dist/core/slash-commands.d.ts +15 -0
  432. package/dist/core/slash-commands.d.ts.map +1 -0
  433. package/dist/core/slash-commands.js +32 -0
  434. package/dist/core/slash-commands.js.map +1 -0
  435. package/dist/core/source-info.d.ts +35 -0
  436. package/dist/core/source-info.d.ts.map +1 -0
  437. package/dist/core/source-info.js +48 -0
  438. package/dist/core/source-info.js.map +1 -0
  439. package/dist/core/system-prompt.d.ts +77 -0
  440. package/dist/core/system-prompt.d.ts.map +1 -0
  441. package/dist/core/system-prompt.js +150 -0
  442. package/dist/core/system-prompt.js.map +1 -0
  443. package/dist/core/telemetry.d.ts +3 -0
  444. package/dist/core/telemetry.d.ts.map +1 -0
  445. package/dist/core/telemetry.js +9 -0
  446. package/dist/core/telemetry.js.map +1 -0
  447. package/dist/core/timings.d.ts +10 -0
  448. package/dist/core/timings.d.ts.map +1 -0
  449. package/dist/core/timings.js +41 -0
  450. package/dist/core/timings.js.map +1 -0
  451. package/dist/core/tools/bash.d.ts +100 -0
  452. package/dist/core/tools/bash.d.ts.map +1 -0
  453. package/dist/core/tools/bash.js +363 -0
  454. package/dist/core/tools/bash.js.map +1 -0
  455. package/dist/core/tools/edit-diff.d.ts +101 -0
  456. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  457. package/dist/core/tools/edit-diff.js +421 -0
  458. package/dist/core/tools/edit-diff.js.map +1 -0
  459. package/dist/core/tools/edit.d.ts +44 -0
  460. package/dist/core/tools/edit.d.ts.map +1 -0
  461. package/dist/core/tools/edit.js +145 -0
  462. package/dist/core/tools/edit.js.map +1 -0
  463. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  464. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  465. package/dist/core/tools/file-mutation-queue.js +52 -0
  466. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  467. package/dist/core/tools/find.d.ts +42 -0
  468. package/dist/core/tools/find.d.ts.map +1 -0
  469. package/dist/core/tools/find.js +267 -0
  470. package/dist/core/tools/find.js.map +1 -0
  471. package/dist/core/tools/grep.d.ts +39 -0
  472. package/dist/core/tools/grep.d.ts.map +1 -0
  473. package/dist/core/tools/grep.js +257 -0
  474. package/dist/core/tools/grep.js.map +1 -0
  475. package/dist/core/tools/index.d.ts +43 -0
  476. package/dist/core/tools/index.d.ts.map +1 -0
  477. package/dist/core/tools/index.js +129 -0
  478. package/dist/core/tools/index.js.map +1 -0
  479. package/dist/core/tools/ls.d.ts +41 -0
  480. package/dist/core/tools/ls.d.ts.map +1 -0
  481. package/dist/core/tools/ls.js +127 -0
  482. package/dist/core/tools/ls.js.map +1 -0
  483. package/dist/core/tools/output-accumulator.d.ts +63 -0
  484. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  485. package/dist/core/tools/output-accumulator.js +214 -0
  486. package/dist/core/tools/output-accumulator.js.map +1 -0
  487. package/dist/core/tools/path-utils.d.ts +10 -0
  488. package/dist/core/tools/path-utils.d.ts.map +1 -0
  489. package/dist/core/tools/path-utils.js +99 -0
  490. package/dist/core/tools/path-utils.js.map +1 -0
  491. package/dist/core/tools/powershell.d.ts +16 -0
  492. package/dist/core/tools/powershell.d.ts.map +1 -0
  493. package/dist/core/tools/powershell.js +39 -0
  494. package/dist/core/tools/powershell.js.map +1 -0
  495. package/dist/core/tools/read.d.ts +63 -0
  496. package/dist/core/tools/read.d.ts.map +1 -0
  497. package/dist/core/tools/read.js +302 -0
  498. package/dist/core/tools/read.js.map +1 -0
  499. package/dist/core/tools/render-utils.d.ts +50 -0
  500. package/dist/core/tools/render-utils.d.ts.map +1 -0
  501. package/dist/core/tools/render-utils.js +153 -0
  502. package/dist/core/tools/render-utils.js.map +1 -0
  503. package/dist/core/tools/renderers/bash.d.ts +12 -0
  504. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  505. package/dist/core/tools/renderers/bash.js +89 -0
  506. package/dist/core/tools/renderers/bash.js.map +1 -0
  507. package/dist/core/tools/renderers/edit.d.ts +23 -0
  508. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  509. package/dist/core/tools/renderers/edit.js +168 -0
  510. package/dist/core/tools/renderers/edit.js.map +1 -0
  511. package/dist/core/tools/renderers/find.d.ts +10 -0
  512. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  513. package/dist/core/tools/renderers/find.js +64 -0
  514. package/dist/core/tools/renderers/find.js.map +1 -0
  515. package/dist/core/tools/renderers/grep.d.ts +10 -0
  516. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  517. package/dist/core/tools/renderers/grep.js +69 -0
  518. package/dist/core/tools/renderers/grep.js.map +1 -0
  519. package/dist/core/tools/renderers/index.d.ts +28 -0
  520. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  521. package/dist/core/tools/renderers/index.js +47 -0
  522. package/dist/core/tools/renderers/index.js.map +1 -0
  523. package/dist/core/tools/renderers/ls.d.ts +10 -0
  524. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  525. package/dist/core/tools/renderers/ls.js +58 -0
  526. package/dist/core/tools/renderers/ls.js.map +1 -0
  527. package/dist/core/tools/renderers/read.d.ts +11 -0
  528. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  529. package/dist/core/tools/renderers/read.js +126 -0
  530. package/dist/core/tools/renderers/read.js.map +1 -0
  531. package/dist/core/tools/renderers/write.d.ts +10 -0
  532. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  533. package/dist/core/tools/renderers/write.js +153 -0
  534. package/dist/core/tools/renderers/write.js.map +1 -0
  535. package/dist/core/tools/tool-definition-wrapper.d.ts +26 -0
  536. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -0
  537. package/dist/core/tools/tool-definition-wrapper.js +38 -0
  538. package/dist/core/tools/tool-definition-wrapper.js.map +1 -0
  539. package/dist/core/tools/truncate.d.ts +74 -0
  540. package/dist/core/tools/truncate.d.ts.map +1 -0
  541. package/dist/core/tools/truncate.js +238 -0
  542. package/dist/core/tools/truncate.js.map +1 -0
  543. package/dist/core/tools/write.d.ts +30 -0
  544. package/dist/core/tools/write.d.ts.map +1 -0
  545. package/dist/core/tools/write.js +61 -0
  546. package/dist/core/tools/write.js.map +1 -0
  547. package/dist/core/trust-manager.d.ts +36 -0
  548. package/dist/core/trust-manager.d.ts.map +1 -0
  549. package/dist/core/trust-manager.js +210 -0
  550. package/dist/core/trust-manager.js.map +1 -0
  551. package/dist/core/usage-totals.d.ts +21 -0
  552. package/dist/core/usage-totals.d.ts.map +1 -0
  553. package/dist/core/usage-totals.js +81 -0
  554. package/dist/core/usage-totals.js.map +1 -0
  555. package/dist/core/virtual-models.d.ts +117 -0
  556. package/dist/core/virtual-models.d.ts.map +1 -0
  557. package/dist/core/virtual-models.js +124 -0
  558. package/dist/core/virtual-models.js.map +1 -0
  559. package/dist/extensions/codemode/execute.d.ts +16 -0
  560. package/dist/extensions/codemode/execute.d.ts.map +1 -0
  561. package/dist/extensions/codemode/execute.js +740 -0
  562. package/dist/extensions/codemode/execute.js.map +1 -0
  563. package/dist/extensions/codemode/execute.lazy.d.ts +3 -0
  564. package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -0
  565. package/dist/extensions/codemode/execute.lazy.js +3 -0
  566. package/dist/extensions/codemode/execute.lazy.js.map +1 -0
  567. package/dist/extensions/codemode/index.d.ts +21 -0
  568. package/dist/extensions/codemode/index.d.ts.map +1 -0
  569. package/dist/extensions/codemode/index.js +33 -0
  570. package/dist/extensions/codemode/index.js.map +1 -0
  571. package/dist/extensions/codemode/renderer.d.ts +12 -0
  572. package/dist/extensions/codemode/renderer.d.ts.map +1 -0
  573. package/dist/extensions/codemode/renderer.js +147 -0
  574. package/dist/extensions/codemode/renderer.js.map +1 -0
  575. package/dist/extensions/codemode/tool.d.ts +125 -0
  576. package/dist/extensions/codemode/tool.d.ts.map +1 -0
  577. package/dist/extensions/codemode/tool.js +313 -0
  578. package/dist/extensions/codemode/tool.js.map +1 -0
  579. package/dist/extensions/codemode/worker.d.ts +7 -0
  580. package/dist/extensions/codemode/worker.d.ts.map +1 -0
  581. package/dist/extensions/codemode/worker.js +7 -0
  582. package/dist/extensions/codemode/worker.js.map +1 -0
  583. package/dist/extensions/index.d.ts +3 -0
  584. package/dist/extensions/index.d.ts.map +1 -0
  585. package/dist/extensions/index.js +19 -0
  586. package/dist/extensions/index.js.map +1 -0
  587. package/dist/extensions/llama/client.d.ts +71 -0
  588. package/dist/extensions/llama/client.d.ts.map +1 -0
  589. package/dist/extensions/llama/client.js +334 -0
  590. package/dist/extensions/llama/client.js.map +1 -0
  591. package/dist/extensions/llama/huggingface.d.ts +23 -0
  592. package/dist/extensions/llama/huggingface.d.ts.map +1 -0
  593. package/dist/extensions/llama/huggingface.js +141 -0
  594. package/dist/extensions/llama/huggingface.js.map +1 -0
  595. package/dist/extensions/llama/index.d.ts +3 -0
  596. package/dist/extensions/llama/index.d.ts.map +1 -0
  597. package/dist/extensions/llama/index.js +219 -0
  598. package/dist/extensions/llama/index.js.map +1 -0
  599. package/dist/extensions/llama/provider.d.ts +12 -0
  600. package/dist/extensions/llama/provider.d.ts.map +1 -0
  601. package/dist/extensions/llama/provider.js +236 -0
  602. package/dist/extensions/llama/provider.js.map +1 -0
  603. package/dist/extensions/llama/ui.d.ts +42 -0
  604. package/dist/extensions/llama/ui.d.ts.map +1 -0
  605. package/dist/extensions/llama/ui.js +440 -0
  606. package/dist/extensions/llama/ui.js.map +1 -0
  607. package/dist/extensions/marsai/index.d.ts +18 -0
  608. package/dist/extensions/marsai/index.d.ts.map +1 -0
  609. package/dist/extensions/marsai/index.js +179 -0
  610. package/dist/extensions/marsai/index.js.map +1 -0
  611. package/dist/extensions/marsai/oauth.d.ts +49 -0
  612. package/dist/extensions/marsai/oauth.d.ts.map +1 -0
  613. package/dist/extensions/marsai/oauth.js +291 -0
  614. package/dist/extensions/marsai/oauth.js.map +1 -0
  615. package/dist/extensions/marsai/web-tools.d.ts +31 -0
  616. package/dist/extensions/marsai/web-tools.d.ts.map +1 -0
  617. package/dist/extensions/marsai/web-tools.js +298 -0
  618. package/dist/extensions/marsai/web-tools.js.map +1 -0
  619. package/dist/extensions/mcp/cli.d.ts +23 -0
  620. package/dist/extensions/mcp/cli.d.ts.map +1 -0
  621. package/dist/extensions/mcp/cli.js +558 -0
  622. package/dist/extensions/mcp/cli.js.map +1 -0
  623. package/dist/extensions/mcp/cli.lazy.d.ts +3 -0
  624. package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -0
  625. package/dist/extensions/mcp/cli.lazy.js +3 -0
  626. package/dist/extensions/mcp/cli.lazy.js.map +1 -0
  627. package/dist/extensions/mcp/config.d.ts +84 -0
  628. package/dist/extensions/mcp/config.d.ts.map +1 -0
  629. package/dist/extensions/mcp/config.js +192 -0
  630. package/dist/extensions/mcp/config.js.map +1 -0
  631. package/dist/extensions/mcp/index.d.ts +79 -0
  632. package/dist/extensions/mcp/index.d.ts.map +1 -0
  633. package/dist/extensions/mcp/index.js +1206 -0
  634. package/dist/extensions/mcp/index.js.map +1 -0
  635. package/dist/extensions/mcp/log.d.ts +16 -0
  636. package/dist/extensions/mcp/log.d.ts.map +1 -0
  637. package/dist/extensions/mcp/log.js +66 -0
  638. package/dist/extensions/mcp/log.js.map +1 -0
  639. package/dist/extensions/mcp/oauth.d.ts +64 -0
  640. package/dist/extensions/mcp/oauth.d.ts.map +1 -0
  641. package/dist/extensions/mcp/oauth.js +188 -0
  642. package/dist/extensions/mcp/oauth.js.map +1 -0
  643. package/dist/extensions/mcp/resources.d.ts +36 -0
  644. package/dist/extensions/mcp/resources.d.ts.map +1 -0
  645. package/dist/extensions/mcp/resources.js +262 -0
  646. package/dist/extensions/mcp/resources.js.map +1 -0
  647. package/dist/extensions/mcp/runtime.d.ts +99 -0
  648. package/dist/extensions/mcp/runtime.d.ts.map +1 -0
  649. package/dist/extensions/mcp/runtime.js +380 -0
  650. package/dist/extensions/mcp/runtime.js.map +1 -0
  651. package/dist/extensions/mcp/runtime.lazy.d.ts +3 -0
  652. package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -0
  653. package/dist/extensions/mcp/runtime.lazy.js +3 -0
  654. package/dist/extensions/mcp/runtime.lazy.js.map +1 -0
  655. package/dist/extensions/mcp/tools.d.ts +65 -0
  656. package/dist/extensions/mcp/tools.d.ts.map +1 -0
  657. package/dist/extensions/mcp/tools.js +257 -0
  658. package/dist/extensions/mcp/tools.js.map +1 -0
  659. package/dist/extensions/mcp/ui.d.ts +61 -0
  660. package/dist/extensions/mcp/ui.d.ts.map +1 -0
  661. package/dist/extensions/mcp/ui.js +195 -0
  662. package/dist/extensions/mcp/ui.js.map +1 -0
  663. package/dist/extensions/subagent/agents.d.ts +23 -0
  664. package/dist/extensions/subagent/agents.d.ts.map +1 -0
  665. package/dist/extensions/subagent/agents.js +121 -0
  666. package/dist/extensions/subagent/agents.js.map +1 -0
  667. package/dist/extensions/subagent/index.d.ts +16 -0
  668. package/dist/extensions/subagent/index.d.ts.map +1 -0
  669. package/dist/extensions/subagent/index.js +1080 -0
  670. package/dist/extensions/subagent/index.js.map +1 -0
  671. package/dist/extensions/subagent/recon-child.d.ts +9 -0
  672. package/dist/extensions/subagent/recon-child.d.ts.map +1 -0
  673. package/dist/extensions/subagent/recon-child.js +80 -0
  674. package/dist/extensions/subagent/recon-child.js.map +1 -0
  675. package/dist/extensions/subagent/recon.d.ts +17 -0
  676. package/dist/extensions/subagent/recon.d.ts.map +1 -0
  677. package/dist/extensions/subagent/recon.js +56 -0
  678. package/dist/extensions/subagent/recon.js.map +1 -0
  679. package/dist/extensions/tool-search/index.d.ts +12 -0
  680. package/dist/extensions/tool-search/index.d.ts.map +1 -0
  681. package/dist/extensions/tool-search/index.js +15 -0
  682. package/dist/extensions/tool-search/index.js.map +1 -0
  683. package/dist/extensions/tool-search/tool.d.ts +86 -0
  684. package/dist/extensions/tool-search/tool.d.ts.map +1 -0
  685. package/dist/extensions/tool-search/tool.js +255 -0
  686. package/dist/extensions/tool-search/tool.js.map +1 -0
  687. package/dist/index.d.ts +45 -0
  688. package/dist/index.d.ts.map +1 -0
  689. package/dist/index.js +54 -0
  690. package/dist/index.js.map +1 -0
  691. package/dist/main.d.ts +16 -0
  692. package/dist/main.d.ts.map +1 -0
  693. package/dist/main.js +835 -0
  694. package/dist/main.js.map +1 -0
  695. package/dist/migrations.d.ts +33 -0
  696. package/dist/migrations.d.ts.map +1 -0
  697. package/dist/migrations.js +282 -0
  698. package/dist/migrations.js.map +1 -0
  699. package/dist/modes/index.d.ts +10 -0
  700. package/dist/modes/index.d.ts.map +1 -0
  701. package/dist/modes/index.js +8 -0
  702. package/dist/modes/index.js.map +1 -0
  703. package/dist/modes/interactive/assets/clankolas.png +0 -0
  704. package/dist/modes/interactive/bug-report.d.ts +16 -0
  705. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  706. package/dist/modes/interactive/bug-report.js +210 -0
  707. package/dist/modes/interactive/bug-report.js.map +1 -0
  708. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  709. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  710. package/dist/modes/interactive/chat-viewport.js +28 -0
  711. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  712. package/dist/modes/interactive/components/armin.d.ts +37 -0
  713. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  714. package/dist/modes/interactive/components/armin.js +335 -0
  715. package/dist/modes/interactive/components/armin.js.map +1 -0
  716. package/dist/modes/interactive/components/assistant-message.d.ts +29 -0
  717. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  718. package/dist/modes/interactive/components/assistant-message.js +182 -0
  719. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  720. package/dist/modes/interactive/components/auth-url.d.ts +14 -0
  721. package/dist/modes/interactive/components/auth-url.d.ts.map +1 -0
  722. package/dist/modes/interactive/components/auth-url.js +37 -0
  723. package/dist/modes/interactive/components/auth-url.js.map +1 -0
  724. package/dist/modes/interactive/components/bash-execution.d.ts +38 -0
  725. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  726. package/dist/modes/interactive/components/bash-execution.js +178 -0
  727. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  728. package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  729. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  730. package/dist/modes/interactive/components/bordered-loader.js +54 -0
  731. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  732. package/dist/modes/interactive/components/branch-summary-message.d.ts +21 -0
  733. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  734. package/dist/modes/interactive/components/branch-summary-message.js +62 -0
  735. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  736. package/dist/modes/interactive/components/compaction-summary-message.d.ts +21 -0
  737. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  738. package/dist/modes/interactive/components/compaction-summary-message.js +63 -0
  739. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  740. package/dist/modes/interactive/components/config-selector.d.ts +102 -0
  741. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  742. package/dist/modes/interactive/components/config-selector.js +758 -0
  743. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  744. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  745. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  746. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  747. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  748. package/dist/modes/interactive/components/custom-editor.d.ts +30 -0
  749. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  750. package/dist/modes/interactive/components/custom-editor.js +122 -0
  751. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  752. package/dist/modes/interactive/components/custom-entry.d.ts +21 -0
  753. package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -0
  754. package/dist/modes/interactive/components/custom-entry.js +59 -0
  755. package/dist/modes/interactive/components/custom-entry.js.map +1 -0
  756. package/dist/modes/interactive/components/custom-message.d.ts +25 -0
  757. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  758. package/dist/modes/interactive/components/custom-message.js +96 -0
  759. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  760. package/dist/modes/interactive/components/diff.d.ts +12 -0
  761. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  762. package/dist/modes/interactive/components/diff.js +139 -0
  763. package/dist/modes/interactive/components/diff.js.map +1 -0
  764. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  765. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  766. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  767. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  768. package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
  769. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
  770. package/dist/modes/interactive/components/earendil-announcement.js +40 -0
  771. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
  772. package/dist/modes/interactive/components/easter-egg-3d.d.ts +104 -0
  773. package/dist/modes/interactive/components/easter-egg-3d.d.ts.map +1 -0
  774. package/dist/modes/interactive/components/easter-egg-3d.js +1139 -0
  775. package/dist/modes/interactive/components/easter-egg-3d.js.map +1 -0
  776. package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts +6 -0
  777. package/dist/modes/interactive/components/easter-egg-3d.lazy.d.ts.map +1 -0
  778. package/dist/modes/interactive/components/easter-egg-3d.lazy.js +23 -0
  779. package/dist/modes/interactive/components/easter-egg-3d.lazy.js.map +1 -0
  780. package/dist/modes/interactive/components/extension-editor.d.ts +26 -0
  781. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  782. package/dist/modes/interactive/components/extension-editor.js +107 -0
  783. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  784. package/dist/modes/interactive/components/extension-input.d.ts +25 -0
  785. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  786. package/dist/modes/interactive/components/extension-input.js +67 -0
  787. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  788. package/dist/modes/interactive/components/extension-selector.d.ts +27 -0
  789. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  790. package/dist/modes/interactive/components/extension-selector.js +95 -0
  791. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  792. package/dist/modes/interactive/components/first-time-setup.d.ts +26 -0
  793. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -0
  794. package/dist/modes/interactive/components/first-time-setup.js +118 -0
  795. package/dist/modes/interactive/components/first-time-setup.js.map +1 -0
  796. package/dist/modes/interactive/components/footer.d.ts +39 -0
  797. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  798. package/dist/modes/interactive/components/footer.js +265 -0
  799. package/dist/modes/interactive/components/footer.js.map +1 -0
  800. package/dist/modes/interactive/components/index.d.ts +33 -0
  801. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  802. package/dist/modes/interactive/components/index.js +34 -0
  803. package/dist/modes/interactive/components/index.js.map +1 -0
  804. package/dist/modes/interactive/components/keybinding-hints.d.ts +13 -0
  805. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  806. package/dist/modes/interactive/components/keybinding-hints.js +36 -0
  807. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  808. package/dist/modes/interactive/components/login-dialog.d.ts +59 -0
  809. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  810. package/dist/modes/interactive/components/login-dialog.js +289 -0
  811. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  812. package/dist/modes/interactive/components/markdown-transform.d.ts +4 -0
  813. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  814. package/dist/modes/interactive/components/markdown-transform.js +20 -0
  815. package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
  816. package/dist/modes/interactive/components/mermaid.d.ts +12 -0
  817. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
  818. package/dist/modes/interactive/components/mermaid.js +80 -0
  819. package/dist/modes/interactive/components/mermaid.js.map +1 -0
  820. package/dist/modes/interactive/components/model-selector.d.ts +61 -0
  821. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  822. package/dist/modes/interactive/components/model-selector.js +380 -0
  823. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  824. package/dist/modes/interactive/components/oauth-selector.d.ts +40 -0
  825. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  826. package/dist/modes/interactive/components/oauth-selector.js +175 -0
  827. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  828. package/dist/modes/interactive/components/pi-logo.d.ts +20 -0
  829. package/dist/modes/interactive/components/pi-logo.d.ts.map +1 -0
  830. package/dist/modes/interactive/components/pi-logo.js +41 -0
  831. package/dist/modes/interactive/components/pi-logo.js.map +1 -0
  832. package/dist/modes/interactive/components/radius-login-selector.d.ts +15 -0
  833. package/dist/modes/interactive/components/radius-login-selector.d.ts.map +1 -0
  834. package/dist/modes/interactive/components/radius-login-selector.js +85 -0
  835. package/dist/modes/interactive/components/radius-login-selector.js.map +1 -0
  836. package/dist/modes/interactive/components/scoped-models-selector.d.ts +47 -0
  837. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  838. package/dist/modes/interactive/components/scoped-models-selector.js +337 -0
  839. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  840. package/dist/modes/interactive/components/session-selector-search.d.ts +27 -0
  841. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  842. package/dist/modes/interactive/components/session-selector-search.js +219 -0
  843. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  844. package/dist/modes/interactive/components/session-selector.d.ts +96 -0
  845. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  846. package/dist/modes/interactive/components/session-selector.js +885 -0
  847. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  848. package/dist/modes/interactive/components/settings-selector.d.ts +98 -0
  849. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  850. package/dist/modes/interactive/components/settings-selector.js +753 -0
  851. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  852. package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
  853. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  854. package/dist/modes/interactive/components/settings-submenu.js +167 -0
  855. package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
  856. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  857. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  858. package/dist/modes/interactive/components/show-images-selector.js +39 -0
  859. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  860. package/dist/modes/interactive/components/skill-invocation-message.d.ts +22 -0
  861. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  862. package/dist/modes/interactive/components/skill-invocation-message.js +65 -0
  863. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  864. package/dist/modes/interactive/components/status-indicator.d.ts +32 -0
  865. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -0
  866. package/dist/modes/interactive/components/status-indicator.js +88 -0
  867. package/dist/modes/interactive/components/status-indicator.js.map +1 -0
  868. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  869. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  870. package/dist/modes/interactive/components/theme-selector.js +50 -0
  871. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  872. package/dist/modes/interactive/components/themed-text.d.ts +17 -0
  873. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -0
  874. package/dist/modes/interactive/components/themed-text.js +29 -0
  875. package/dist/modes/interactive/components/themed-text.js.map +1 -0
  876. package/dist/modes/interactive/components/thinking-selector.d.ts +23 -0
  877. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  878. package/dist/modes/interactive/components/thinking-selector.js +109 -0
  879. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  880. package/dist/modes/interactive/components/tool-execution.d.ts +79 -0
  881. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  882. package/dist/modes/interactive/components/tool-execution.js +336 -0
  883. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  884. package/dist/modes/interactive/components/tree-selector.d.ts +96 -0
  885. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  886. package/dist/modes/interactive/components/tree-selector.js +1255 -0
  887. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  888. package/dist/modes/interactive/components/trust-selector.d.ts +23 -0
  889. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -0
  890. package/dist/modes/interactive/components/trust-selector.js +91 -0
  891. package/dist/modes/interactive/components/trust-selector.js.map +1 -0
  892. package/dist/modes/interactive/components/user-message-selector.d.ts +31 -0
  893. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  894. package/dist/modes/interactive/components/user-message-selector.js +122 -0
  895. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  896. package/dist/modes/interactive/components/user-message.d.ts +18 -0
  897. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  898. package/dist/modes/interactive/components/user-message.js +54 -0
  899. package/dist/modes/interactive/components/user-message.js.map +1 -0
  900. package/dist/modes/interactive/components/visual-truncate.d.ts +48 -0
  901. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  902. package/dist/modes/interactive/components/visual-truncate.js +66 -0
  903. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  904. package/dist/modes/interactive/external-editor.d.ts +13 -0
  905. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  906. package/dist/modes/interactive/external-editor.js +50 -0
  907. package/dist/modes/interactive/external-editor.js.map +1 -0
  908. package/dist/modes/interactive/interactive-mode.d.ts +528 -0
  909. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  910. package/dist/modes/interactive/interactive-mode.js +6347 -0
  911. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  912. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  913. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  914. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  915. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  916. package/dist/modes/interactive/model-search.d.ts +22 -0
  917. package/dist/modes/interactive/model-search.d.ts.map +1 -0
  918. package/dist/modes/interactive/model-search.js +36 -0
  919. package/dist/modes/interactive/model-search.js.map +1 -0
  920. package/dist/modes/interactive/program-status-reporter.d.ts +34 -0
  921. package/dist/modes/interactive/program-status-reporter.d.ts.map +1 -0
  922. package/dist/modes/interactive/program-status-reporter.js +110 -0
  923. package/dist/modes/interactive/program-status-reporter.js.map +1 -0
  924. package/dist/modes/interactive/session-share.d.ts +18 -0
  925. package/dist/modes/interactive/session-share.d.ts.map +1 -0
  926. package/dist/modes/interactive/session-share.js +195 -0
  927. package/dist/modes/interactive/session-share.js.map +1 -0
  928. package/dist/modes/interactive/theme/dark.json +78 -0
  929. package/dist/modes/interactive/theme/light.json +78 -0
  930. package/dist/modes/interactive/theme/system-theme.d.ts +55 -0
  931. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -0
  932. package/dist/modes/interactive/theme/system-theme.js +546 -0
  933. package/dist/modes/interactive/theme/system-theme.js.map +1 -0
  934. package/dist/modes/interactive/theme/theme-controller.d.ts +81 -0
  935. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -0
  936. package/dist/modes/interactive/theme/theme-controller.js +210 -0
  937. package/dist/modes/interactive/theme/theme-controller.js.map +1 -0
  938. package/dist/modes/interactive/theme/theme-schema.d.ts +28 -0
  939. package/dist/modes/interactive/theme/theme-schema.d.ts.map +1 -0
  940. package/dist/modes/interactive/theme/theme-schema.js +105 -0
  941. package/dist/modes/interactive/theme/theme-schema.js.map +1 -0
  942. package/dist/modes/interactive/theme/theme-tokens.d.ts +257 -0
  943. package/dist/modes/interactive/theme/theme-tokens.d.ts.map +1 -0
  944. package/dist/modes/interactive/theme/theme-tokens.js +94 -0
  945. package/dist/modes/interactive/theme/theme-tokens.js.map +1 -0
  946. package/dist/modes/interactive/theme/theme.d.ts +165 -0
  947. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  948. package/dist/modes/interactive/theme/theme.js +917 -0
  949. package/dist/modes/interactive/theme/theme.js.map +1 -0
  950. package/dist/modes/interactive/tui-renderer.d.ts +22 -0
  951. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  952. package/dist/modes/interactive/tui-renderer.js +67 -0
  953. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  954. package/dist/modes/json-event.d.ts +34 -0
  955. package/dist/modes/json-event.d.ts.map +1 -0
  956. package/dist/modes/json-event.js +29 -0
  957. package/dist/modes/json-event.js.map +1 -0
  958. package/dist/modes/print-mode.d.ts +28 -0
  959. package/dist/modes/print-mode.d.ts.map +1 -0
  960. package/dist/modes/print-mode.js +155 -0
  961. package/dist/modes/print-mode.js.map +1 -0
  962. package/dist/modes/rpc/jsonl.d.ts +17 -0
  963. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  964. package/dist/modes/rpc/jsonl.js +49 -0
  965. package/dist/modes/rpc/jsonl.js.map +1 -0
  966. package/dist/modes/rpc/rpc-client.d.ts +254 -0
  967. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  968. package/dist/modes/rpc/rpc-client.js +499 -0
  969. package/dist/modes/rpc/rpc-client.js.map +1 -0
  970. package/dist/modes/rpc/rpc-mode.d.ts +20 -0
  971. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  972. package/dist/modes/rpc/rpc-mode.js +685 -0
  973. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  974. package/dist/modes/rpc/rpc-types.d.ts +478 -0
  975. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  976. package/dist/modes/rpc/rpc-types.js +8 -0
  977. package/dist/modes/rpc/rpc-types.js.map +1 -0
  978. package/dist/package-manager-cli.d.ts +9 -0
  979. package/dist/package-manager-cli.d.ts.map +1 -0
  980. package/dist/package-manager-cli.js +1076 -0
  981. package/dist/package-manager-cli.js.map +1 -0
  982. package/dist/rpc-entry.d.ts +3 -0
  983. package/dist/rpc-entry.d.ts.map +1 -0
  984. package/dist/rpc-entry.js +11 -0
  985. package/dist/rpc-entry.js.map +1 -0
  986. package/dist/utils/abort.d.ts +5 -0
  987. package/dist/utils/abort.d.ts.map +1 -0
  988. package/dist/utils/abort.js +48 -0
  989. package/dist/utils/abort.js.map +1 -0
  990. package/dist/utils/ansi.d.ts +10 -0
  991. package/dist/utils/ansi.d.ts.map +1 -0
  992. package/dist/utils/ansi.js +74 -0
  993. package/dist/utils/ansi.js.map +1 -0
  994. package/dist/utils/changelog.d.ts +22 -0
  995. package/dist/utils/changelog.d.ts.map +1 -0
  996. package/dist/utils/changelog.js +171 -0
  997. package/dist/utils/changelog.js.map +1 -0
  998. package/dist/utils/child-process.d.ts +18 -0
  999. package/dist/utils/child-process.d.ts.map +1 -0
  1000. package/dist/utils/child-process.js +106 -0
  1001. package/dist/utils/child-process.js.map +1 -0
  1002. package/dist/utils/cli-invocation.d.ts +11 -0
  1003. package/dist/utils/cli-invocation.d.ts.map +1 -0
  1004. package/dist/utils/cli-invocation.js +23 -0
  1005. package/dist/utils/cli-invocation.js.map +1 -0
  1006. package/dist/utils/clipboard-command.d.ts +7 -0
  1007. package/dist/utils/clipboard-command.d.ts.map +1 -0
  1008. package/dist/utils/clipboard-command.js +52 -0
  1009. package/dist/utils/clipboard-command.js.map +1 -0
  1010. package/dist/utils/clipboard-image.d.ts +11 -0
  1011. package/dist/utils/clipboard-image.d.ts.map +1 -0
  1012. package/dist/utils/clipboard-image.js +214 -0
  1013. package/dist/utils/clipboard-image.js.map +1 -0
  1014. package/dist/utils/clipboard.d.ts +6 -0
  1015. package/dist/utils/clipboard.d.ts.map +1 -0
  1016. package/dist/utils/clipboard.js +162 -0
  1017. package/dist/utils/clipboard.js.map +1 -0
  1018. package/dist/utils/deprecation.d.ts +4 -0
  1019. package/dist/utils/deprecation.d.ts.map +1 -0
  1020. package/dist/utils/deprecation.js +13 -0
  1021. package/dist/utils/deprecation.js.map +1 -0
  1022. package/dist/utils/exif-orientation.d.ts +5 -0
  1023. package/dist/utils/exif-orientation.d.ts.map +1 -0
  1024. package/dist/utils/exif-orientation.js +157 -0
  1025. package/dist/utils/exif-orientation.js.map +1 -0
  1026. package/dist/utils/frontmatter.d.ts +8 -0
  1027. package/dist/utils/frontmatter.d.ts.map +1 -0
  1028. package/dist/utils/frontmatter.js +27 -0
  1029. package/dist/utils/frontmatter.js.map +1 -0
  1030. package/dist/utils/fs-watch.d.ts +5 -0
  1031. package/dist/utils/fs-watch.d.ts.map +1 -0
  1032. package/dist/utils/fs-watch.js +25 -0
  1033. package/dist/utils/fs-watch.js.map +1 -0
  1034. package/dist/utils/git.d.ts +26 -0
  1035. package/dist/utils/git.d.ts.map +1 -0
  1036. package/dist/utils/git.js +195 -0
  1037. package/dist/utils/git.js.map +1 -0
  1038. package/dist/utils/html.d.ts +7 -0
  1039. package/dist/utils/html.d.ts.map +1 -0
  1040. package/dist/utils/html.js +40 -0
  1041. package/dist/utils/html.js.map +1 -0
  1042. package/dist/utils/image-convert.d.ts +22 -0
  1043. package/dist/utils/image-convert.d.ts.map +1 -0
  1044. package/dist/utils/image-convert.js +84 -0
  1045. package/dist/utils/image-convert.js.map +1 -0
  1046. package/dist/utils/image-process.d.ts +18 -0
  1047. package/dist/utils/image-process.d.ts.map +1 -0
  1048. package/dist/utils/image-process.js +83 -0
  1049. package/dist/utils/image-process.js.map +1 -0
  1050. package/dist/utils/image-resize-core.d.ts +42 -0
  1051. package/dist/utils/image-resize-core.d.ts.map +1 -0
  1052. package/dist/utils/image-resize-core.js +131 -0
  1053. package/dist/utils/image-resize-core.js.map +1 -0
  1054. package/dist/utils/image-resize-worker.d.ts +2 -0
  1055. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  1056. package/dist/utils/image-resize-worker.js +32 -0
  1057. package/dist/utils/image-resize-worker.js.map +1 -0
  1058. package/dist/utils/image-resize.d.ts +16 -0
  1059. package/dist/utils/image-resize.d.ts.map +1 -0
  1060. package/dist/utils/image-resize.js +96 -0
  1061. package/dist/utils/image-resize.js.map +1 -0
  1062. package/dist/utils/json.d.ts +3 -0
  1063. package/dist/utils/json.d.ts.map +1 -0
  1064. package/dist/utils/json.js +7 -0
  1065. package/dist/utils/json.js.map +1 -0
  1066. package/dist/utils/management-http.d.ts +25 -0
  1067. package/dist/utils/management-http.d.ts.map +1 -0
  1068. package/dist/utils/management-http.js +54 -0
  1069. package/dist/utils/management-http.js.map +1 -0
  1070. package/dist/utils/mime.d.ts +3 -0
  1071. package/dist/utils/mime.d.ts.map +1 -0
  1072. package/dist/utils/mime.js +110 -0
  1073. package/dist/utils/mime.js.map +1 -0
  1074. package/dist/utils/open-browser.d.ts +9 -0
  1075. package/dist/utils/open-browser.d.ts.map +1 -0
  1076. package/dist/utils/open-browser.js +25 -0
  1077. package/dist/utils/open-browser.js.map +1 -0
  1078. package/dist/utils/output-files.d.ts +15 -0
  1079. package/dist/utils/output-files.d.ts.map +1 -0
  1080. package/dist/utils/output-files.js +30 -0
  1081. package/dist/utils/output-files.js.map +1 -0
  1082. package/dist/utils/paths.d.ts +51 -0
  1083. package/dist/utils/paths.d.ts.map +1 -0
  1084. package/dist/utils/paths.js +156 -0
  1085. package/dist/utils/paths.js.map +1 -0
  1086. package/dist/utils/photon.d.ts +21 -0
  1087. package/dist/utils/photon.d.ts.map +1 -0
  1088. package/dist/utils/photon.js +121 -0
  1089. package/dist/utils/photon.js.map +1 -0
  1090. package/dist/utils/pi-user-agent.d.ts +3 -0
  1091. package/dist/utils/pi-user-agent.d.ts.map +1 -0
  1092. package/dist/utils/pi-user-agent.js +6 -0
  1093. package/dist/utils/pi-user-agent.js.map +1 -0
  1094. package/dist/utils/shell.d.ts +32 -0
  1095. package/dist/utils/shell.d.ts.map +1 -0
  1096. package/dist/utils/shell.js +235 -0
  1097. package/dist/utils/shell.js.map +1 -0
  1098. package/dist/utils/sleep.d.ts +5 -0
  1099. package/dist/utils/sleep.d.ts.map +1 -0
  1100. package/dist/utils/sleep.js +17 -0
  1101. package/dist/utils/sleep.js.map +1 -0
  1102. package/dist/utils/syntax-highlight.d.ts +18 -0
  1103. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  1104. package/dist/utils/syntax-highlight.js +191 -0
  1105. package/dist/utils/syntax-highlight.js.map +1 -0
  1106. package/dist/utils/text.d.ts +8 -0
  1107. package/dist/utils/text.d.ts.map +1 -0
  1108. package/dist/utils/text.js +9 -0
  1109. package/dist/utils/text.js.map +1 -0
  1110. package/dist/utils/tool-result-images.d.ts +21 -0
  1111. package/dist/utils/tool-result-images.d.ts.map +1 -0
  1112. package/dist/utils/tool-result-images.js +48 -0
  1113. package/dist/utils/tool-result-images.js.map +1 -0
  1114. package/dist/utils/tools-manager.d.ts +13 -0
  1115. package/dist/utils/tools-manager.d.ts.map +1 -0
  1116. package/dist/utils/tools-manager.js +339 -0
  1117. package/dist/utils/tools-manager.js.map +1 -0
  1118. package/dist/utils/version-check.d.ts +19 -0
  1119. package/dist/utils/version-check.d.ts.map +1 -0
  1120. package/dist/utils/version-check.js +81 -0
  1121. package/dist/utils/version-check.js.map +1 -0
  1122. package/dist/utils/windows-self-update.d.ts +3 -0
  1123. package/dist/utils/windows-self-update.d.ts.map +1 -0
  1124. package/dist/utils/windows-self-update.js +77 -0
  1125. package/dist/utils/windows-self-update.js.map +1 -0
  1126. package/dist/utils/wsl.d.ts +3 -0
  1127. package/dist/utils/wsl.d.ts.map +1 -0
  1128. package/dist/utils/wsl.js +15 -0
  1129. package/dist/utils/wsl.js.map +1 -0
  1130. package/dist/utils/zip.d.ts +7 -0
  1131. package/dist/utils/zip.d.ts.map +1 -0
  1132. package/dist/utils/zip.js +60 -0
  1133. package/dist/utils/zip.js.map +1 -0
  1134. package/docs/cli-integration.md +106 -0
  1135. package/docs/cli.md +343 -0
  1136. package/docs/codemode.md +230 -0
  1137. package/docs/compaction.md +463 -0
  1138. package/docs/configuration.md +47 -0
  1139. package/docs/containerization.md +183 -0
  1140. package/docs/custom-provider.md +227 -0
  1141. package/docs/docs.json +220 -0
  1142. package/docs/environment-variables.md +103 -0
  1143. package/docs/extensions.md +3366 -0
  1144. package/docs/how-pi-works.md +49 -0
  1145. package/docs/images/doom-extension.png +0 -0
  1146. package/docs/images/exy.png +0 -0
  1147. package/docs/images/interactive-mode.png +0 -0
  1148. package/docs/images/tree-view.png +0 -0
  1149. package/docs/index.md +39 -0
  1150. package/docs/json.md +226 -0
  1151. package/docs/keybindings.md +195 -0
  1152. package/docs/llama-cpp.md +129 -0
  1153. package/docs/mcp.md +274 -0
  1154. package/docs/message-types.md +279 -0
  1155. package/docs/models-configuration.md +200 -0
  1156. package/docs/models.md +226 -0
  1157. package/docs/nvidia-rtx-llama-cpp.md +96 -0
  1158. package/docs/packages.md +153 -0
  1159. package/docs/prompt-templates.md +59 -0
  1160. package/docs/providers.md +247 -0
  1161. package/docs/quickstart.md +140 -0
  1162. package/docs/rpc-commands.md +860 -0
  1163. package/docs/rpc-extension-ui.md +200 -0
  1164. package/docs/rpc.md +195 -0
  1165. package/docs/sdk.md +147 -0
  1166. package/docs/security.md +99 -0
  1167. package/docs/session-format.md +293 -0
  1168. package/docs/sessions.md +74 -0
  1169. package/docs/settings.md +173 -0
  1170. package/docs/shell-aliases.md +93 -0
  1171. package/docs/skills.md +93 -0
  1172. package/docs/slash-commands.md +61 -0
  1173. package/docs/terminal-setup.md +235 -0
  1174. package/docs/termux.md +117 -0
  1175. package/docs/themes.md +138 -0
  1176. package/docs/tmux.md +61 -0
  1177. package/docs/tui.md +197 -0
  1178. package/docs/usage.md +94 -0
  1179. package/docs/virtual-models.md +114 -0
  1180. package/docs/windows.md +108 -0
  1181. package/package.json +37 -37
  1182. package/schemas/keybindings.schema.json +393 -0
  1183. package/schemas/models.schema.json +1236 -0
  1184. package/schemas/settings.schema.json +800 -0
  1185. package/schemas/theme.schema.json +365 -0
  1186. package/LICENSE +0 -21
  1187. package/bin/mars.cjs +0 -133
@@ -0,0 +1,3710 @@
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
+ import { readFileSync } from "node:fs";
16
+ import { basename, dirname } from "node:path";
17
+ import { runToolCall, } from "@earendil-works/pi-agent-core";
18
+ import { contentText, getCurrentSystemMessage, getCurrentTools, retryDelayMs } from "@earendil-works/pi-ai";
19
+ import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRecoverableLength, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@earendil-works/pi-ai/compat";
20
+ import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
21
+ import { stripFrontmatter } from "../utils/frontmatter.js";
22
+ import { processImage } from "../utils/image-process.js";
23
+ import { sleep } from "../utils/sleep.js";
24
+ import { normalizeToolResultImages } from "../utils/tool-result-images.js";
25
+ import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
26
+ import { executeBashWithOperations } from "./bash-executor.js";
27
+ import { generateBugReportSummary } from "./bug-report.js";
28
+ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateProjectedContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
29
+ import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.js";
30
+ import { exportSessionToHtml } from "./export-html/index.js";
31
+ import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
32
+ import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
33
+ import { emitSessionShutdownEvent } from "./extensions/runner.js";
34
+ import { createToolNameMatcher, isMcpToolName } from "./mcp-servers.js";
35
+ import { convertToLlm } from "./messages.js";
36
+ import { ModelRegistry } from "./model-registry.js";
37
+ import { NestedToolCallRunner } from "./nested-tool-calls.js";
38
+ import { expandPromptTemplate } from "./prompt-templates.js";
39
+ import { exportSessionToJsonl } from "./session-export.js";
40
+ import { getLatestCompactionEntry, SessionManager, } from "./session-manager.js";
41
+ import { applyToolModifiers, DEFAULT_TOOL_NAMES, } from "./settings-manager.js";
42
+ import { BUILTIN_PATH_PREFIX, createSyntheticSourceInfo, isSyntheticPath } from "./source-info.js";
43
+ import { buildSystemPrompt, buildSystemPromptSections, diffSystemPromptSections, normalizeBuildSystemPromptOptions, } from "./system-prompt.js";
44
+ import { createLocalBashOperations } from "./tools/bash.js";
45
+ import { createAllToolDefinitions } from "./tools/index.js";
46
+ import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
47
+ import { addUsageToTotals, combineUsage, createUsageTotals } from "./usage-totals.js";
48
+ import { findLatestResponse, getBranchSelection, getVirtualModelState, isVirtualModel, VIRTUAL_MODEL_STATE_ENTRY, } from "./virtual-models.js";
49
+ /**
50
+ * Stream functions that resolve auth through a given ModelRuntime themselves, such as the one
51
+ * createAgentSession installs. Summaries sent through them must not pass pre-resolved credentials:
52
+ * the runtime would take them as an explicit API key instead of the stored OAuth login (#11520).
53
+ */
54
+ const runtimeStreamFunctions = new WeakMap();
55
+ /** Mark `streamFn` as resolving auth through `modelRuntime` on its own. */
56
+ export function markRuntimeStreamFunction(streamFn, modelRuntime) {
57
+ runtimeStreamFunctions.set(streamFn, modelRuntime);
58
+ }
59
+ /**
60
+ * Parse a skill block from message text.
61
+ * Returns null if the text doesn't contain a skill block.
62
+ */
63
+ export function parseSkillBlock(text) {
64
+ const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
65
+ if (!match)
66
+ return null;
67
+ return {
68
+ name: match[1],
69
+ location: match[2],
70
+ content: match[3],
71
+ userMessage: match[4]?.trim() || undefined,
72
+ };
73
+ }
74
+ // ============================================================================
75
+ // Types
76
+ // ============================================================================
77
+ function withoutDeletedHeaders(headers) {
78
+ return headers
79
+ ? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))
80
+ : undefined;
81
+ }
82
+ function estimateMessagesTokens(messages) {
83
+ let tokens = 0;
84
+ for (const message of messages) {
85
+ tokens += estimateTokens(message);
86
+ }
87
+ return tokens;
88
+ }
89
+ // ============================================================================
90
+ // AgentSession Class
91
+ // ============================================================================
92
+ export class AgentSession {
93
+ agent;
94
+ sessionManager;
95
+ settingsManager;
96
+ _scopedModels;
97
+ // Event subscription state
98
+ _unsubscribeAgent;
99
+ _eventListeners = [];
100
+ _isAgentRunActive = false;
101
+ _promptPreflightCount = 0;
102
+ _agentRunAbortRequested = false;
103
+ _idleWaitPromise;
104
+ _resolveIdleWait;
105
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
106
+ _steeringMessages = [];
107
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
108
+ _followUpMessages = [];
109
+ /** Queued user messages whose images are normalized when they are delivered. */
110
+ _queuedMessagesWithImages = new WeakSet();
111
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
112
+ _pendingNextTurnMessages = [];
113
+ /** Context-only custom messages queued during a run, flushed once the current turn's tool results are in. */
114
+ _pendingCustomMessages = [];
115
+ // Compaction state
116
+ _compactionAbortController = undefined;
117
+ _autoCompactionAbortController = undefined;
118
+ _overflowRecoveryAttempted = false;
119
+ // Branch summarization state
120
+ _branchSummaryAbortController = undefined;
121
+ // Retry state
122
+ _retryAbortController = undefined;
123
+ _retryAttempt = 0;
124
+ /**
125
+ * Failed response that the next request repeats, set by auto-retry and overflow recovery. The
126
+ * retry is routed with it as `failed`, since the context no longer contains it.
127
+ */
128
+ _failedResponse;
129
+ // Bash execution state
130
+ _bashAbortControllers = new Set();
131
+ _pendingBashMessages = [];
132
+ // Extension system
133
+ _extensionRunner;
134
+ _turnIndex = 0;
135
+ _entryIdsByMessage = new WeakMap();
136
+ _boundaryDispatchedMessages = new WeakSet();
137
+ _lastAssistantMessage;
138
+ _lastActivityOutcome = "completed";
139
+ _isBeforeSettle = false;
140
+ _abortDuringBeforeSettle = false;
141
+ _isEmittingAgentSettled = false;
142
+ _deferredSettledActions = [];
143
+ _resourceLoader;
144
+ _customTools;
145
+ _baseToolDefinitions = new Map();
146
+ _cwd;
147
+ _extensionRunnerRef;
148
+ _initialActiveToolNames;
149
+ /**
150
+ * Tools of the restored or reloaded loadout that are not registered yet, such as tools of MCP
151
+ * servers that are still connecting. They are activated when they are registered, and dropped when
152
+ * `setActiveToolsByName()` deactivates a tool or the next agent run starts.
153
+ */
154
+ _pendingToolNames = new Set();
155
+ _usesDefaultTools;
156
+ _defaultToolModifiers;
157
+ /** Matches the `--tools` entries: tool names or patterns. */
158
+ _allowedTools;
159
+ /**
160
+ * Whether the allowlist filters MCP tools: it is empty (`--no-tools`) or names an MCP tool
161
+ * (`mcp__*`). Otherwise it keeps MCP tools registered for codemode and tool_search.
162
+ */
163
+ _allowlistFiltersMcp = false;
164
+ _excludedTools;
165
+ _baseToolsOverride;
166
+ _sessionStartEvent;
167
+ _extensionUIContext;
168
+ _extensionMode = "print";
169
+ _extensionCommandContextActions;
170
+ _extensionAbortHandler;
171
+ _extensionShutdownHandler;
172
+ _extensionErrorListener;
173
+ _extensionErrorUnsubscriber;
174
+ _modelRuntime;
175
+ _cacheWarmer;
176
+ // Tool registry for extension getTools/setTools
177
+ _toolRegistry = new Map();
178
+ /** Created on the first `ctx.executeTool()` call. */
179
+ _nestedToolCalls;
180
+ /** Declared tools whose declarations requests leave out, from `prepareLoadout` hooks. */
181
+ _hiddenDeclarations = new Set();
182
+ _toolDefinitions = new Map();
183
+ _toolPromptSnippets = new Map();
184
+ _toolPromptGuidelines = new Map();
185
+ _baseSystemPromptOptions;
186
+ /** Prompt options after before_agent_start mutations for the active run. */
187
+ _runSystemPromptOptions;
188
+ constructor(config) {
189
+ this.agent = config.agent;
190
+ this.sessionManager = config.sessionManager;
191
+ this.settingsManager = config.settingsManager;
192
+ this._scopedModels = config.scopedModels ?? [];
193
+ this._resourceLoader = config.resourceLoader;
194
+ this._customTools = config.customTools ?? [];
195
+ this._cwd = config.cwd;
196
+ this._modelRuntime = config.modelRuntime;
197
+ this._cacheWarmer = config.cacheWarmer;
198
+ if (this._cacheWarmer) {
199
+ this._cacheWarmer.onWarmed = (entry) => this._emit({ type: "entry_appended", entry });
200
+ }
201
+ this._extensionRunnerRef = config.extensionRunnerRef;
202
+ this._initialActiveToolNames = config.initialActiveToolNames;
203
+ this._usesDefaultTools = config.usesDefaultTools ?? false;
204
+ this._defaultToolModifiers = config.defaultToolModifiers ?? [];
205
+ if (config.allowedToolNames) {
206
+ this._allowedTools = createToolNameMatcher(config.allowedToolNames);
207
+ this._allowlistFiltersMcp =
208
+ config.allowedToolNames.length === 0 || config.allowedToolNames.some((entry) => entry.startsWith("mcp__"));
209
+ }
210
+ this._excludedTools = config.excludedToolNames ? createToolNameMatcher(config.excludedToolNames) : undefined;
211
+ this._baseToolsOverride = config.baseToolsOverride;
212
+ this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
213
+ // Always subscribe to agent events for internal handling
214
+ // (session persistence, extensions, auto-compaction, retry logic)
215
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
216
+ this._installAgentToolHooks();
217
+ this._installAgentNextTurnRefresh();
218
+ this._installAgentRequestProjection();
219
+ this._installAgentBoundaryHooks();
220
+ this._installHiddenDeclarationsProjection();
221
+ this._installAgentForcedPromptProjection();
222
+ this._buildRuntime({
223
+ activeToolNames: this._initialActiveToolNames,
224
+ includeAllExtensionTools: true,
225
+ });
226
+ if (this._usesDefaultTools)
227
+ this._restoreToolsFromTranscript(this._defaultToolModifiers);
228
+ }
229
+ get modelRuntime() {
230
+ return this._modelRuntime;
231
+ }
232
+ async _getRequiredRequestAuth(model, signal) {
233
+ let result;
234
+ try {
235
+ result = await this._modelRuntime.getAuth(model, { signal });
236
+ }
237
+ catch (error) {
238
+ const cause = error instanceof Error ? error.cause : undefined;
239
+ if (cause instanceof Error && cause.message === "authHeader requires a resolved API key") {
240
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
241
+ }
242
+ throw error;
243
+ }
244
+ if (result && (result.auth.apiKey || result.auth.headers)) {
245
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
246
+ return {
247
+ model: requestModel,
248
+ apiKey: result.auth.apiKey,
249
+ headers: withoutDeletedHeaders(result.auth.headers),
250
+ env: result.env,
251
+ };
252
+ }
253
+ const isOAuth = this._modelRuntime.isUsingOAuth(model.provider);
254
+ if (isOAuth) {
255
+ throw new Error(`Authentication failed for "${model.provider}". ` +
256
+ `Credentials may have expired or network is unavailable. ` +
257
+ `Run '/login ${model.provider}' to re-authenticate.`);
258
+ }
259
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
260
+ }
261
+ async _getSummarizationRequestAuth(selectedModel, signal) {
262
+ // Route a virtual model first: summaries size their input and output from the model they get.
263
+ const { model, thinkingLevel } = isVirtualModel(selectedModel)
264
+ ? await this._modelRuntime.resolveModel(selectedModel, convertToLlm(this.messages), {
265
+ reason: "direct",
266
+ thinkingLevel: this.thinkingLevel,
267
+ signal,
268
+ })
269
+ : { model: selectedModel, thinkingLevel: this.thinkingLevel };
270
+ if (this.agent.streamFunction === streamSimple) {
271
+ return { ...(await this._getRequiredRequestAuth(model, signal)), thinkingLevel };
272
+ }
273
+ if (runtimeStreamFunctions.get(this.agent.streamFunction) === this._modelRuntime) {
274
+ return { model, thinkingLevel };
275
+ }
276
+ try {
277
+ const result = await this._modelRuntime.getAuth(model, { signal });
278
+ if (!result)
279
+ return { model, thinkingLevel };
280
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
281
+ return {
282
+ model: requestModel,
283
+ apiKey: result.auth.apiKey,
284
+ headers: withoutDeletedHeaders(result.auth.headers),
285
+ env: result.env,
286
+ thinkingLevel,
287
+ };
288
+ }
289
+ catch (error) {
290
+ if (signal?.aborted)
291
+ throw error;
292
+ return { model, thinkingLevel };
293
+ }
294
+ }
295
+ /**
296
+ * The model whose limits apply to `message`, or undefined when the message came from another
297
+ * model. Under a virtual selection, that is the physical model that produced it.
298
+ */
299
+ _modelForMessage(message) {
300
+ const model = this.model;
301
+ if (model && isVirtualModel(model))
302
+ return this._modelRuntime.getPhysicalModel(message.provider, message.model);
303
+ return model?.provider === message.provider && model.id === message.model ? model : undefined;
304
+ }
305
+ /**
306
+ * Record the selection on the current branch when the branch implies another one, so a resume
307
+ * restores it. Tree navigation can leave the latest `model_change` on another branch; responses
308
+ * cannot record a virtual selection because they name physical models. Responses do record a
309
+ * physical selection unless the branch holds a virtual one; checking a physical selection against
310
+ * responses would record it on every prompt while `prepareRequest` redirects to another model.
311
+ */
312
+ _recordSelection() {
313
+ const model = this.model;
314
+ if (!model)
315
+ return;
316
+ const getModel = (provider, modelId) => this._modelRuntime.getModel(provider, modelId);
317
+ const recorded = getBranchSelection(this.sessionManager.getBranch(), getModel);
318
+ if (!recorded || (recorded.provider === model.provider && recorded.modelId === model.id))
319
+ return;
320
+ const recordedModel = getModel(recorded.provider, recorded.modelId);
321
+ if (!isVirtualModel(model) && !(recordedModel && isVirtualModel(recordedModel)))
322
+ return;
323
+ this.sessionManager.appendModelChange(model.provider, model.id);
324
+ }
325
+ /** The model whose limits apply to the conversation. */
326
+ _limitsModel() {
327
+ return this.routedModel?.model ?? this.model;
328
+ }
329
+ /**
330
+ * Install tool hooks once on the Agent instance.
331
+ *
332
+ * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
333
+ * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
334
+ * registered tool execution to the extension context. Tool call and tool result interception now
335
+ * happens here instead of in wrappers.
336
+ */
337
+ _installAgentToolHooks() {
338
+ this.agent.beforeToolCall = (context) => this._beforeToolCall(context);
339
+ this.agent.afterToolCall = (context) => this._afterToolCall(context);
340
+ }
341
+ /** `tool_call` handlers. `parentToolCallId` is set for calls another tool made. */
342
+ async _beforeToolCall({ toolCall, args }, parentToolCallId) {
343
+ const runner = this._extensionRunner;
344
+ if (!runner.hasHandlers("tool_call")) {
345
+ return undefined;
346
+ }
347
+ try {
348
+ return await runner.emitToolCall({
349
+ type: "tool_call",
350
+ toolName: toolCall.name,
351
+ toolCallId: toolCall.id,
352
+ ...(parentToolCallId ? { parentToolCallId } : {}),
353
+ input: args,
354
+ });
355
+ }
356
+ catch (err) {
357
+ if (err instanceof Error) {
358
+ throw err;
359
+ }
360
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
361
+ }
362
+ }
363
+ /** `tool_result` handlers and image normalization. `parentToolCallId` is set for calls another tool made. */
364
+ async _afterToolCall({ toolCall, args, result, isError }, parentToolCallId) {
365
+ const runner = this._extensionRunner;
366
+ const hookResult = runner.hasHandlers("tool_result")
367
+ ? await runner.emitToolResult({
368
+ type: "tool_result",
369
+ toolName: toolCall.name,
370
+ toolCallId: toolCall.id,
371
+ ...(parentToolCallId ? { parentToolCallId } : {}),
372
+ input: args,
373
+ content: result.content,
374
+ details: result.details,
375
+ ...(result.structuredContent === undefined ? {} : { structuredContent: result.structuredContent }),
376
+ isError,
377
+ usage: result.usage,
378
+ })
379
+ : undefined;
380
+ const content = hookResult?.content ?? result.content ?? [];
381
+ // Runs after the extension hook so images injected or replaced by extensions are normalized too.
382
+ const resizeOptions = this._limitsModel()?.inputLimits?.images?.resize;
383
+ const normalizedContent = await normalizeToolResultImages(content, {
384
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
385
+ ...(resizeOptions ? { resizeOptions } : {}),
386
+ });
387
+ if (!hookResult && normalizedContent === content) {
388
+ return undefined;
389
+ }
390
+ // The hook result already dropped structured content that replaced content no longer matches.
391
+ return {
392
+ content: normalizedContent,
393
+ details: hookResult?.details,
394
+ structuredContent: hookResult ? hookResult.structuredContent : result.structuredContent,
395
+ isError: hookResult?.isError ?? isError,
396
+ usage: hookResult?.usage,
397
+ };
398
+ }
399
+ /**
400
+ * Run a call that the tool call `parentToolCallId` made through `ctx.executeTool()`. It goes
401
+ * through the agent's tool pipeline with the session's hooks, against the callable tools.
402
+ */
403
+ async _executeNestedToolCall(parentToolCallId, name, args, options) {
404
+ this._nestedToolCalls ??= new NestedToolCallRunner({
405
+ getTools: () => this._getCallableTools(),
406
+ isSequential: () => this.agent.toolExecution === "sequential",
407
+ runToolCall: (toolCall, parentId, signal, onUpdate) => {
408
+ const assistantMessage = this._findLastAssistantMessage();
409
+ if (!assistantMessage) {
410
+ return Promise.resolve({
411
+ toolCall,
412
+ result: { content: [{ type: "text", text: "No assistant message issued this call" }], details: {} },
413
+ isError: true,
414
+ });
415
+ }
416
+ return runToolCall(toolCall, {
417
+ tools: this._getCallableTools(),
418
+ assistantMessage,
419
+ context: { messages: this.agent.state.messages, tools: this.agent.state.tools },
420
+ beforeToolCall: (context) => this._beforeToolCall(context, parentId),
421
+ afterToolCall: (context) => this._afterToolCall(context, parentId),
422
+ signal,
423
+ onUpdate,
424
+ });
425
+ },
426
+ emit: async (event) => {
427
+ await this._extensionRunner.emit(event);
428
+ this._emit(event);
429
+ },
430
+ });
431
+ return this._nestedToolCalls.execute(parentToolCallId, name, args, options);
432
+ }
433
+ /** Whether `projection`, the current session projection, exceeds the compaction threshold of `model`. */
434
+ _exceedsCompactionThreshold(model, projection) {
435
+ if (model.contextWindow <= 0)
436
+ return false;
437
+ return shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens, model.contextWindow, this.settingsManager.getCompactionSettings(this.model));
438
+ }
439
+ async _compactBeforeNextAssistantResponse(context) {
440
+ const projection = this.sessionManager.buildSessionProjection();
441
+ // A virtual selection is checked in prepareRequest, against the model the request is routed to.
442
+ const model = this.model;
443
+ if (!model || isVirtualModel(model) || !this._exceedsCompactionThreshold(model, projection)) {
444
+ return { ...context, messages: projection.messages };
445
+ }
446
+ await this._runAutoCompaction("threshold", false);
447
+ return { ...context, messages: this.sessionManager.buildSessionProjection().messages };
448
+ }
449
+ _installAgentRequestProjection() {
450
+ const previousPrepareRequest = this.agent.prepareRequest;
451
+ this.agent.prepareRequest = async (request, signal) => {
452
+ const failed = this._failedResponse;
453
+ this._failedResponse = undefined;
454
+ const prepare = async () => {
455
+ const projection = this.sessionManager.buildSessionProjection();
456
+ const canonicalContext = {
457
+ ...request.context,
458
+ messages: projection.messages,
459
+ // Messages declare the provider-visible loadout; context.tools keeps executable implementations.
460
+ tools: this.agent.state.tools.slice(),
461
+ };
462
+ const previous = await previousPrepareRequest?.({
463
+ ...request,
464
+ context: canonicalContext,
465
+ model: this.agent.state.model,
466
+ thinkingLevel: this.agent.state.thinkingLevel,
467
+ }, signal);
468
+ return { previous, context: previous?.context ?? canonicalContext, projection };
469
+ };
470
+ let { previous, context, projection } = await prepare();
471
+ const model = previous?.model ?? this.agent.state.model;
472
+ const thinkingLevel = previous?.thinkingLevel ?? this.agent.state.thinkingLevel;
473
+ if (!isVirtualModel(model))
474
+ return { ...previous, context, model, thinkingLevel };
475
+ // The selection stays in agent state; only this request uses the routed model. A routing
476
+ // failure rejects, which ends the run with an error response. Only messages the user wrote
477
+ // start a turn; extension messages can follow them, e.g. from before_agent_start.
478
+ const lastResponse = context.messages.findLastIndex((message) => message.role === "assistant");
479
+ const userTurn = context.messages.slice(lastResponse + 1).some((message) => message.role === "user");
480
+ const state = getVirtualModelState(this.sessionManager.getBranch(), model.provider, model.id);
481
+ const route = await this._modelRuntime.resolveModel(model, convertToLlm(context.messages), {
482
+ reason: failed ? "retry" : userTurn ? "user" : "continuation",
483
+ thinkingLevel,
484
+ signal,
485
+ failed,
486
+ state,
487
+ });
488
+ if (route.state !== undefined && route.state !== state) {
489
+ const data = { provider: model.provider, modelId: model.id, state: route.state };
490
+ const entry = this.sessionManager.getEntry(this.sessionManager.appendCustomEntry(VIRTUAL_MODEL_STATE_ENTRY, data));
491
+ if (entry)
492
+ this._emit({ type: "entry_appended", entry });
493
+ }
494
+ // The route stands: the router already decided this request. The state entry does not change
495
+ // the projection.
496
+ if (this._exceedsCompactionThreshold(route.model, projection)) {
497
+ await this._runAutoCompaction("threshold", false);
498
+ ({ previous, context } = await prepare());
499
+ }
500
+ return { ...previous, context, model: route.model, thinkingLevel: route.thinkingLevel };
501
+ };
502
+ }
503
+ async _dispatchTurnEndBoundary(message, toolResults) {
504
+ this._lastActivityOutcome =
505
+ message.stopReason === "aborted" ? "aborted" : message.stopReason === "error" ? "error" : "completed";
506
+ const messageEntryId = this._findPersistedMessageEntryId(message);
507
+ if (!this._extensionRunner.hasHandlers("turn_end"))
508
+ return false;
509
+ if (!messageEntryId) {
510
+ this._extensionRunner.emitError({
511
+ extensionPath: "<boundary>",
512
+ event: "turn_end",
513
+ error: "turn_end could not resolve the persisted assistant entry ID",
514
+ });
515
+ return false;
516
+ }
517
+ const toolResultEntryIds = toolResults.flatMap((result) => {
518
+ const entryId = this._findPersistedMessageEntryId(result);
519
+ return entryId ? [entryId] : [];
520
+ });
521
+ const boundary = await this._extensionRunner.emitBoundary({
522
+ type: "turn_end",
523
+ turnIndex: this._turnIndex,
524
+ message,
525
+ toolResults,
526
+ messageEntryId,
527
+ toolResultEntryIds,
528
+ outcome: this._lastActivityOutcome,
529
+ }, (entries) => this._buildBoundaryContext(entries, "turn_end"));
530
+ this._commitBoundaryDrafts(boundary.entries);
531
+ if (boundary.continue && !this._buildBoundaryContext([], "turn_end").canContinue) {
532
+ this._reportInvalidBoundaryContinuation("turn_end");
533
+ return false;
534
+ }
535
+ return boundary.continue;
536
+ }
537
+ _installAgentBoundaryHooks() {
538
+ const previousFinishTurn = this.agent.finishTurn;
539
+ this.agent.finishTurn = async (turn, signal) => {
540
+ this._boundaryDispatchedMessages.add(turn.message);
541
+ const extensionContinue = await this._dispatchTurnEndBoundary(turn.message, turn.toolResults);
542
+ const previousDecision = await previousFinishTurn?.(turn, signal);
543
+ if (previousDecision?.action === "end")
544
+ return previousDecision;
545
+ if (extensionContinue || previousDecision?.action === "continue")
546
+ return { action: "continue" };
547
+ return undefined;
548
+ };
549
+ }
550
+ _installAgentNextTurnRefresh() {
551
+ const previousPrepareNextTurnWithContext = this.agent.prepareNextTurnWithContext ??
552
+ (this.agent.prepareNextTurn
553
+ ? async (_turn, signal) => await this.agent.prepareNextTurn?.(signal)
554
+ : undefined);
555
+ this.agent.prepareNextTurnWithContext = async (turn, signal) => {
556
+ const context = await this._compactBeforeNextAssistantResponse(turn.context);
557
+ const previousSnapshot = await previousPrepareNextTurnWithContext?.({ ...turn, context }, signal);
558
+ const nextContext = previousSnapshot?.context ?? context;
559
+ const runOptions = this._runSystemPromptOptions ?? this._baseSystemPromptOptions;
560
+ const options = normalizeBuildSystemPromptOptions({
561
+ ...runOptions,
562
+ selectedTools: this.getActiveToolNames(),
563
+ toolSnippets: { ...this._baseSystemPromptOptions.toolSnippets, ...runOptions.toolSnippets },
564
+ toolGuidelines: { ...this._baseSystemPromptOptions.toolGuidelines, ...runOptions.toolGuidelines },
565
+ });
566
+ const updateMessage = this._preparePromptAndToolLoadout(options, nextContext.messages);
567
+ // Keep session.systemPrompt and ctx.getSystemPrompt() in step with what the provider sees.
568
+ this._runSystemPromptOptions = options;
569
+ return {
570
+ ...previousSnapshot,
571
+ context: {
572
+ ...nextContext,
573
+ tools: this.agent.state.tools.slice(),
574
+ },
575
+ messages: updateMessage
576
+ ? [...(previousSnapshot?.messages ?? []), updateMessage]
577
+ : previousSnapshot?.messages,
578
+ model: this.agent.state.model,
579
+ thinkingLevel: this.agent.state.thinkingLevel,
580
+ };
581
+ };
582
+ }
583
+ // =========================================================================
584
+ // Event Subscription
585
+ // =========================================================================
586
+ _refreshFinalizedContext() {
587
+ const projection = this.sessionManager.buildSessionProjection();
588
+ for (const entry of projection.entries) {
589
+ for (const message of entry.messages)
590
+ this._entryIdsByMessage.set(message, entry.sourceEntry.id);
591
+ }
592
+ this.agent.state.messages = projection.messages;
593
+ }
594
+ _applyBoundaryDrafts(manager, drafts) {
595
+ const appended = [];
596
+ for (const draft of drafts) {
597
+ let entryId;
598
+ switch (draft.type) {
599
+ case "custom":
600
+ entryId = manager.appendCustomEntry(draft.customType, draft.data);
601
+ break;
602
+ case "custom_message":
603
+ entryId = manager.appendCustomMessageEntry(draft.customType, draft.content, draft.display, draft.details);
604
+ break;
605
+ case "context_edit":
606
+ entryId = manager.appendContextEdit(draft.targetId, draft.replacement);
607
+ break;
608
+ case "compaction": {
609
+ const tokensBefore = estimateProjectedContextTokens(manager.buildSessionProjection(), manager.getBranch()).tokens;
610
+ entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, draft.details, true, draft.usage);
611
+ break;
612
+ }
613
+ }
614
+ const entry = manager.getEntry(entryId);
615
+ if (entry)
616
+ appended.push(entry);
617
+ }
618
+ return appended;
619
+ }
620
+ _createBoundaryPreviewManager(drafts) {
621
+ const header = this.sessionManager.getHeader();
622
+ if (!header)
623
+ throw new Error("Session header is missing");
624
+ const manager = SessionManager.inMemory(this._cwd, undefined, [header, ...this.sessionManager.getBranch()]);
625
+ this._applyBoundaryDrafts(manager, drafts);
626
+ return manager;
627
+ }
628
+ _getPendingBoundaryMessages() {
629
+ return [...this.agent.peekQueuedMessages(), ...this._pendingCustomMessages];
630
+ }
631
+ _buildBoundaryContext(drafts, boundary) {
632
+ const projection = this._createBoundaryPreviewManager(drafts).buildSessionProjection();
633
+ const pendingMessages = this._getPendingBoundaryMessages();
634
+ const llmMessages = convertToLlm(projection.messages);
635
+ const finalRole = llmMessages[llmMessages.length - 1]?.role;
636
+ const hasNonSystemContext = llmMessages.some((message) => message.role !== "system");
637
+ const contextCanContinue = hasNonSystemContext && finalRole !== "assistant";
638
+ const pendingCustomContext = this._pendingCustomMessages.length > 0;
639
+ return {
640
+ contextEntries: projection.entries,
641
+ contextMessages: projection.messages,
642
+ llmMessages,
643
+ pendingMessages,
644
+ canContinue: contextCanContinue ||
645
+ pendingCustomContext ||
646
+ (boundary === "turn_end"
647
+ ? this.agent.hasQueuedMessages()
648
+ : finalRole === "assistant" && this.agent.hasQueuedMessages()),
649
+ };
650
+ }
651
+ _commitBoundaryDrafts(drafts) {
652
+ const appended = this._applyBoundaryDrafts(this.sessionManager, drafts);
653
+ this._refreshFinalizedContext();
654
+ for (const entry of appended)
655
+ this._emit({ type: "entry_appended", entry });
656
+ }
657
+ _reportInvalidBoundaryContinuation(event) {
658
+ this._extensionRunner.emitError({
659
+ extensionPath: "<boundary>",
660
+ event,
661
+ error: `${event} requested continuation without runnable model context`,
662
+ });
663
+ }
664
+ /** Emit an event to all listeners */
665
+ _emit(event) {
666
+ for (const l of this._eventListeners) {
667
+ l(event);
668
+ }
669
+ }
670
+ _emitQueueUpdate() {
671
+ this._emit({
672
+ type: "queue_update",
673
+ steering: [...this._steeringMessages],
674
+ followUp: [...this._followUpMessages],
675
+ });
676
+ }
677
+ async _emitSessionCompactFailed(event) {
678
+ if (this._extensionRunner.hasHandlers("session_compact_failed")) {
679
+ await this._extensionRunner.emit({ type: "session_compact_failed", ...event });
680
+ }
681
+ }
682
+ _getIdleWaitPromise() {
683
+ if (!this._idleWaitPromise) {
684
+ this._idleWaitPromise = new Promise((resolve) => {
685
+ this._resolveIdleWait = resolve;
686
+ });
687
+ }
688
+ return this._idleWaitPromise;
689
+ }
690
+ _resolveIdleWaitIfIdle() {
691
+ if (!this.isIdle || !this._resolveIdleWait) {
692
+ return;
693
+ }
694
+ const resolve = this._resolveIdleWait;
695
+ this._idleWaitPromise = undefined;
696
+ this._resolveIdleWait = undefined;
697
+ resolve();
698
+ }
699
+ async _emitAgentSettled() {
700
+ this._cacheWarmer?.onAgentSettled();
701
+ this._isAgentRunActive = false;
702
+ this._isEmittingAgentSettled = true;
703
+ try {
704
+ const aborted = this._agentRunAbortRequested;
705
+ await this._extensionRunner.emit({ type: "agent_settled", aborted });
706
+ this._emit({ type: "agent_settled", aborted });
707
+ }
708
+ finally {
709
+ this._isEmittingAgentSettled = false;
710
+ }
711
+ const deferred = this._deferredSettledActions.splice(0);
712
+ if (deferred.length > 0) {
713
+ try {
714
+ for (const action of deferred)
715
+ await action();
716
+ }
717
+ finally {
718
+ this._resolveIdleWaitIfIdle();
719
+ }
720
+ return;
721
+ }
722
+ this._resolveIdleWaitIfIdle();
723
+ }
724
+ /** Internal handler for agent events - shared by subscribe and reconnect */
725
+ _handleAgentEvent = async (event) => {
726
+ // An abort requested while the run was starting, e.g. during before_agent_start, stops it
727
+ // here. agent_start is awaited before the first request.
728
+ if (event.type === "agent_start" && this._agentRunAbortRequested)
729
+ this.agent.abort();
730
+ // Record the calls a tool made through ctx.executeTool() and their usage on its result message.
731
+ if (this._nestedToolCalls) {
732
+ if (event.type === "message_start" && event.message.role === "toolResult") {
733
+ const message = event.message;
734
+ const summary = this._nestedToolCalls.takeRecord(message.toolCallId);
735
+ if (summary?.calls)
736
+ message.nestedCalls = summary.calls;
737
+ if (summary?.usage) {
738
+ message.usage = message.usage ? combineUsage(message.usage, summary.usage) : summary.usage;
739
+ }
740
+ }
741
+ else if (event.type === "agent_end") {
742
+ this._nestedToolCalls.clear();
743
+ }
744
+ }
745
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
746
+ // This ensures the UI sees the updated queue state
747
+ if (event.type === "message_start" && event.message.role === "user") {
748
+ this._overflowRecoveryAttempted = false;
749
+ const messageText = contentText(event.message.content, "");
750
+ // Check steering queue first
751
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
752
+ if (steeringIndex !== -1) {
753
+ this._steeringMessages.splice(steeringIndex, 1);
754
+ this._emitQueueUpdate();
755
+ }
756
+ else {
757
+ // Check follow-up queue
758
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
759
+ if (followUpIndex !== -1) {
760
+ this._followUpMessages.splice(followUpIndex, 1);
761
+ this._emitQueueUpdate();
762
+ }
763
+ }
764
+ // Normalize queued images at delivery, before events and persistence see the message,
765
+ // so they get the same resize as idle prompts with the current model's limits (#11738).
766
+ if (this._queuedMessagesWithImages.has(event.message)) {
767
+ this._queuedMessagesWithImages.delete(event.message);
768
+ await this._normalizeQueuedMessageImages(event.message);
769
+ }
770
+ }
771
+ // Emit to extensions first, then notify public listeners.
772
+ await this._emitExtensionEvent(event);
773
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
774
+ // Handle session persistence
775
+ if (event.type === "message_end") {
776
+ let entryId;
777
+ // Check if this is a custom message from extensions
778
+ if (event.message.role === "custom") {
779
+ // Persist as CustomMessageEntry
780
+ entryId = this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
781
+ }
782
+ else if (event.message.role === "system" ||
783
+ event.message.role === "user" ||
784
+ event.message.role === "assistant" ||
785
+ event.message.role === "toolResult") {
786
+ // Regular LLM message - persist as SessionMessageEntry
787
+ entryId = this.sessionManager.appendMessage(event.message);
788
+ }
789
+ if (entryId)
790
+ this._entryIdsByMessage.set(event.message, entryId);
791
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
792
+ if (event.message.role === "assistant") {
793
+ const assistantMsg = event.message;
794
+ this._lastAssistantMessage = assistantMsg;
795
+ if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "length") {
796
+ this._overflowRecoveryAttempted = false;
797
+ }
798
+ // Reset retry counter immediately on successful assistant response
799
+ // This prevents accumulation across multiple LLM calls within a turn
800
+ if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
801
+ this._emit({
802
+ type: "auto_retry_end",
803
+ success: true,
804
+ attempt: this._retryAttempt,
805
+ });
806
+ this._retryAttempt = 0;
807
+ }
808
+ }
809
+ }
810
+ // A turn ends after its assistant message and every tool result has been appended,
811
+ // so this is the first point in the run where a context-only custom message can be
812
+ // inserted without landing between a tool call and its result. Flushing after the
813
+ // extension and listener dispatch above also picks up messages that turn_end
814
+ // handlers queued.
815
+ if (event.type === "turn_end") {
816
+ this._flushPendingCustomMessages();
817
+ }
818
+ };
819
+ _willRetryAfterAgentEnd(event) {
820
+ if (this._agentRunAbortRequested)
821
+ return false;
822
+ const settings = this.settingsManager.getRetrySettings();
823
+ if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
824
+ return false;
825
+ }
826
+ for (let i = event.messages.length - 1; i >= 0; i--) {
827
+ const message = event.messages[i];
828
+ if (message.role === "assistant") {
829
+ return this._isRetryableError(message);
830
+ }
831
+ }
832
+ return false;
833
+ }
834
+ _findPersistedMessageEntryId(message) {
835
+ const mapped = this._entryIdsByMessage.get(message);
836
+ if (mapped)
837
+ return mapped;
838
+ for (const entry of [...this.sessionManager.getBranch()].reverse()) {
839
+ if (entry.type === "message" && entry.message === message)
840
+ return entry.id;
841
+ }
842
+ const messageIndex = this.agent.state.messages.indexOf(message);
843
+ if (messageIndex < 0)
844
+ return undefined;
845
+ const projection = this.sessionManager.buildSessionProjection();
846
+ let projectedIndex = 0;
847
+ for (const entry of projection.entries) {
848
+ for (let i = 0; i < entry.messages.length; i++) {
849
+ if (projectedIndex === messageIndex) {
850
+ this._entryIdsByMessage.set(message, entry.sourceEntry.id);
851
+ return entry.sourceEntry.id;
852
+ }
853
+ projectedIndex++;
854
+ }
855
+ }
856
+ return undefined;
857
+ }
858
+ /**
859
+ * Persistently omit a failed attempt and its tool results from model context. Results are
860
+ * found in the projected context, so the pair stays together whether the attempt comes from
861
+ * the current run or a resumed session. An unpaired result fails the next request (#11227).
862
+ */
863
+ _omitRecoveryAttempt(message) {
864
+ const toolCallIds = new Set(message.content.flatMap((block) => (block.type === "toolCall" ? [block.id] : [])));
865
+ // A context edit replaces the projected copy, so match it by source entry as well.
866
+ const entryId = this._findPersistedMessageEntryId(message);
867
+ const messages = this.agent.state.messages;
868
+ const index = messages.findIndex((m) => m === message || (entryId !== undefined && this._entryIdsByMessage.get(m) === entryId));
869
+ const toolResults = [];
870
+ for (const m of index < 0 ? [] : messages.slice(index + 1)) {
871
+ if (m.role === "assistant")
872
+ break;
873
+ if (m.role === "toolResult" && toolCallIds.has(m.toolCallId))
874
+ toolResults.push(m);
875
+ }
876
+ const targets = [message, ...toolResults];
877
+ const targetIds = targets.map((target) => this._findPersistedMessageEntryId(target));
878
+ const unresolvedProjectedTarget = targets.some((target, index) => targetIds[index] === undefined && this.agent.state.messages.includes(target));
879
+ if (unresolvedProjectedTarget) {
880
+ throw new Error("Cannot persist recovery omission because a projected message has no source entry");
881
+ }
882
+ for (const targetId of targetIds) {
883
+ if (!targetId)
884
+ continue;
885
+ const editId = this.sessionManager.appendContextEdit(targetId, null);
886
+ const entry = this.sessionManager.getEntry(editId);
887
+ if (entry)
888
+ this._emit({ type: "entry_appended", entry });
889
+ }
890
+ this._refreshFinalizedContext();
891
+ }
892
+ /** Find the last assistant message in agent state (including aborted ones) */
893
+ _findLastAssistantMessage() {
894
+ const messages = this.agent.state.messages;
895
+ for (let i = messages.length - 1; i >= 0; i--) {
896
+ const msg = messages[i];
897
+ if (msg.role === "assistant") {
898
+ return msg;
899
+ }
900
+ }
901
+ return undefined;
902
+ }
903
+ _replaceMessageInPlace(target, replacement) {
904
+ // Agent-core stores the finalized message object in its state before emitting message_end.
905
+ // SessionManager persistence happens later in _handleAgentEvent() with event.message.
906
+ // Mutating this object in place keeps agent state, later turn/agent events, listeners,
907
+ // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
908
+ if (target === replacement) {
909
+ return;
910
+ }
911
+ const targetRecord = target;
912
+ for (const key of Object.keys(targetRecord)) {
913
+ delete targetRecord[key];
914
+ }
915
+ Object.assign(targetRecord, replacement);
916
+ }
917
+ /** Emit extension events based on agent events */
918
+ async _emitExtensionEvent(event) {
919
+ if (event.type === "agent_start") {
920
+ this._turnIndex = 0;
921
+ await this._extensionRunner.emit({ type: "agent_start" });
922
+ }
923
+ else if (event.type === "agent_end") {
924
+ await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
925
+ }
926
+ else if (event.type === "turn_start") {
927
+ const extensionEvent = {
928
+ type: "turn_start",
929
+ turnIndex: this._turnIndex,
930
+ timestamp: Date.now(),
931
+ };
932
+ await this._extensionRunner.emit(extensionEvent);
933
+ }
934
+ else if (event.type === "turn_end") {
935
+ if (event.message.role === "assistant" && !this._boundaryDispatchedMessages.delete(event.message)) {
936
+ await this._dispatchTurnEndBoundary(event.message, event.toolResults);
937
+ }
938
+ this._turnIndex++;
939
+ }
940
+ else if (event.type === "message_start") {
941
+ const extensionEvent = {
942
+ type: "message_start",
943
+ message: event.message,
944
+ };
945
+ await this._extensionRunner.emit(extensionEvent);
946
+ }
947
+ else if (event.type === "message_update") {
948
+ const extensionEvent = {
949
+ type: "message_update",
950
+ message: event.message,
951
+ assistantMessageEvent: event.assistantMessageEvent,
952
+ };
953
+ await this._extensionRunner.emit(extensionEvent);
954
+ }
955
+ else if (event.type === "message_end") {
956
+ const extensionEvent = {
957
+ type: "message_end",
958
+ message: event.message,
959
+ };
960
+ const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
961
+ if (replacement) {
962
+ // Untyped extension handlers can return messages with null/missing content;
963
+ // normalize so it never enters agent state or session history.
964
+ const normalized = (replacement.role === "user" ||
965
+ replacement.role === "assistant" ||
966
+ replacement.role === "toolResult" ||
967
+ replacement.role === "custom") &&
968
+ replacement.content == null
969
+ ? { ...replacement, content: [] }
970
+ : replacement;
971
+ this._replaceMessageInPlace(event.message, normalized);
972
+ }
973
+ }
974
+ else if (event.type === "tool_execution_start") {
975
+ const extensionEvent = {
976
+ type: "tool_execution_start",
977
+ toolCallId: event.toolCallId,
978
+ toolName: event.toolName,
979
+ args: event.args,
980
+ };
981
+ await this._extensionRunner.emit(extensionEvent);
982
+ }
983
+ else if (event.type === "tool_execution_update") {
984
+ const extensionEvent = {
985
+ type: "tool_execution_update",
986
+ toolCallId: event.toolCallId,
987
+ toolName: event.toolName,
988
+ args: event.args,
989
+ partialResult: event.partialResult,
990
+ };
991
+ await this._extensionRunner.emit(extensionEvent);
992
+ }
993
+ else if (event.type === "tool_execution_end") {
994
+ const extensionEvent = {
995
+ type: "tool_execution_end",
996
+ toolCallId: event.toolCallId,
997
+ toolName: event.toolName,
998
+ result: event.result,
999
+ isError: event.isError,
1000
+ ...(event.durationMs === undefined ? {} : { durationMs: event.durationMs }),
1001
+ };
1002
+ await this._extensionRunner.emit(extensionEvent);
1003
+ }
1004
+ }
1005
+ /**
1006
+ * Subscribe to agent events.
1007
+ * Session persistence is handled internally (saves messages on message_end).
1008
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
1009
+ */
1010
+ subscribe(listener) {
1011
+ this._eventListeners.push(listener);
1012
+ // Return unsubscribe function for this specific listener
1013
+ return () => {
1014
+ const index = this._eventListeners.indexOf(listener);
1015
+ if (index !== -1) {
1016
+ this._eventListeners.splice(index, 1);
1017
+ }
1018
+ };
1019
+ }
1020
+ /** Disconnect from agent events during disposal. */
1021
+ _disconnectFromAgent() {
1022
+ if (this._unsubscribeAgent) {
1023
+ this._unsubscribeAgent();
1024
+ this._unsubscribeAgent = undefined;
1025
+ }
1026
+ }
1027
+ /**
1028
+ * Remove all listeners and disconnect from agent.
1029
+ * Call this when completely done with the session.
1030
+ */
1031
+ dispose() {
1032
+ try {
1033
+ this.abortRetry();
1034
+ this.abortCompaction();
1035
+ this.abortBranchSummary();
1036
+ this.abortBash();
1037
+ this.agent.abort();
1038
+ }
1039
+ catch {
1040
+ // Dispose must succeed even if an abort hook throws.
1041
+ }
1042
+ this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().");
1043
+ this._disconnectFromAgent();
1044
+ this._eventListeners = [];
1045
+ if (this._cacheWarmer) {
1046
+ this._cacheWarmer.onWarmed = undefined;
1047
+ this._cacheWarmer.cancel();
1048
+ }
1049
+ cleanupSessionResources(this.sessionId);
1050
+ }
1051
+ // =========================================================================
1052
+ // Read-only State Access
1053
+ // =========================================================================
1054
+ /** Refresh the public finalized transcript from the canonical session projection. */
1055
+ refreshContext() {
1056
+ this._refreshFinalizedContext();
1057
+ }
1058
+ /** Full agent state */
1059
+ get state() {
1060
+ return this.agent.state;
1061
+ }
1062
+ /** Current cache-warming state and the policy inputs that produced it. */
1063
+ get cacheWarmingStatus() {
1064
+ return this._cacheWarmer?.status;
1065
+ }
1066
+ /** Persist the cache-warming mode and immediately reconcile active warming. */
1067
+ setCacheWarmingMode(mode) {
1068
+ this.settingsManager.setCacheWarmingMode(mode);
1069
+ this._cacheWarmer?.onModeChanged();
1070
+ }
1071
+ /** Current model (may be undefined if not yet selected) */
1072
+ get model() {
1073
+ return this.agent.state.model;
1074
+ }
1075
+ /** Current thinking level */
1076
+ get thinkingLevel() {
1077
+ return this.agent.state.thinkingLevel;
1078
+ }
1079
+ /** Under a virtual selection, the physical model and thinking level of the latest successful response. */
1080
+ get routedModel() {
1081
+ if (!this.model || !isVirtualModel(this.model))
1082
+ return undefined;
1083
+ const latest = findLatestResponse(this.agent.state.messages);
1084
+ const model = latest && this._modelRuntime.getPhysicalModel(latest.provider, latest.model);
1085
+ return model && { model, thinkingLevel: latest?.thinkingLevel };
1086
+ }
1087
+ /** Whether the session is currently processing an agent run or post-run continuation. */
1088
+ get isStreaming() {
1089
+ return this._isAgentRunActive;
1090
+ }
1091
+ /** Whether the session has no active agent run, compaction, branch summary, retry, or queued continuation. */
1092
+ get isIdle() {
1093
+ return !this._isAgentRunActive && !this.isCompacting;
1094
+ }
1095
+ /** Current effective system prompt, including changes not yet sent to the model. */
1096
+ get systemPrompt() {
1097
+ return buildSystemPrompt(this._runSystemPromptOptions ?? this._baseSystemPromptOptions);
1098
+ }
1099
+ /** Current retry attempt (0 if not retrying) */
1100
+ get retryAttempt() {
1101
+ return this._retryAttempt;
1102
+ }
1103
+ /**
1104
+ * Get the names of currently active tools, which are the tools declared to the model.
1105
+ * Tools with `codemode` or `deferred` exposure are callable from other tools without being active.
1106
+ */
1107
+ getActiveToolNames() {
1108
+ return this.agent.state.tools.map((t) => t.name);
1109
+ }
1110
+ /** Get the names of the tools that tools can call through `ctx.executeTool()`. */
1111
+ getCallableToolNames() {
1112
+ return this._getCallableTools().map((t) => t.name);
1113
+ }
1114
+ /**
1115
+ * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
1116
+ */
1117
+ getAllTools() {
1118
+ return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
1119
+ name: definition.name,
1120
+ description: definition.description,
1121
+ parameters: definition.parameters,
1122
+ promptGuidelines: definition.promptGuidelines,
1123
+ exposure: this._getToolExposure(definition.name),
1124
+ ...(definition.namespace ? { namespace: definition.namespace } : {}),
1125
+ ...(definition.annotations ? { annotations: { ...definition.annotations } } : {}),
1126
+ ...(definition.reachesTools ? { reachesTools: definition.reachesTools } : {}),
1127
+ sourceInfo,
1128
+ }));
1129
+ }
1130
+ getToolDefinition(name) {
1131
+ return this._toolDefinitions.get(name)?.definition;
1132
+ }
1133
+ /**
1134
+ * Set active tools by name.
1135
+ * Only tools in the registry can be enabled. Unknown and hidden tool names are ignored.
1136
+ * Also rebuilds the system prompt to reflect the new tool set.
1137
+ * Changes take effect on the next agent turn.
1138
+ */
1139
+ setActiveToolsByName(toolNames) {
1140
+ const previous = this.getActiveToolNames();
1141
+ this._setActiveTools(toolNames);
1142
+ // A loadout that deactivates a tool replaces the restored one, whose pending tools are dropped.
1143
+ // One that only adds tools, like activating tool_search, keeps them.
1144
+ const active = new Set(this.getActiveToolNames());
1145
+ if (previous.some((name) => !active.has(name)))
1146
+ this._pendingToolNames.clear();
1147
+ }
1148
+ _setActiveTools(toolNames) {
1149
+ const tools = this._applyToolLoadout(toolNames);
1150
+ for (const tool of tools)
1151
+ this._pendingToolNames.delete(tool.name);
1152
+ this._rebuildSystemPrompt(tools.map((tool) => tool.name));
1153
+ }
1154
+ /**
1155
+ * Whether `--tools` and `--exclude-tools` keep the tool registered. MCP tools stay registered
1156
+ * unless the allowlist filters them (see `_allowlistFiltersMcp`).
1157
+ */
1158
+ _isAllowedTool(name) {
1159
+ if (this._excludedTools?.(name))
1160
+ return false;
1161
+ if (!this._allowedTools || this._allowedTools(name))
1162
+ return true;
1163
+ return !this._allowlistFiltersMcp && isMcpToolName(name);
1164
+ }
1165
+ /**
1166
+ * Whether the tool may be active, which declares it to the model. MCP tools the allowlist keeps
1167
+ * without matching them are only for codemode and tool_search: they may be declared only when
1168
+ * tool_search can load them (non-`direct` exposure and tool_search registered). This also applies
1169
+ * to tools restored from the transcript or set by extensions.
1170
+ */
1171
+ _isActivatable(name) {
1172
+ if (!this._allowedTools || this._allowedTools(name) || !isMcpToolName(name))
1173
+ return true;
1174
+ return this._getToolExposure(name) !== "direct" && this._toolRegistry.has("tool_search");
1175
+ }
1176
+ _getToolExposure(name) {
1177
+ return this._toolDefinitions.get(name)?.definition.exposure ?? "direct";
1178
+ }
1179
+ /**
1180
+ * Tools callable through `ctx.executeTool()`: the active `direct` tools and every registered
1181
+ * `codemode` or `deferred` tool.
1182
+ */
1183
+ _getCallableTools(active = new Set(this.getActiveToolNames())) {
1184
+ return [...this._toolRegistry.values()].filter((tool) => {
1185
+ const exposure = this._getToolExposure(tool.name);
1186
+ return exposure === "codemode" || exposure === "deferred" || (exposure === "direct" && active.has(tool.name));
1187
+ });
1188
+ }
1189
+ /**
1190
+ * Set the agent's tools for the given active tool names and return them. The active tools are
1191
+ * the registered, non-hidden ones; they are declared to the model. Active tools with a
1192
+ * `prepareLoadout` hook can change the declared descriptions and hide declarations from
1193
+ * requests (see {@link _installHiddenDeclarationsProjection}).
1194
+ *
1195
+ * The active tools are a set: tools that stay active keep their current order and newly active
1196
+ * ones are appended, so reordering the same names does not change the prompt (#11495).
1197
+ */
1198
+ _applyToolLoadout(toolNames) {
1199
+ const requested = new Set(toolNames);
1200
+ const kept = this.getActiveToolNames().filter((name) => requested.has(name));
1201
+ const tools = [...new Set([...kept, ...requested])].flatMap((name) => {
1202
+ const tool = this._toolRegistry.get(name);
1203
+ return tool && this._getToolExposure(name) !== "hidden" && this._isActivatable(name) ? [tool] : [];
1204
+ });
1205
+ const hooks = tools.flatMap((tool) => {
1206
+ const entry = this._toolDefinitions.get(tool.name);
1207
+ return entry?.definition.prepareLoadout ? [entry] : [];
1208
+ });
1209
+ const hidden = new Set();
1210
+ let declared = tools;
1211
+ if (hooks.length > 0) {
1212
+ const loadout = {
1213
+ declared: tools,
1214
+ callable: this._getCallableTools(new Set(tools.map((tool) => tool.name))),
1215
+ registered: [...this._toolRegistry.values()],
1216
+ getExposure: (name) => this._getToolExposure(name),
1217
+ getNamespace: (name) => this._toolDefinitions.get(name)?.definition.namespace,
1218
+ getPromptGuidelines: (name) => this._toolPromptGuidelines.get(name) ?? [],
1219
+ };
1220
+ const descriptions = new Map();
1221
+ for (const { definition, sourceInfo } of hooks) {
1222
+ try {
1223
+ const changes = definition.prepareLoadout?.(loadout);
1224
+ for (const [name, description] of Object.entries(changes?.descriptions ?? {})) {
1225
+ descriptions.set(name, description);
1226
+ }
1227
+ for (const name of changes?.hiddenDeclarations ?? [])
1228
+ hidden.add(name);
1229
+ }
1230
+ catch (error) {
1231
+ this._extensionRunner.emitError({
1232
+ extensionPath: sourceInfo.path,
1233
+ event: "prepare_loadout",
1234
+ error: error instanceof Error ? error.message : String(error),
1235
+ stack: error instanceof Error ? error.stack : undefined,
1236
+ });
1237
+ }
1238
+ }
1239
+ declared = tools.map((tool) => {
1240
+ const description = descriptions.get(tool.name);
1241
+ return description === undefined ? tool : { ...tool, description };
1242
+ });
1243
+ }
1244
+ this._hiddenDeclarations = hidden;
1245
+ this.agent.state.tools = declared;
1246
+ return declared;
1247
+ }
1248
+ /** Whether compaction or branch summarization is currently running */
1249
+ get isCompacting() {
1250
+ return (this._autoCompactionAbortController !== undefined ||
1251
+ this._compactionAbortController !== undefined ||
1252
+ this._branchSummaryAbortController !== undefined);
1253
+ }
1254
+ /** All messages including custom types like BashExecutionMessage */
1255
+ get messages() {
1256
+ return this.agent.state.messages;
1257
+ }
1258
+ /** Current steering mode */
1259
+ get steeringMode() {
1260
+ return this.agent.steeringMode;
1261
+ }
1262
+ /** Current follow-up mode */
1263
+ get followUpMode() {
1264
+ return this.agent.followUpMode;
1265
+ }
1266
+ /** Current session file path, or undefined if sessions are disabled */
1267
+ get sessionFile() {
1268
+ return this.sessionManager.getSessionFile();
1269
+ }
1270
+ /** Current session ID */
1271
+ get sessionId() {
1272
+ return this.sessionManager.getSessionId();
1273
+ }
1274
+ /** Current session display name, if set */
1275
+ get sessionName() {
1276
+ return this.sessionManager.getSessionName();
1277
+ }
1278
+ /** Scoped models for cycling (from --models flag) */
1279
+ get scopedModels() {
1280
+ return this._scopedModels;
1281
+ }
1282
+ /** Update scoped models for cycling */
1283
+ setScopedModels(scopedModels) {
1284
+ this._scopedModels = scopedModels;
1285
+ }
1286
+ /** File-based prompt templates */
1287
+ get promptTemplates() {
1288
+ return this._resourceLoader.getPrompts().prompts;
1289
+ }
1290
+ _normalizePromptSnippet(text) {
1291
+ if (!text)
1292
+ return undefined;
1293
+ const oneLine = text
1294
+ .replace(/[\r\n]+/g, " ")
1295
+ .replace(/\s+/g, " ")
1296
+ .trim();
1297
+ return oneLine.length > 0 ? oneLine : undefined;
1298
+ }
1299
+ _normalizePromptGuidelines(guidelines) {
1300
+ if (!guidelines || guidelines.length === 0) {
1301
+ return [];
1302
+ }
1303
+ const unique = new Set();
1304
+ for (const guideline of guidelines) {
1305
+ const normalized = guideline.trim();
1306
+ if (normalized.length > 0) {
1307
+ unique.add(normalized);
1308
+ }
1309
+ }
1310
+ return Array.from(unique);
1311
+ }
1312
+ _rebuildSystemPrompt(toolNames) {
1313
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
1314
+ const toolSnippets = {};
1315
+ for (const name of this._toolRegistry.keys()) {
1316
+ const snippet = this._toolPromptSnippets.get(name);
1317
+ // Tools without a snippet are not listed.
1318
+ if (snippet)
1319
+ toolSnippets[name] = snippet;
1320
+ }
1321
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
1322
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
1323
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : "";
1324
+ const loadedSkills = this._resourceLoader.getSkills().skills;
1325
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
1326
+ this._baseSystemPromptOptions = normalizeBuildSystemPromptOptions({
1327
+ cwd: this._cwd,
1328
+ skills: loadedSkills,
1329
+ contextFiles: loadedContextFiles,
1330
+ customPrompt: loaderSystemPrompt,
1331
+ appendSystemPrompt,
1332
+ selectedTools: validToolNames,
1333
+ hiddenTools: [...this._hiddenDeclarations],
1334
+ toolSnippets,
1335
+ toolGuidelines: Object.fromEntries(this._toolPromptGuidelines),
1336
+ });
1337
+ }
1338
+ /**
1339
+ * Apply a prompt and tool loadout for the next request. Sets the executable tools and
1340
+ * returns a system message patching the prompt sections the model currently has (replayed
1341
+ * from `messages`), or undefined when the prompt is unchanged. Tool changes are declared by
1342
+ * the agent loop before the request.
1343
+ *
1344
+ * A forced prompt does not affect the transcript: the structured sections are still diffed
1345
+ * and persisted, and the forced text is projected onto the request by
1346
+ * {@link _installAgentForcedPromptProjection}.
1347
+ */
1348
+ _preparePromptAndToolLoadout(options, messages = this.agent.state.messages) {
1349
+ options.selectedTools = this._applyToolLoadout(options.selectedTools).map((tool) => tool.name);
1350
+ // The tool list and rules must match the declarations the request carries.
1351
+ options.hiddenTools = [...this._hiddenDeclarations];
1352
+ const sections = diffSystemPromptSections(getCurrentSystemMessage(messages)?.sections ?? {}, buildSystemPromptSections(options));
1353
+ return sections ? { role: "system", content: "", sections, timestamp: Date.now() } : undefined;
1354
+ }
1355
+ /**
1356
+ * Send a forced prompt as the provider's leading system prompt without recording it.
1357
+ *
1358
+ * A `before_agent_start` handler that returns `systemPrompt` needs that exact text at the
1359
+ * head of the request; a mid-conversation system message would leave the original prompt
1360
+ * in place. The forced text is a rendering of the current prompt, so the transcript keeps
1361
+ * its structured sections and the request is projected instead: the system messages
1362
+ * collapse into one head holding the forced text and the current tools. Runs after the
1363
+ * `context` extension handlers.
1364
+ */
1365
+ /**
1366
+ * Remove the declarations that `prepareLoadout` hooks hide from every request. The whole
1367
+ * transcript is filtered with the current set, so the projected declarations stay consistent
1368
+ * across requests and only change when the loadout does.
1369
+ */
1370
+ _installHiddenDeclarationsProjection() {
1371
+ const previousTransformContext = this.agent.transformContext;
1372
+ this.agent.transformContext = async (messages, signal) => {
1373
+ const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
1374
+ const hidden = this._hiddenDeclarations;
1375
+ if (hidden.size === 0)
1376
+ return transformed;
1377
+ return transformed.map((message) => {
1378
+ if (message.role !== "system" || (!message.toolsAdded && !message.toolsRemoved))
1379
+ return message;
1380
+ const { toolsAdded, toolsRemoved, ...rest } = message;
1381
+ const added = toolsAdded?.filter((tool) => !hidden.has(tool.name)) ?? [];
1382
+ const removed = toolsRemoved?.filter((tool) => !hidden.has(tool.name)) ?? [];
1383
+ return {
1384
+ ...rest,
1385
+ ...(added.length > 0 ? { toolsAdded: added } : {}),
1386
+ ...(removed.length > 0 ? { toolsRemoved: removed } : {}),
1387
+ };
1388
+ });
1389
+ };
1390
+ }
1391
+ _installAgentForcedPromptProjection() {
1392
+ const previousTransformContext = this.agent.transformContext;
1393
+ this.agent.transformContext = async (messages, signal) => {
1394
+ const transformed = previousTransformContext ? await previousTransformContext(messages, signal) : messages;
1395
+ const forced = this._runSystemPromptOptions?.forceSystemPrompt;
1396
+ if (forced === undefined)
1397
+ return transformed;
1398
+ const current = getCurrentSystemMessage(transformed);
1399
+ const head = {
1400
+ role: "system",
1401
+ content: forced,
1402
+ ...(current?.toolsAdded ? { toolsAdded: current.toolsAdded } : {}),
1403
+ timestamp: current?.timestamp ?? Date.now(),
1404
+ };
1405
+ return [head, ...transformed.filter((message) => message.role !== "system")];
1406
+ };
1407
+ }
1408
+ /**
1409
+ * Restore the active tool loadout declared by the session transcript, if it declares one.
1410
+ * Tools reachable only from other tools are never declared, but they do not depend on the active
1411
+ * set, so the transcript's declarations are the whole loadout.
1412
+ * @param modifiers `+name`/`-name` entries applied to the restored loadout.
1413
+ */
1414
+ _restoreToolsFromTranscript(modifiers = []) {
1415
+ this._pendingToolNames.clear();
1416
+ // All system messages on the branch, including those before a compaction. Compaction snapshots
1417
+ // are derived from these, so replaying them gives the current loadout.
1418
+ const systemMessages = this.sessionManager
1419
+ .getBranch()
1420
+ .flatMap((entry) => (entry.type === "message" && entry.message.role === "system" ? [entry.message] : []));
1421
+ // No recorded loadout: keep the current tools.
1422
+ if (systemMessages.length === 0)
1423
+ return;
1424
+ // Tools the branch ever added or removed. Removed tools stay inactive.
1425
+ const mentioned = new Set(systemMessages
1426
+ .flatMap((message) => [...(message.toolsAdded ?? []), ...(message.toolsRemoved ?? [])])
1427
+ .map((tool) => tool.name));
1428
+ // Extension tools the branch never mentioned were registered after it recorded its loadout, so
1429
+ // they are activated like newly registered tools. Built-in tools follow `defaultTools` instead.
1430
+ const newTools = [...this._toolRegistry.keys()].filter((name) => !mentioned.has(name) && !this._baseToolDefinitions.has(name) && this._isActivatedOnRegistration(name));
1431
+ // The recorded loadout plus the new tools, with `--tools +name`/`-name` applied.
1432
+ const names = applyToolModifiers([...getCurrentTools(systemMessages).map((tool) => tool.name), ...newTools], modifiers);
1433
+ // Recorded tools that are not registered yet, such as MCP tools of servers still connecting, are
1434
+ // activated when they register. Excluded tools never register, so they are not kept pending.
1435
+ this._pendingToolNames = new Set(names.filter((name) => this._isAllowedTool(name)));
1436
+ // Ignores names that are not registered.
1437
+ this._setActiveTools(names);
1438
+ }
1439
+ // =========================================================================
1440
+ // Prompting
1441
+ // =========================================================================
1442
+ /**
1443
+ * Start a run from a user or custom message. The session counts as busy from here on, so
1444
+ * messages sent while before_agent_start handlers run are queued into this run instead of
1445
+ * starting another, and an abort requested meanwhile aborts the run as soon as it exists.
1446
+ * @param onStarted Called once the run's messages are prepared, before the first request.
1447
+ */
1448
+ async _startRun(trigger, onStarted) {
1449
+ this._isAgentRunActive = true;
1450
+ this._agentRunAbortRequested = false;
1451
+ let messages;
1452
+ try {
1453
+ messages = await this._prepareRun(trigger);
1454
+ }
1455
+ catch (error) {
1456
+ this._isAgentRunActive = false;
1457
+ this._flushPendingBashMessages();
1458
+ this._flushPendingCustomMessages();
1459
+ this._resolveIdleWaitIfIdle();
1460
+ throw error;
1461
+ }
1462
+ // Messages held while the run was starting go before its starting messages, as they would
1463
+ // have while idle. No run exists yet, so they cannot split a tool call from its result.
1464
+ this._flushPendingBashMessages();
1465
+ this._flushPendingCustomMessages();
1466
+ onStarted?.();
1467
+ // Compaction before the prompt may have scheduled a retry; the new prompt replaces it.
1468
+ this._failedResponse = undefined;
1469
+ this._recordSelection();
1470
+ // The run records the loadout in the transcript; restored tools that did not register by now
1471
+ // are dropped, so a tool that never registers does not stay pending.
1472
+ this._pendingToolNames.clear();
1473
+ try {
1474
+ await this.agent.prompt(messages);
1475
+ while (!this._agentRunAbortRequested) {
1476
+ if (await this._handlePostAgentRun()) {
1477
+ if (this._agentRunAbortRequested)
1478
+ break;
1479
+ await this.agent.continue();
1480
+ continue;
1481
+ }
1482
+ if (this._agentRunAbortRequested || !(await this._runBeforeSettleBoundary()))
1483
+ break;
1484
+ if (this._agentRunAbortRequested)
1485
+ break;
1486
+ await this.agent.continue();
1487
+ }
1488
+ }
1489
+ finally {
1490
+ if (this._agentRunAbortRequested)
1491
+ this._finishCancelledRetry();
1492
+ this._failedResponse = undefined;
1493
+ this._runSystemPromptOptions = undefined;
1494
+ this._flushPendingBashMessages();
1495
+ this._flushPendingCustomMessages();
1496
+ await this._emitAgentSettled();
1497
+ }
1498
+ }
1499
+ /**
1500
+ * Prepare a run and return its starting messages: compact first when needed, emit
1501
+ * before_agent_start, apply the run's prompt options and tool loadout, and build the starting
1502
+ * message followed by pending nextTurn messages (consumed here) and handler messages, with a
1503
+ * system patch first when the prompt changed.
1504
+ */
1505
+ async _prepareRun(trigger) {
1506
+ // Check if we need to compact before sending (catches aborted responses).
1507
+ // The starting message is sent below, so do not call agent.continue() here.
1508
+ const lastAssistant = this._findLastAssistantMessage();
1509
+ if (lastAssistant) {
1510
+ await this._checkCompaction(lastAssistant, false);
1511
+ }
1512
+ const selectedToolsBefore = this._baseSystemPromptOptions.selectedTools;
1513
+ const result = await this._extensionRunner.emitBeforeAgentStart(trigger, this._baseSystemPromptOptions);
1514
+ // Handlers may edit event.systemPromptOptions.selectedTools or call setActiveTools(),
1515
+ // which updates the live loadout instead. An explicit edit wins; otherwise the live
1516
+ // loadout is authoritative, so a setActiveTools() call is not undone here.
1517
+ const handlerEditedTools = result.systemPromptOptions.selectedTools.length !== selectedToolsBefore.length ||
1518
+ result.systemPromptOptions.selectedTools.some((name, index) => name !== selectedToolsBefore[index]);
1519
+ if (!handlerEditedTools)
1520
+ result.systemPromptOptions.selectedTools = this.getActiveToolNames();
1521
+ const messages = [];
1522
+ if (trigger.messageType === "custom") {
1523
+ messages.push(trigger.message);
1524
+ }
1525
+ else {
1526
+ // Normalize images after before_agent_start so extension-driven model selection
1527
+ // determines the resize profile used for the request and history.
1528
+ const normalized = await this._normalizePromptImages(trigger.images);
1529
+ const text = normalized.hints.length > 0 ? `${trigger.prompt}\n\n${normalized.hints.join("\n")}` : trigger.prompt;
1530
+ messages.push({
1531
+ role: "user",
1532
+ content: [{ type: "text", text }, ...normalized.images],
1533
+ timestamp: Date.now(),
1534
+ });
1535
+ }
1536
+ // Inject any pending "nextTurn" messages as context alongside the starting message
1537
+ messages.push(...this._pendingNextTurnMessages);
1538
+ this._pendingNextTurnMessages = [];
1539
+ for (const msg of result.messages) {
1540
+ messages.push({
1541
+ role: "custom",
1542
+ customType: msg.customType,
1543
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1544
+ content: msg.content ?? [],
1545
+ display: msg.display,
1546
+ details: msg.details,
1547
+ timestamp: Date.now(),
1548
+ });
1549
+ }
1550
+ const updateMessage = this._preparePromptAndToolLoadout(result.systemPromptOptions);
1551
+ this._runSystemPromptOptions = result.systemPromptOptions;
1552
+ if (updateMessage)
1553
+ messages.unshift(updateMessage);
1554
+ return messages;
1555
+ }
1556
+ async _handlePostAgentRun() {
1557
+ const message = this._lastAssistantMessage;
1558
+ this._lastAssistantMessage = undefined;
1559
+ if (this._agentRunAbortRequested) {
1560
+ this._finishCancelledRetry();
1561
+ return false;
1562
+ }
1563
+ if (!message)
1564
+ return this.agent.hasQueuedMessages();
1565
+ if (this._isRetryableError(message) && (await this._prepareRetry(message))) {
1566
+ if (this._agentRunAbortRequested)
1567
+ this._finishCancelledRetry();
1568
+ this._failedResponse = message;
1569
+ return !this._agentRunAbortRequested;
1570
+ }
1571
+ if (this._agentRunAbortRequested) {
1572
+ this._finishCancelledRetry();
1573
+ return false;
1574
+ }
1575
+ if (message.stopReason === "error" && this._retryAttempt > 0) {
1576
+ this._emit({
1577
+ type: "auto_retry_end",
1578
+ success: false,
1579
+ attempt: this._retryAttempt,
1580
+ finalError: message.errorMessage,
1581
+ });
1582
+ this._retryAttempt = 0;
1583
+ }
1584
+ if (await this._checkCompaction(message)) {
1585
+ return !this._agentRunAbortRequested;
1586
+ }
1587
+ // The low-level loop drains both queues before agent_end. Messages queued by
1588
+ // agent_end handlers require a fresh run before pre-settlement handlers fire.
1589
+ return !this._agentRunAbortRequested && this.agent.hasQueuedMessages();
1590
+ }
1591
+ async _runBeforeSettleBoundary() {
1592
+ if (!this._extensionRunner.hasHandlers("agent_before_settle"))
1593
+ return this.agent.hasQueuedMessages();
1594
+ this._isBeforeSettle = true;
1595
+ this._abortDuringBeforeSettle = false;
1596
+ try {
1597
+ const result = await this._extensionRunner.emitBoundary({ type: "agent_before_settle", outcome: this._lastActivityOutcome }, (entries) => this._buildBoundaryContext(entries, "agent_before_settle"));
1598
+ this._commitBoundaryDrafts(result.entries);
1599
+ this._flushPendingCustomMessages();
1600
+ const finalContext = this._buildBoundaryContext([], "agent_before_settle");
1601
+ if (this._abortDuringBeforeSettle)
1602
+ return false;
1603
+ const shouldContinue = result.continue || this.agent.hasQueuedMessages();
1604
+ if (shouldContinue && !finalContext.canContinue) {
1605
+ if (result.continue)
1606
+ this._reportInvalidBoundaryContinuation("agent_before_settle");
1607
+ return false;
1608
+ }
1609
+ return shouldContinue;
1610
+ }
1611
+ finally {
1612
+ this._isBeforeSettle = false;
1613
+ }
1614
+ }
1615
+ async _runInputHandlers(text, images, source, streamingBehavior) {
1616
+ if (!this._extensionRunner.hasHandlers("input")) {
1617
+ return { text, images };
1618
+ }
1619
+ const inputResult = await this._extensionRunner.emitInput(text, images, source, streamingBehavior);
1620
+ if (inputResult.action === "handled") {
1621
+ return undefined;
1622
+ }
1623
+ if (inputResult.action === "transform") {
1624
+ return { text: inputResult.text, images: inputResult.images ?? images };
1625
+ }
1626
+ return { text, images };
1627
+ }
1628
+ async _normalizePromptImages(images) {
1629
+ if (!images)
1630
+ return { images: [], hints: [] };
1631
+ const normalizedImages = [];
1632
+ const hints = [];
1633
+ for (const image of images) {
1634
+ const processed = await processImage(Buffer.from(image.data, "base64"), image.mimeType, {
1635
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
1636
+ resizeOptions: this._limitsModel()?.inputLimits?.images?.resize,
1637
+ });
1638
+ if (!processed.ok) {
1639
+ hints.push(processed.message);
1640
+ continue;
1641
+ }
1642
+ normalizedImages.push({ type: "image", data: processed.data, mimeType: processed.mimeType });
1643
+ hints.push(...processed.hints);
1644
+ }
1645
+ return { images: normalizedImages, hints };
1646
+ }
1647
+ /**
1648
+ * Send a prompt to the agent.
1649
+ * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
1650
+ * - Expands file-based prompt templates by default
1651
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
1652
+ * - Validates model and API key before sending (when not streaming)
1653
+ * @throws Error if streaming and no streamingBehavior specified
1654
+ * @throws Error if no model selected or no API key available (when not streaming)
1655
+ */
1656
+ async prompt(text, options) {
1657
+ if (this._isEmittingAgentSettled) {
1658
+ this._deferredSettledActions.push(async () => await this.prompt(text, options));
1659
+ return;
1660
+ }
1661
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
1662
+ const preflightResult = options?.preflightResult;
1663
+ // Handle extension commands first (execute immediately, even during streaming)
1664
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
1665
+ if (expandPromptTemplates && text.startsWith("/")) {
1666
+ const handled = await this._tryExecuteExtensionCommand(text);
1667
+ if (handled) {
1668
+ // Extension command executed, no prompt to send
1669
+ preflightResult?.("handled");
1670
+ return;
1671
+ }
1672
+ }
1673
+ if (this._compactionAbortController !== undefined || this._branchSummaryAbortController !== undefined) {
1674
+ throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
1675
+ }
1676
+ // Reserve the context through async input hooks and auth checks so tree navigation cannot
1677
+ // start meanwhile (#9154). _startRun marks the run active synchronously, so there is no gap.
1678
+ this._promptPreflightCount++;
1679
+ let trigger;
1680
+ try {
1681
+ trigger = await this._preparePrompt(text, options);
1682
+ }
1683
+ finally {
1684
+ this._promptPreflightCount--;
1685
+ }
1686
+ if (trigger)
1687
+ await this._startRun(trigger, () => preflightResult?.("started"));
1688
+ }
1689
+ /**
1690
+ * Run input hooks, expand templates, queue while streaming, and validate model and auth.
1691
+ * Returns the run trigger, or undefined when the prompt was handled or queued.
1692
+ */
1693
+ async _preparePrompt(text, options) {
1694
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
1695
+ const preflightResult = options?.preflightResult;
1696
+ // Emit input event for extension interception (before skill/template expansion)
1697
+ const processedInput = await this._runInputHandlers(text, options?.images, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
1698
+ if (!processedInput) {
1699
+ preflightResult?.("handled");
1700
+ return undefined;
1701
+ }
1702
+ const { text: currentText, images: currentImages } = processedInput;
1703
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
1704
+ let expandedText = currentText;
1705
+ if (expandPromptTemplates) {
1706
+ expandedText = this._expandSkillCommand(expandedText);
1707
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1708
+ }
1709
+ // If streaming, queue via steer() or followUp() based on option
1710
+ if (this.isStreaming) {
1711
+ if (!options?.streamingBehavior) {
1712
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
1713
+ }
1714
+ if (options.streamingBehavior === "followUp") {
1715
+ await this._queueFollowUp(expandedText, currentImages);
1716
+ }
1717
+ else {
1718
+ await this._queueSteer(expandedText, currentImages);
1719
+ }
1720
+ preflightResult?.("queued");
1721
+ return undefined;
1722
+ }
1723
+ // Validate model
1724
+ if (!this.model) {
1725
+ throw new Error(formatNoModelSelectedMessage());
1726
+ }
1727
+ const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
1728
+ (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
1729
+ if (!hasConfiguredAuth) {
1730
+ const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
1731
+ if (isOAuth) {
1732
+ throw new Error(`Authentication failed for "${this.model.provider}". ` +
1733
+ `Credentials may have expired or network is unavailable. ` +
1734
+ `Run '/login ${this.model.provider}' to re-authenticate.`);
1735
+ }
1736
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
1737
+ }
1738
+ return { messageType: "user", prompt: expandedText, images: currentImages };
1739
+ }
1740
+ /**
1741
+ * Try to execute an extension command. Returns true if command was found and executed.
1742
+ */
1743
+ async _tryExecuteExtensionCommand(text) {
1744
+ // Parse command name and args
1745
+ const spaceIndex = text.indexOf(" ");
1746
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1747
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
1748
+ const command = this._extensionRunner.getCommand(commandName);
1749
+ if (!command)
1750
+ return false;
1751
+ // Get command context from extension runner (includes session control methods)
1752
+ const ctx = this._extensionRunner.createCommandContext();
1753
+ try {
1754
+ await command.handler(args, ctx);
1755
+ return true;
1756
+ }
1757
+ catch (err) {
1758
+ // Emit error via extension runner
1759
+ this._extensionRunner.emitError({
1760
+ extensionPath: `command:${commandName}`,
1761
+ event: "command",
1762
+ error: err instanceof Error ? err.message : String(err),
1763
+ });
1764
+ return true;
1765
+ }
1766
+ }
1767
+ /**
1768
+ * Expand skill commands (/skill:name args) to their full content.
1769
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
1770
+ * Emits errors via extension runner if file read fails.
1771
+ */
1772
+ _expandSkillCommand(text) {
1773
+ if (!text.startsWith("/skill:"))
1774
+ return text;
1775
+ const spaceIndex = text.indexOf(" ");
1776
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
1777
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
1778
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
1779
+ if (!skill)
1780
+ return text; // Unknown skill, pass through
1781
+ try {
1782
+ const content = readFileSync(skill.filePath, "utf-8");
1783
+ const body = stripFrontmatter(content).trim();
1784
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
1785
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
1786
+ }
1787
+ catch (err) {
1788
+ // Emit error like extension commands do
1789
+ this._extensionRunner.emitError({
1790
+ extensionPath: skill.filePath,
1791
+ event: "skill_expansion",
1792
+ error: err instanceof Error ? err.message : String(err),
1793
+ });
1794
+ return text; // Return original on error
1795
+ }
1796
+ }
1797
+ async _queueUserInput(text, images, behavior, source) {
1798
+ if (text.startsWith("/")) {
1799
+ this._throwIfExtensionCommand(text);
1800
+ }
1801
+ const processedInput = await this._runInputHandlers(text, images, source, this.isStreaming ? behavior : undefined);
1802
+ if (!processedInput)
1803
+ return "handled";
1804
+ let expandedText = this._expandSkillCommand(processedInput.text);
1805
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1806
+ if (behavior === "steer") {
1807
+ await this._queueSteer(expandedText, processedInput.images);
1808
+ }
1809
+ else {
1810
+ await this._queueFollowUp(expandedText, processedInput.images);
1811
+ }
1812
+ return "queued";
1813
+ }
1814
+ /**
1815
+ * Queue a steering message while the agent is running.
1816
+ * Delivered after the current assistant turn finishes executing its tool calls,
1817
+ * before the next LLM call.
1818
+ * Expands skill commands and prompt templates. Errors on extension commands.
1819
+ * @param images Optional image attachments to include with the message
1820
+ * @param options Input source; defaults to interactive
1821
+ * @throws Error if text is an extension command
1822
+ */
1823
+ async steer(text, images, options) {
1824
+ return this._queueUserInput(text, images, "steer", options?.source ?? "interactive");
1825
+ }
1826
+ /**
1827
+ * Queue a follow-up message to be processed after the agent finishes.
1828
+ * Delivered only when agent has no more tool calls or steering messages.
1829
+ * Expands skill commands and prompt templates. Errors on extension commands.
1830
+ * @param images Optional image attachments to include with the message
1831
+ * @param options Input source; defaults to interactive
1832
+ * @throws Error if text is an extension command
1833
+ */
1834
+ async followUp(text, images, options) {
1835
+ return this._queueUserInput(text, images, "followUp", options?.source ?? "interactive");
1836
+ }
1837
+ /**
1838
+ * Internal: Queue a steering message (already expanded, no extension command check).
1839
+ */
1840
+ async _queueSteer(text, images) {
1841
+ this._steeringMessages.push(text);
1842
+ this._emitQueueUpdate();
1843
+ const content = [{ type: "text", text }];
1844
+ if (images) {
1845
+ content.push(...images);
1846
+ }
1847
+ const message = { role: "user", content, timestamp: Date.now() };
1848
+ if (images?.length)
1849
+ this._queuedMessagesWithImages.add(message);
1850
+ this.agent.steer(message);
1851
+ }
1852
+ /**
1853
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
1854
+ */
1855
+ async _queueFollowUp(text, images) {
1856
+ this._followUpMessages.push(text);
1857
+ this._emitQueueUpdate();
1858
+ const content = [{ type: "text", text }];
1859
+ if (images) {
1860
+ content.push(...images);
1861
+ }
1862
+ const message = { role: "user", content, timestamp: Date.now() };
1863
+ if (images?.length)
1864
+ this._queuedMessagesWithImages.add(message);
1865
+ this.agent.followUp(message);
1866
+ }
1867
+ /** Replace a queued user message's images in place with normalized ones, appending hints to its text. */
1868
+ async _normalizeQueuedMessageImages(message) {
1869
+ if (typeof message.content === "string")
1870
+ return;
1871
+ const [first, ...rest] = message.content;
1872
+ if (first?.type !== "text")
1873
+ return;
1874
+ const images = rest.filter((block) => block.type === "image");
1875
+ const normalized = await this._normalizePromptImages(images);
1876
+ const text = normalized.hints.length > 0 ? `${first.text}\n\n${normalized.hints.join("\n")}` : first.text;
1877
+ message.content = [
1878
+ { type: "text", text },
1879
+ ...rest.filter((block) => block.type !== "image"),
1880
+ ...normalized.images,
1881
+ ];
1882
+ }
1883
+ /**
1884
+ * Throw an error if the text is an extension command.
1885
+ */
1886
+ _throwIfExtensionCommand(text) {
1887
+ const spaceIndex = text.indexOf(" ");
1888
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1889
+ const command = this._extensionRunner.getCommand(commandName);
1890
+ if (command) {
1891
+ throw new Error(`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
1892
+ }
1893
+ }
1894
+ /**
1895
+ * Send a custom message to the session. Creates a CustomMessageEntry.
1896
+ *
1897
+ * Handles four cases:
1898
+ * - Streaming: queues message, processed when loop pulls from queue
1899
+ * - Streaming + triggerTurn false: appended to state/session once the current turn ends
1900
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
1901
+ * - Not streaming + no trigger: appends to state/session, no turn
1902
+ *
1903
+ * @param message Custom message with customType, content, display, details
1904
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
1905
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
1906
+ */
1907
+ async sendCustomMessage(message, options) {
1908
+ const appMessage = {
1909
+ role: "custom",
1910
+ customType: message.customType,
1911
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1912
+ content: message.content ?? [],
1913
+ display: message.display,
1914
+ details: message.details,
1915
+ timestamp: Date.now(),
1916
+ };
1917
+ if (options?.deliverAs === "nextTurn") {
1918
+ this._pendingNextTurnMessages.push(appMessage);
1919
+ }
1920
+ else if (this.isStreaming && options?.triggerTurn !== false) {
1921
+ if (options?.deliverAs === "followUp") {
1922
+ this.agent.followUp(appMessage);
1923
+ }
1924
+ else {
1925
+ this.agent.steer(appMessage);
1926
+ }
1927
+ }
1928
+ else if (options?.triggerTurn) {
1929
+ if (this._isEmittingAgentSettled) {
1930
+ this._deferredSettledActions.push(async () => await this.sendCustomMessage(message, options));
1931
+ return;
1932
+ }
1933
+ await this._startRun({ messageType: "custom", message: appMessage });
1934
+ }
1935
+ else if (this.isStreaming) {
1936
+ // Appending now would put the message between an assistant tool call and its
1937
+ // result, which providers that validate message order reject on replay. Defer
1938
+ // to the end of the turn. Nothing is emitted yet: message events must not
1939
+ // describe messages the session tree does not contain.
1940
+ this._pendingCustomMessages.push(appMessage);
1941
+ }
1942
+ else {
1943
+ this._appendCustomMessage(appMessage);
1944
+ }
1945
+ }
1946
+ _appendCustomMessage(appMessage) {
1947
+ this.sessionManager.appendCustomMessageEntry(appMessage.customType, appMessage.content, appMessage.display, appMessage.details);
1948
+ this._refreshFinalizedContext();
1949
+ this._emit({ type: "message_start", message: appMessage });
1950
+ this._emit({ type: "message_end", message: appMessage });
1951
+ }
1952
+ /**
1953
+ * Append custom messages queued while the agent was running.
1954
+ * Called once the current turn's tool results are in agent state and session history.
1955
+ */
1956
+ _flushPendingCustomMessages() {
1957
+ if (this._pendingCustomMessages.length === 0)
1958
+ return;
1959
+ const pending = this._pendingCustomMessages;
1960
+ this._pendingCustomMessages = [];
1961
+ for (const appMessage of pending) {
1962
+ this._appendCustomMessage(appMessage);
1963
+ }
1964
+ }
1965
+ /**
1966
+ * Send a user message to the agent. Always triggers a turn.
1967
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
1968
+ *
1969
+ * @param content User message content (string or content array)
1970
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
1971
+ * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.
1972
+ */
1973
+ async sendUserMessage(content, options) {
1974
+ // Normalize content to text string + optional images
1975
+ let text;
1976
+ let images;
1977
+ if (typeof content === "string") {
1978
+ text = content;
1979
+ }
1980
+ else {
1981
+ const textParts = [];
1982
+ images = [];
1983
+ for (const part of content) {
1984
+ if (part.type === "text") {
1985
+ textParts.push(part.text);
1986
+ }
1987
+ else {
1988
+ images.push(part);
1989
+ }
1990
+ }
1991
+ text = textParts.join("\n");
1992
+ if (images.length === 0)
1993
+ images = undefined;
1994
+ }
1995
+ await this.prompt(text, {
1996
+ expandPromptTemplates: options?.expandPromptTemplates ?? false,
1997
+ streamingBehavior: options?.deliverAs,
1998
+ images,
1999
+ source: "extension",
2000
+ });
2001
+ }
2002
+ /**
2003
+ * Clear all queued messages and return them.
2004
+ * Useful for restoring to editor when user aborts.
2005
+ * @returns Object with steering and followUp arrays
2006
+ */
2007
+ clearQueue() {
2008
+ const steering = [...this._steeringMessages];
2009
+ const followUp = [...this._followUpMessages];
2010
+ this._steeringMessages = [];
2011
+ this._followUpMessages = [];
2012
+ this.agent.clearAllQueues();
2013
+ this._emitQueueUpdate();
2014
+ return { steering, followUp };
2015
+ }
2016
+ /** Number of pending messages (includes both steering and follow-up) */
2017
+ get pendingMessageCount() {
2018
+ return this._steeringMessages.length + this._followUpMessages.length;
2019
+ }
2020
+ /** Get pending steering messages (read-only) */
2021
+ getSteeringMessages() {
2022
+ return this._steeringMessages;
2023
+ }
2024
+ /** Get pending follow-up messages (read-only) */
2025
+ getFollowUpMessages() {
2026
+ return this._followUpMessages;
2027
+ }
2028
+ get resourceLoader() {
2029
+ return this._resourceLoader;
2030
+ }
2031
+ /**
2032
+ * Abort current operation and wait for agent to become idle.
2033
+ */
2034
+ async abort() {
2035
+ if (this._isAgentRunActive) {
2036
+ this._agentRunAbortRequested = true;
2037
+ }
2038
+ this.abortRetry();
2039
+ this.abortCompaction();
2040
+ this.abortBranchSummary();
2041
+ if (this._isBeforeSettle)
2042
+ this._abortDuringBeforeSettle = true;
2043
+ this.agent.abort();
2044
+ await this.waitForIdle();
2045
+ }
2046
+ async waitForIdle() {
2047
+ if (this.isIdle) {
2048
+ return;
2049
+ }
2050
+ await this._getIdleWaitPromise();
2051
+ }
2052
+ // =========================================================================
2053
+ // Model Management
2054
+ // =========================================================================
2055
+ async _emitModelSelect(nextModel, previousModel, source) {
2056
+ if (modelsAreEqual(previousModel, nextModel))
2057
+ return;
2058
+ await this._extensionRunner.emit({
2059
+ type: "model_select",
2060
+ model: nextModel,
2061
+ previousModel,
2062
+ source,
2063
+ });
2064
+ }
2065
+ /**
2066
+ * Set model directly.
2067
+ * Validates that auth is configured and saves to the session transcript.
2068
+ * Persists to global defaults only when options.persist is true.
2069
+ * @throws Error if no auth is configured for the model
2070
+ */
2071
+ async setModel(model, options = {}) {
2072
+ if (!(await this._modelRuntime.checkAuth(model.provider))) {
2073
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
2074
+ }
2075
+ const previousModel = this.model;
2076
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(model);
2077
+ this.agent.state.model = model;
2078
+ this.sessionManager.appendModelChange(model.provider, model.id);
2079
+ if (options.persist) {
2080
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
2081
+ this._addPersistedDefaultToNonEmptyScope(model);
2082
+ }
2083
+ // Apply thinking level for the new model.
2084
+ // Per-model thinking level overrides take priority over the global default.
2085
+ // Model persistence does not implicitly rewrite the global thinking default.
2086
+ this.setThinkingLevel(thinkingLevel);
2087
+ await this._emitModelSelect(model, previousModel, "set");
2088
+ }
2089
+ _addPersistedDefaultToNonEmptyScope(model) {
2090
+ if (this._scopedModels.length === 0)
2091
+ return;
2092
+ if (this._scopedModels.some((scoped) => modelsAreEqual(scoped.model, model)))
2093
+ return;
2094
+ this._scopedModels = [...this._scopedModels, { model }];
2095
+ const enabledModels = this.settingsManager.getEnabledModels();
2096
+ if (!enabledModels?.length)
2097
+ return;
2098
+ const modelReference = `${model.provider}/${model.id}`;
2099
+ if (enabledModels.some((pattern) => pattern.toLowerCase() === modelReference.toLowerCase()))
2100
+ return;
2101
+ this.settingsManager.setEnabledModels([...enabledModels, modelReference]);
2102
+ }
2103
+ /**
2104
+ * Cycle to next/previous model.
2105
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
2106
+ * @param direction - "forward" (default) or "backward"
2107
+ * @returns The new model info, or undefined if only one model available
2108
+ */
2109
+ async cycleModel(direction = "forward", options = {}) {
2110
+ if (this._scopedModels.length > 0) {
2111
+ return this._cycleScopedModel(direction, options);
2112
+ }
2113
+ return this._cycleAvailableModel(direction, options);
2114
+ }
2115
+ async _cycleScopedModel(direction, options) {
2116
+ const availableIds = new Set(this._modelRuntime.getAvailableSnapshot().map((model) => `${model.provider}\0${model.id}`));
2117
+ const scopedModels = this._scopedModels.filter((scoped) => availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`));
2118
+ if (scopedModels.length <= 1)
2119
+ return undefined;
2120
+ const currentModel = this.model;
2121
+ let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
2122
+ if (currentIndex === -1)
2123
+ currentIndex = 0;
2124
+ const len = scopedModels.length;
2125
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
2126
+ const next = scopedModels[nextIndex];
2127
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.model, next.thinkingLevel);
2128
+ // Apply model
2129
+ this.agent.state.model = next.model;
2130
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id);
2131
+ if (options.persist) {
2132
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
2133
+ this._addPersistedDefaultToNonEmptyScope(next.model);
2134
+ }
2135
+ // Apply thinking level for the new model.
2136
+ // - Explicit scoped model thinking level overrides defaults
2137
+ // - Per-model thinking level overrides take priority over the global default
2138
+ // setThinkingLevel clamps to model capabilities.
2139
+ // Model persistence does not implicitly rewrite the global thinking default.
2140
+ this.setThinkingLevel(thinkingLevel);
2141
+ await this._emitModelSelect(next.model, currentModel, "cycle");
2142
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
2143
+ }
2144
+ async _cycleAvailableModel(direction, options) {
2145
+ const availableModels = this._modelRuntime.getAvailableSnapshot();
2146
+ if (availableModels.length <= 1)
2147
+ return undefined;
2148
+ const currentModel = this.model;
2149
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
2150
+ if (currentIndex === -1)
2151
+ currentIndex = 0;
2152
+ const len = availableModels.length;
2153
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
2154
+ const nextModel = availableModels[nextIndex];
2155
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(nextModel);
2156
+ this.agent.state.model = nextModel;
2157
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
2158
+ if (options.persist) {
2159
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
2160
+ this._addPersistedDefaultToNonEmptyScope(nextModel);
2161
+ }
2162
+ // Apply thinking level for the new model.
2163
+ // Model persistence does not implicitly rewrite the global thinking default.
2164
+ this.setThinkingLevel(thinkingLevel);
2165
+ await this._emitModelSelect(nextModel, currentModel, "cycle");
2166
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
2167
+ }
2168
+ // =========================================================================
2169
+ // Thinking Level Management
2170
+ // =========================================================================
2171
+ /**
2172
+ * Set thinking level.
2173
+ * Clamps to model capabilities based on available thinking levels.
2174
+ * Saves the clamped level to the session transcript only if the level actually changes.
2175
+ * Persists the requested level to global defaults only when options.persist is true.
2176
+ */
2177
+ setThinkingLevel(level, options = {}) {
2178
+ const availableLevels = this.getAvailableThinkingLevels();
2179
+ const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
2180
+ // Only persist if actually changing
2181
+ const previousLevel = this.agent.state.thinkingLevel;
2182
+ const isChanging = effectiveLevel !== previousLevel;
2183
+ this.agent.state.thinkingLevel = effectiveLevel;
2184
+ if (options.persist) {
2185
+ this.settingsManager.setDefaultThinkingLevel(level);
2186
+ }
2187
+ if (isChanging) {
2188
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
2189
+ this._emit({ type: "thinking_level_changed", level: effectiveLevel });
2190
+ void this._extensionRunner.emit({
2191
+ type: "thinking_level_select",
2192
+ level: effectiveLevel,
2193
+ previousLevel,
2194
+ });
2195
+ }
2196
+ }
2197
+ /**
2198
+ * Cycle to next thinking level.
2199
+ * @returns New level, or undefined if model doesn't support thinking
2200
+ */
2201
+ cycleThinkingLevel(options = {}) {
2202
+ if (!this.supportsThinking())
2203
+ return undefined;
2204
+ const levels = this.getAvailableThinkingLevels();
2205
+ const currentIndex = levels.indexOf(this.thinkingLevel);
2206
+ const nextIndex = (currentIndex + 1) % levels.length;
2207
+ const nextLevel = levels[nextIndex];
2208
+ this.setThinkingLevel(nextLevel, options);
2209
+ return nextLevel;
2210
+ }
2211
+ /**
2212
+ * Get available thinking levels for current model.
2213
+ * The provider will clamp to what the specific model supports internally.
2214
+ */
2215
+ getAvailableThinkingLevels() {
2216
+ if (!this.model)
2217
+ return [...THINKING_LEVEL_OPTIONS];
2218
+ return getSupportedThinkingLevels(this.model);
2219
+ }
2220
+ /**
2221
+ * Check if current model supports thinking/reasoning.
2222
+ */
2223
+ supportsThinking() {
2224
+ return !!this.model?.reasoning;
2225
+ }
2226
+ _getThinkingLevelForModelSwitch(targetModel, explicitLevel) {
2227
+ if (explicitLevel !== undefined) {
2228
+ return explicitLevel;
2229
+ }
2230
+ // Per-model default takes priority when switching to a model that has one
2231
+ if (targetModel) {
2232
+ const perModel = this.settingsManager.getModelThinkingLevel(targetModel.provider, targetModel.id);
2233
+ if (perModel !== undefined) {
2234
+ return perModel;
2235
+ }
2236
+ }
2237
+ return this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
2238
+ }
2239
+ _clampThinkingLevel(level, _availableLevels) {
2240
+ return this.model ? clampThinkingLevel(this.model, level) : "off";
2241
+ }
2242
+ // =========================================================================
2243
+ // Queue Mode Management
2244
+ // =========================================================================
2245
+ syncQueueModesFromSettings() {
2246
+ this.agent.steeringMode = this.settingsManager.getSteeringMode();
2247
+ this.agent.followUpMode = this.settingsManager.getFollowUpMode();
2248
+ }
2249
+ /**
2250
+ * Set steering message mode.
2251
+ * Saves to settings.
2252
+ */
2253
+ setSteeringMode(mode) {
2254
+ this.agent.steeringMode = mode;
2255
+ this.settingsManager.setSteeringMode(mode);
2256
+ }
2257
+ /**
2258
+ * Set follow-up message mode.
2259
+ * Saves to settings.
2260
+ */
2261
+ setFollowUpMode(mode) {
2262
+ this.agent.followUpMode = mode;
2263
+ this.settingsManager.setFollowUpMode(mode);
2264
+ }
2265
+ // =========================================================================
2266
+ // Compaction
2267
+ // =========================================================================
2268
+ /** Generate Pi's built-in compaction summary for manual and automatic compaction. */
2269
+ async _runDefaultCompaction(preparation, model, customInstructions, signal, reason) {
2270
+ // Resolve the request only when Pi summarizes itself: routing may call models or fail.
2271
+ const request = await this._getSummarizationRequestAuth(model, signal);
2272
+ return compact(preparation, request.model, request.apiKey, request.headers, customInstructions, signal, request.thinkingLevel, this.agent.streamFunction, request.env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason }), undefined);
2273
+ }
2274
+ _clearManualCompactionState() {
2275
+ this._compactionAbortController = undefined;
2276
+ this._resolveIdleWaitIfIdle();
2277
+ }
2278
+ /**
2279
+ * Manually compact the session context.
2280
+ *
2281
+ * This is the manual entry point used by `/compact`, RPC, and extensions. It is
2282
+ * separate from automatic threshold/overflow compaction, which enters through
2283
+ * `_checkCompaction()` and `_runAutoCompaction()`. After preparation and the
2284
+ * `session_before_compact` hook, both paths call the lower-level `compact()`
2285
+ * function imported from `./compaction/index.ts`, unless the hook cancels or
2286
+ * supplies a custom result.
2287
+ *
2288
+ * Aborts the current agent operation first. Manual compaction never retries or
2289
+ * continues the interrupted agent turn.
2290
+ *
2291
+ * @param customInstructions Optional instructions for the compaction summary
2292
+ */
2293
+ async compact(customInstructions) {
2294
+ await this.abort();
2295
+ this._compactionAbortController = new AbortController();
2296
+ this._emit({ type: "compaction_start", reason: "manual" });
2297
+ let fromExtension = false;
2298
+ let cancelledByExtension = false;
2299
+ try {
2300
+ const model = this.model;
2301
+ if (!model) {
2302
+ throw new Error(formatNoModelSelectedMessage());
2303
+ }
2304
+ const settings = this.settingsManager.getCompactionSettings(model);
2305
+ const pathEntries = this.sessionManager.getBranch();
2306
+ const preparation = prepareCompaction(pathEntries, settings);
2307
+ if (!preparation) {
2308
+ // Check why we can't compact
2309
+ const lastEntry = pathEntries[pathEntries.length - 1];
2310
+ if (lastEntry?.type === "compaction") {
2311
+ throw new Error("Already compacted");
2312
+ }
2313
+ throw new Error("Nothing to compact (session too small)");
2314
+ }
2315
+ let extensionCompaction;
2316
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
2317
+ const result = (await this._extensionRunner.emit({
2318
+ type: "session_before_compact",
2319
+ preparation,
2320
+ branchEntries: pathEntries,
2321
+ customInstructions,
2322
+ reason: "manual",
2323
+ willRetry: false,
2324
+ signal: this._compactionAbortController.signal,
2325
+ }));
2326
+ if (result?.cancel) {
2327
+ cancelledByExtension = true;
2328
+ throw new Error("Compaction cancelled");
2329
+ }
2330
+ if (result?.compaction) {
2331
+ extensionCompaction = result.compaction;
2332
+ fromExtension = true;
2333
+ }
2334
+ }
2335
+ let summary;
2336
+ let firstKeptEntryId;
2337
+ let tokensBefore;
2338
+ let usage;
2339
+ let details;
2340
+ if (extensionCompaction) {
2341
+ // Extension provided compaction content
2342
+ summary = extensionCompaction.summary;
2343
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
2344
+ tokensBefore = extensionCompaction.tokensBefore;
2345
+ usage = extensionCompaction.usage;
2346
+ details = extensionCompaction.details;
2347
+ }
2348
+ else {
2349
+ // Shared default summary generator, also used by automatic compaction.
2350
+ const result = await this._runDefaultCompaction(preparation, model, customInstructions, this._compactionAbortController.signal, "manual");
2351
+ summary = result.summary;
2352
+ firstKeptEntryId = result.firstKeptEntryId;
2353
+ tokensBefore = result.tokensBefore;
2354
+ usage = result.usage;
2355
+ details = result.details;
2356
+ }
2357
+ if (this._compactionAbortController.signal.aborted) {
2358
+ throw new Error("Compaction cancelled");
2359
+ }
2360
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
2361
+ const newEntries = this.sessionManager.getEntries();
2362
+ this._refreshFinalizedContext();
2363
+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
2364
+ // Get the saved compaction entry for the extension event
2365
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
2366
+ if (this._extensionRunner && savedCompactionEntry) {
2367
+ await this._extensionRunner.emit({
2368
+ type: "session_compact",
2369
+ compactionEntry: savedCompactionEntry,
2370
+ fromExtension,
2371
+ reason: "manual",
2372
+ willRetry: false,
2373
+ });
2374
+ }
2375
+ const compactionResult = {
2376
+ summary,
2377
+ firstKeptEntryId,
2378
+ tokensBefore,
2379
+ estimatedTokensAfter,
2380
+ usage,
2381
+ details,
2382
+ };
2383
+ // compaction_end listeners may submit queued prompts, so expose idle state before notifying them.
2384
+ this._clearManualCompactionState();
2385
+ this._emit({
2386
+ type: "compaction_end",
2387
+ reason: "manual",
2388
+ result: compactionResult,
2389
+ aborted: false,
2390
+ willRetry: false,
2391
+ });
2392
+ return compactionResult;
2393
+ }
2394
+ catch (error) {
2395
+ const message = error instanceof Error ? error.message : String(error);
2396
+ const aborted = this._compactionAbortController.signal.aborted || cancelledByExtension;
2397
+ const errorMessage = aborted ? undefined : `Compaction failed: ${message}`;
2398
+ this._clearManualCompactionState();
2399
+ this._emit({
2400
+ type: "compaction_end",
2401
+ reason: "manual",
2402
+ result: undefined,
2403
+ aborted,
2404
+ willRetry: false,
2405
+ errorMessage,
2406
+ });
2407
+ await this._emitSessionCompactFailed({
2408
+ reason: "manual",
2409
+ errorMessage,
2410
+ aborted,
2411
+ willRetry: false,
2412
+ fromExtension,
2413
+ });
2414
+ throw error;
2415
+ }
2416
+ finally {
2417
+ this._clearManualCompactionState();
2418
+ }
2419
+ }
2420
+ /**
2421
+ * Cancel in-progress compaction (manual or auto).
2422
+ */
2423
+ abortCompaction() {
2424
+ this._compactionAbortController?.abort();
2425
+ this._autoCompactionAbortController?.abort();
2426
+ }
2427
+ /**
2428
+ * Cancel in-progress branch summarization.
2429
+ */
2430
+ abortBranchSummary() {
2431
+ this._branchSummaryAbortController?.abort();
2432
+ }
2433
+ /**
2434
+ * Dispatch automatic compaction after `agent_end` or before prompt submission.
2435
+ * Manual compaction does not call this method; it enters through `compact()`.
2436
+ *
2437
+ * Automatic cases:
2438
+ * 1. Overflow with retry: a context-overflow error or recoverable length stop;
2439
+ * remove the failed assistant message, compact, and retry the turn once.
2440
+ * 2. Overflow without retry: a successful response exceeded the configured
2441
+ * context window; compact but preserve the completed response.
2442
+ * 3. Threshold without retry: valid or estimated context usage crossed the
2443
+ * configured threshold; compact without retrying the completed response.
2444
+ *
2445
+ * Each case calls `_runAutoCompaction()`. After preparation and the
2446
+ * `session_before_compact` hook, that method calls the lower-level `compact()`
2447
+ * function imported from `./compaction/index.ts`, unless the hook cancels or
2448
+ * supplies a custom result.
2449
+ *
2450
+ * @param assistantMessage The assistant message to check
2451
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
2452
+ * @returns Whether the post-run loop should call `agent.continue()` for overflow recovery or queued messages
2453
+ */
2454
+ async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
2455
+ const settings = this.settingsManager.getCompactionSettings(this.model);
2456
+ if (!settings.enabled)
2457
+ return false;
2458
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
2459
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
2460
+ return false;
2461
+ // Skip overflow check if the message came from a different model.
2462
+ // This handles the case where user switched from a smaller-context model (e.g. opus)
2463
+ // to a larger-context model (e.g. codex) - the overflow error from the old model
2464
+ // shouldn't trigger compaction for the new model. Under a virtual selection, the
2465
+ // physical model that produced the message supplies the limits.
2466
+ const messageModel = this._modelForMessage(assistantMessage);
2467
+ const sameModel = messageModel !== undefined;
2468
+ const contextWindow = (messageModel ?? this.model)?.contextWindow ?? 0;
2469
+ // Skip compaction checks if this assistant message is older than the latest
2470
+ // compaction boundary. This prevents a stale pre-compaction usage/error
2471
+ // from retriggering compaction on the first prompt after compaction.
2472
+ const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
2473
+ const assistantIsFromBeforeCompaction = compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
2474
+ if (assistantIsFromBeforeCompaction) {
2475
+ return false;
2476
+ }
2477
+ // Automatic cases 1 and 2: context overflow.
2478
+ // A length stop is recoverable when output ended below the model's original desired limit,
2479
+ // independent of the configured context size or any context-clamped provider request limit.
2480
+ const currentProjection = this.sessionManager.buildSessionProjection();
2481
+ const assistantEntryId = this._findPersistedMessageEntryId(assistantMessage);
2482
+ const assistantIsProjected = assistantEntryId === undefined ||
2483
+ currentProjection.entries.some((entry) => entry.sourceEntry.id === assistantEntryId &&
2484
+ entry.messages.some((message) => message.role === "assistant"));
2485
+ const branch = this.sessionManager.getBranch();
2486
+ const assistantIndex = assistantEntryId ? branch.findIndex((entry) => entry.id === assistantEntryId) : -1;
2487
+ const entriesAfterAssistant = assistantIndex >= 0 ? branch.slice(assistantIndex + 1) : [];
2488
+ const hasPostAssistantContextEdit = entriesAfterAssistant.some((entry) => entry.type === "context_edit");
2489
+ const latestAssistantEdit = entriesAfterAssistant
2490
+ .filter((entry) => entry.type === "context_edit" && entry.targetId === assistantEntryId)
2491
+ .at(-1);
2492
+ const assistantRetainedForExplicitRecovery = assistantEntryId === undefined ||
2493
+ (!entriesAfterAssistant.some((entry) => entry.type === "compaction") &&
2494
+ latestAssistantEdit?.replacement !== null);
2495
+ const assistantUsageMatchesProjection = assistantIsProjected && !hasPostAssistantContextEdit;
2496
+ const explicitOverflow = assistantMessage.stopReason === "error" && isContextOverflow(assistantMessage);
2497
+ const contextOverflow = sameModel &&
2498
+ ((explicitOverflow && assistantRetainedForExplicitRecovery) ||
2499
+ (assistantUsageMatchesProjection && isContextOverflow(assistantMessage, contextWindow)));
2500
+ const recoverableLength = sameModel && assistantIsProjected && isRecoverableLength(assistantMessage, messageModel.maxTokens);
2501
+ if (contextOverflow || recoverableLength) {
2502
+ const willRetry = assistantMessage.stopReason !== "stop";
2503
+ // Case 2: the response completed successfully. Compact, but do not retry because
2504
+ // agent.continue() cannot continue from a completed assistant response.
2505
+ if (!willRetry) {
2506
+ return await this._runAutoCompaction("overflow", false);
2507
+ }
2508
+ if (this._overflowRecoveryAttempted) {
2509
+ const errorMessage = contextOverflow
2510
+ ? "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model."
2511
+ : "Truncated response recovery failed after one compact-and-retry attempt.";
2512
+ this._emit({
2513
+ type: "compaction_end",
2514
+ reason: "overflow",
2515
+ result: undefined,
2516
+ aborted: false,
2517
+ willRetry: false,
2518
+ errorMessage,
2519
+ });
2520
+ await this._emitSessionCompactFailed({
2521
+ reason: "overflow",
2522
+ errorMessage,
2523
+ aborted: false,
2524
+ willRetry: false,
2525
+ fromExtension: false,
2526
+ });
2527
+ return false;
2528
+ }
2529
+ // Persistently omit the selected final attempt before post-run recovery compaction.
2530
+ this._overflowRecoveryAttempted = true;
2531
+ this._omitRecoveryAttempt(assistantMessage);
2532
+ const retry = await this._runAutoCompaction("overflow", willRetry);
2533
+ if (retry)
2534
+ this._failedResponse = assistantMessage;
2535
+ return retry;
2536
+ }
2537
+ // Case 3: threshold compaction without retry.
2538
+ // For error messages or all-zero usage messages, estimate from the last valid response.
2539
+ // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
2540
+ // responses can still compact and do not reset context accounting.
2541
+ let contextTokens;
2542
+ const projection = currentProjection;
2543
+ const hasContextEdits = projection.entries.some((entry) => entry.sourceEntry.type === "context_edit");
2544
+ const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
2545
+ if (hasContextEdits) {
2546
+ contextTokens = estimateProjectedContextTokens(projection, branch).tokens;
2547
+ }
2548
+ else if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
2549
+ const messages = this.agent.state.messages;
2550
+ const estimate = estimateContextTokens(messages);
2551
+ // Without provider usage, estimate.tokens is the pure message-size estimate.
2552
+ // Only usage-backed estimates need the stale pre-compaction check.
2553
+ if (estimate.lastUsageIndex !== null) {
2554
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
2555
+ // have stale usage reflecting the old (larger) context and would falsely
2556
+ // trigger compaction right after one just finished.
2557
+ const usageMsg = messages[estimate.lastUsageIndex];
2558
+ if (compactionEntry &&
2559
+ usageMsg.role === "assistant" &&
2560
+ usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
2561
+ return false;
2562
+ }
2563
+ }
2564
+ contextTokens = estimate.tokens;
2565
+ }
2566
+ else {
2567
+ contextTokens = directContextTokens;
2568
+ }
2569
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
2570
+ return await this._runAutoCompaction("threshold", false);
2571
+ }
2572
+ return false;
2573
+ }
2574
+ /**
2575
+ * Execute threshold or overflow compaction. Manual compaction uses
2576
+ * `AgentSession.compact()` instead. Both paths call the lower-level `compact()`
2577
+ * function imported from `./compaction/index.ts` after preparation and extension
2578
+ * interception.
2579
+ *
2580
+ * @param reason Automatic trigger selected by `_checkCompaction()`
2581
+ * @param willRetry Whether to continue the interrupted turn after overflow compaction
2582
+ * @returns Whether the post-run loop should call `agent.continue()`
2583
+ */
2584
+ async _runAutoCompaction(reason, willRetry) {
2585
+ const model = this.model;
2586
+ const settings = this.settingsManager.getCompactionSettings(model);
2587
+ let abortController;
2588
+ let started = false;
2589
+ let fromExtension = false;
2590
+ let cancelledByExtension = false;
2591
+ try {
2592
+ if (!model) {
2593
+ return false;
2594
+ }
2595
+ const pathEntries = this.sessionManager.getBranch();
2596
+ const preparation = prepareCompaction(pathEntries, settings);
2597
+ if (!preparation) {
2598
+ return false;
2599
+ }
2600
+ abortController = new AbortController();
2601
+ this._autoCompactionAbortController = abortController;
2602
+ started = true;
2603
+ this._emit({ type: "compaction_start", reason });
2604
+ abortController.signal.throwIfAborted();
2605
+ let extensionCompaction;
2606
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
2607
+ const extensionResult = (await this._extensionRunner.emit({
2608
+ type: "session_before_compact",
2609
+ preparation,
2610
+ branchEntries: pathEntries,
2611
+ customInstructions: undefined,
2612
+ reason,
2613
+ willRetry,
2614
+ signal: abortController.signal,
2615
+ }));
2616
+ if (extensionResult?.cancel) {
2617
+ cancelledByExtension = true;
2618
+ throw new Error("Compaction cancelled");
2619
+ }
2620
+ if (extensionResult?.compaction) {
2621
+ extensionCompaction = extensionResult.compaction;
2622
+ fromExtension = true;
2623
+ }
2624
+ }
2625
+ abortController.signal.throwIfAborted();
2626
+ let summary;
2627
+ let firstKeptEntryId;
2628
+ let tokensBefore;
2629
+ let usage;
2630
+ let details;
2631
+ if (extensionCompaction) {
2632
+ // Extension provided compaction content
2633
+ summary = extensionCompaction.summary;
2634
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
2635
+ tokensBefore = extensionCompaction.tokensBefore;
2636
+ usage = extensionCompaction.usage;
2637
+ details = extensionCompaction.details;
2638
+ }
2639
+ else {
2640
+ // Shared default summary generator, also used by manual compaction.
2641
+ const compactResult = await this._runDefaultCompaction(preparation, model, undefined, abortController.signal, reason);
2642
+ summary = compactResult.summary;
2643
+ firstKeptEntryId = compactResult.firstKeptEntryId;
2644
+ tokensBefore = compactResult.tokensBefore;
2645
+ usage = compactResult.usage;
2646
+ details = compactResult.details;
2647
+ }
2648
+ abortController.signal.throwIfAborted();
2649
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
2650
+ const newEntries = this.sessionManager.getEntries();
2651
+ this._refreshFinalizedContext();
2652
+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);
2653
+ // Get the saved compaction entry for the extension event
2654
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
2655
+ if (this._extensionRunner && savedCompactionEntry) {
2656
+ await this._extensionRunner.emit({
2657
+ type: "session_compact",
2658
+ compactionEntry: savedCompactionEntry,
2659
+ fromExtension,
2660
+ reason,
2661
+ willRetry,
2662
+ });
2663
+ }
2664
+ const result = {
2665
+ summary,
2666
+ firstKeptEntryId,
2667
+ tokensBefore,
2668
+ estimatedTokensAfter,
2669
+ usage,
2670
+ details,
2671
+ };
2672
+ this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
2673
+ if (willRetry)
2674
+ return true;
2675
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
2676
+ // Continue once so queued messages are delivered.
2677
+ return this.agent.hasQueuedMessages();
2678
+ }
2679
+ catch (error) {
2680
+ const message = error instanceof Error ? error.message : "compaction failed";
2681
+ const aborted = abortController?.signal.aborted === true || cancelledByExtension;
2682
+ if (started) {
2683
+ const errorMessage = aborted
2684
+ ? undefined
2685
+ : reason === "overflow"
2686
+ ? `Context overflow recovery failed: ${message}`
2687
+ : `Auto-compaction failed: ${message}`;
2688
+ this._emit({
2689
+ type: "compaction_end",
2690
+ reason,
2691
+ result: undefined,
2692
+ aborted,
2693
+ willRetry: false,
2694
+ errorMessage,
2695
+ });
2696
+ await this._emitSessionCompactFailed({
2697
+ reason,
2698
+ errorMessage,
2699
+ aborted,
2700
+ willRetry: false,
2701
+ fromExtension,
2702
+ });
2703
+ }
2704
+ return false;
2705
+ }
2706
+ finally {
2707
+ if (this._autoCompactionAbortController === abortController) {
2708
+ this._autoCompactionAbortController = undefined;
2709
+ }
2710
+ this._resolveIdleWaitIfIdle();
2711
+ }
2712
+ }
2713
+ /**
2714
+ * Toggle auto-compaction setting.
2715
+ */
2716
+ setAutoCompactionEnabled(enabled) {
2717
+ this.settingsManager.setCompactionEnabled(enabled);
2718
+ }
2719
+ /** Whether auto-compaction is enabled */
2720
+ get autoCompactionEnabled() {
2721
+ return this.settingsManager.getCompactionEnabled();
2722
+ }
2723
+ async bindExtensions(bindings) {
2724
+ if (bindings.uiContext !== undefined) {
2725
+ this._extensionUIContext = bindings.uiContext;
2726
+ }
2727
+ if (bindings.mode !== undefined) {
2728
+ this._extensionMode = bindings.mode;
2729
+ }
2730
+ if (bindings.commandContextActions !== undefined) {
2731
+ this._extensionCommandContextActions = bindings.commandContextActions;
2732
+ }
2733
+ if (bindings.abortHandler !== undefined) {
2734
+ this._extensionAbortHandler = bindings.abortHandler;
2735
+ }
2736
+ if (bindings.shutdownHandler !== undefined) {
2737
+ this._extensionShutdownHandler = bindings.shutdownHandler;
2738
+ }
2739
+ if (bindings.onError !== undefined) {
2740
+ this._extensionErrorListener = bindings.onError;
2741
+ }
2742
+ this._applyExtensionBindings(this._extensionRunner);
2743
+ await this._extensionRunner.emit(this._sessionStartEvent);
2744
+ this._extensionRunner.reportUnhandledMcpServers();
2745
+ await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
2746
+ }
2747
+ async extendResourcesFromExtensions(reason) {
2748
+ if (!this._extensionRunner.hasHandlers("resources_discover")) {
2749
+ return;
2750
+ }
2751
+ const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
2752
+ if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
2753
+ return;
2754
+ }
2755
+ const extensionPaths = {
2756
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
2757
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
2758
+ themePaths: this.buildExtensionResourcePaths(themePaths),
2759
+ };
2760
+ this._resourceLoader.extendResources(extensionPaths);
2761
+ this._rebuildSystemPrompt(this.getActiveToolNames());
2762
+ }
2763
+ buildExtensionResourcePaths(entries) {
2764
+ return entries.map((entry) => {
2765
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
2766
+ const baseDir = isSyntheticPath(entry.extensionPath) ? undefined : dirname(entry.extensionPath);
2767
+ return {
2768
+ path: entry.path,
2769
+ metadata: {
2770
+ source,
2771
+ scope: "temporary",
2772
+ origin: "top-level",
2773
+ baseDir,
2774
+ },
2775
+ };
2776
+ });
2777
+ }
2778
+ getExtensionSourceLabel(extensionPath) {
2779
+ if (isSyntheticPath(extensionPath)) {
2780
+ return `extension:${extensionPath.replace(/[<>]/g, "")}`;
2781
+ }
2782
+ const base = basename(extensionPath);
2783
+ const name = base.replace(/\.(ts|js)$/, "");
2784
+ return `extension:${name}`;
2785
+ }
2786
+ _applyExtensionBindings(runner) {
2787
+ runner.setUIContext(this._extensionUIContext, this._extensionMode);
2788
+ runner.bindCommandContext(this._extensionCommandContextActions);
2789
+ this._extensionErrorUnsubscriber?.();
2790
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
2791
+ ? runner.onError(this._extensionErrorListener)
2792
+ : undefined;
2793
+ }
2794
+ _refreshCurrentModelFromRegistry() {
2795
+ const currentModel = this.model;
2796
+ if (!currentModel) {
2797
+ return;
2798
+ }
2799
+ const refreshedModel = this._modelRuntime.getModel(currentModel.provider, currentModel.id);
2800
+ if (!refreshedModel || refreshedModel === currentModel) {
2801
+ return;
2802
+ }
2803
+ this.agent.state.model = refreshedModel;
2804
+ }
2805
+ _bindExtensionCore(runner) {
2806
+ const getCommands = () => {
2807
+ const extensionCommands = runner.getRegisteredCommands().map((command) => ({
2808
+ name: command.invocationName,
2809
+ description: command.description,
2810
+ source: "extension",
2811
+ sourceInfo: command.sourceInfo,
2812
+ }));
2813
+ const templates = this.promptTemplates.map((template) => ({
2814
+ name: template.name,
2815
+ description: template.description,
2816
+ source: "prompt",
2817
+ sourceInfo: template.sourceInfo,
2818
+ }));
2819
+ const skills = this._resourceLoader.getSkills().skills.map((skill) => ({
2820
+ name: `skill:${skill.name}`,
2821
+ description: skill.description,
2822
+ source: "skill",
2823
+ sourceInfo: skill.sourceInfo,
2824
+ }));
2825
+ return [...extensionCommands, ...templates, ...skills];
2826
+ };
2827
+ runner.bindCore({
2828
+ sendMessage: (message, options) => {
2829
+ this.sendCustomMessage(message, options).catch((err) => {
2830
+ runner.emitError({
2831
+ extensionPath: "<runtime>",
2832
+ event: "send_message",
2833
+ error: err instanceof Error ? err.message : String(err),
2834
+ });
2835
+ });
2836
+ },
2837
+ sendUserMessage: (content, options) => {
2838
+ this.sendUserMessage(content, options).catch((err) => {
2839
+ runner.emitError({
2840
+ extensionPath: "<runtime>",
2841
+ event: "send_user_message",
2842
+ error: err instanceof Error ? err.message : String(err),
2843
+ });
2844
+ });
2845
+ },
2846
+ appendEntry: (customType, data) => {
2847
+ const entryId = this.sessionManager.appendCustomEntry(customType, data);
2848
+ const entry = this.sessionManager.getEntry(entryId);
2849
+ if (entry) {
2850
+ this._emit({ type: "entry_appended", entry });
2851
+ }
2852
+ },
2853
+ setSessionName: (name) => {
2854
+ this.setSessionName(name);
2855
+ },
2856
+ getSessionName: () => {
2857
+ return this.sessionManager.getSessionName();
2858
+ },
2859
+ setLabel: (entryId, label) => {
2860
+ this.sessionManager.appendLabelChange(entryId, label);
2861
+ },
2862
+ getActiveTools: () => this.getActiveToolNames(),
2863
+ getAllTools: () => this.getAllTools(),
2864
+ getSettings: () => this.settingsManager.getSettings(),
2865
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
2866
+ refreshTools: () => this._refreshToolRegistry(),
2867
+ getCommands,
2868
+ setModel: async (model) => {
2869
+ if (!this._modelRuntime.hasConfiguredAuth(model.provider))
2870
+ return false;
2871
+ await this.setModel(model);
2872
+ return true;
2873
+ },
2874
+ getThinkingLevel: () => this.thinkingLevel,
2875
+ setThinkingLevel: (level) => this.setThinkingLevel(level),
2876
+ }, {
2877
+ getModel: () => this.model,
2878
+ getScopedModels: () => this._scopedModels,
2879
+ isIdle: () => this.isIdle,
2880
+ isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
2881
+ getSignal: () => this.agent.signal,
2882
+ abort: () => {
2883
+ if (this._extensionAbortHandler) {
2884
+ this._extensionAbortHandler();
2885
+ return;
2886
+ }
2887
+ void this.abort();
2888
+ },
2889
+ hasPendingMessages: () => this.pendingMessageCount > 0,
2890
+ shutdown: () => {
2891
+ this._extensionShutdownHandler?.();
2892
+ },
2893
+ getContextUsage: () => this.getContextUsage(),
2894
+ compact: (options) => {
2895
+ void (async () => {
2896
+ try {
2897
+ const result = await this.compact(options?.customInstructions);
2898
+ options?.onComplete?.(result);
2899
+ }
2900
+ catch (error) {
2901
+ const err = error instanceof Error ? error : new Error(String(error));
2902
+ options?.onError?.(err);
2903
+ }
2904
+ })();
2905
+ },
2906
+ getSystemPrompt: () => this.systemPrompt,
2907
+ getSystemPromptOptions: () => this._baseSystemPromptOptions,
2908
+ executeTool: (callerId, name, args, options) => this._executeNestedToolCall(callerId, name, args, options),
2909
+ getCallableTools: () => this._getCallableTools(),
2910
+ }, {
2911
+ registerProvider: (name, config) => {
2912
+ this._modelRuntime.registerProvider(name, config);
2913
+ this._refreshCurrentModelFromRegistry();
2914
+ },
2915
+ registerNativeProvider: (provider) => {
2916
+ this._modelRuntime.registerNativeProvider(provider);
2917
+ this._refreshCurrentModelFromRegistry();
2918
+ },
2919
+ unregisterProvider: (name) => {
2920
+ this._modelRuntime.unregisterProvider(name);
2921
+ this._refreshCurrentModelFromRegistry();
2922
+ },
2923
+ registerVirtualModel: (definition) => {
2924
+ this._modelRuntime.registerVirtualModel(definition);
2925
+ this._refreshCurrentModelFromRegistry();
2926
+ },
2927
+ unregisterVirtualModel: (provider, id) => {
2928
+ this._modelRuntime.unregisterVirtualModel(provider, id);
2929
+ this._refreshCurrentModelFromRegistry();
2930
+ },
2931
+ });
2932
+ }
2933
+ _refreshToolRegistry(options) {
2934
+ // Tools that were already activated on registration. A tool whose exposure changes to
2935
+ // `direct` or `model-only` (for example from `hidden`) is activated like a new tool.
2936
+ const previousActivatedOnRegistration = new Set([...this._toolRegistry.keys()].filter((name) => this._isActivatedOnRegistration(name)));
2937
+ const previousActiveToolNames = this.getActiveToolNames();
2938
+ const allowedTools = this._allowedTools;
2939
+ const registeredTools = this._extensionRunner.getAllRegisteredTools();
2940
+ const allCustomTools = [
2941
+ ...registeredTools,
2942
+ ...this._customTools.map((definition) => ({
2943
+ definition,
2944
+ sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
2945
+ })),
2946
+ ].filter((tool) => this._isAllowedTool(tool.definition.name));
2947
+ const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
2948
+ .filter(([name]) => this._isAllowedTool(name))
2949
+ .map(([name, definition]) => [
2950
+ name,
2951
+ {
2952
+ definition,
2953
+ sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${name}`, { source: "builtin" }),
2954
+ },
2955
+ ]));
2956
+ for (const tool of allCustomTools) {
2957
+ definitionRegistry.set(tool.definition.name, {
2958
+ definition: tool.definition,
2959
+ sourceInfo: tool.sourceInfo,
2960
+ });
2961
+ }
2962
+ this._toolDefinitions = definitionRegistry;
2963
+ this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
2964
+ .map(({ definition }) => {
2965
+ const snippet = this._normalizePromptSnippet(definition.promptSnippet);
2966
+ return snippet ? [definition.name, snippet] : undefined;
2967
+ })
2968
+ .filter((entry) => entry !== undefined));
2969
+ this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
2970
+ .map(({ definition }) => {
2971
+ const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
2972
+ return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
2973
+ })
2974
+ .filter((entry) => entry !== undefined));
2975
+ const runner = this._extensionRunner;
2976
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
2977
+ const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
2978
+ .filter((definition) => this._isAllowedTool(definition.name))
2979
+ .map((definition) => ({
2980
+ definition,
2981
+ sourceInfo: createSyntheticSourceInfo(`${BUILTIN_PATH_PREFIX}${definition.name}`, {
2982
+ source: "builtin",
2983
+ }),
2984
+ })), runner);
2985
+ const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
2986
+ for (const tool of wrappedExtensionTools) {
2987
+ toolRegistry.set(tool.name, tool);
2988
+ }
2989
+ this._toolRegistry = toolRegistry;
2990
+ const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => this._isAllowedTool(name));
2991
+ if (allowedTools) {
2992
+ for (const toolName of this._toolRegistry.keys()) {
2993
+ // Naming or matching a tool activates it even when it is not active by default. MCP tools
2994
+ // kept registered without being named stay inactive.
2995
+ if (allowedTools(toolName) && this._isDeclarable(toolName)) {
2996
+ nextActiveToolNames.push(toolName);
2997
+ }
2998
+ }
2999
+ }
3000
+ else if (options?.includeAllExtensionTools) {
3001
+ for (const tool of wrappedExtensionTools) {
3002
+ if (this._isActivatedOnRegistration(tool.name))
3003
+ nextActiveToolNames.push(tool.name);
3004
+ }
3005
+ }
3006
+ else if (!options?.activeToolNames) {
3007
+ for (const toolName of this._toolRegistry.keys()) {
3008
+ if (!previousActivatedOnRegistration.has(toolName) && this._isActivatedOnRegistration(toolName)) {
3009
+ nextActiveToolNames.push(toolName);
3010
+ }
3011
+ }
3012
+ }
3013
+ // Pending tools that are registered now become active.
3014
+ nextActiveToolNames.push(...this._pendingToolNames);
3015
+ this._setActiveTools([...new Set(nextActiveToolNames)]);
3016
+ }
3017
+ /** Whether activating the tool declares it to the model. */
3018
+ _isDeclarable(name) {
3019
+ const exposure = this._getToolExposure(name);
3020
+ return exposure === "direct" || exposure === "model-only";
3021
+ }
3022
+ /** Whether registering the tool activates it, which declares it to the model. */
3023
+ _isActivatedOnRegistration(name) {
3024
+ return this._isDeclarable(name) && this._toolDefinitions.get(name)?.definition.defaultActive !== false;
3025
+ }
3026
+ _buildRuntime(options) {
3027
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
3028
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
3029
+ const shellPath = this.settingsManager.getShellPath();
3030
+ const baseToolDefinitions = this._baseToolsOverride
3031
+ ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
3032
+ name,
3033
+ createToolDefinitionFromAgentTool(tool),
3034
+ ]))
3035
+ : createAllToolDefinitions(this._cwd, {
3036
+ read: { autoResizeImages },
3037
+ bash: { commandPrefix: shellCommandPrefix, shellPath },
3038
+ });
3039
+ this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
3040
+ const extensionsResult = this._resourceLoader.getExtensions();
3041
+ if (options.flagValues) {
3042
+ for (const [name, value] of options.flagValues) {
3043
+ extensionsResult.runtime.flagValues.set(name, value);
3044
+ }
3045
+ }
3046
+ this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, new ModelRegistry(this._modelRuntime));
3047
+ if (this._extensionRunnerRef) {
3048
+ this._extensionRunnerRef.current = this._extensionRunner;
3049
+ }
3050
+ this._bindExtensionCore(this._extensionRunner);
3051
+ this._applyExtensionBindings(this._extensionRunner);
3052
+ const defaultActiveToolNames = this._baseToolsOverride
3053
+ ? Object.keys(this._baseToolsOverride)
3054
+ : ["read", "bash", "edit", "write"];
3055
+ const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
3056
+ this._refreshToolRegistry({
3057
+ activeToolNames: baseActiveToolNames,
3058
+ includeAllExtensionTools: options.includeAllExtensionTools,
3059
+ });
3060
+ }
3061
+ async reload(options) {
3062
+ if (this.isStreaming) {
3063
+ throw new Error("Wait for the current response to finish before reloading.");
3064
+ }
3065
+ if (this.isCompacting) {
3066
+ throw new Error("Wait for compaction to finish before reloading.");
3067
+ }
3068
+ const oldRunner = this._extensionRunner;
3069
+ const previousFlagValues = oldRunner.getFlagValues();
3070
+ await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason: "reload" });
3071
+ oldRunner.invalidate();
3072
+ const getDefaultTools = () => this._usesDefaultTools
3073
+ ? applyToolModifiers(this.settingsManager.getDefaultTools() ?? DEFAULT_TOOL_NAMES, this._defaultToolModifiers)
3074
+ : [];
3075
+ const previousDefaultTools = new Set(getDefaultTools());
3076
+ await this.settingsManager.reload();
3077
+ this.syncQueueModesFromSettings();
3078
+ resetApiProviders();
3079
+ await this._resourceLoader.reload();
3080
+ // Activate tools newly added to defaultTools. Removed ones stay active, and tools disabled
3081
+ // during the session stay disabled unless the setting newly adds them.
3082
+ const addedDefaultTools = getDefaultTools().filter((name) => !previousDefaultTools.has(name));
3083
+ // Tools the new extensions register later, such as MCP tools, are pending until then.
3084
+ for (const name of this.getActiveToolNames())
3085
+ this._pendingToolNames.add(name);
3086
+ this._buildRuntime({
3087
+ activeToolNames: [...this.getActiveToolNames(), ...addedDefaultTools],
3088
+ flagValues: previousFlagValues,
3089
+ includeAllExtensionTools: true,
3090
+ });
3091
+ const hasBindings = this._extensionUIContext ||
3092
+ this._extensionCommandContextActions ||
3093
+ this._extensionShutdownHandler ||
3094
+ this._extensionErrorListener;
3095
+ if (hasBindings) {
3096
+ await options?.beforeSessionStart?.();
3097
+ await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
3098
+ this._extensionRunner.reportUnhandledMcpServers();
3099
+ await this.extendResourcesFromExtensions("reload");
3100
+ }
3101
+ }
3102
+ // =========================================================================
3103
+ // Auto-Retry
3104
+ // =========================================================================
3105
+ /**
3106
+ * Check if an error is retryable (overloaded, rate limit, server errors).
3107
+ * Context overflow errors are NOT retryable (handled by compaction instead).
3108
+ */
3109
+ _isRetryableError(message) {
3110
+ // Context overflow is handled by compaction, not retry.
3111
+ if (isContextOverflow(message, (this._modelForMessage(message) ?? this.model)?.contextWindow ?? 0))
3112
+ return false;
3113
+ return isRetryableAssistantError(message);
3114
+ }
3115
+ /**
3116
+ * Retry policy + callbacks shared by compaction and branch-summary summarization calls.
3117
+ * Uses the same `settings.retry` budget/backoff as agent-turn retries so a single transient
3118
+ * stream drop no longer fails the whole operation. `source` carries the context
3119
+ * the TUI needs to render the retry and recreate the underlying indicator.
3120
+ */
3121
+ _summarizationRetryCallbacks(source) {
3122
+ return {
3123
+ onRetryScheduled: (attempt, maxAttempts, delayMs, errorMessage) => {
3124
+ this._emit({
3125
+ type: "summarization_retry_scheduled",
3126
+ attempt,
3127
+ maxAttempts,
3128
+ delayMs,
3129
+ errorMessage,
3130
+ });
3131
+ },
3132
+ onRetryAttemptStart: () => {
3133
+ this._emit({
3134
+ type: "summarization_retry_attempt_start",
3135
+ ...source,
3136
+ });
3137
+ },
3138
+ onRetryFinished: () => {
3139
+ this._emit({ type: "summarization_retry_finished" });
3140
+ },
3141
+ };
3142
+ }
3143
+ _finishCancelledRetry() {
3144
+ if (this._retryAttempt === 0)
3145
+ return;
3146
+ const attempt = this._retryAttempt;
3147
+ this._retryAttempt = 0;
3148
+ this._emit({
3149
+ type: "auto_retry_end",
3150
+ success: false,
3151
+ attempt,
3152
+ finalError: "Retry cancelled",
3153
+ });
3154
+ }
3155
+ /**
3156
+ * Prepare a retryable error for continuation with exponential backoff.
3157
+ * @returns true if the caller should continue the agent, false otherwise
3158
+ */
3159
+ async _prepareRetry(message) {
3160
+ const settings = this.settingsManager.getRetrySettings();
3161
+ if (!settings.enabled) {
3162
+ return false;
3163
+ }
3164
+ this._retryAttempt++;
3165
+ if (this._retryAttempt > settings.maxRetries) {
3166
+ // Preserve the completed attempt count so post-run handling can emit the final failure.
3167
+ this._retryAttempt--;
3168
+ return false;
3169
+ }
3170
+ const delayMs = retryDelayMs(settings, this._retryAttempt);
3171
+ this._emit({
3172
+ type: "auto_retry_start",
3173
+ attempt: this._retryAttempt,
3174
+ maxAttempts: settings.maxRetries,
3175
+ delayMs,
3176
+ errorMessage: message.errorMessage || "Unknown error",
3177
+ });
3178
+ // Keep the failed attempt in raw history while durably omitting it from model projection.
3179
+ this._omitRecoveryAttempt(message);
3180
+ // Wait with exponential backoff (abortable)
3181
+ this._retryAbortController = new AbortController();
3182
+ try {
3183
+ await sleep(delayMs, this._retryAbortController.signal);
3184
+ }
3185
+ catch {
3186
+ // Aborted during sleep - emit end event so UI can clean up
3187
+ this._finishCancelledRetry();
3188
+ return false;
3189
+ }
3190
+ finally {
3191
+ this._retryAbortController = undefined;
3192
+ }
3193
+ return true;
3194
+ }
3195
+ /**
3196
+ * Cancel in-progress retry.
3197
+ */
3198
+ abortRetry() {
3199
+ this._retryAbortController?.abort();
3200
+ }
3201
+ /** Whether auto-retry is currently in progress */
3202
+ get isRetrying() {
3203
+ return this._retryAbortController !== undefined;
3204
+ }
3205
+ /** Whether auto-retry is enabled */
3206
+ get autoRetryEnabled() {
3207
+ return this.settingsManager.getRetryEnabled();
3208
+ }
3209
+ /**
3210
+ * Toggle auto-retry setting.
3211
+ */
3212
+ setAutoRetryEnabled(enabled) {
3213
+ this.settingsManager.setRetryEnabled(enabled);
3214
+ }
3215
+ // =========================================================================
3216
+ // Bash Execution
3217
+ // =========================================================================
3218
+ /**
3219
+ * Execute a bash command.
3220
+ * Adds result to agent context and session.
3221
+ * @param command The bash command to execute
3222
+ * @param onChunk Optional streaming callback for output
3223
+ * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
3224
+ * @param options.id Optional identifier included in bash execution update events
3225
+ * @param options.operations Custom BashOperations for remote execution
3226
+ */
3227
+ async executeBash(command, onChunk, options) {
3228
+ const abortController = new AbortController();
3229
+ this._bashAbortControllers.add(abortController);
3230
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
3231
+ const prefix = this.settingsManager.getShellCommandPrefix();
3232
+ const shellPath = this.settingsManager.getShellPath();
3233
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
3234
+ try {
3235
+ const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
3236
+ onChunk: (delta) => {
3237
+ onChunk?.(delta);
3238
+ this._emit({ type: "bash_execution_update", id: options?.id, delta });
3239
+ },
3240
+ signal: abortController.signal,
3241
+ });
3242
+ this.recordBashResult(command, result, options);
3243
+ return result;
3244
+ }
3245
+ finally {
3246
+ this._bashAbortControllers.delete(abortController);
3247
+ }
3248
+ }
3249
+ /**
3250
+ * Record a bash execution result in session history.
3251
+ * Used by executeBash and by extensions that handle bash execution themselves.
3252
+ */
3253
+ recordBashResult(command, result, options) {
3254
+ const bashMessage = {
3255
+ role: "bashExecution",
3256
+ command,
3257
+ output: result.output,
3258
+ exitCode: result.exitCode,
3259
+ cancelled: result.cancelled,
3260
+ truncated: result.truncated,
3261
+ fullOutputPath: result.fullOutputPath,
3262
+ timestamp: Date.now(),
3263
+ excludeFromContext: options?.excludeFromContext,
3264
+ };
3265
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
3266
+ if (this.isStreaming) {
3267
+ // Queue for later - will be flushed on agent_end
3268
+ this._pendingBashMessages.push(bashMessage);
3269
+ }
3270
+ else {
3271
+ this.sessionManager.appendMessage(bashMessage);
3272
+ this._refreshFinalizedContext();
3273
+ }
3274
+ }
3275
+ /**
3276
+ * Cancel running bash command.
3277
+ */
3278
+ abortBash() {
3279
+ for (const abortController of [...this._bashAbortControllers]) {
3280
+ abortController.abort();
3281
+ }
3282
+ }
3283
+ /** Whether a bash command is currently running */
3284
+ get isBashRunning() {
3285
+ return this._bashAbortControllers.size > 0;
3286
+ }
3287
+ /** Whether there are pending bash messages waiting to be flushed */
3288
+ get hasPendingBashMessages() {
3289
+ return this._pendingBashMessages.length > 0;
3290
+ }
3291
+ /**
3292
+ * Flush pending bash messages to agent state and session.
3293
+ * Called after agent turn completes to maintain proper message ordering.
3294
+ */
3295
+ _flushPendingBashMessages() {
3296
+ if (this._pendingBashMessages.length === 0)
3297
+ return;
3298
+ for (const bashMessage of this._pendingBashMessages) {
3299
+ this.sessionManager.appendMessage(bashMessage);
3300
+ }
3301
+ this._pendingBashMessages = [];
3302
+ this._refreshFinalizedContext();
3303
+ }
3304
+ // =========================================================================
3305
+ // Session Management
3306
+ // =========================================================================
3307
+ /**
3308
+ * Set a display name for the current session.
3309
+ */
3310
+ setSessionName(name) {
3311
+ this.sessionManager.appendSessionInfo(name);
3312
+ const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() };
3313
+ this._emit(event);
3314
+ void this._extensionRunner.emit(event);
3315
+ }
3316
+ // =========================================================================
3317
+ // Tree Navigation
3318
+ // =========================================================================
3319
+ /**
3320
+ * Navigate to a different node in the session tree.
3321
+ * Unlike fork() which creates a new session file, this stays in the same file.
3322
+ *
3323
+ * @param targetId The entry ID to navigate to
3324
+ * @param options.summarize Whether user wants to summarize abandoned branch
3325
+ * @param options.customInstructions Custom instructions for summarizer
3326
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
3327
+ * @param options.label Label to attach to the branch summary entry
3328
+ * @returns Result with editorText (if user message) and cancelled status
3329
+ */
3330
+ async navigateTree(targetId, options = {}) {
3331
+ if (this.isStreaming || this._promptPreflightCount > 0) {
3332
+ throw new Error("Wait for the current response to finish before navigating the session tree.");
3333
+ }
3334
+ if (this.isCompacting) {
3335
+ throw new Error("Wait for the current compaction or tree navigation to finish before navigating the session tree.");
3336
+ }
3337
+ const oldLeafId = this.sessionManager.getLeafId();
3338
+ // No-op if already at target
3339
+ if (targetId === oldLeafId) {
3340
+ return { cancelled: false };
3341
+ }
3342
+ // Model required for summarization
3343
+ if (options.summarize && !this.model) {
3344
+ throw new Error("No model available for summarization");
3345
+ }
3346
+ const targetEntry = this.sessionManager.getEntry(targetId);
3347
+ if (!targetEntry) {
3348
+ throw new Error(`Entry ${targetId} not found`);
3349
+ }
3350
+ // Collect entries to summarize (from old leaf to common ancestor)
3351
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
3352
+ // Prepare event data - mutable so extensions can override
3353
+ let customInstructions = options.customInstructions;
3354
+ let replaceInstructions = options.replaceInstructions;
3355
+ let label = options.label;
3356
+ const preparation = {
3357
+ targetId,
3358
+ oldLeafId,
3359
+ commonAncestorId,
3360
+ entriesToSummarize,
3361
+ userWantsSummary: options.summarize ?? false,
3362
+ customInstructions,
3363
+ replaceInstructions,
3364
+ label,
3365
+ };
3366
+ // Set up abort controller for summarization
3367
+ const abortController = new AbortController();
3368
+ this._branchSummaryAbortController = abortController;
3369
+ try {
3370
+ let extensionSummary;
3371
+ let fromExtension = false;
3372
+ // Emit session_before_tree event
3373
+ if (this._extensionRunner.hasHandlers("session_before_tree")) {
3374
+ const result = (await this._extensionRunner.emit({
3375
+ type: "session_before_tree",
3376
+ preparation,
3377
+ signal: abortController.signal,
3378
+ }));
3379
+ if (result?.cancel) {
3380
+ return { cancelled: true };
3381
+ }
3382
+ if (result?.summary && options.summarize) {
3383
+ extensionSummary = result.summary;
3384
+ fromExtension = true;
3385
+ }
3386
+ // Allow extensions to override instructions and label
3387
+ if (result?.customInstructions !== undefined) {
3388
+ customInstructions = result.customInstructions;
3389
+ }
3390
+ if (result?.replaceInstructions !== undefined) {
3391
+ replaceInstructions = result.replaceInstructions;
3392
+ }
3393
+ if (result?.label !== undefined) {
3394
+ label = result.label;
3395
+ }
3396
+ }
3397
+ // Run default summarizer if needed
3398
+ let summaryText;
3399
+ let summaryDetails;
3400
+ let summaryUsage;
3401
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
3402
+ const signal = abortController.signal;
3403
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
3404
+ const result = await generateBranchSummary(entriesToSummarize, {
3405
+ ...(await this._getSummarizationRequestAuth(this.model, signal)),
3406
+ signal,
3407
+ customInstructions,
3408
+ replaceInstructions,
3409
+ reserveTokens: branchSummarySettings.reserveTokens,
3410
+ streamFn: this.agent.streamFunction,
3411
+ retry: this.settingsManager.getRetrySettings(),
3412
+ callbacks: this._summarizationRetryCallbacks({ source: "branchSummary" }),
3413
+ });
3414
+ if (result.aborted) {
3415
+ return { cancelled: true, aborted: true };
3416
+ }
3417
+ if (result.error) {
3418
+ throw new Error(result.error);
3419
+ }
3420
+ summaryText = result.summary;
3421
+ summaryUsage = result.usage;
3422
+ summaryDetails = {
3423
+ readFiles: result.readFiles || [],
3424
+ modifiedFiles: result.modifiedFiles || [],
3425
+ };
3426
+ }
3427
+ else if (extensionSummary) {
3428
+ summaryText = extensionSummary.summary;
3429
+ summaryDetails = extensionSummary.details;
3430
+ summaryUsage = extensionSummary.usage;
3431
+ }
3432
+ // Determine the new leaf position based on target type
3433
+ let newLeafId;
3434
+ let editorText;
3435
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
3436
+ // User message: leaf = parent (null if root), text goes to editor
3437
+ newLeafId = targetEntry.parentId;
3438
+ editorText = contentText(targetEntry.message.content, "");
3439
+ }
3440
+ else if (targetEntry.type === "custom_message") {
3441
+ // Custom message: leaf = parent (null if root), text goes to editor
3442
+ newLeafId = targetEntry.parentId;
3443
+ editorText = contentText(targetEntry.content, "");
3444
+ }
3445
+ else {
3446
+ // Non-user message: leaf = selected node
3447
+ newLeafId = targetId;
3448
+ }
3449
+ // Switch leaf (with or without summary)
3450
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
3451
+ let summaryEntry;
3452
+ if (summaryText) {
3453
+ // Create summary at target position (can be null for root)
3454
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension, summaryUsage);
3455
+ summaryEntry = this.sessionManager.getEntry(summaryId);
3456
+ // Attach label to the summary entry
3457
+ if (label) {
3458
+ this.sessionManager.appendLabelChange(summaryId, label);
3459
+ }
3460
+ }
3461
+ else if (newLeafId === null) {
3462
+ // No summary, navigating to root - reset leaf
3463
+ this.sessionManager.resetLeaf();
3464
+ }
3465
+ else {
3466
+ // No summary, navigating to non-root
3467
+ this.sessionManager.branch(newLeafId);
3468
+ }
3469
+ // Attach label to target entry when not summarizing (no summary entry to label)
3470
+ if (label && !summaryText) {
3471
+ this.sessionManager.appendLabelChange(targetId, label);
3472
+ }
3473
+ // Update finalized context from the canonical session projection.
3474
+ this._refreshFinalizedContext();
3475
+ this._restoreToolsFromTranscript();
3476
+ // The selected context is installed; session_tree handlers may now prompt or navigate again.
3477
+ this._branchSummaryAbortController = undefined;
3478
+ await this._extensionRunner.emit({
3479
+ type: "session_tree",
3480
+ newLeafId: this.sessionManager.getLeafId(),
3481
+ oldLeafId,
3482
+ summaryEntry,
3483
+ fromExtension: summaryText ? fromExtension : undefined,
3484
+ });
3485
+ // Emit to custom tools
3486
+ return { editorText, cancelled: false, summaryEntry };
3487
+ }
3488
+ finally {
3489
+ // A navigation started from session_tree owns the controller now; do not clear it.
3490
+ if (this._branchSummaryAbortController === abortController) {
3491
+ this._branchSummaryAbortController = undefined;
3492
+ }
3493
+ this._resolveIdleWaitIfIdle();
3494
+ }
3495
+ }
3496
+ /**
3497
+ * Get all user messages from session for fork selector.
3498
+ */
3499
+ getUserMessagesForForking() {
3500
+ const entries = this.sessionManager.getEntries();
3501
+ const result = [];
3502
+ for (const entry of entries) {
3503
+ if (entry.type !== "message")
3504
+ continue;
3505
+ if (entry.message.role !== "user")
3506
+ continue;
3507
+ const text = contentText(entry.message.content, "");
3508
+ if (text) {
3509
+ result.push({ entryId: entry.id, text });
3510
+ }
3511
+ }
3512
+ return result;
3513
+ }
3514
+ /**
3515
+ * Get session statistics. Aggregates over ALL session entries (including
3516
+ * history that was compacted away), so token/cost totals reflect what was
3517
+ * actually billed across the session.
3518
+ */
3519
+ getSessionStats() {
3520
+ let userMessages = 0;
3521
+ let assistantMessages = 0;
3522
+ let toolResults = 0;
3523
+ let totalMessages = 0;
3524
+ let toolCalls = 0;
3525
+ const usageTotals = createUsageTotals();
3526
+ for (const entry of this.sessionManager.getEntries()) {
3527
+ if (entry.type === "usage") {
3528
+ addUsageToTotals(usageTotals, entry.usage);
3529
+ }
3530
+ else if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
3531
+ addUsageToTotals(usageTotals, entry.usage);
3532
+ }
3533
+ if (entry.type !== "message")
3534
+ continue;
3535
+ totalMessages++;
3536
+ const message = entry.message;
3537
+ if (message.role === "user") {
3538
+ userMessages++;
3539
+ }
3540
+ else if (message.role === "toolResult") {
3541
+ toolResults++;
3542
+ if (message.usage) {
3543
+ addUsageToTotals(usageTotals, message.usage);
3544
+ }
3545
+ }
3546
+ else if (message.role === "assistant") {
3547
+ assistantMessages++;
3548
+ const assistantMsg = message;
3549
+ if (Array.isArray(assistantMsg.content)) {
3550
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
3551
+ }
3552
+ addUsageToTotals(usageTotals, assistantMsg.usage);
3553
+ }
3554
+ }
3555
+ return {
3556
+ sessionFile: this.sessionFile,
3557
+ sessionId: this.sessionId,
3558
+ userMessages,
3559
+ assistantMessages,
3560
+ toolCalls,
3561
+ toolResults,
3562
+ totalMessages,
3563
+ tokens: {
3564
+ input: usageTotals.input,
3565
+ output: usageTotals.output,
3566
+ cacheRead: usageTotals.cacheRead,
3567
+ cacheWrite: usageTotals.cacheWrite,
3568
+ total: usageTotals.input + usageTotals.output + usageTotals.cacheRead + usageTotals.cacheWrite,
3569
+ },
3570
+ cost: usageTotals.cost,
3571
+ contextUsage: this.getContextUsage(),
3572
+ };
3573
+ }
3574
+ getContextUsage() {
3575
+ const model = this._limitsModel();
3576
+ if (!model)
3577
+ return undefined;
3578
+ const contextWindow = model.contextWindow ?? 0;
3579
+ if (contextWindow <= 0)
3580
+ return undefined;
3581
+ // After compaction, the last assistant usage reflects pre-compaction context size.
3582
+ // We can only trust usage from an assistant that responded after the latest compaction.
3583
+ // If no such assistant exists, context token count is unknown until the next LLM response.
3584
+ const projection = this.sessionManager.buildSessionProjection();
3585
+ const branch = this.sessionManager.getBranch();
3586
+ const latestCompaction = getLatestCompactionEntry(branch);
3587
+ if (latestCompaction) {
3588
+ const projectedAssistants = new Set(projection.entries.flatMap((entry) => entry.messages.some((message) => message.role === "assistant" &&
3589
+ message.stopReason !== "aborted" &&
3590
+ message.stopReason !== "error" &&
3591
+ calculateContextTokens(message.usage) > 0)
3592
+ ? [entry.sourceEntry.id]
3593
+ : []));
3594
+ const compactionIndex = branch.findIndex((entry) => entry.id === latestCompaction.id);
3595
+ const hasPostCompactionUsage = branch
3596
+ .slice(compactionIndex + 1)
3597
+ .some((entry) => projectedAssistants.has(entry.id));
3598
+ if (!hasPostCompactionUsage)
3599
+ return { tokens: null, contextWindow, percent: null };
3600
+ }
3601
+ const estimate = estimateProjectedContextTokens(projection, branch);
3602
+ const percent = (estimate.tokens / contextWindow) * 100;
3603
+ return {
3604
+ tokens: estimate.tokens,
3605
+ contextWindow,
3606
+ percent,
3607
+ };
3608
+ }
3609
+ /**
3610
+ * Export session to HTML.
3611
+ * @param outputPath Optional output path (defaults to session directory)
3612
+ * @param options Optional export presentation settings
3613
+ * @returns Path to exported file
3614
+ */
3615
+ async exportToHtml(outputPath, options = {}) {
3616
+ const themeName = [options.themeName, this.settingsManager.getTheme()].find((candidate) => candidate !== undefined && getThemeByName(candidate) !== undefined);
3617
+ // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
3618
+ const toolRenderer = createToolHtmlRenderer({
3619
+ getToolRenderers: (name) => this._extensionRunner.resolveToolRenderers(name, () => this.getToolDefinition(name)),
3620
+ theme,
3621
+ cwd: this.sessionManager.getCwd(),
3622
+ });
3623
+ return await exportSessionToHtml(this.sessionManager, this.state, {
3624
+ outputPath,
3625
+ themeName,
3626
+ toolRenderer,
3627
+ });
3628
+ }
3629
+ /**
3630
+ * Export the current session branch to a JSONL file.
3631
+ * Writes the session header followed by all entries on the current branch path.
3632
+ * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
3633
+ * @returns The resolved output file path.
3634
+ */
3635
+ exportToJsonl(outputPath) {
3636
+ return exportSessionToJsonl(this.sessionManager, outputPath);
3637
+ }
3638
+ /**
3639
+ * Ask the current model to describe what went wrong in this session for a bug report.
3640
+ * Used when the user declines to share the transcript itself.
3641
+ */
3642
+ async summarizeForBugReport(options) {
3643
+ const model = this.model;
3644
+ if (!model) {
3645
+ throw new Error("No model selected");
3646
+ }
3647
+ return generateBugReportSummary({
3648
+ ...(await this._getSummarizationRequestAuth(model, options.signal)),
3649
+ messages: this.messages,
3650
+ hint: options.hint,
3651
+ signal: options.signal,
3652
+ streamFn: this.agent.streamFunction,
3653
+ retry: this.settingsManager.getRetrySettings(),
3654
+ sessionId: this.sessionId,
3655
+ });
3656
+ }
3657
+ // =========================================================================
3658
+ // Utilities
3659
+ // =========================================================================
3660
+ /**
3661
+ * Get text content of last assistant message.
3662
+ * Useful for /copy command.
3663
+ * @returns Text content, or undefined if no assistant message exists
3664
+ */
3665
+ getLastAssistantText() {
3666
+ const lastAssistant = this.messages
3667
+ .slice()
3668
+ .reverse()
3669
+ .find((m) => {
3670
+ if (m.role !== "assistant")
3671
+ return false;
3672
+ const msg = m;
3673
+ // Skip aborted messages with no content
3674
+ if (msg.stopReason === "aborted" && msg.content.length === 0)
3675
+ return false;
3676
+ return true;
3677
+ });
3678
+ if (!lastAssistant)
3679
+ return undefined;
3680
+ let text = "";
3681
+ for (const content of lastAssistant.content) {
3682
+ if (content.type === "text") {
3683
+ text += content.text;
3684
+ }
3685
+ }
3686
+ return text.trim() || undefined;
3687
+ }
3688
+ // =========================================================================
3689
+ // Extension System
3690
+ // =========================================================================
3691
+ createReplacedSessionContext() {
3692
+ const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
3693
+ context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
3694
+ context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
3695
+ return context;
3696
+ }
3697
+ /**
3698
+ * Check if extensions have handlers for a specific event type.
3699
+ */
3700
+ hasExtensionHandlers(eventType) {
3701
+ return this._extensionRunner.hasHandlers(eventType);
3702
+ }
3703
+ /**
3704
+ * Get the extension runner (for setting UI context and error handlers).
3705
+ */
3706
+ get extensionRunner() {
3707
+ return this._extensionRunner;
3708
+ }
3709
+ }
3710
+ //# sourceMappingURL=agent-session.js.map