@maxmo74/pi-coding-agent 0.0.0-stage → 1.4.0-max.1

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