@aibyzero/byz 0.0.0 → 0.1.2

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 (1313) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +21 -0
  3. package/README.md +136 -5
  4. package/dist/cli.js +46 -0
  5. package/dist/core/export-html/template.css +1066 -0
  6. package/dist/core/export-html/template.html +55 -0
  7. package/dist/core/export-html/template.js +1864 -0
  8. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  9. package/dist/core/export-html/vendor/marked.min.js +78 -0
  10. package/dist/modes/interactive/assets/clankolas.png +0 -0
  11. package/dist/modes/interactive/theme/dark.json +90 -0
  12. package/dist/modes/interactive/theme/light.json +89 -0
  13. package/dist/modes/interactive/theme/theme-schema.json +352 -0
  14. package/dist/runtime/bun/cli.d.ts +3 -0
  15. package/dist/runtime/bun/cli.d.ts.map +1 -0
  16. package/dist/runtime/bun/cli.js +11 -0
  17. package/dist/runtime/bun/cli.js.map +1 -0
  18. package/dist/runtime/bun/register-bedrock.d.ts +2 -0
  19. package/dist/runtime/bun/register-bedrock.d.ts.map +1 -0
  20. package/dist/runtime/bun/register-bedrock.js +4 -0
  21. package/dist/runtime/bun/register-bedrock.js.map +1 -0
  22. package/dist/runtime/bun/restore-sandbox-env.d.ts +17 -0
  23. package/dist/runtime/bun/restore-sandbox-env.d.ts.map +1 -0
  24. package/dist/runtime/bun/restore-sandbox-env.js +36 -0
  25. package/dist/runtime/bun/restore-sandbox-env.js.map +1 -0
  26. package/dist/runtime/bundle/chunks/anthropic-messages-JWX2WP65.js +45 -0
  27. package/dist/runtime/bundle/chunks/anthropic.js +75 -0
  28. package/dist/runtime/bundle/chunks/azure-openai-responses-5ENVCQ7U.js +2 -0
  29. package/dist/runtime/bundle/chunks/bedrock-converse-stream.js +74 -0
  30. package/dist/runtime/bundle/chunks/chunk-4L3WN2XY.js +2 -0
  31. package/dist/runtime/bundle/chunks/chunk-6CYCI3EJ.js +12 -0
  32. package/dist/runtime/bundle/chunks/chunk-6R7UI4IY.js +2 -0
  33. package/dist/runtime/bundle/chunks/chunk-AXIIZGTV.js +2 -0
  34. package/dist/runtime/bundle/chunks/chunk-DRQDKNXA.js +2 -0
  35. package/dist/runtime/bundle/chunks/chunk-GMWCTUPB.js +2 -0
  36. package/dist/runtime/bundle/chunks/chunk-GPPBJGBU.js +50 -0
  37. package/dist/runtime/bundle/chunks/chunk-JUUC5AZY.js +2 -0
  38. package/dist/runtime/bundle/chunks/chunk-L2ZPNLYD.js +2 -0
  39. package/dist/runtime/bundle/chunks/chunk-MNAIPA3J.js +2 -0
  40. package/dist/runtime/bundle/chunks/chunk-NBBFIJUL.js +11 -0
  41. package/dist/runtime/bundle/chunks/chunk-NUHFSC37.js +25 -0
  42. package/dist/runtime/bundle/chunks/chunk-PGXDEOVV.js +2 -0
  43. package/dist/runtime/bundle/chunks/chunk-PJACZCIR.js +2 -0
  44. package/dist/runtime/bundle/chunks/chunk-PRRNXB7S.js +2 -0
  45. package/dist/runtime/bundle/chunks/chunk-Q4KIHSRR.js +1547 -0
  46. package/dist/runtime/bundle/chunks/chunk-TEPMHNKQ.js +2 -0
  47. package/dist/runtime/bundle/chunks/chunk-TRDNDS6A.js +4 -0
  48. package/dist/runtime/bundle/chunks/chunk-UAQELI3K.js +2 -0
  49. package/dist/runtime/bundle/chunks/chunk-XDUWOHPL.js +6 -0
  50. package/dist/runtime/bundle/chunks/chunk-XNGRGP62.js +2 -0
  51. package/dist/runtime/bundle/chunks/dist-RDWOYWHR.js +13 -0
  52. package/dist/runtime/bundle/chunks/github-copilot.js +2 -0
  53. package/dist/runtime/bundle/chunks/google-generative-ai-XDKMGBCJ.js +2 -0
  54. package/dist/runtime/bundle/chunks/google-vertex-D5FGEO3Y.js +2 -0
  55. package/dist/runtime/bundle/chunks/image-resize-worker.js +2 -0
  56. package/dist/runtime/bundle/chunks/kimi-coding.js +2 -0
  57. package/dist/runtime/bundle/chunks/lib-HGQMNYVT.js +9 -0
  58. package/dist/runtime/bundle/chunks/mistral-conversations-YK73UAOZ.js +5 -0
  59. package/dist/runtime/bundle/chunks/multipart-parser-SQ6GDJL7.js +3 -0
  60. package/dist/runtime/bundle/chunks/openai-codex-responses-GJVBJXLB.js +8 -0
  61. package/dist/runtime/bundle/chunks/openai-codex.js +75 -0
  62. package/dist/runtime/bundle/chunks/openai-completions-XGHMB3UO.js +7 -0
  63. package/dist/runtime/bundle/chunks/openai-responses-BSOJMSEV.js +2 -0
  64. package/dist/runtime/bundle/chunks/openrouter-images-N4XVVFSD.js +2 -0
  65. package/dist/runtime/bundle/chunks/openrouter.js +75 -0
  66. package/dist/runtime/bundle/chunks/pi-messages-TPFH44NP.js +8 -0
  67. package/dist/runtime/bundle/chunks/radius.js +75 -0
  68. package/dist/runtime/bundle/chunks/src-UK77SYZE.js +4 -0
  69. package/dist/runtime/bundle/chunks/xai.js +2 -0
  70. package/dist/runtime/bundle/cli.js +3 -0
  71. package/dist/runtime/bundle/client.js +2 -0
  72. package/dist/runtime/bundle/index.js +2 -0
  73. package/dist/runtime/bundle/rpc-entry.js +3 -0
  74. package/dist/runtime/cli/args.d.ts +61 -0
  75. package/dist/runtime/cli/args.d.ts.map +1 -0
  76. package/dist/runtime/cli/args.js +439 -0
  77. package/dist/runtime/cli/args.js.map +1 -0
  78. package/dist/runtime/cli/auth-check.d.ts +19 -0
  79. package/dist/runtime/cli/auth-check.d.ts.map +1 -0
  80. package/dist/runtime/cli/auth-check.js +50 -0
  81. package/dist/runtime/cli/auth-check.js.map +1 -0
  82. package/dist/runtime/cli/auth-command.d.ts +24 -0
  83. package/dist/runtime/cli/auth-command.d.ts.map +1 -0
  84. package/dist/runtime/cli/auth-command.js +103 -0
  85. package/dist/runtime/cli/auth-command.js.map +1 -0
  86. package/dist/runtime/cli/config-selector.d.ts +16 -0
  87. package/dist/runtime/cli/config-selector.d.ts.map +1 -0
  88. package/dist/runtime/cli/config-selector.js +31 -0
  89. package/dist/runtime/cli/config-selector.js.map +1 -0
  90. package/dist/runtime/cli/credential-print.d.ts +13 -0
  91. package/dist/runtime/cli/credential-print.d.ts.map +1 -0
  92. package/dist/runtime/cli/credential-print.js +76 -0
  93. package/dist/runtime/cli/credential-print.js.map +1 -0
  94. package/dist/runtime/cli/experimental/auth.d.ts +16 -0
  95. package/dist/runtime/cli/experimental/auth.d.ts.map +1 -0
  96. package/dist/runtime/cli/experimental/auth.js +13 -0
  97. package/dist/runtime/cli/experimental/auth.js.map +1 -0
  98. package/dist/runtime/cli/experimental/cli.d.ts +6 -0
  99. package/dist/runtime/cli/experimental/cli.d.ts.map +1 -0
  100. package/dist/runtime/cli/experimental/cli.js +5 -0
  101. package/dist/runtime/cli/experimental/cli.js.map +1 -0
  102. package/dist/runtime/cli/experimental/command-options.d.ts +17 -0
  103. package/dist/runtime/cli/experimental/command-options.d.ts.map +1 -0
  104. package/dist/runtime/cli/experimental/command-options.js +35 -0
  105. package/dist/runtime/cli/experimental/command-options.js.map +1 -0
  106. package/dist/runtime/cli/experimental/command.d.ts +63 -0
  107. package/dist/runtime/cli/experimental/command.d.ts.map +1 -0
  108. package/dist/runtime/cli/experimental/command.js +130 -0
  109. package/dist/runtime/cli/experimental/command.js.map +1 -0
  110. package/dist/runtime/cli/experimental/commands/client.d.ts +13 -0
  111. package/dist/runtime/cli/experimental/commands/client.d.ts.map +1 -0
  112. package/dist/runtime/cli/experimental/commands/client.js +25 -0
  113. package/dist/runtime/cli/experimental/commands/client.js.map +1 -0
  114. package/dist/runtime/cli/experimental/commands/pi.d.ts +15 -0
  115. package/dist/runtime/cli/experimental/commands/pi.d.ts.map +1 -0
  116. package/dist/runtime/cli/experimental/commands/pi.js +28 -0
  117. package/dist/runtime/cli/experimental/commands/pi.js.map +1 -0
  118. package/dist/runtime/cli/experimental/commands/server.d.ts +13 -0
  119. package/dist/runtime/cli/experimental/commands/server.d.ts.map +1 -0
  120. package/dist/runtime/cli/experimental/commands/server.js +25 -0
  121. package/dist/runtime/cli/experimental/commands/server.js.map +1 -0
  122. package/dist/runtime/cli/experimental/transport-address.d.ts +10 -0
  123. package/dist/runtime/cli/experimental/transport-address.d.ts.map +1 -0
  124. package/dist/runtime/cli/experimental/transport-address.js +38 -0
  125. package/dist/runtime/cli/experimental/transport-address.js.map +1 -0
  126. package/dist/runtime/cli/file-processor.d.ts +15 -0
  127. package/dist/runtime/cli/file-processor.d.ts.map +1 -0
  128. package/dist/runtime/cli/file-processor.js +71 -0
  129. package/dist/runtime/cli/file-processor.js.map +1 -0
  130. package/dist/runtime/cli/initial-message.d.ts +18 -0
  131. package/dist/runtime/cli/initial-message.d.ts.map +1 -0
  132. package/dist/runtime/cli/initial-message.js +22 -0
  133. package/dist/runtime/cli/initial-message.js.map +1 -0
  134. package/dist/runtime/cli/list-models.d.ts +9 -0
  135. package/dist/runtime/cli/list-models.d.ts.map +1 -0
  136. package/dist/runtime/cli/list-models.js +98 -0
  137. package/dist/runtime/cli/list-models.js.map +1 -0
  138. package/dist/runtime/cli/project-trust.d.ts +10 -0
  139. package/dist/runtime/cli/project-trust.d.ts.map +1 -0
  140. package/dist/runtime/cli/project-trust.js +48 -0
  141. package/dist/runtime/cli/project-trust.js.map +1 -0
  142. package/dist/runtime/cli/session-picker.d.ts +10 -0
  143. package/dist/runtime/cli/session-picker.d.ts.map +1 -0
  144. package/dist/runtime/cli/session-picker.js +36 -0
  145. package/dist/runtime/cli/session-picker.js.map +1 -0
  146. package/dist/runtime/cli/startup-ui.d.ts +20 -0
  147. package/dist/runtime/cli/startup-ui.d.ts.map +1 -0
  148. package/dist/runtime/cli/startup-ui.js +184 -0
  149. package/dist/runtime/cli/startup-ui.js.map +1 -0
  150. package/dist/runtime/cli.d.ts +3 -0
  151. package/dist/runtime/cli.d.ts.map +1 -0
  152. package/dist/runtime/cli.js +19 -0
  153. package/dist/runtime/cli.js.map +1 -0
  154. package/dist/runtime/client/index.d.ts +3 -0
  155. package/dist/runtime/client/index.d.ts.map +1 -0
  156. package/dist/runtime/client/index.js +3 -0
  157. package/dist/runtime/client/index.js.map +1 -0
  158. package/dist/runtime/client/remote-session.d.ts +53 -0
  159. package/dist/runtime/client/remote-session.d.ts.map +1 -0
  160. package/dist/runtime/client/remote-session.js +340 -0
  161. package/dist/runtime/client/remote-session.js.map +1 -0
  162. package/dist/runtime/client/transcript.d.ts +12 -0
  163. package/dist/runtime/client/transcript.d.ts.map +1 -0
  164. package/dist/runtime/client/transcript.js +98 -0
  165. package/dist/runtime/client/transcript.js.map +1 -0
  166. package/dist/runtime/config.d.ts +98 -0
  167. package/dist/runtime/config.d.ts.map +1 -0
  168. package/dist/runtime/config.js +469 -0
  169. package/dist/runtime/config.js.map +1 -0
  170. package/dist/runtime/core/agent-session-runtime.d.ts +119 -0
  171. package/dist/runtime/core/agent-session-runtime.d.ts.map +1 -0
  172. package/dist/runtime/core/agent-session-runtime.js +309 -0
  173. package/dist/runtime/core/agent-session-runtime.js.map +1 -0
  174. package/dist/runtime/core/agent-session-services.d.ts +86 -0
  175. package/dist/runtime/core/agent-session-services.d.ts.map +1 -0
  176. package/dist/runtime/core/agent-session-services.js +134 -0
  177. package/dist/runtime/core/agent-session-services.js.map +1 -0
  178. package/dist/runtime/core/agent-session.d.ts +678 -0
  179. package/dist/runtime/core/agent-session.d.ts.map +1 -0
  180. package/dist/runtime/core/agent-session.js +2808 -0
  181. package/dist/runtime/core/agent-session.js.map +1 -0
  182. package/dist/runtime/core/auth-guidance.d.ts +5 -0
  183. package/dist/runtime/core/auth-guidance.d.ts.map +1 -0
  184. package/dist/runtime/core/auth-guidance.js +21 -0
  185. package/dist/runtime/core/auth-guidance.js.map +1 -0
  186. package/dist/runtime/core/auth-storage.d.ts +72 -0
  187. package/dist/runtime/core/auth-storage.d.ts.map +1 -0
  188. package/dist/runtime/core/auth-storage.js +426 -0
  189. package/dist/runtime/core/auth-storage.js.map +1 -0
  190. package/dist/runtime/core/bash-executor.d.ts +32 -0
  191. package/dist/runtime/core/bash-executor.d.ts.map +1 -0
  192. package/dist/runtime/core/bash-executor.js +111 -0
  193. package/dist/runtime/core/bash-executor.js.map +1 -0
  194. package/dist/runtime/core/cache-stats.d.ts +49 -0
  195. package/dist/runtime/core/cache-stats.d.ts.map +1 -0
  196. package/dist/runtime/core/cache-stats.js +101 -0
  197. package/dist/runtime/core/cache-stats.js.map +1 -0
  198. package/dist/runtime/core/compaction/branch-summarization.d.ts +98 -0
  199. package/dist/runtime/core/compaction/branch-summarization.d.ts.map +1 -0
  200. package/dist/runtime/core/compaction/branch-summarization.js +250 -0
  201. package/dist/runtime/core/compaction/branch-summarization.js.map +1 -0
  202. package/dist/runtime/core/compaction/compaction.d.ts +143 -0
  203. package/dist/runtime/core/compaction/compaction.d.ts.map +1 -0
  204. package/dist/runtime/core/compaction/compaction.js +669 -0
  205. package/dist/runtime/core/compaction/compaction.js.map +1 -0
  206. package/dist/runtime/core/compaction/index.d.ts +7 -0
  207. package/dist/runtime/core/compaction/index.d.ts.map +1 -0
  208. package/dist/runtime/core/compaction/index.js +7 -0
  209. package/dist/runtime/core/compaction/index.js.map +1 -0
  210. package/dist/runtime/core/compaction/utils.d.ts +38 -0
  211. package/dist/runtime/core/compaction/utils.d.ts.map +1 -0
  212. package/dist/runtime/core/compaction/utils.js +142 -0
  213. package/dist/runtime/core/compaction/utils.js.map +1 -0
  214. package/dist/runtime/core/defaults.d.ts +4 -0
  215. package/dist/runtime/core/defaults.d.ts.map +1 -0
  216. package/dist/runtime/core/defaults.js +11 -0
  217. package/dist/runtime/core/defaults.js.map +1 -0
  218. package/dist/runtime/core/diagnostics.d.ts +15 -0
  219. package/dist/runtime/core/diagnostics.d.ts.map +1 -0
  220. package/dist/runtime/core/diagnostics.js +2 -0
  221. package/dist/runtime/core/diagnostics.js.map +1 -0
  222. package/dist/runtime/core/event-bus.d.ts +9 -0
  223. package/dist/runtime/core/event-bus.d.ts.map +1 -0
  224. package/dist/runtime/core/event-bus.js +25 -0
  225. package/dist/runtime/core/event-bus.js.map +1 -0
  226. package/dist/runtime/core/exec.d.ts +29 -0
  227. package/dist/runtime/core/exec.d.ts.map +1 -0
  228. package/dist/runtime/core/exec.js +75 -0
  229. package/dist/runtime/core/exec.js.map +1 -0
  230. package/dist/runtime/core/experimental.d.ts +6 -0
  231. package/dist/runtime/core/experimental.d.ts.map +1 -0
  232. package/dist/runtime/core/experimental.js +8 -0
  233. package/dist/runtime/core/experimental.js.map +1 -0
  234. package/dist/runtime/core/export-html/ansi-to-html.d.ts +22 -0
  235. package/dist/runtime/core/export-html/ansi-to-html.d.ts.map +1 -0
  236. package/dist/runtime/core/export-html/ansi-to-html.js +249 -0
  237. package/dist/runtime/core/export-html/ansi-to-html.js.map +1 -0
  238. package/dist/runtime/core/export-html/index.d.ts +37 -0
  239. package/dist/runtime/core/export-html/index.d.ts.map +1 -0
  240. package/dist/runtime/core/export-html/index.js +226 -0
  241. package/dist/runtime/core/export-html/index.js.map +1 -0
  242. package/dist/runtime/core/export-html/template.css +1066 -0
  243. package/dist/runtime/core/export-html/template.html +55 -0
  244. package/dist/runtime/core/export-html/template.js +1864 -0
  245. package/dist/runtime/core/export-html/tool-renderer.d.ts +34 -0
  246. package/dist/runtime/core/export-html/tool-renderer.d.ts.map +1 -0
  247. package/dist/runtime/core/export-html/tool-renderer.js +108 -0
  248. package/dist/runtime/core/export-html/tool-renderer.js.map +1 -0
  249. package/dist/runtime/core/export-html/vendor/highlight.min.js +1213 -0
  250. package/dist/runtime/core/export-html/vendor/marked.min.js +78 -0
  251. package/dist/runtime/core/extensions/index.d.ts +12 -0
  252. package/dist/runtime/core/extensions/index.d.ts.map +1 -0
  253. package/dist/runtime/core/extensions/index.js +9 -0
  254. package/dist/runtime/core/extensions/index.js.map +1 -0
  255. package/dist/runtime/core/extensions/loader.d.ts +23 -0
  256. package/dist/runtime/core/extensions/loader.d.ts.map +1 -0
  257. package/dist/runtime/core/extensions/loader.js +648 -0
  258. package/dist/runtime/core/extensions/loader.js.map +1 -0
  259. package/dist/runtime/core/extensions/runner.d.ts +173 -0
  260. package/dist/runtime/core/extensions/runner.d.ts.map +1 -0
  261. package/dist/runtime/core/extensions/runner.js +967 -0
  262. package/dist/runtime/core/extensions/runner.js.map +1 -0
  263. package/dist/runtime/core/extensions/types.d.ts +1328 -0
  264. package/dist/runtime/core/extensions/types.d.ts.map +1 -0
  265. package/dist/runtime/core/extensions/types.js +48 -0
  266. package/dist/runtime/core/extensions/types.js.map +1 -0
  267. package/dist/runtime/core/extensions/wrapper.d.ts +20 -0
  268. package/dist/runtime/core/extensions/wrapper.d.ts.map +1 -0
  269. package/dist/runtime/core/extensions/wrapper.js +41 -0
  270. package/dist/runtime/core/extensions/wrapper.js.map +1 -0
  271. package/dist/runtime/core/footer-data-provider.d.ts +64 -0
  272. package/dist/runtime/core/footer-data-provider.d.ts.map +1 -0
  273. package/dist/runtime/core/footer-data-provider.js +338 -0
  274. package/dist/runtime/core/footer-data-provider.js.map +1 -0
  275. package/dist/runtime/core/http-dispatcher.d.ts +22 -0
  276. package/dist/runtime/core/http-dispatcher.d.ts.map +1 -0
  277. package/dist/runtime/core/http-dispatcher.js +96 -0
  278. package/dist/runtime/core/http-dispatcher.js.map +1 -0
  279. package/dist/runtime/core/index.d.ts +13 -0
  280. package/dist/runtime/core/index.d.ts.map +1 -0
  281. package/dist/runtime/core/index.js +13 -0
  282. package/dist/runtime/core/index.js.map +1 -0
  283. package/dist/runtime/core/keybindings.d.ts +423 -0
  284. package/dist/runtime/core/keybindings.d.ts.map +1 -0
  285. package/dist/runtime/core/keybindings.js +317 -0
  286. package/dist/runtime/core/keybindings.js.map +1 -0
  287. package/dist/runtime/core/messages.d.ts +77 -0
  288. package/dist/runtime/core/messages.d.ts.map +1 -0
  289. package/dist/runtime/core/messages.js +123 -0
  290. package/dist/runtime/core/messages.js.map +1 -0
  291. package/dist/runtime/core/model-config.d.ts +576 -0
  292. package/dist/runtime/core/model-config.d.ts.map +1 -0
  293. package/dist/runtime/core/model-config.js +256 -0
  294. package/dist/runtime/core/model-config.js.map +1 -0
  295. package/dist/runtime/core/model-registry.d.ts +45 -0
  296. package/dist/runtime/core/model-registry.d.ts.map +1 -0
  297. package/dist/runtime/core/model-registry.js +107 -0
  298. package/dist/runtime/core/model-registry.js.map +1 -0
  299. package/dist/runtime/core/model-resolver.d.ts +124 -0
  300. package/dist/runtime/core/model-resolver.d.ts.map +1 -0
  301. package/dist/runtime/core/model-resolver.js +589 -0
  302. package/dist/runtime/core/model-resolver.js.map +1 -0
  303. package/dist/runtime/core/model-runtime.d.ts +100 -0
  304. package/dist/runtime/core/model-runtime.d.ts.map +1 -0
  305. package/dist/runtime/core/model-runtime.js +599 -0
  306. package/dist/runtime/core/model-runtime.js.map +1 -0
  307. package/dist/runtime/core/models-store.d.ts +22 -0
  308. package/dist/runtime/core/models-store.d.ts.map +1 -0
  309. package/dist/runtime/core/models-store.js +115 -0
  310. package/dist/runtime/core/models-store.js.map +1 -0
  311. package/dist/runtime/core/output-guard.d.ts +7 -0
  312. package/dist/runtime/core/output-guard.d.ts.map +1 -0
  313. package/dist/runtime/core/output-guard.js +89 -0
  314. package/dist/runtime/core/output-guard.js.map +1 -0
  315. package/dist/runtime/core/package-manager.d.ts +213 -0
  316. package/dist/runtime/core/package-manager.d.ts.map +1 -0
  317. package/dist/runtime/core/package-manager.js +2177 -0
  318. package/dist/runtime/core/package-manager.js.map +1 -0
  319. package/dist/runtime/core/pi-manifest.d.ts +8 -0
  320. package/dist/runtime/core/pi-manifest.d.ts.map +1 -0
  321. package/dist/runtime/core/pi-manifest.js +26 -0
  322. package/dist/runtime/core/pi-manifest.js.map +1 -0
  323. package/dist/runtime/core/project-trust.d.ts +15 -0
  324. package/dist/runtime/core/project-trust.d.ts.map +1 -0
  325. package/dist/runtime/core/project-trust.js +59 -0
  326. package/dist/runtime/core/project-trust.js.map +1 -0
  327. package/dist/runtime/core/prompt-templates.d.ts +54 -0
  328. package/dist/runtime/core/prompt-templates.d.ts.map +1 -0
  329. package/dist/runtime/core/prompt-templates.js +236 -0
  330. package/dist/runtime/core/prompt-templates.js.map +1 -0
  331. package/dist/runtime/core/provider-attribution.d.ts +4 -0
  332. package/dist/runtime/core/provider-attribution.d.ts.map +1 -0
  333. package/dist/runtime/core/provider-attribution.js +72 -0
  334. package/dist/runtime/core/provider-attribution.js.map +1 -0
  335. package/dist/runtime/core/provider-composer.d.ts +58 -0
  336. package/dist/runtime/core/provider-composer.d.ts.map +1 -0
  337. package/dist/runtime/core/provider-composer.js +396 -0
  338. package/dist/runtime/core/provider-composer.js.map +1 -0
  339. package/dist/runtime/core/radius.d.ts +2 -0
  340. package/dist/runtime/core/radius.d.ts.map +1 -0
  341. package/dist/runtime/core/radius.js +2 -0
  342. package/dist/runtime/core/radius.js.map +1 -0
  343. package/dist/runtime/core/remote-catalog-provider.d.ts +5 -0
  344. package/dist/runtime/core/remote-catalog-provider.d.ts.map +1 -0
  345. package/dist/runtime/core/remote-catalog-provider.js +122 -0
  346. package/dist/runtime/core/remote-catalog-provider.js.map +1 -0
  347. package/dist/runtime/core/resolve-config-value.d.ts +30 -0
  348. package/dist/runtime/core/resolve-config-value.d.ts.map +1 -0
  349. package/dist/runtime/core/resolve-config-value.js +247 -0
  350. package/dist/runtime/core/resolve-config-value.js.map +1 -0
  351. package/dist/runtime/core/resource-loader.d.ts +221 -0
  352. package/dist/runtime/core/resource-loader.d.ts.map +1 -0
  353. package/dist/runtime/core/resource-loader.js +875 -0
  354. package/dist/runtime/core/resource-loader.js.map +1 -0
  355. package/dist/runtime/core/runtime-credentials.d.ts +15 -0
  356. package/dist/runtime/core/runtime-credentials.d.ts.map +1 -0
  357. package/dist/runtime/core/runtime-credentials.js +39 -0
  358. package/dist/runtime/core/runtime-credentials.js.map +1 -0
  359. package/dist/runtime/core/sdk.d.ts +108 -0
  360. package/dist/runtime/core/sdk.d.ts.map +1 -0
  361. package/dist/runtime/core/sdk.js +275 -0
  362. package/dist/runtime/core/sdk.js.map +1 -0
  363. package/dist/runtime/core/session-cwd.d.ts +19 -0
  364. package/dist/runtime/core/session-cwd.d.ts.map +1 -0
  365. package/dist/runtime/core/session-cwd.js +38 -0
  366. package/dist/runtime/core/session-cwd.js.map +1 -0
  367. package/dist/runtime/core/session-export.d.ts +4 -0
  368. package/dist/runtime/core/session-export.d.ts.map +1 -0
  369. package/dist/runtime/core/session-export.js +32 -0
  370. package/dist/runtime/core/session-export.js.map +1 -0
  371. package/dist/runtime/core/session-manager.d.ts +356 -0
  372. package/dist/runtime/core/session-manager.d.ts.map +1 -0
  373. package/dist/runtime/core/session-manager.js +1341 -0
  374. package/dist/runtime/core/session-manager.js.map +1 -0
  375. package/dist/runtime/core/settings-diagnostics.d.ts +9 -0
  376. package/dist/runtime/core/settings-diagnostics.d.ts.map +1 -0
  377. package/dist/runtime/core/settings-diagnostics.js +21 -0
  378. package/dist/runtime/core/settings-diagnostics.js.map +1 -0
  379. package/dist/runtime/core/settings-manager.d.ts +324 -0
  380. package/dist/runtime/core/settings-manager.d.ts.map +1 -0
  381. package/dist/runtime/core/settings-manager.js +980 -0
  382. package/dist/runtime/core/settings-manager.js.map +1 -0
  383. package/dist/runtime/core/skills.d.ts +60 -0
  384. package/dist/runtime/core/skills.d.ts.map +1 -0
  385. package/dist/runtime/core/skills.js +405 -0
  386. package/dist/runtime/core/skills.js.map +1 -0
  387. package/dist/runtime/core/slash-commands.d.ts +15 -0
  388. package/dist/runtime/core/slash-commands.d.ts.map +1 -0
  389. package/dist/runtime/core/slash-commands.js +27 -0
  390. package/dist/runtime/core/slash-commands.js.map +1 -0
  391. package/dist/runtime/core/source-info.d.ts +18 -0
  392. package/dist/runtime/core/source-info.d.ts.map +1 -0
  393. package/dist/runtime/core/source-info.js +19 -0
  394. package/dist/runtime/core/source-info.js.map +1 -0
  395. package/dist/runtime/core/system-prompt.d.ts +28 -0
  396. package/dist/runtime/core/system-prompt.d.ts.map +1 -0
  397. package/dist/runtime/core/system-prompt.js +119 -0
  398. package/dist/runtime/core/system-prompt.js.map +1 -0
  399. package/dist/runtime/core/telemetry.d.ts +3 -0
  400. package/dist/runtime/core/telemetry.d.ts.map +1 -0
  401. package/dist/runtime/core/telemetry.js +9 -0
  402. package/dist/runtime/core/telemetry.js.map +1 -0
  403. package/dist/runtime/core/timings.d.ts +10 -0
  404. package/dist/runtime/core/timings.d.ts.map +1 -0
  405. package/dist/runtime/core/timings.js +41 -0
  406. package/dist/runtime/core/timings.js.map +1 -0
  407. package/dist/runtime/core/tools/bash.d.ts +87 -0
  408. package/dist/runtime/core/tools/bash.d.ts.map +1 -0
  409. package/dist/runtime/core/tools/bash.js +410 -0
  410. package/dist/runtime/core/tools/bash.js.map +1 -0
  411. package/dist/runtime/core/tools/edit-diff.d.ts +101 -0
  412. package/dist/runtime/core/tools/edit-diff.d.ts.map +1 -0
  413. package/dist/runtime/core/tools/edit-diff.js +421 -0
  414. package/dist/runtime/core/tools/edit-diff.js.map +1 -0
  415. package/dist/runtime/core/tools/edit.d.ts +55 -0
  416. package/dist/runtime/core/tools/edit.d.ts.map +1 -0
  417. package/dist/runtime/core/tools/edit.js +306 -0
  418. package/dist/runtime/core/tools/edit.js.map +1 -0
  419. package/dist/runtime/core/tools/file-mutation-queue.d.ts +6 -0
  420. package/dist/runtime/core/tools/file-mutation-queue.d.ts.map +1 -0
  421. package/dist/runtime/core/tools/file-mutation-queue.js +52 -0
  422. package/dist/runtime/core/tools/file-mutation-queue.js.map +1 -0
  423. package/dist/runtime/core/tools/find.d.ts +42 -0
  424. package/dist/runtime/core/tools/find.d.ts.map +1 -0
  425. package/dist/runtime/core/tools/find.js +302 -0
  426. package/dist/runtime/core/tools/find.js.map +1 -0
  427. package/dist/runtime/core/tools/grep.d.ts +41 -0
  428. package/dist/runtime/core/tools/grep.d.ts.map +1 -0
  429. package/dist/runtime/core/tools/grep.js +308 -0
  430. package/dist/runtime/core/tools/grep.js.map +1 -0
  431. package/dist/runtime/core/tools/index.d.ts +43 -0
  432. package/dist/runtime/core/tools/index.d.ts.map +1 -0
  433. package/dist/runtime/core/tools/index.js +129 -0
  434. package/dist/runtime/core/tools/index.js.map +1 -0
  435. package/dist/runtime/core/tools/ls.d.ts +41 -0
  436. package/dist/runtime/core/tools/ls.d.ts.map +1 -0
  437. package/dist/runtime/core/tools/ls.js +171 -0
  438. package/dist/runtime/core/tools/ls.js.map +1 -0
  439. package/dist/runtime/core/tools/output-accumulator.d.ts +52 -0
  440. package/dist/runtime/core/tools/output-accumulator.d.ts.map +1 -0
  441. package/dist/runtime/core/tools/output-accumulator.js +184 -0
  442. package/dist/runtime/core/tools/output-accumulator.js.map +1 -0
  443. package/dist/runtime/core/tools/path-utils.d.ts +10 -0
  444. package/dist/runtime/core/tools/path-utils.d.ts.map +1 -0
  445. package/dist/runtime/core/tools/path-utils.js +99 -0
  446. package/dist/runtime/core/tools/path-utils.js.map +1 -0
  447. package/dist/runtime/core/tools/powershell.d.ts +16 -0
  448. package/dist/runtime/core/tools/powershell.d.ts.map +1 -0
  449. package/dist/runtime/core/tools/powershell.js +39 -0
  450. package/dist/runtime/core/tools/powershell.js.map +1 -0
  451. package/dist/runtime/core/tools/read.d.ts +39 -0
  452. package/dist/runtime/core/tools/read.d.ts.map +1 -0
  453. package/dist/runtime/core/tools/read.js +282 -0
  454. package/dist/runtime/core/tools/read.js.map +1 -0
  455. package/dist/runtime/core/tools/render-utils.d.ts +24 -0
  456. package/dist/runtime/core/tools/render-utils.d.ts.map +1 -0
  457. package/dist/runtime/core/tools/render-utils.js +65 -0
  458. package/dist/runtime/core/tools/render-utils.js.map +1 -0
  459. package/dist/runtime/core/tools/tool-definition-wrapper.d.ts +14 -0
  460. package/dist/runtime/core/tools/tool-definition-wrapper.d.ts.map +1 -0
  461. package/dist/runtime/core/tools/tool-definition-wrapper.js +36 -0
  462. package/dist/runtime/core/tools/tool-definition-wrapper.js.map +1 -0
  463. package/dist/runtime/core/tools/truncate.d.ts +70 -0
  464. package/dist/runtime/core/tools/truncate.d.ts.map +1 -0
  465. package/dist/runtime/core/tools/truncate.js +215 -0
  466. package/dist/runtime/core/tools/truncate.js.map +1 -0
  467. package/dist/runtime/core/tools/write.d.ts +30 -0
  468. package/dist/runtime/core/tools/write.d.ts.map +1 -0
  469. package/dist/runtime/core/tools/write.js +203 -0
  470. package/dist/runtime/core/tools/write.js.map +1 -0
  471. package/dist/runtime/core/trust-manager.d.ts +36 -0
  472. package/dist/runtime/core/trust-manager.d.ts.map +1 -0
  473. package/dist/runtime/core/trust-manager.js +203 -0
  474. package/dist/runtime/core/trust-manager.js.map +1 -0
  475. package/dist/runtime/core/usage-totals.d.ts +19 -0
  476. package/dist/runtime/core/usage-totals.d.ts.map +1 -0
  477. package/dist/runtime/core/usage-totals.js +52 -0
  478. package/dist/runtime/core/usage-totals.js.map +1 -0
  479. package/dist/runtime/extensions/index.d.ts +3 -0
  480. package/dist/runtime/extensions/index.d.ts.map +1 -0
  481. package/dist/runtime/extensions/index.js +3 -0
  482. package/dist/runtime/extensions/index.js.map +1 -0
  483. package/dist/runtime/extensions/llama/client.d.ts +67 -0
  484. package/dist/runtime/extensions/llama/client.d.ts.map +1 -0
  485. package/dist/runtime/extensions/llama/client.js +309 -0
  486. package/dist/runtime/extensions/llama/client.js.map +1 -0
  487. package/dist/runtime/extensions/llama/huggingface.d.ts +23 -0
  488. package/dist/runtime/extensions/llama/huggingface.d.ts.map +1 -0
  489. package/dist/runtime/extensions/llama/huggingface.js +141 -0
  490. package/dist/runtime/extensions/llama/huggingface.js.map +1 -0
  491. package/dist/runtime/extensions/llama/index.d.ts +3 -0
  492. package/dist/runtime/extensions/llama/index.d.ts.map +1 -0
  493. package/dist/runtime/extensions/llama/index.js +219 -0
  494. package/dist/runtime/extensions/llama/index.js.map +1 -0
  495. package/dist/runtime/extensions/llama/provider.d.ts +12 -0
  496. package/dist/runtime/extensions/llama/provider.d.ts.map +1 -0
  497. package/dist/runtime/extensions/llama/provider.js +146 -0
  498. package/dist/runtime/extensions/llama/provider.js.map +1 -0
  499. package/dist/runtime/extensions/llama/ui.d.ts +42 -0
  500. package/dist/runtime/extensions/llama/ui.d.ts.map +1 -0
  501. package/dist/runtime/extensions/llama/ui.js +416 -0
  502. package/dist/runtime/extensions/llama/ui.js.map +1 -0
  503. package/dist/runtime/index.d.ts +37 -0
  504. package/dist/runtime/index.d.ts.map +1 -0
  505. package/dist/runtime/index.js +49 -0
  506. package/dist/runtime/index.js.map +1 -0
  507. package/dist/runtime/main.d.ts +16 -0
  508. package/dist/runtime/main.d.ts.map +1 -0
  509. package/dist/runtime/main.js +799 -0
  510. package/dist/runtime/main.js.map +1 -0
  511. package/dist/runtime/migrations.d.ts +33 -0
  512. package/dist/runtime/migrations.d.ts.map +1 -0
  513. package/dist/runtime/migrations.js +282 -0
  514. package/dist/runtime/migrations.js.map +1 -0
  515. package/dist/runtime/modes/index.d.ts +10 -0
  516. package/dist/runtime/modes/index.d.ts.map +1 -0
  517. package/dist/runtime/modes/index.js +8 -0
  518. package/dist/runtime/modes/index.js.map +1 -0
  519. package/dist/runtime/modes/interactive/assets/clankolas.png +0 -0
  520. package/dist/runtime/modes/interactive/components/armin.d.ts +34 -0
  521. package/dist/runtime/modes/interactive/components/armin.d.ts.map +1 -0
  522. package/dist/runtime/modes/interactive/components/armin.js +333 -0
  523. package/dist/runtime/modes/interactive/components/armin.js.map +1 -0
  524. package/dist/runtime/modes/interactive/components/assistant-message.d.ts +25 -0
  525. package/dist/runtime/modes/interactive/components/assistant-message.d.ts.map +1 -0
  526. package/dist/runtime/modes/interactive/components/assistant-message.js +150 -0
  527. package/dist/runtime/modes/interactive/components/assistant-message.js.map +1 -0
  528. package/dist/runtime/modes/interactive/components/bash-execution.d.ts +34 -0
  529. package/dist/runtime/modes/interactive/components/bash-execution.d.ts.map +1 -0
  530. package/dist/runtime/modes/interactive/components/bash-execution.js +175 -0
  531. package/dist/runtime/modes/interactive/components/bash-execution.js.map +1 -0
  532. package/dist/runtime/modes/interactive/components/bordered-loader.d.ts +16 -0
  533. package/dist/runtime/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  534. package/dist/runtime/modes/interactive/components/bordered-loader.js +54 -0
  535. package/dist/runtime/modes/interactive/components/bordered-loader.js.map +1 -0
  536. package/dist/runtime/modes/interactive/components/branch-summary-message.d.ts +16 -0
  537. package/dist/runtime/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  538. package/dist/runtime/modes/interactive/components/branch-summary-message.js +44 -0
  539. package/dist/runtime/modes/interactive/components/branch-summary-message.js.map +1 -0
  540. package/dist/runtime/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  541. package/dist/runtime/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  542. package/dist/runtime/modes/interactive/components/compaction-summary-message.js +45 -0
  543. package/dist/runtime/modes/interactive/components/compaction-summary-message.js.map +1 -0
  544. package/dist/runtime/modes/interactive/components/config-selector.d.ts +102 -0
  545. package/dist/runtime/modes/interactive/components/config-selector.d.ts.map +1 -0
  546. package/dist/runtime/modes/interactive/components/config-selector.js +761 -0
  547. package/dist/runtime/modes/interactive/components/config-selector.js.map +1 -0
  548. package/dist/runtime/modes/interactive/components/countdown-timer.d.ts +14 -0
  549. package/dist/runtime/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  550. package/dist/runtime/modes/interactive/components/countdown-timer.js +33 -0
  551. package/dist/runtime/modes/interactive/components/countdown-timer.js.map +1 -0
  552. package/dist/runtime/modes/interactive/components/custom-editor.d.ts +21 -0
  553. package/dist/runtime/modes/interactive/components/custom-editor.d.ts.map +1 -0
  554. package/dist/runtime/modes/interactive/components/custom-editor.js +77 -0
  555. package/dist/runtime/modes/interactive/components/custom-editor.js.map +1 -0
  556. package/dist/runtime/modes/interactive/components/custom-entry.d.ts +19 -0
  557. package/dist/runtime/modes/interactive/components/custom-entry.d.ts.map +1 -0
  558. package/dist/runtime/modes/interactive/components/custom-entry.js +52 -0
  559. package/dist/runtime/modes/interactive/components/custom-entry.js.map +1 -0
  560. package/dist/runtime/modes/interactive/components/custom-message.d.ts +22 -0
  561. package/dist/runtime/modes/interactive/components/custom-message.d.ts.map +1 -0
  562. package/dist/runtime/modes/interactive/components/custom-message.js +87 -0
  563. package/dist/runtime/modes/interactive/components/custom-message.js.map +1 -0
  564. package/dist/runtime/modes/interactive/components/daxnuts.d.ts +23 -0
  565. package/dist/runtime/modes/interactive/components/daxnuts.d.ts.map +1 -0
  566. package/dist/runtime/modes/interactive/components/daxnuts.js +140 -0
  567. package/dist/runtime/modes/interactive/components/daxnuts.js.map +1 -0
  568. package/dist/runtime/modes/interactive/components/diff.d.ts +12 -0
  569. package/dist/runtime/modes/interactive/components/diff.d.ts.map +1 -0
  570. package/dist/runtime/modes/interactive/components/diff.js +133 -0
  571. package/dist/runtime/modes/interactive/components/diff.js.map +1 -0
  572. package/dist/runtime/modes/interactive/components/dynamic-border.d.ts +15 -0
  573. package/dist/runtime/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  574. package/dist/runtime/modes/interactive/components/dynamic-border.js +21 -0
  575. package/dist/runtime/modes/interactive/components/dynamic-border.js.map +1 -0
  576. package/dist/runtime/modes/interactive/components/earendil-announcement.d.ts +5 -0
  577. package/dist/runtime/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
  578. package/dist/runtime/modes/interactive/components/earendil-announcement.js +40 -0
  579. package/dist/runtime/modes/interactive/components/earendil-announcement.js.map +1 -0
  580. package/dist/runtime/modes/interactive/components/extension-editor.d.ts +21 -0
  581. package/dist/runtime/modes/interactive/components/extension-editor.d.ts.map +1 -0
  582. package/dist/runtime/modes/interactive/components/extension-editor.js +98 -0
  583. package/dist/runtime/modes/interactive/components/extension-editor.js.map +1 -0
  584. package/dist/runtime/modes/interactive/components/extension-input.d.ts +23 -0
  585. package/dist/runtime/modes/interactive/components/extension-input.d.ts.map +1 -0
  586. package/dist/runtime/modes/interactive/components/extension-input.js +61 -0
  587. package/dist/runtime/modes/interactive/components/extension-input.js.map +1 -0
  588. package/dist/runtime/modes/interactive/components/extension-selector.d.ts +26 -0
  589. package/dist/runtime/modes/interactive/components/extension-selector.d.ts.map +1 -0
  590. package/dist/runtime/modes/interactive/components/extension-selector.js +83 -0
  591. package/dist/runtime/modes/interactive/components/extension-selector.js.map +1 -0
  592. package/dist/runtime/modes/interactive/components/first-time-setup.d.ts +25 -0
  593. package/dist/runtime/modes/interactive/components/first-time-setup.d.ts.map +1 -0
  594. package/dist/runtime/modes/interactive/components/first-time-setup.js +103 -0
  595. package/dist/runtime/modes/interactive/components/first-time-setup.js.map +1 -0
  596. package/dist/runtime/modes/interactive/components/footer.d.ts +32 -0
  597. package/dist/runtime/modes/interactive/components/footer.d.ts.map +1 -0
  598. package/dist/runtime/modes/interactive/components/footer.js +222 -0
  599. package/dist/runtime/modes/interactive/components/footer.js.map +1 -0
  600. package/dist/runtime/modes/interactive/components/index.d.ts +34 -0
  601. package/dist/runtime/modes/interactive/components/index.d.ts.map +1 -0
  602. package/dist/runtime/modes/interactive/components/index.js +35 -0
  603. package/dist/runtime/modes/interactive/components/index.js.map +1 -0
  604. package/dist/runtime/modes/interactive/components/keybinding-hints.d.ts +13 -0
  605. package/dist/runtime/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  606. package/dist/runtime/modes/interactive/components/keybinding-hints.js +36 -0
  607. package/dist/runtime/modes/interactive/components/keybinding-hints.js.map +1 -0
  608. package/dist/runtime/modes/interactive/components/login-dialog.d.ts +52 -0
  609. package/dist/runtime/modes/interactive/components/login-dialog.d.ts.map +1 -0
  610. package/dist/runtime/modes/interactive/components/login-dialog.js +188 -0
  611. package/dist/runtime/modes/interactive/components/login-dialog.js.map +1 -0
  612. package/dist/runtime/modes/interactive/components/markdown-transform.d.ts +3 -0
  613. package/dist/runtime/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  614. package/dist/runtime/modes/interactive/components/markdown-transform.js +19 -0
  615. package/dist/runtime/modes/interactive/components/markdown-transform.js.map +1 -0
  616. package/dist/runtime/modes/interactive/components/mermaid.d.ts +11 -0
  617. package/dist/runtime/modes/interactive/components/mermaid.d.ts.map +1 -0
  618. package/dist/runtime/modes/interactive/components/mermaid.js +75 -0
  619. package/dist/runtime/modes/interactive/components/mermaid.js.map +1 -0
  620. package/dist/runtime/modes/interactive/components/model-selector.d.ts +60 -0
  621. package/dist/runtime/modes/interactive/components/model-selector.d.ts.map +1 -0
  622. package/dist/runtime/modes/interactive/components/model-selector.js +370 -0
  623. package/dist/runtime/modes/interactive/components/model-selector.js.map +1 -0
  624. package/dist/runtime/modes/interactive/components/oauth-selector.d.ts +33 -0
  625. package/dist/runtime/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  626. package/dist/runtime/modes/interactive/components/oauth-selector.js +163 -0
  627. package/dist/runtime/modes/interactive/components/oauth-selector.js.map +1 -0
  628. package/dist/runtime/modes/interactive/components/scoped-models-selector.d.ts +46 -0
  629. package/dist/runtime/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  630. package/dist/runtime/modes/interactive/components/scoped-models-selector.js +328 -0
  631. package/dist/runtime/modes/interactive/components/scoped-models-selector.js.map +1 -0
  632. package/dist/runtime/modes/interactive/components/session-selector-search.d.ts +23 -0
  633. package/dist/runtime/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  634. package/dist/runtime/modes/interactive/components/session-selector-search.js +155 -0
  635. package/dist/runtime/modes/interactive/components/session-selector-search.js.map +1 -0
  636. package/dist/runtime/modes/interactive/components/session-selector.d.ts +95 -0
  637. package/dist/runtime/modes/interactive/components/session-selector.d.ts.map +1 -0
  638. package/dist/runtime/modes/interactive/components/session-selector.js +867 -0
  639. package/dist/runtime/modes/interactive/components/session-selector.js.map +1 -0
  640. package/dist/runtime/modes/interactive/components/settings-selector.d.ts +90 -0
  641. package/dist/runtime/modes/interactive/components/settings-selector.d.ts.map +1 -0
  642. package/dist/runtime/modes/interactive/components/settings-selector.js +695 -0
  643. package/dist/runtime/modes/interactive/components/settings-selector.js.map +1 -0
  644. package/dist/runtime/modes/interactive/components/settings-submenu.d.ts +72 -0
  645. package/dist/runtime/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  646. package/dist/runtime/modes/interactive/components/settings-submenu.js +165 -0
  647. package/dist/runtime/modes/interactive/components/settings-submenu.js.map +1 -0
  648. package/dist/runtime/modes/interactive/components/show-images-selector.d.ts +10 -0
  649. package/dist/runtime/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  650. package/dist/runtime/modes/interactive/components/show-images-selector.js +39 -0
  651. package/dist/runtime/modes/interactive/components/show-images-selector.js.map +1 -0
  652. package/dist/runtime/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  653. package/dist/runtime/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  654. package/dist/runtime/modes/interactive/components/skill-invocation-message.js +47 -0
  655. package/dist/runtime/modes/interactive/components/skill-invocation-message.js.map +1 -0
  656. package/dist/runtime/modes/interactive/components/status-indicator.d.ts +28 -0
  657. package/dist/runtime/modes/interactive/components/status-indicator.d.ts.map +1 -0
  658. package/dist/runtime/modes/interactive/components/status-indicator.js +60 -0
  659. package/dist/runtime/modes/interactive/components/status-indicator.js.map +1 -0
  660. package/dist/runtime/modes/interactive/components/theme-selector.d.ts +11 -0
  661. package/dist/runtime/modes/interactive/components/theme-selector.d.ts.map +1 -0
  662. package/dist/runtime/modes/interactive/components/theme-selector.js +50 -0
  663. package/dist/runtime/modes/interactive/components/theme-selector.js.map +1 -0
  664. package/dist/runtime/modes/interactive/components/thinking-selector.d.ts +23 -0
  665. package/dist/runtime/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  666. package/dist/runtime/modes/interactive/components/thinking-selector.js +109 -0
  667. package/dist/runtime/modes/interactive/components/thinking-selector.js.map +1 -0
  668. package/dist/runtime/modes/interactive/components/tool-execution.d.ts +63 -0
  669. package/dist/runtime/modes/interactive/components/tool-execution.d.ts.map +1 -0
  670. package/dist/runtime/modes/interactive/components/tool-execution.js +326 -0
  671. package/dist/runtime/modes/interactive/components/tool-execution.js.map +1 -0
  672. package/dist/runtime/modes/interactive/components/tree-selector.d.ts +94 -0
  673. package/dist/runtime/modes/interactive/components/tree-selector.d.ts.map +1 -0
  674. package/dist/runtime/modes/interactive/components/tree-selector.js +1245 -0
  675. package/dist/runtime/modes/interactive/components/tree-selector.js.map +1 -0
  676. package/dist/runtime/modes/interactive/components/trust-selector.d.ts +23 -0
  677. package/dist/runtime/modes/interactive/components/trust-selector.d.ts.map +1 -0
  678. package/dist/runtime/modes/interactive/components/trust-selector.js +91 -0
  679. package/dist/runtime/modes/interactive/components/trust-selector.js.map +1 -0
  680. package/dist/runtime/modes/interactive/components/user-message-selector.d.ts +30 -0
  681. package/dist/runtime/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  682. package/dist/runtime/modes/interactive/components/user-message-selector.js +114 -0
  683. package/dist/runtime/modes/interactive/components/user-message-selector.js.map +1 -0
  684. package/dist/runtime/modes/interactive/components/user-message.d.ts +16 -0
  685. package/dist/runtime/modes/interactive/components/user-message.d.ts.map +1 -0
  686. package/dist/runtime/modes/interactive/components/user-message.js +49 -0
  687. package/dist/runtime/modes/interactive/components/user-message.js.map +1 -0
  688. package/dist/runtime/modes/interactive/components/visual-truncate.d.ts +24 -0
  689. package/dist/runtime/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  690. package/dist/runtime/modes/interactive/components/visual-truncate.js +33 -0
  691. package/dist/runtime/modes/interactive/components/visual-truncate.js.map +1 -0
  692. package/dist/runtime/modes/interactive/external-editor.d.ts +12 -0
  693. package/dist/runtime/modes/interactive/external-editor.d.ts.map +1 -0
  694. package/dist/runtime/modes/interactive/external-editor.js +38 -0
  695. package/dist/runtime/modes/interactive/external-editor.js.map +1 -0
  696. package/dist/runtime/modes/interactive/interactive-mode.d.ts +446 -0
  697. package/dist/runtime/modes/interactive/interactive-mode.d.ts.map +1 -0
  698. package/dist/runtime/modes/interactive/interactive-mode.js +5509 -0
  699. package/dist/runtime/modes/interactive/interactive-mode.js.map +1 -0
  700. package/dist/runtime/modes/interactive/model-catalog-refresh.d.ts +7 -0
  701. package/dist/runtime/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  702. package/dist/runtime/modes/interactive/model-catalog-refresh.js +34 -0
  703. package/dist/runtime/modes/interactive/model-catalog-refresh.js.map +1 -0
  704. package/dist/runtime/modes/interactive/model-search.d.ts +12 -0
  705. package/dist/runtime/modes/interactive/model-search.d.ts.map +1 -0
  706. package/dist/runtime/modes/interactive/model-search.js +15 -0
  707. package/dist/runtime/modes/interactive/model-search.js.map +1 -0
  708. package/dist/runtime/modes/interactive/session-share.d.ts +16 -0
  709. package/dist/runtime/modes/interactive/session-share.d.ts.map +1 -0
  710. package/dist/runtime/modes/interactive/session-share.js +188 -0
  711. package/dist/runtime/modes/interactive/session-share.js.map +1 -0
  712. package/dist/runtime/modes/interactive/theme/dark.json +90 -0
  713. package/dist/runtime/modes/interactive/theme/light.json +89 -0
  714. package/dist/runtime/modes/interactive/theme/theme-controller.d.ts +40 -0
  715. package/dist/runtime/modes/interactive/theme/theme-controller.d.ts.map +1 -0
  716. package/dist/runtime/modes/interactive/theme/theme-controller.js +125 -0
  717. package/dist/runtime/modes/interactive/theme/theme-controller.js.map +1 -0
  718. package/dist/runtime/modes/interactive/theme/theme-schema.json +352 -0
  719. package/dist/runtime/modes/interactive/theme/theme.d.ts +122 -0
  720. package/dist/runtime/modes/interactive/theme/theme.d.ts.map +1 -0
  721. package/dist/runtime/modes/interactive/theme/theme.js +1092 -0
  722. package/dist/runtime/modes/interactive/theme/theme.js.map +1 -0
  723. package/dist/runtime/modes/json-event.d.ts +34 -0
  724. package/dist/runtime/modes/json-event.d.ts.map +1 -0
  725. package/dist/runtime/modes/json-event.js +29 -0
  726. package/dist/runtime/modes/json-event.js.map +1 -0
  727. package/dist/runtime/modes/print-mode.d.ts +28 -0
  728. package/dist/runtime/modes/print-mode.d.ts.map +1 -0
  729. package/dist/runtime/modes/print-mode.js +142 -0
  730. package/dist/runtime/modes/print-mode.js.map +1 -0
  731. package/dist/runtime/modes/rpc/jsonl.d.ts +17 -0
  732. package/dist/runtime/modes/rpc/jsonl.d.ts.map +1 -0
  733. package/dist/runtime/modes/rpc/jsonl.js +49 -0
  734. package/dist/runtime/modes/rpc/jsonl.js.map +1 -0
  735. package/dist/runtime/modes/rpc/rpc-client.d.ts +254 -0
  736. package/dist/runtime/modes/rpc/rpc-client.d.ts.map +1 -0
  737. package/dist/runtime/modes/rpc/rpc-client.js +495 -0
  738. package/dist/runtime/modes/rpc/rpc-client.js.map +1 -0
  739. package/dist/runtime/modes/rpc/rpc-mode.d.ts +20 -0
  740. package/dist/runtime/modes/rpc/rpc-mode.d.ts.map +1 -0
  741. package/dist/runtime/modes/rpc/rpc-mode.js +657 -0
  742. package/dist/runtime/modes/rpc/rpc-mode.js.map +1 -0
  743. package/dist/runtime/modes/rpc/rpc-types.d.ts +469 -0
  744. package/dist/runtime/modes/rpc/rpc-types.d.ts.map +1 -0
  745. package/dist/runtime/modes/rpc/rpc-types.js +8 -0
  746. package/dist/runtime/modes/rpc/rpc-types.js.map +1 -0
  747. package/dist/runtime/package-manager-cli.d.ts +9 -0
  748. package/dist/runtime/package-manager-cli.d.ts.map +1 -0
  749. package/dist/runtime/package-manager-cli.js +961 -0
  750. package/dist/runtime/package-manager-cli.js.map +1 -0
  751. package/dist/runtime/rpc-entry.d.ts +3 -0
  752. package/dist/runtime/rpc-entry.d.ts.map +1 -0
  753. package/dist/runtime/rpc-entry.js +11 -0
  754. package/dist/runtime/rpc-entry.js.map +1 -0
  755. package/dist/runtime/server/create-harness.d.ts +26 -0
  756. package/dist/runtime/server/create-harness.d.ts.map +1 -0
  757. package/dist/runtime/server/create-harness.js +106 -0
  758. package/dist/runtime/server/create-harness.js.map +1 -0
  759. package/dist/runtime/utils/abort.d.ts +5 -0
  760. package/dist/runtime/utils/abort.d.ts.map +1 -0
  761. package/dist/runtime/utils/abort.js +48 -0
  762. package/dist/runtime/utils/abort.js.map +1 -0
  763. package/dist/runtime/utils/ansi.d.ts +2 -0
  764. package/dist/runtime/utils/ansi.d.ts.map +1 -0
  765. package/dist/runtime/utils/ansi.js +52 -0
  766. package/dist/runtime/utils/ansi.js.map +1 -0
  767. package/dist/runtime/utils/changelog.d.ts +22 -0
  768. package/dist/runtime/utils/changelog.d.ts.map +1 -0
  769. package/dist/runtime/utils/changelog.js +165 -0
  770. package/dist/runtime/utils/changelog.js.map +1 -0
  771. package/dist/runtime/utils/child-process.d.ts +18 -0
  772. package/dist/runtime/utils/child-process.d.ts.map +1 -0
  773. package/dist/runtime/utils/child-process.js +106 -0
  774. package/dist/runtime/utils/child-process.js.map +1 -0
  775. package/dist/runtime/utils/clipboard-image.d.ts +11 -0
  776. package/dist/runtime/utils/clipboard-image.d.ts.map +1 -0
  777. package/dist/runtime/utils/clipboard-image.js +245 -0
  778. package/dist/runtime/utils/clipboard-image.js.map +1 -0
  779. package/dist/runtime/utils/clipboard-native.d.ts +11 -0
  780. package/dist/runtime/utils/clipboard-native.d.ts.map +1 -0
  781. package/dist/runtime/utils/clipboard-native.js +20 -0
  782. package/dist/runtime/utils/clipboard-native.js.map +1 -0
  783. package/dist/runtime/utils/clipboard.d.ts +4 -0
  784. package/dist/runtime/utils/clipboard.d.ts.map +1 -0
  785. package/dist/runtime/utils/clipboard.js +161 -0
  786. package/dist/runtime/utils/clipboard.js.map +1 -0
  787. package/dist/runtime/utils/deprecation.d.ts +4 -0
  788. package/dist/runtime/utils/deprecation.d.ts.map +1 -0
  789. package/dist/runtime/utils/deprecation.js +13 -0
  790. package/dist/runtime/utils/deprecation.js.map +1 -0
  791. package/dist/runtime/utils/exif-orientation.d.ts +5 -0
  792. package/dist/runtime/utils/exif-orientation.d.ts.map +1 -0
  793. package/dist/runtime/utils/exif-orientation.js +158 -0
  794. package/dist/runtime/utils/exif-orientation.js.map +1 -0
  795. package/dist/runtime/utils/frontmatter.d.ts +8 -0
  796. package/dist/runtime/utils/frontmatter.d.ts.map +1 -0
  797. package/dist/runtime/utils/frontmatter.js +27 -0
  798. package/dist/runtime/utils/frontmatter.js.map +1 -0
  799. package/dist/runtime/utils/fs-watch.d.ts +5 -0
  800. package/dist/runtime/utils/fs-watch.d.ts.map +1 -0
  801. package/dist/runtime/utils/fs-watch.js +25 -0
  802. package/dist/runtime/utils/fs-watch.js.map +1 -0
  803. package/dist/runtime/utils/git.d.ts +26 -0
  804. package/dist/runtime/utils/git.d.ts.map +1 -0
  805. package/dist/runtime/utils/git.js +195 -0
  806. package/dist/runtime/utils/git.js.map +1 -0
  807. package/dist/runtime/utils/html.d.ts +7 -0
  808. package/dist/runtime/utils/html.d.ts.map +1 -0
  809. package/dist/runtime/utils/html.js +40 -0
  810. package/dist/runtime/utils/html.js.map +1 -0
  811. package/dist/runtime/utils/image-convert.d.ts +10 -0
  812. package/dist/runtime/utils/image-convert.d.ts.map +1 -0
  813. package/dist/runtime/utils/image-convert.js +45 -0
  814. package/dist/runtime/utils/image-convert.js.map +1 -0
  815. package/dist/runtime/utils/image-process.d.ts +18 -0
  816. package/dist/runtime/utils/image-process.d.ts.map +1 -0
  817. package/dist/runtime/utils/image-process.js +83 -0
  818. package/dist/runtime/utils/image-process.js.map +1 -0
  819. package/dist/runtime/utils/image-resize-core.d.ts +30 -0
  820. package/dist/runtime/utils/image-resize-core.d.ts.map +1 -0
  821. package/dist/runtime/utils/image-resize-core.js +124 -0
  822. package/dist/runtime/utils/image-resize-core.js.map +1 -0
  823. package/dist/runtime/utils/image-resize-worker.d.ts +2 -0
  824. package/dist/runtime/utils/image-resize-worker.d.ts.map +1 -0
  825. package/dist/runtime/utils/image-resize-worker.js +31 -0
  826. package/dist/runtime/utils/image-resize-worker.js.map +1 -0
  827. package/dist/runtime/utils/image-resize.d.ts +16 -0
  828. package/dist/runtime/utils/image-resize.d.ts.map +1 -0
  829. package/dist/runtime/utils/image-resize.js +97 -0
  830. package/dist/runtime/utils/image-resize.js.map +1 -0
  831. package/dist/runtime/utils/json.d.ts +3 -0
  832. package/dist/runtime/utils/json.d.ts.map +1 -0
  833. package/dist/runtime/utils/json.js +7 -0
  834. package/dist/runtime/utils/json.js.map +1 -0
  835. package/dist/runtime/utils/management-http.d.ts +25 -0
  836. package/dist/runtime/utils/management-http.d.ts.map +1 -0
  837. package/dist/runtime/utils/management-http.js +54 -0
  838. package/dist/runtime/utils/management-http.js.map +1 -0
  839. package/dist/runtime/utils/mime.d.ts +3 -0
  840. package/dist/runtime/utils/mime.d.ts.map +1 -0
  841. package/dist/runtime/utils/mime.js +110 -0
  842. package/dist/runtime/utils/mime.js.map +1 -0
  843. package/dist/runtime/utils/open-browser.d.ts +9 -0
  844. package/dist/runtime/utils/open-browser.d.ts.map +1 -0
  845. package/dist/runtime/utils/open-browser.js +22 -0
  846. package/dist/runtime/utils/open-browser.js.map +1 -0
  847. package/dist/runtime/utils/paths.d.ts +34 -0
  848. package/dist/runtime/utils/paths.d.ts.map +1 -0
  849. package/dist/runtime/utils/paths.js +114 -0
  850. package/dist/runtime/utils/paths.js.map +1 -0
  851. package/dist/runtime/utils/photon.d.ts +21 -0
  852. package/dist/runtime/utils/photon.d.ts.map +1 -0
  853. package/dist/runtime/utils/photon.js +121 -0
  854. package/dist/runtime/utils/photon.js.map +1 -0
  855. package/dist/runtime/utils/pi-user-agent.d.ts +2 -0
  856. package/dist/runtime/utils/pi-user-agent.d.ts.map +1 -0
  857. package/dist/runtime/utils/pi-user-agent.js +5 -0
  858. package/dist/runtime/utils/pi-user-agent.js.map +1 -0
  859. package/dist/runtime/utils/shell.d.ts +34 -0
  860. package/dist/runtime/utils/shell.d.ts.map +1 -0
  861. package/dist/runtime/utils/shell.js +214 -0
  862. package/dist/runtime/utils/shell.js.map +1 -0
  863. package/dist/runtime/utils/sleep.d.ts +5 -0
  864. package/dist/runtime/utils/sleep.d.ts.map +1 -0
  865. package/dist/runtime/utils/sleep.js +17 -0
  866. package/dist/runtime/utils/sleep.js.map +1 -0
  867. package/dist/runtime/utils/syntax-highlight.d.ts +13 -0
  868. package/dist/runtime/utils/syntax-highlight.d.ts.map +1 -0
  869. package/dist/runtime/utils/syntax-highlight.js +177 -0
  870. package/dist/runtime/utils/syntax-highlight.js.map +1 -0
  871. package/dist/runtime/utils/text.d.ts +8 -0
  872. package/dist/runtime/utils/text.d.ts.map +1 -0
  873. package/dist/runtime/utils/text.js +9 -0
  874. package/dist/runtime/utils/text.js.map +1 -0
  875. package/dist/runtime/utils/tool-result-images.d.ts +19 -0
  876. package/dist/runtime/utils/tool-result-images.d.ts.map +1 -0
  877. package/dist/runtime/utils/tool-result-images.js +45 -0
  878. package/dist/runtime/utils/tool-result-images.js.map +1 -0
  879. package/dist/runtime/utils/tools-manager.d.ts +12 -0
  880. package/dist/runtime/utils/tools-manager.d.ts.map +1 -0
  881. package/dist/runtime/utils/tools-manager.js +321 -0
  882. package/dist/runtime/utils/tools-manager.js.map +1 -0
  883. package/dist/runtime/utils/version-check.d.ts +19 -0
  884. package/dist/runtime/utils/version-check.d.ts.map +1 -0
  885. package/dist/runtime/utils/version-check.js +79 -0
  886. package/dist/runtime/utils/version-check.js.map +1 -0
  887. package/dist/runtime/utils/windows-self-update.d.ts +3 -0
  888. package/dist/runtime/utils/windows-self-update.d.ts.map +1 -0
  889. package/dist/runtime/utils/windows-self-update.js +77 -0
  890. package/dist/runtime/utils/windows-self-update.js.map +1 -0
  891. package/dist/update.js +134 -0
  892. package/dist/workflows.js +264 -0
  893. package/docs/compaction.md +416 -0
  894. package/docs/containerization.md +111 -0
  895. package/docs/custom-provider.md +777 -0
  896. package/docs/development.md +71 -0
  897. package/docs/docs.json +156 -0
  898. package/docs/environment-variables.md +94 -0
  899. package/docs/extensions.md +3002 -0
  900. package/docs/images/doom-extension.png +0 -0
  901. package/docs/images/exy.png +0 -0
  902. package/docs/images/interactive-mode.png +0 -0
  903. package/docs/images/tree-view.png +0 -0
  904. package/docs/index.md +84 -0
  905. package/docs/json.md +98 -0
  906. package/docs/keybindings.md +236 -0
  907. package/docs/llama-cpp.md +101 -0
  908. package/docs/models.md +571 -0
  909. package/docs/packages.md +228 -0
  910. package/docs/prompt-templates.md +96 -0
  911. package/docs/providers.md +317 -0
  912. package/docs/quickstart.md +167 -0
  913. package/docs/rpc.md +1618 -0
  914. package/docs/sdk.md +1219 -0
  915. package/docs/security.md +59 -0
  916. package/docs/session-format.md +438 -0
  917. package/docs/sessions.md +145 -0
  918. package/docs/settings.md +361 -0
  919. package/docs/shell-aliases.md +13 -0
  920. package/docs/skills.md +232 -0
  921. package/docs/terminal-setup.md +165 -0
  922. package/docs/termux.md +127 -0
  923. package/docs/themes.md +320 -0
  924. package/docs/tmux.md +63 -0
  925. package/docs/tui.md +942 -0
  926. package/docs/usage.md +310 -0
  927. package/docs/windows.md +39 -0
  928. package/examples/README.md +25 -0
  929. package/examples/extensions/README.md +213 -0
  930. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  931. package/examples/extensions/bash-spawn-hook.ts +30 -0
  932. package/examples/extensions/bookmark.ts +50 -0
  933. package/examples/extensions/border-status-editor.ts +150 -0
  934. package/examples/extensions/built-in-tool-renderer.ts +249 -0
  935. package/examples/extensions/claude-rules.ts +86 -0
  936. package/examples/extensions/commands.ts +72 -0
  937. package/examples/extensions/confirm-destructive.ts +59 -0
  938. package/examples/extensions/custom-compaction.ts +117 -0
  939. package/examples/extensions/custom-footer.ts +64 -0
  940. package/examples/extensions/custom-header.ts +73 -0
  941. package/examples/extensions/custom-provider-anthropic/index.ts +611 -0
  942. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  943. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  944. package/examples/extensions/custom-provider-gitlab-duo/index.ts +405 -0
  945. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  946. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  947. package/examples/extensions/dirty-repo-guard.ts +56 -0
  948. package/examples/extensions/doom-overlay/README.md +46 -0
  949. package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
  950. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  951. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  952. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  953. package/examples/extensions/doom-overlay/doom-component.ts +132 -0
  954. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  955. package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
  956. package/examples/extensions/doom-overlay/index.ts +74 -0
  957. package/examples/extensions/doom-overlay/wad-finder.ts +55 -0
  958. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  959. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  960. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  961. package/examples/extensions/dynamic-resources/index.ts +15 -0
  962. package/examples/extensions/dynamic-tools.ts +74 -0
  963. package/examples/extensions/entry-renderer.ts +41 -0
  964. package/examples/extensions/event-bus.ts +43 -0
  965. package/examples/extensions/file-trigger.ts +41 -0
  966. package/examples/extensions/git-checkpoint.ts +53 -0
  967. package/examples/extensions/git-merge-and-resolve.ts +115 -0
  968. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  969. package/examples/extensions/gondolin/index.ts +531 -0
  970. package/examples/extensions/gondolin/package-lock.json +185 -0
  971. package/examples/extensions/gondolin/package.json +19 -0
  972. package/examples/extensions/handoff.ts +190 -0
  973. package/examples/extensions/hello.ts +26 -0
  974. package/examples/extensions/hidden-thinking-label.ts +53 -0
  975. package/examples/extensions/inline-bash.ts +94 -0
  976. package/examples/extensions/input-transform-streaming.ts +39 -0
  977. package/examples/extensions/input-transform.ts +43 -0
  978. package/examples/extensions/interactive-shell.ts +196 -0
  979. package/examples/extensions/kimi-deferred-tools.ts +61 -0
  980. package/examples/extensions/mac-system-theme.ts +47 -0
  981. package/examples/extensions/message-renderer.ts +59 -0
  982. package/examples/extensions/minimal-mode.ts +426 -0
  983. package/examples/extensions/modal-editor.ts +85 -0
  984. package/examples/extensions/model-status.ts +31 -0
  985. package/examples/extensions/notify.ts +57 -0
  986. package/examples/extensions/overlay-qa-tests.ts +1450 -0
  987. package/examples/extensions/overlay-test.ts +153 -0
  988. package/examples/extensions/permission-gate.ts +34 -0
  989. package/examples/extensions/pirate.ts +47 -0
  990. package/examples/extensions/plan-mode/README.md +66 -0
  991. package/examples/extensions/plan-mode/index.ts +390 -0
  992. package/examples/extensions/plan-mode/utils.ts +168 -0
  993. package/examples/extensions/preset.ts +436 -0
  994. package/examples/extensions/project-trust.ts +64 -0
  995. package/examples/extensions/prompt-customizer.ts +97 -0
  996. package/examples/extensions/protected-paths.ts +30 -0
  997. package/examples/extensions/provider-payload.ts +18 -0
  998. package/examples/extensions/qna.ts +118 -0
  999. package/examples/extensions/question.ts +286 -0
  1000. package/examples/extensions/questionnaire.ts +448 -0
  1001. package/examples/extensions/rainbow-editor.ts +88 -0
  1002. package/examples/extensions/reload-runtime.ts +37 -0
  1003. package/examples/extensions/rpc-demo.ts +118 -0
  1004. package/examples/extensions/sandbox/index.ts +321 -0
  1005. package/examples/extensions/sandbox/package-lock.json +92 -0
  1006. package/examples/extensions/sandbox/package.json +19 -0
  1007. package/examples/extensions/send-user-message.ts +97 -0
  1008. package/examples/extensions/session-name.ts +27 -0
  1009. package/examples/extensions/shutdown-command.ts +63 -0
  1010. package/examples/extensions/snake.ts +343 -0
  1011. package/examples/extensions/space-invaders.ts +560 -0
  1012. package/examples/extensions/ssh.ts +220 -0
  1013. package/examples/extensions/status-line.ts +32 -0
  1014. package/examples/extensions/structured-output.ts +65 -0
  1015. package/examples/extensions/subagent/README.md +177 -0
  1016. package/examples/extensions/subagent/agents/planner.md +37 -0
  1017. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  1018. package/examples/extensions/subagent/agents/scout.md +50 -0
  1019. package/examples/extensions/subagent/agents/worker.md +24 -0
  1020. package/examples/extensions/subagent/agents.ts +157 -0
  1021. package/examples/extensions/subagent/index.ts +1038 -0
  1022. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  1023. package/examples/extensions/subagent/prompts/implement.md +10 -0
  1024. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  1025. package/examples/extensions/summarize.ts +199 -0
  1026. package/examples/extensions/system-prompt-header.ts +17 -0
  1027. package/examples/extensions/tic-tac-toe.ts +1008 -0
  1028. package/examples/extensions/timed-confirm.ts +70 -0
  1029. package/examples/extensions/titlebar-spinner.ts +58 -0
  1030. package/examples/extensions/todo.ts +297 -0
  1031. package/examples/extensions/tool-override.ts +144 -0
  1032. package/examples/extensions/tools.ts +146 -0
  1033. package/examples/extensions/trigger-compact.ts +50 -0
  1034. package/examples/extensions/truncated-tool.ts +195 -0
  1035. package/examples/extensions/widget-placement.ts +9 -0
  1036. package/examples/extensions/with-deps/index.ts +32 -0
  1037. package/examples/extensions/with-deps/package-lock.json +31 -0
  1038. package/examples/extensions/with-deps/package.json +22 -0
  1039. package/examples/extensions/working-indicator.ts +123 -0
  1040. package/examples/extensions/working-message-test.ts +25 -0
  1041. package/examples/rpc-extension-ui.ts +641 -0
  1042. package/examples/sdk/01-minimal.ts +26 -0
  1043. package/examples/sdk/02-custom-model.ts +49 -0
  1044. package/examples/sdk/03-custom-prompt.ts +75 -0
  1045. package/examples/sdk/04-skills.ts +55 -0
  1046. package/examples/sdk/05-tools.ts +48 -0
  1047. package/examples/sdk/06-extensions.ts +99 -0
  1048. package/examples/sdk/07-context-files.ts +47 -0
  1049. package/examples/sdk/08-prompt-templates.ts +51 -0
  1050. package/examples/sdk/09-api-keys-and-oauth.ts +34 -0
  1051. package/examples/sdk/10-settings.ts +53 -0
  1052. package/examples/sdk/11-sessions.ts +52 -0
  1053. package/examples/sdk/12-full-control.ts +74 -0
  1054. package/examples/sdk/13-session-runtime.ts +67 -0
  1055. package/examples/sdk/README.md +140 -0
  1056. package/package.json +66 -12
  1057. package/upstream.json +6 -0
  1058. package/workflows/cm/LICENSE +21 -0
  1059. package/workflows/cm/README.md +333 -0
  1060. package/workflows/cm/THIRD_PARTY_NOTICES.md +29 -0
  1061. package/workflows/cm/VERSION +1 -0
  1062. package/workflows/cm/agents/cm-backend-agent.md +34 -0
  1063. package/workflows/cm/agents/cm-contract-agent.md +34 -0
  1064. package/workflows/cm/agents/cm-database-agent.md +34 -0
  1065. package/workflows/cm/agents/cm-frontend-agent.md +33 -0
  1066. package/workflows/cm/agents/cm-miniprogram-agent.md +33 -0
  1067. package/workflows/cm/agents/cm-ui-agent.md +34 -0
  1068. package/workflows/cm/assets/docs/command-picker-mobile.svg +56 -0
  1069. package/workflows/cm/assets/docs/command-picker.svg +56 -0
  1070. package/workflows/cm/assets/docs/user-guide-hero-mobile.svg +35 -0
  1071. package/workflows/cm/assets/docs/user-guide-hero.svg +36 -0
  1072. package/workflows/cm/assets/readme/delivery-flow.svg +86 -0
  1073. package/workflows/cm/assets/readme/hero.svg +77 -0
  1074. package/workflows/cm/assets/readme/recovery-record.svg +73 -0
  1075. package/workflows/cm/assets/readme/test-evidence.svg +64 -0
  1076. package/workflows/cm/compat/claude-commands/cm-ai.md +3 -0
  1077. package/workflows/cm/compat/claude-commands/cm-check.md +3 -0
  1078. package/workflows/cm/compat/claude-commands/cm-fix.md +3 -0
  1079. package/workflows/cm/compat/claude-commands/cm-idea.md +3 -0
  1080. package/workflows/cm/compat/claude-commands/cm-init.md +3 -0
  1081. package/workflows/cm/compat/claude-commands/cm-prd.md +3 -0
  1082. package/workflows/cm/compat/claude-commands/cm-refactor.md +3 -0
  1083. package/workflows/cm/compat/claude-commands/cm-test.md +3 -0
  1084. package/workflows/cm/docs/architecture.md +130 -0
  1085. package/workflows/cm/docs/fixes/.reviews/fix-manifest-runtime-checkbox-drift-r1.md +33 -0
  1086. package/workflows/cm/docs/fixes/.reviews/fix-manifest-runtime-checkbox-drift-r2.md +31 -0
  1087. package/workflows/cm/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-a1-handoff.json +56 -0
  1088. package/workflows/cm/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-a2-handoff.json +85 -0
  1089. package/workflows/cm/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-r1.md +53 -0
  1090. package/workflows/cm/docs/fixes/.reviews/fix-model-call-boundary-identity-T-FIX-model-call-boundary-identity-r2.md +80 -0
  1091. package/workflows/cm/docs/fixes/.reviews/fix-review-evidence-scope-honesty-T-FIX-review-evidence-scope-honesty-a1-handoff.json +35 -0
  1092. package/workflows/cm/docs/fixes/.reviews/fix-review-evidence-scope-honesty-T-FIX-review-evidence-scope-honesty-r1.md +33 -0
  1093. package/workflows/cm/docs/fixes/.reviews/fix-windows-cp1252-log-output-r1.md +30 -0
  1094. package/workflows/cm/docs/fixes/.reviews/fix-windows-cp1252-log-output-r2.md +16 -0
  1095. package/workflows/cm/docs/fixes/.reviews/openai-compatible-depth-fixture-T-FIX-openai-compatible-depth-fixture-a1-handoff.json +40 -0
  1096. package/workflows/cm/docs/fixes/.reviews/openai-compatible-depth-fixture-T-FIX-openai-compatible-depth-fixture-r1.md +30 -0
  1097. package/workflows/cm/docs/fixes/20260729-windows-cp1252-log-output.md +65 -0
  1098. package/workflows/cm/docs/fixes/20260804-manifest-runtime-checkbox-drift.md +67 -0
  1099. package/workflows/cm/docs/fixes/20260806-model-call-boundary-identity.md +80 -0
  1100. package/workflows/cm/docs/fixes/20260807-prelanding-integrity.md +58 -0
  1101. package/workflows/cm/docs/fixes/20260826-openai-compatible-depth-fixture.md +39 -0
  1102. package/workflows/cm/docs/installation.md +149 -0
  1103. package/workflows/cm/docs/sample-prd/prd-funding-rate-alert.md +42 -0
  1104. package/workflows/cm/docs/sample-specs/docs//351/234/200/346/261/202/347/244/272/344/276/213.md +24 -0
  1105. package/workflows/cm/docs/user-guide.md +521 -0
  1106. package/workflows/cm/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/README.md +19 -0
  1107. package/workflows/cm/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.excalidraw +3650 -0
  1108. package/workflows/cm/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.mp4 +0 -0
  1109. package/workflows/cm/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.png +0 -0
  1110. package/workflows/cm/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.spec.json +223 -0
  1111. package/workflows/cm/package.json +45 -0
  1112. package/workflows/cm/runtime/external-expert.md +302 -0
  1113. package/workflows/cm/runtime/logging.md +206 -0
  1114. package/workflows/cm/runtime/model-efficiency.md +201 -0
  1115. package/workflows/cm/runtime/orchestration.md +113 -0
  1116. package/workflows/cm/runtime/project-context.md +37 -0
  1117. package/workflows/cm/runtime/review.md +114 -0
  1118. package/workflows/cm/runtime/task-gates.md +114 -0
  1119. package/workflows/cm/runtime/task-handoff.schema.json +103 -0
  1120. package/workflows/cm/runtime/test-contract.md +212 -0
  1121. package/workflows/cm/runtime/workflow-config.md +115 -0
  1122. package/workflows/cm/runtime/workflow-routing.md +82 -0
  1123. package/workflows/cm/scripts/cm-check-runtime.ps1 +69 -0
  1124. package/workflows/cm/scripts/cm-check-runtime.sh +866 -0
  1125. package/workflows/cm/scripts/cm-log-event.py +1270 -0
  1126. package/workflows/cm/scripts/cm-openai-compatible-call.py +661 -0
  1127. package/workflows/cm/scripts/cm-prd-review-gate.py +319 -0
  1128. package/workflows/cm/scripts/cm-prd-timing.py +272 -0
  1129. package/workflows/cm/scripts/cm-spec-manifest.py +171 -0
  1130. package/workflows/cm/scripts/cm-task-gate.py +760 -0
  1131. package/workflows/cm/scripts/cm-usage-report.py +516 -0
  1132. package/workflows/cm/scripts/cm_workflow_config.py +612 -0
  1133. package/workflows/cm/scripts/scan-public-safety.py +89 -0
  1134. package/workflows/cm/scripts/test-cm-log-event.py +1213 -0
  1135. package/workflows/cm/scripts/test-cm-openai-compatible-call.py +1185 -0
  1136. package/workflows/cm/scripts/test-cm-prd-review-gate.py +243 -0
  1137. package/workflows/cm/scripts/test-cm-prd-timing.py +168 -0
  1138. package/workflows/cm/scripts/test-cm-usage-report.py +584 -0
  1139. package/workflows/cm/scripts/test-shell-compat.sh +338 -0
  1140. package/workflows/cm/scripts/test-spec-manifest.py +220 -0
  1141. package/workflows/cm/scripts/test-task-gate.py +540 -0
  1142. package/workflows/cm/scripts/test-workflow-config.py +394 -0
  1143. package/workflows/cm/scripts/validate-public-repo.py +200 -0
  1144. package/workflows/cm/scripts/validate-test-cases.py +127 -0
  1145. package/workflows/cm/skills/cm-ai/SKILL.md +120 -0
  1146. package/workflows/cm/skills/cm-ai/references/N1-init.md +92 -0
  1147. package/workflows/cm/skills/cm-ai/references/N2-enter-feature.md +38 -0
  1148. package/workflows/cm/skills/cm-ai/references/N3-execute-task.md +99 -0
  1149. package/workflows/cm/skills/cm-ai/references/N4-review.md +96 -0
  1150. package/workflows/cm/skills/cm-ai/references/N5-mark-done.md +107 -0
  1151. package/workflows/cm/skills/cm-ai/references/N6-qa-eval.md +102 -0
  1152. package/workflows/cm/skills/cm-ai/references/N7-context.md +23 -0
  1153. package/workflows/cm/skills/cm-ai/references/N8-finish.md +97 -0
  1154. package/workflows/cm/skills/cm-backend-engineer/SKILL.md +100 -0
  1155. package/workflows/cm/skills/cm-check/SKILL.md +60 -0
  1156. package/workflows/cm/skills/cm-contract-engineer/SKILL.md +136 -0
  1157. package/workflows/cm/skills/cm-database-engineer/SKILL.md +89 -0
  1158. package/workflows/cm/skills/cm-devops-engineer/SKILL.md +137 -0
  1159. package/workflows/cm/skills/cm-doc-syncer/SKILL.md +150 -0
  1160. package/workflows/cm/skills/cm-finance-expert/SKILL.md +85 -0
  1161. package/workflows/cm/skills/cm-fix/SKILL.md +159 -0
  1162. package/workflows/cm/skills/cm-frontend-engineer/SKILL.md +127 -0
  1163. package/workflows/cm/skills/cm-idea/SKILL.md +42 -0
  1164. package/workflows/cm/skills/cm-idea/references/domains/trading.md +97 -0
  1165. package/workflows/cm/skills/cm-idea/references/example-prd.md +92 -0
  1166. package/workflows/cm/skills/cm-idea/references/idea-to-prd.md +282 -0
  1167. package/workflows/cm/skills/cm-init/SKILL.md +158 -0
  1168. package/workflows/cm/skills/cm-miniprogram-engineer/SKILL.md +141 -0
  1169. package/workflows/cm/skills/cm-miniprogram-engineer/references/platform-readiness.md +58 -0
  1170. package/workflows/cm/skills/cm-miniprogram-engineer/references/release-checklist.md +59 -0
  1171. package/workflows/cm/skills/cm-prd/SKILL.md +521 -0
  1172. package/workflows/cm/skills/cm-prd/references/brownfield.md +13 -0
  1173. package/workflows/cm/skills/cm-prd/references/change-mode.md +145 -0
  1174. package/workflows/cm/skills/cm-prd/references/context-scope.md +62 -0
  1175. package/workflows/cm/skills/cm-prd/references/greenfield.md +80 -0
  1176. package/workflows/cm/skills/cm-prd/references/phase-timing.md +60 -0
  1177. package/workflows/cm/skills/cm-prd/references/spec-self-check.md +22 -0
  1178. package/workflows/cm/skills/cm-product-manager/SKILL.md +83 -0
  1179. package/workflows/cm/skills/cm-qa-engineer/SKILL.md +142 -0
  1180. package/workflows/cm/skills/cm-refactor/SKILL.md +209 -0
  1181. package/workflows/cm/skills/cm-test/SKILL.md +259 -0
  1182. package/workflows/cm/skills/cm-ui-engineer/SKILL.md +105 -0
  1183. package/workflows/cm/skills/codebase-context/SKILL.md +489 -0
  1184. package/workflows/cm/skills/darwin-skill/NOTICE.md +26 -0
  1185. package/workflows/cm/skills/darwin-skill/README.md +272 -0
  1186. package/workflows/cm/skills/darwin-skill/SKILL.md +492 -0
  1187. package/workflows/cm/skills/darwin-skill/references/runtime-neutrality.md +68 -0
  1188. package/workflows/cm/skills/darwin-skill/references/skilllens-evidence.md +142 -0
  1189. package/workflows/cm/skills/darwin-skill/scripts/screenshot.mjs +71 -0
  1190. package/workflows/cm/skills/darwin-skill/templates/result-card-dark.html +698 -0
  1191. package/workflows/cm/skills/darwin-skill/templates/result-card-white.html +444 -0
  1192. package/workflows/cm/skills/darwin-skill/templates/result-card.html +616 -0
  1193. package/workflows/cm/skills/external-expert/SKILL.md +250 -0
  1194. package/workflows/cm/templates/arch-reference.md +68 -0
  1195. package/workflows/cm/templates/auto-update/cm-announce.sh +19 -0
  1196. package/workflows/cm/templates/auto-update/cm-update.sh +274 -0
  1197. package/workflows/cm/templates/cm-workflow.yml +52 -0
  1198. package/workflows/cm/templates/dashboard/dashboard.html +153 -0
  1199. package/workflows/cm/templates/dashboard/serve.sh +10 -0
  1200. package/workflows/cm/templates/hooks/pre-commit-cm-task-check +67 -0
  1201. package/workflows/cm/templates/pixel/cm-pixel.html +388 -0
  1202. package/workflows/cm/templates/pixel/cm-pixel.sh +212 -0
  1203. package/workflows/cm/templates/pixel/dev/README.md +20 -0
  1204. package/workflows/cm/templates/pixel/dev/atlas-preview.png +0 -0
  1205. package/workflows/cm/templates/pixel/dev/build.py +55 -0
  1206. package/workflows/cm/templates/pixel/dev/sheets/roguelikeChar_transparent.png +0 -0
  1207. package/workflows/cm/templates/pixel/dev/sheets/roguelikeCity_tilemap.png +0 -0
  1208. package/workflows/cm/templates/pixel/dev/sheets/roguelikeIndoor_transparent.png +0 -0
  1209. package/workflows/cm/templates/pixel/dev/template.html +388 -0
  1210. package/workflows/cm/templates/pixel/serve.sh +12 -0
  1211. package/workflows/cm/templates/refactor/cm-refactor-denies.json +14 -0
  1212. package/workflows/cm/templates/rules/backend-api.md +36 -0
  1213. package/workflows/cm/templates/rules/coding-style.md +44 -0
  1214. package/workflows/cm/templates/rules/database.md +27 -0
  1215. package/workflows/cm/templates/rules/finance.md +32 -0
  1216. package/workflows/cm/templates/rules/frontend.md +32 -0
  1217. package/workflows/cm/templates/rules/git-workflow.md +25 -0
  1218. package/workflows/cm/templates/rules/miniprogram.md +31 -0
  1219. package/workflows/cm/templates/rules/security.md +31 -0
  1220. package/workflows/cm/templates/rules/smart-contract.md +28 -0
  1221. package/workflows/cm/templates/rules/testing.md +36 -0
  1222. package/workflows/cm/templates/statusline/cm-statusline.sh +73 -0
  1223. package/workflows/cm/templates/ui-lens/cm-ui-lens-extract.mjs +55 -0
  1224. package/workflows/cm-plugin/LICENSE +21 -0
  1225. package/workflows/cm-plugin/README.md +195 -0
  1226. package/workflows/cm-plugin/VERSION +1 -0
  1227. package/workflows/cm-plugin/agents/cm-plugin-backend-agent.md +34 -0
  1228. package/workflows/cm-plugin/agents/cm-plugin-extension-agent.md +35 -0
  1229. package/workflows/cm-plugin/agents/cm-plugin-ui-agent.md +34 -0
  1230. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N1-init.md +60 -0
  1231. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N2-enter-feature.md +51 -0
  1232. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N3-execute-task.md +32 -0
  1233. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N4-review.md +58 -0
  1234. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N5-mark-done.md +80 -0
  1235. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N6-qa-eval.md +69 -0
  1236. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N7-context.md +23 -0
  1237. package/workflows/cm-plugin/commands/cm-plugin-ai-nodes/N8-finish.md +61 -0
  1238. package/workflows/cm-plugin/commands/cm-plugin-prd-modes/brownfield.md +13 -0
  1239. package/workflows/cm-plugin/commands/cm-plugin-prd-modes/change-mode.md +130 -0
  1240. package/workflows/cm-plugin/commands/cm-plugin-prd-modes/greenfield.md +82 -0
  1241. package/workflows/cm-plugin/commands/cm-plugin:ai.md +75 -0
  1242. package/workflows/cm-plugin/commands/cm-plugin:check.md +66 -0
  1243. package/workflows/cm-plugin/commands/cm-plugin:fix.md +100 -0
  1244. package/workflows/cm-plugin/commands/cm-plugin:idea.md +29 -0
  1245. package/workflows/cm-plugin/commands/cm-plugin:init.md +145 -0
  1246. package/workflows/cm-plugin/commands/cm-plugin:prd.md +403 -0
  1247. package/workflows/cm-plugin/commands/cm-plugin:refactor.md +147 -0
  1248. package/workflows/cm-plugin/commands/cm-plugin:rewrite.md +90 -0
  1249. package/workflows/cm-plugin/commands/cm-plugin:scout.md +202 -0
  1250. package/workflows/cm-plugin/docs//346/265/213/350/257/225/346/214/207/345/274/225-/345/277/253/351/200/237/344/270/212/346/211/213.md +189 -0
  1251. package/workflows/cm-plugin/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/README.md +17 -0
  1252. package/workflows/cm-plugin/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.excalidraw +3650 -0
  1253. package/workflows/cm-plugin/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.mp4 +0 -0
  1254. package/workflows/cm-plugin/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.png +0 -0
  1255. package/workflows/cm-plugin/docs//351/207/215/346/236/204/346/265/201/347/250/213/350/256/276/350/256/241/refactor-flow.spec.json +223 -0
  1256. package/workflows/cm-plugin/package.json +33 -0
  1257. package/workflows/cm-plugin/skills/cm-plugin-backend-engineer/SKILL.md +100 -0
  1258. package/workflows/cm-plugin/skills/cm-plugin-devops-engineer/NOTICE.md +14 -0
  1259. package/workflows/cm-plugin/skills/cm-plugin-devops-engineer/SKILL.md +120 -0
  1260. package/workflows/cm-plugin/skills/cm-plugin-devops-engineer/references/cws-ci-cd.md +139 -0
  1261. package/workflows/cm-plugin/skills/cm-plugin-devops-engineer/references/cws-submission-checklist.md +87 -0
  1262. package/workflows/cm-plugin/skills/cm-plugin-doc-syncer/SKILL.md +149 -0
  1263. package/workflows/cm-plugin/skills/cm-plugin-extension-engineer/SKILL.md +105 -0
  1264. package/workflows/cm-plugin/skills/cm-plugin-product-manager/SKILL.md +83 -0
  1265. package/workflows/cm-plugin/skills/cm-plugin-qa-engineer/NOTICE.md +14 -0
  1266. package/workflows/cm-plugin/skills/cm-plugin-qa-engineer/SKILL.md +134 -0
  1267. package/workflows/cm-plugin/skills/cm-plugin-qa-engineer/references/cws-scan-checklist.md +136 -0
  1268. package/workflows/cm-plugin/skills/cm-plugin-qa-engineer/references/cws-violation-codes.md +68 -0
  1269. package/workflows/cm-plugin/skills/cm-plugin-ui-engineer/SKILL.md +94 -0
  1270. package/workflows/cm-plugin/skills/codebase-context/SKILL.md +489 -0
  1271. package/workflows/cm-plugin/skills/darwin-skill/NOTICE.md +24 -0
  1272. package/workflows/cm-plugin/skills/darwin-skill/README.md +272 -0
  1273. package/workflows/cm-plugin/skills/darwin-skill/SKILL.md +492 -0
  1274. package/workflows/cm-plugin/skills/darwin-skill/references/runtime-neutrality.md +68 -0
  1275. package/workflows/cm-plugin/skills/darwin-skill/references/skilllens-evidence.md +142 -0
  1276. package/workflows/cm-plugin/skills/darwin-skill/scripts/screenshot.mjs +71 -0
  1277. package/workflows/cm-plugin/skills/darwin-skill/templates/result-card-dark.html +698 -0
  1278. package/workflows/cm-plugin/skills/darwin-skill/templates/result-card-white.html +444 -0
  1279. package/workflows/cm-plugin/skills/darwin-skill/templates/result-card.html +616 -0
  1280. package/workflows/cm-plugin/skills/idea-to-prd/SKILL.md +289 -0
  1281. package/workflows/cm-plugin/skills/idea-to-prd/references/domains/trading.md +97 -0
  1282. package/workflows/cm-plugin/skills/idea-to-prd/references/example-prd.md +92 -0
  1283. package/workflows/cm-plugin/templates/arch-reference.md +55 -0
  1284. package/workflows/cm-plugin/templates/auto-update/cm-announce.sh +19 -0
  1285. package/workflows/cm-plugin/templates/auto-update/cm-update.sh +251 -0
  1286. package/workflows/cm-plugin/templates/dashboard/dashboard.html +153 -0
  1287. package/workflows/cm-plugin/templates/dashboard/serve.sh +10 -0
  1288. package/workflows/cm-plugin/templates/e2e/extension-harness.ts +110 -0
  1289. package/workflows/cm-plugin/templates/e2e/smoke.spec.example.ts +51 -0
  1290. package/workflows/cm-plugin/templates/hooks/pre-commit-cm-task-check +33 -0
  1291. package/workflows/cm-plugin/templates/pixel/cm-pixel.html +388 -0
  1292. package/workflows/cm-plugin/templates/pixel/cm-pixel.sh +212 -0
  1293. package/workflows/cm-plugin/templates/pixel/dev/README.md +20 -0
  1294. package/workflows/cm-plugin/templates/pixel/dev/atlas-preview.png +0 -0
  1295. package/workflows/cm-plugin/templates/pixel/dev/build.py +55 -0
  1296. package/workflows/cm-plugin/templates/pixel/dev/sheets/roguelikeChar_transparent.png +0 -0
  1297. package/workflows/cm-plugin/templates/pixel/dev/sheets/roguelikeCity_tilemap.png +0 -0
  1298. package/workflows/cm-plugin/templates/pixel/dev/sheets/roguelikeIndoor_transparent.png +0 -0
  1299. package/workflows/cm-plugin/templates/pixel/dev/template.html +388 -0
  1300. package/workflows/cm-plugin/templates/pixel/serve.sh +12 -0
  1301. package/workflows/cm-plugin/templates/refactor/cm-refactor-denies.json +14 -0
  1302. package/workflows/cm-plugin/templates/rules/backend-api.md +36 -0
  1303. package/workflows/cm-plugin/templates/rules/chrome-extension.md +53 -0
  1304. package/workflows/cm-plugin/templates/rules/coding-style.md +44 -0
  1305. package/workflows/cm-plugin/templates/rules/frontend.md +32 -0
  1306. package/workflows/cm-plugin/templates/rules/git-workflow.md +25 -0
  1307. package/workflows/cm-plugin/templates/rules/security.md +31 -0
  1308. package/workflows/cm-plugin/templates/rules/testing.md +36 -0
  1309. package/workflows/cm-plugin/templates/scripts/cm-plugin-codex.sh +52 -0
  1310. package/workflows/cm-plugin/templates/scripts/cm-plugin-log.sh +41 -0
  1311. package/workflows/cm-plugin/templates/scripts/cm-plugin-preflight.sh +60 -0
  1312. package/workflows/cm-plugin/templates/statusline/cm-plugin-statusline.sh +73 -0
  1313. package/workflows.lock.json +40 -0
@@ -0,0 +1,2808 @@
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 { contentText } from "@earendil-works/pi-ai";
18
+ import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRecoverableLength, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@earendil-works/pi-ai/compat";
19
+ import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
20
+ import { stripFrontmatter } from "../utils/frontmatter.js";
21
+ import { sleep } from "../utils/sleep.js";
22
+ import { normalizeToolResultImages } from "../utils/tool-result-images.js";
23
+ import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
24
+ import { executeBashWithOperations } from "./bash-executor.js";
25
+ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
26
+ import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "./defaults.js";
27
+ import { exportSessionToHtml } from "./export-html/index.js";
28
+ import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
29
+ import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
30
+ import { emitSessionShutdownEvent } from "./extensions/runner.js";
31
+ import { ModelRegistry } from "./model-registry.js";
32
+ import { expandPromptTemplate } from "./prompt-templates.js";
33
+ import { exportSessionToJsonl } from "./session-export.js";
34
+ import { getLatestCompactionEntry } from "./session-manager.js";
35
+ import { createSyntheticSourceInfo } from "./source-info.js";
36
+ import { buildSystemPrompt } from "./system-prompt.js";
37
+ import { createLocalBashOperations } from "./tools/bash.js";
38
+ import { createAllToolDefinitions } from "./tools/index.js";
39
+ import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
40
+ import { addUsageToTotals, createUsageTotals } from "./usage-totals.js";
41
+ /**
42
+ * Parse a skill block from message text.
43
+ * Returns null if the text doesn't contain a skill block.
44
+ */
45
+ export function parseSkillBlock(text) {
46
+ const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
47
+ if (!match)
48
+ return null;
49
+ return {
50
+ name: match[1],
51
+ location: match[2],
52
+ content: match[3],
53
+ userMessage: match[4]?.trim() || undefined,
54
+ };
55
+ }
56
+ // ============================================================================
57
+ // Types
58
+ // ============================================================================
59
+ function withoutDeletedHeaders(headers) {
60
+ return headers
61
+ ? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))
62
+ : undefined;
63
+ }
64
+ function estimateMessagesTokens(messages) {
65
+ let tokens = 0;
66
+ for (const message of messages) {
67
+ tokens += estimateTokens(message);
68
+ }
69
+ return tokens;
70
+ }
71
+ // ============================================================================
72
+ // Constants
73
+ // ============================================================================
74
+ // ============================================================================
75
+ // AgentSession Class
76
+ // ============================================================================
77
+ export class AgentSession {
78
+ agent;
79
+ sessionManager;
80
+ settingsManager;
81
+ _scopedModels;
82
+ // Event subscription state
83
+ _unsubscribeAgent;
84
+ _eventListeners = [];
85
+ _isAgentRunActive = false;
86
+ _idleWaitPromise;
87
+ _resolveIdleWait;
88
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
89
+ _steeringMessages = [];
90
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
91
+ _followUpMessages = [];
92
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
93
+ _pendingNextTurnMessages = [];
94
+ /** Context-only custom messages queued during a run, flushed once the current turn's tool results are in. */
95
+ _pendingCustomMessages = [];
96
+ // Compaction state
97
+ _compactionAbortController = undefined;
98
+ _autoCompactionAbortController = undefined;
99
+ _overflowRecoveryAttempted = false;
100
+ // Branch summarization state
101
+ _branchSummaryAbortController = undefined;
102
+ // Retry state
103
+ _retryAbortController = undefined;
104
+ _retryAttempt = 0;
105
+ // Bash execution state
106
+ _bashAbortControllers = new Set();
107
+ _pendingBashMessages = [];
108
+ // Extension system
109
+ _extensionRunner;
110
+ _turnIndex = 0;
111
+ _resourceLoader;
112
+ _customTools;
113
+ _baseToolDefinitions = new Map();
114
+ _cwd;
115
+ _extensionRunnerRef;
116
+ _initialActiveToolNames;
117
+ _allowedToolNames;
118
+ _excludedToolNames;
119
+ _baseToolsOverride;
120
+ _sessionStartEvent;
121
+ _extensionUIContext;
122
+ _extensionMode = "print";
123
+ _extensionCommandContextActions;
124
+ _extensionAbortHandler;
125
+ _extensionShutdownHandler;
126
+ _extensionErrorListener;
127
+ _extensionErrorUnsubscriber;
128
+ _modelRuntime;
129
+ // Tool registry for extension getTools/setTools
130
+ _toolRegistry = new Map();
131
+ _toolDefinitions = new Map();
132
+ _toolPromptSnippets = new Map();
133
+ _toolPromptGuidelines = new Map();
134
+ // Base system prompt (without extension appends) - used to apply fresh appends each turn
135
+ _baseSystemPrompt = "";
136
+ _baseSystemPromptOptions;
137
+ _systemPromptOverride;
138
+ constructor(config) {
139
+ this.agent = config.agent;
140
+ this.sessionManager = config.sessionManager;
141
+ this.settingsManager = config.settingsManager;
142
+ this._scopedModels = config.scopedModels ?? [];
143
+ this._resourceLoader = config.resourceLoader;
144
+ this._customTools = config.customTools ?? [];
145
+ this._cwd = config.cwd;
146
+ this._modelRuntime = config.modelRuntime;
147
+ this._extensionRunnerRef = config.extensionRunnerRef;
148
+ this._initialActiveToolNames = config.initialActiveToolNames;
149
+ this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
150
+ this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
151
+ this._baseToolsOverride = config.baseToolsOverride;
152
+ this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
153
+ // Always subscribe to agent events for internal handling
154
+ // (session persistence, extensions, auto-compaction, retry logic)
155
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
156
+ this._installAgentToolHooks();
157
+ this._installAgentNextTurnRefresh();
158
+ this._buildRuntime({
159
+ activeToolNames: this._initialActiveToolNames,
160
+ includeAllExtensionTools: true,
161
+ });
162
+ }
163
+ get modelRuntime() {
164
+ return this._modelRuntime;
165
+ }
166
+ async _getRequiredRequestAuth(model) {
167
+ let result;
168
+ try {
169
+ result = await this._modelRuntime.getAuth(model);
170
+ }
171
+ catch (error) {
172
+ const cause = error instanceof Error ? error.cause : undefined;
173
+ if (cause instanceof Error && cause.message === "authHeader requires a resolved API key") {
174
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
175
+ }
176
+ throw error;
177
+ }
178
+ if (result && (result.auth.apiKey || result.auth.headers)) {
179
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
180
+ return {
181
+ model: requestModel,
182
+ apiKey: result.auth.apiKey,
183
+ headers: withoutDeletedHeaders(result.auth.headers),
184
+ env: result.env,
185
+ };
186
+ }
187
+ const isOAuth = this._modelRuntime.isUsingOAuth(model.provider);
188
+ if (isOAuth) {
189
+ throw new Error(`Authentication failed for "${model.provider}". ` +
190
+ `Credentials may have expired or network is unavailable. ` +
191
+ `Run '/login ${model.provider}' to re-authenticate.`);
192
+ }
193
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
194
+ }
195
+ async _getSummarizationRequestAuth(model) {
196
+ if (this.agent.streamFunction === streamSimple) {
197
+ return this._getRequiredRequestAuth(model);
198
+ }
199
+ try {
200
+ const result = await this._modelRuntime.getAuth(model);
201
+ if (!result)
202
+ return { model };
203
+ const requestModel = result.auth.baseUrl ? { ...model, baseUrl: result.auth.baseUrl } : model;
204
+ return {
205
+ model: requestModel,
206
+ apiKey: result.auth.apiKey,
207
+ headers: withoutDeletedHeaders(result.auth.headers),
208
+ env: result.env,
209
+ };
210
+ }
211
+ catch {
212
+ return { model };
213
+ }
214
+ }
215
+ /**
216
+ * Install tool hooks once on the Agent instance.
217
+ *
218
+ * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
219
+ * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
220
+ * registered tool execution to the extension context. Tool call and tool result interception now
221
+ * happens here instead of in wrappers.
222
+ */
223
+ _installAgentToolHooks() {
224
+ this.agent.beforeToolCall = async ({ toolCall, args }) => {
225
+ const runner = this._extensionRunner;
226
+ if (!runner.hasHandlers("tool_call")) {
227
+ return undefined;
228
+ }
229
+ try {
230
+ return await runner.emitToolCall({
231
+ type: "tool_call",
232
+ toolName: toolCall.name,
233
+ toolCallId: toolCall.id,
234
+ input: args,
235
+ });
236
+ }
237
+ catch (err) {
238
+ if (err instanceof Error) {
239
+ throw err;
240
+ }
241
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
242
+ }
243
+ };
244
+ this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
245
+ const runner = this._extensionRunner;
246
+ const hookResult = runner.hasHandlers("tool_result")
247
+ ? await runner.emitToolResult({
248
+ type: "tool_result",
249
+ toolName: toolCall.name,
250
+ toolCallId: toolCall.id,
251
+ input: args,
252
+ content: result.content,
253
+ details: result.details,
254
+ isError,
255
+ usage: result.usage,
256
+ })
257
+ : undefined;
258
+ const content = hookResult?.content ?? result.content ?? [];
259
+ // Runs after the extension hook so images injected or replaced by extensions are normalized too.
260
+ const normalizedContent = await normalizeToolResultImages(content, {
261
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
262
+ });
263
+ if (!hookResult && normalizedContent === content) {
264
+ return undefined;
265
+ }
266
+ return {
267
+ content: normalizedContent,
268
+ details: hookResult?.details,
269
+ isError: hookResult?.isError ?? isError,
270
+ usage: hookResult?.usage,
271
+ };
272
+ };
273
+ }
274
+ _installAgentNextTurnRefresh() {
275
+ const previousPrepareNextTurnWithContext = this.agent.prepareNextTurnWithContext ??
276
+ (this.agent.prepareNextTurn
277
+ ? async (_turn, signal) => await this.agent.prepareNextTurn?.(signal)
278
+ : undefined);
279
+ this.agent.prepareNextTurnWithContext = async (turn, signal) => {
280
+ const previousSnapshot = await previousPrepareNextTurnWithContext?.(turn, signal);
281
+ const previousContext = previousSnapshot?.context ?? turn.context;
282
+ return {
283
+ ...previousSnapshot,
284
+ context: {
285
+ ...previousContext,
286
+ systemPrompt: this._systemPromptOverride ?? this._baseSystemPrompt,
287
+ tools: this.agent.state.tools.slice(),
288
+ },
289
+ model: this.agent.state.model,
290
+ thinkingLevel: this.agent.state.thinkingLevel,
291
+ };
292
+ };
293
+ }
294
+ // =========================================================================
295
+ // Event Subscription
296
+ // =========================================================================
297
+ /** Emit an event to all listeners */
298
+ _emit(event) {
299
+ for (const l of this._eventListeners) {
300
+ l(event);
301
+ }
302
+ }
303
+ _emitQueueUpdate() {
304
+ this._emit({
305
+ type: "queue_update",
306
+ steering: [...this._steeringMessages],
307
+ followUp: [...this._followUpMessages],
308
+ });
309
+ }
310
+ async _emitSessionCompactFailed(event) {
311
+ if (this._extensionRunner.hasHandlers("session_compact_failed")) {
312
+ await this._extensionRunner.emit({ type: "session_compact_failed", ...event });
313
+ }
314
+ }
315
+ _getIdleWaitPromise() {
316
+ if (!this._idleWaitPromise) {
317
+ this._idleWaitPromise = new Promise((resolve) => {
318
+ this._resolveIdleWait = resolve;
319
+ });
320
+ }
321
+ return this._idleWaitPromise;
322
+ }
323
+ _resolveIdleWaitIfIdle() {
324
+ if (this._isAgentRunActive || !this._resolveIdleWait) {
325
+ return;
326
+ }
327
+ const resolve = this._resolveIdleWait;
328
+ this._idleWaitPromise = undefined;
329
+ this._resolveIdleWait = undefined;
330
+ resolve();
331
+ }
332
+ async _emitAgentSettled() {
333
+ this._isAgentRunActive = false;
334
+ try {
335
+ await this._extensionRunner.emit({ type: "agent_settled" });
336
+ this._emit({ type: "agent_settled" });
337
+ }
338
+ finally {
339
+ this._resolveIdleWaitIfIdle();
340
+ }
341
+ }
342
+ // Track last assistant message for auto-compaction check
343
+ _lastAssistantMessage = undefined;
344
+ /** Internal handler for agent events - shared by subscribe and reconnect */
345
+ _handleAgentEvent = async (event) => {
346
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
347
+ // This ensures the UI sees the updated queue state
348
+ if (event.type === "message_start" && event.message.role === "user") {
349
+ this._overflowRecoveryAttempted = false;
350
+ const messageText = contentText(event.message.content, "");
351
+ if (messageText) {
352
+ // Check steering queue first
353
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
354
+ if (steeringIndex !== -1) {
355
+ this._steeringMessages.splice(steeringIndex, 1);
356
+ this._emitQueueUpdate();
357
+ }
358
+ else {
359
+ // Check follow-up queue
360
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
361
+ if (followUpIndex !== -1) {
362
+ this._followUpMessages.splice(followUpIndex, 1);
363
+ this._emitQueueUpdate();
364
+ }
365
+ }
366
+ }
367
+ }
368
+ // Emit to extensions first
369
+ await this._emitExtensionEvent(event);
370
+ // Notify all listeners
371
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
372
+ // Handle session persistence
373
+ if (event.type === "message_end") {
374
+ // Check if this is a custom message from extensions
375
+ if (event.message.role === "custom") {
376
+ // Persist as CustomMessageEntry
377
+ this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
378
+ }
379
+ else if (event.message.role === "user" ||
380
+ event.message.role === "assistant" ||
381
+ event.message.role === "toolResult") {
382
+ // Regular LLM message - persist as SessionMessageEntry
383
+ this.sessionManager.appendMessage(event.message);
384
+ }
385
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
386
+ // Track assistant message for auto-compaction (checked on agent_end)
387
+ if (event.message.role === "assistant") {
388
+ this._lastAssistantMessage = event.message;
389
+ const assistantMsg = event.message;
390
+ if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "length") {
391
+ this._overflowRecoveryAttempted = false;
392
+ }
393
+ // Reset retry counter immediately on successful assistant response
394
+ // This prevents accumulation across multiple LLM calls within a turn
395
+ if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
396
+ this._emit({
397
+ type: "auto_retry_end",
398
+ success: true,
399
+ attempt: this._retryAttempt,
400
+ });
401
+ this._retryAttempt = 0;
402
+ }
403
+ }
404
+ }
405
+ // A turn ends after its assistant message and every tool result has been appended,
406
+ // so this is the first point in the run where a context-only custom message can be
407
+ // inserted without landing between a tool call and its result. Flushing after the
408
+ // extension and listener dispatch above also picks up messages that turn_end
409
+ // handlers queued.
410
+ if (event.type === "turn_end") {
411
+ this._flushPendingCustomMessages();
412
+ }
413
+ };
414
+ _willRetryAfterAgentEnd(event) {
415
+ const settings = this.settingsManager.getRetrySettings();
416
+ if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
417
+ return false;
418
+ }
419
+ for (let i = event.messages.length - 1; i >= 0; i--) {
420
+ const message = event.messages[i];
421
+ if (message.role === "assistant") {
422
+ return this._isRetryableError(message);
423
+ }
424
+ }
425
+ return false;
426
+ }
427
+ /** Find the last assistant message in agent state (including aborted ones) */
428
+ _findLastAssistantMessage() {
429
+ const messages = this.agent.state.messages;
430
+ for (let i = messages.length - 1; i >= 0; i--) {
431
+ const msg = messages[i];
432
+ if (msg.role === "assistant") {
433
+ return msg;
434
+ }
435
+ }
436
+ return undefined;
437
+ }
438
+ _replaceMessageInPlace(target, replacement) {
439
+ // Agent-core stores the finalized message object in its state before emitting message_end.
440
+ // SessionManager persistence happens later in _handleAgentEvent() with event.message.
441
+ // Mutating this object in place keeps agent state, later turn/agent events, listeners,
442
+ // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
443
+ if (target === replacement) {
444
+ return;
445
+ }
446
+ const targetRecord = target;
447
+ for (const key of Object.keys(targetRecord)) {
448
+ delete targetRecord[key];
449
+ }
450
+ Object.assign(targetRecord, replacement);
451
+ }
452
+ /** Emit extension events based on agent events */
453
+ async _emitExtensionEvent(event) {
454
+ if (event.type === "agent_start") {
455
+ this._turnIndex = 0;
456
+ await this._extensionRunner.emit({ type: "agent_start" });
457
+ }
458
+ else if (event.type === "agent_end") {
459
+ await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
460
+ }
461
+ else if (event.type === "turn_start") {
462
+ const extensionEvent = {
463
+ type: "turn_start",
464
+ turnIndex: this._turnIndex,
465
+ timestamp: Date.now(),
466
+ };
467
+ await this._extensionRunner.emit(extensionEvent);
468
+ }
469
+ else if (event.type === "turn_end") {
470
+ const extensionEvent = {
471
+ type: "turn_end",
472
+ turnIndex: this._turnIndex,
473
+ message: event.message,
474
+ toolResults: event.toolResults,
475
+ };
476
+ await this._extensionRunner.emit(extensionEvent);
477
+ this._turnIndex++;
478
+ }
479
+ else if (event.type === "message_start") {
480
+ const extensionEvent = {
481
+ type: "message_start",
482
+ message: event.message,
483
+ };
484
+ await this._extensionRunner.emit(extensionEvent);
485
+ }
486
+ else if (event.type === "message_update") {
487
+ const extensionEvent = {
488
+ type: "message_update",
489
+ message: event.message,
490
+ assistantMessageEvent: event.assistantMessageEvent,
491
+ };
492
+ await this._extensionRunner.emit(extensionEvent);
493
+ }
494
+ else if (event.type === "message_end") {
495
+ const extensionEvent = {
496
+ type: "message_end",
497
+ message: event.message,
498
+ };
499
+ const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
500
+ if (replacement) {
501
+ // Untyped extension handlers can return messages with null/missing content;
502
+ // normalize so it never enters agent state or session history.
503
+ const normalized = (replacement.role === "user" ||
504
+ replacement.role === "assistant" ||
505
+ replacement.role === "toolResult" ||
506
+ replacement.role === "custom") &&
507
+ replacement.content == null
508
+ ? { ...replacement, content: [] }
509
+ : replacement;
510
+ this._replaceMessageInPlace(event.message, normalized);
511
+ }
512
+ }
513
+ else if (event.type === "tool_execution_start") {
514
+ const extensionEvent = {
515
+ type: "tool_execution_start",
516
+ toolCallId: event.toolCallId,
517
+ toolName: event.toolName,
518
+ args: event.args,
519
+ };
520
+ await this._extensionRunner.emit(extensionEvent);
521
+ }
522
+ else if (event.type === "tool_execution_update") {
523
+ const extensionEvent = {
524
+ type: "tool_execution_update",
525
+ toolCallId: event.toolCallId,
526
+ toolName: event.toolName,
527
+ args: event.args,
528
+ partialResult: event.partialResult,
529
+ };
530
+ await this._extensionRunner.emit(extensionEvent);
531
+ }
532
+ else if (event.type === "tool_execution_end") {
533
+ const extensionEvent = {
534
+ type: "tool_execution_end",
535
+ toolCallId: event.toolCallId,
536
+ toolName: event.toolName,
537
+ result: event.result,
538
+ isError: event.isError,
539
+ };
540
+ await this._extensionRunner.emit(extensionEvent);
541
+ }
542
+ }
543
+ /**
544
+ * Subscribe to agent events.
545
+ * Session persistence is handled internally (saves messages on message_end).
546
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
547
+ */
548
+ subscribe(listener) {
549
+ this._eventListeners.push(listener);
550
+ // Return unsubscribe function for this specific listener
551
+ return () => {
552
+ const index = this._eventListeners.indexOf(listener);
553
+ if (index !== -1) {
554
+ this._eventListeners.splice(index, 1);
555
+ }
556
+ };
557
+ }
558
+ /** Disconnect from agent events during disposal. */
559
+ _disconnectFromAgent() {
560
+ if (this._unsubscribeAgent) {
561
+ this._unsubscribeAgent();
562
+ this._unsubscribeAgent = undefined;
563
+ }
564
+ }
565
+ /**
566
+ * Remove all listeners and disconnect from agent.
567
+ * Call this when completely done with the session.
568
+ */
569
+ dispose() {
570
+ try {
571
+ this.abortRetry();
572
+ this.abortCompaction();
573
+ this.abortBranchSummary();
574
+ this.abortBash();
575
+ this.agent.abort();
576
+ }
577
+ catch {
578
+ // Dispose must succeed even if an abort hook throws.
579
+ }
580
+ 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().");
581
+ this._disconnectFromAgent();
582
+ this._eventListeners = [];
583
+ cleanupSessionResources(this.sessionId);
584
+ }
585
+ // =========================================================================
586
+ // Read-only State Access
587
+ // =========================================================================
588
+ /** Full agent state */
589
+ get state() {
590
+ return this.agent.state;
591
+ }
592
+ /** Current model (may be undefined if not yet selected) */
593
+ get model() {
594
+ return this.agent.state.model;
595
+ }
596
+ /** Current thinking level */
597
+ get thinkingLevel() {
598
+ return this.agent.state.thinkingLevel;
599
+ }
600
+ /** Whether the session is currently processing an agent run or post-run continuation. */
601
+ get isStreaming() {
602
+ return this._isAgentRunActive;
603
+ }
604
+ /** Whether the session has no active agent run, retry, auto-compaction, or queued continuation. */
605
+ get isIdle() {
606
+ return !this._isAgentRunActive;
607
+ }
608
+ /** Current effective system prompt (includes any per-turn extension modifications) */
609
+ get systemPrompt() {
610
+ return this.agent.state.systemPrompt;
611
+ }
612
+ /** Current retry attempt (0 if not retrying) */
613
+ get retryAttempt() {
614
+ return this._retryAttempt;
615
+ }
616
+ /**
617
+ * Get the names of currently active tools.
618
+ * Returns the names of tools currently set on the agent.
619
+ */
620
+ getActiveToolNames() {
621
+ return this.agent.state.tools.map((t) => t.name);
622
+ }
623
+ /**
624
+ * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
625
+ */
626
+ getAllTools() {
627
+ return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
628
+ name: definition.name,
629
+ description: definition.description,
630
+ parameters: definition.parameters,
631
+ promptGuidelines: definition.promptGuidelines,
632
+ sourceInfo,
633
+ }));
634
+ }
635
+ getToolDefinition(name) {
636
+ return this._toolDefinitions.get(name)?.definition;
637
+ }
638
+ /**
639
+ * Set active tools by name.
640
+ * Only tools in the registry can be enabled. Unknown tool names are ignored.
641
+ * Also rebuilds the system prompt to reflect the new tool set.
642
+ * Changes take effect on the next agent turn.
643
+ */
644
+ setActiveToolsByName(toolNames) {
645
+ const tools = [];
646
+ const validToolNames = [];
647
+ for (const name of toolNames) {
648
+ const tool = this._toolRegistry.get(name);
649
+ if (tool) {
650
+ tools.push(tool);
651
+ validToolNames.push(name);
652
+ }
653
+ }
654
+ this.agent.state.tools = tools;
655
+ // Rebuild base system prompt with new tool set
656
+ this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
657
+ this.agent.state.systemPrompt = this._systemPromptOverride ?? this._baseSystemPrompt;
658
+ }
659
+ /** Whether compaction or branch summarization is currently running */
660
+ get isCompacting() {
661
+ return (this._autoCompactionAbortController !== undefined ||
662
+ this._compactionAbortController !== undefined ||
663
+ this._branchSummaryAbortController !== undefined);
664
+ }
665
+ /** All messages including custom types like BashExecutionMessage */
666
+ get messages() {
667
+ return this.agent.state.messages;
668
+ }
669
+ /** Current steering mode */
670
+ get steeringMode() {
671
+ return this.agent.steeringMode;
672
+ }
673
+ /** Current follow-up mode */
674
+ get followUpMode() {
675
+ return this.agent.followUpMode;
676
+ }
677
+ /** Current session file path, or undefined if sessions are disabled */
678
+ get sessionFile() {
679
+ return this.sessionManager.getSessionFile();
680
+ }
681
+ /** Current session ID */
682
+ get sessionId() {
683
+ return this.sessionManager.getSessionId();
684
+ }
685
+ /** Current session display name, if set */
686
+ get sessionName() {
687
+ return this.sessionManager.getSessionName();
688
+ }
689
+ /** Scoped models for cycling (from --models flag) */
690
+ get scopedModels() {
691
+ return this._scopedModels;
692
+ }
693
+ /** Update scoped models for cycling */
694
+ setScopedModels(scopedModels) {
695
+ this._scopedModels = scopedModels;
696
+ }
697
+ /** File-based prompt templates */
698
+ get promptTemplates() {
699
+ return this._resourceLoader.getPrompts().prompts;
700
+ }
701
+ _normalizePromptSnippet(text) {
702
+ if (!text)
703
+ return undefined;
704
+ const oneLine = text
705
+ .replace(/[\r\n]+/g, " ")
706
+ .replace(/\s+/g, " ")
707
+ .trim();
708
+ return oneLine.length > 0 ? oneLine : undefined;
709
+ }
710
+ _normalizePromptGuidelines(guidelines) {
711
+ if (!guidelines || guidelines.length === 0) {
712
+ return [];
713
+ }
714
+ const unique = new Set();
715
+ for (const guideline of guidelines) {
716
+ const normalized = guideline.trim();
717
+ if (normalized.length > 0) {
718
+ unique.add(normalized);
719
+ }
720
+ }
721
+ return Array.from(unique);
722
+ }
723
+ _rebuildSystemPrompt(toolNames) {
724
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
725
+ const toolSnippets = {};
726
+ const promptGuidelines = [];
727
+ for (const name of validToolNames) {
728
+ const snippet = this._toolPromptSnippets.get(name);
729
+ if (snippet) {
730
+ toolSnippets[name] = snippet;
731
+ }
732
+ const toolGuidelines = this._toolPromptGuidelines.get(name);
733
+ if (toolGuidelines) {
734
+ promptGuidelines.push(...toolGuidelines);
735
+ }
736
+ }
737
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
738
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
739
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
740
+ const loadedSkills = this._resourceLoader.getSkills().skills;
741
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
742
+ this._baseSystemPromptOptions = {
743
+ cwd: this._cwd,
744
+ skills: loadedSkills,
745
+ contextFiles: loadedContextFiles,
746
+ customPrompt: loaderSystemPrompt,
747
+ appendSystemPrompt,
748
+ selectedTools: validToolNames,
749
+ toolSnippets,
750
+ promptGuidelines,
751
+ };
752
+ return buildSystemPrompt(this._baseSystemPromptOptions);
753
+ }
754
+ // =========================================================================
755
+ // Prompting
756
+ // =========================================================================
757
+ async _runAgentPrompt(messages) {
758
+ this._isAgentRunActive = true;
759
+ try {
760
+ await this.agent.prompt(messages);
761
+ while (await this._handlePostAgentRun()) {
762
+ await this.agent.continue();
763
+ }
764
+ }
765
+ finally {
766
+ this._systemPromptOverride = undefined;
767
+ this._flushPendingBashMessages();
768
+ this._flushPendingCustomMessages();
769
+ await this._emitAgentSettled();
770
+ }
771
+ }
772
+ async _handlePostAgentRun() {
773
+ const msg = this._lastAssistantMessage;
774
+ this._lastAssistantMessage = undefined;
775
+ if (!msg) {
776
+ return false;
777
+ }
778
+ if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
779
+ return true;
780
+ }
781
+ if (msg.stopReason === "error" && this._retryAttempt > 0) {
782
+ this._emit({
783
+ type: "auto_retry_end",
784
+ success: false,
785
+ attempt: this._retryAttempt,
786
+ finalError: msg.errorMessage,
787
+ });
788
+ this._retryAttempt = 0;
789
+ }
790
+ if (await this._checkCompaction(msg)) {
791
+ return true;
792
+ }
793
+ // The agent loop drains both queues before emitting agent_end. Any messages
794
+ // here were queued by agent_end extension handlers and need a continuation.
795
+ return this.agent.hasQueuedMessages();
796
+ }
797
+ /**
798
+ * Send a prompt to the agent.
799
+ * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
800
+ * - Expands file-based prompt templates by default
801
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
802
+ * - Validates model and API key before sending (when not streaming)
803
+ * @throws Error if streaming and no streamingBehavior specified
804
+ * @throws Error if no model selected or no API key available (when not streaming)
805
+ */
806
+ async prompt(text, options) {
807
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
808
+ const preflightResult = options?.preflightResult;
809
+ let messages;
810
+ try {
811
+ // Handle extension commands first (execute immediately, even during streaming)
812
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
813
+ if (expandPromptTemplates && text.startsWith("/")) {
814
+ const handled = await this._tryExecuteExtensionCommand(text);
815
+ if (handled) {
816
+ // Extension command executed, no prompt to send
817
+ preflightResult?.(true);
818
+ return;
819
+ }
820
+ }
821
+ if (this._compactionAbortController !== undefined) {
822
+ throw new Error("Cannot submit a prompt while compaction is in progress. Wait for compaction to finish and retry.");
823
+ }
824
+ // Emit input event for extension interception (before skill/template expansion)
825
+ let currentText = text;
826
+ let currentImages = options?.images;
827
+ if (this._extensionRunner.hasHandlers("input")) {
828
+ const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive", this.isStreaming ? options?.streamingBehavior : undefined);
829
+ if (inputResult.action === "handled") {
830
+ preflightResult?.(true);
831
+ return;
832
+ }
833
+ if (inputResult.action === "transform") {
834
+ currentText = inputResult.text;
835
+ currentImages = inputResult.images ?? currentImages;
836
+ }
837
+ }
838
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
839
+ let expandedText = currentText;
840
+ if (expandPromptTemplates) {
841
+ expandedText = this._expandSkillCommand(expandedText);
842
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
843
+ }
844
+ // If streaming, queue via steer() or followUp() based on option
845
+ if (this.isStreaming) {
846
+ if (!options?.streamingBehavior) {
847
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
848
+ }
849
+ if (options.streamingBehavior === "followUp") {
850
+ await this._queueFollowUp(expandedText, currentImages);
851
+ }
852
+ else {
853
+ await this._queueSteer(expandedText, currentImages);
854
+ }
855
+ preflightResult?.(true);
856
+ return;
857
+ }
858
+ // Flush any pending bash and custom messages before the new prompt
859
+ this._flushPendingBashMessages();
860
+ this._flushPendingCustomMessages();
861
+ // Validate model
862
+ if (!this.model) {
863
+ throw new Error(formatNoModelSelectedMessage());
864
+ }
865
+ const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
866
+ (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
867
+ if (!hasConfiguredAuth) {
868
+ const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
869
+ if (isOAuth) {
870
+ throw new Error(`Authentication failed for "${this.model.provider}". ` +
871
+ `Credentials may have expired or network is unavailable. ` +
872
+ `Run '/login ${this.model.provider}' to re-authenticate.`);
873
+ }
874
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
875
+ }
876
+ // Check if we need to compact before sending (catches aborted responses).
877
+ // The user's new prompt is sent below, so do not call agent.continue() here.
878
+ const lastAssistant = this._findLastAssistantMessage();
879
+ if (lastAssistant) {
880
+ await this._checkCompaction(lastAssistant, false);
881
+ }
882
+ // Build messages array (custom message if any, then user message)
883
+ messages = [];
884
+ // Add user message
885
+ const userContent = [{ type: "text", text: expandedText }];
886
+ if (currentImages) {
887
+ userContent.push(...currentImages);
888
+ }
889
+ messages.push({
890
+ role: "user",
891
+ content: userContent,
892
+ timestamp: Date.now(),
893
+ });
894
+ // Inject any pending "nextTurn" messages as context alongside the user message
895
+ for (const msg of this._pendingNextTurnMessages) {
896
+ messages.push(msg);
897
+ }
898
+ this._pendingNextTurnMessages = [];
899
+ // Emit before_agent_start extension event
900
+ const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
901
+ // Add all custom messages from extensions
902
+ if (result?.messages) {
903
+ for (const msg of result.messages) {
904
+ messages.push({
905
+ role: "custom",
906
+ customType: msg.customType,
907
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
908
+ content: msg.content ?? [],
909
+ display: msg.display,
910
+ details: msg.details,
911
+ timestamp: Date.now(),
912
+ });
913
+ }
914
+ }
915
+ // Apply extension-modified system prompt, or reset to base
916
+ if (result?.systemPrompt !== undefined) {
917
+ this._systemPromptOverride = result.systemPrompt;
918
+ this.agent.state.systemPrompt = result.systemPrompt;
919
+ }
920
+ else {
921
+ // Ensure we're using the base prompt (in case previous turn had modifications)
922
+ this._systemPromptOverride = undefined;
923
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
924
+ }
925
+ }
926
+ catch (error) {
927
+ preflightResult?.(false);
928
+ throw error;
929
+ }
930
+ if (!messages) {
931
+ return;
932
+ }
933
+ preflightResult?.(true);
934
+ await this._runAgentPrompt(messages);
935
+ }
936
+ /**
937
+ * Try to execute an extension command. Returns true if command was found and executed.
938
+ */
939
+ async _tryExecuteExtensionCommand(text) {
940
+ // Parse command name and args
941
+ const spaceIndex = text.indexOf(" ");
942
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
943
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
944
+ const command = this._extensionRunner.getCommand(commandName);
945
+ if (!command)
946
+ return false;
947
+ // Get command context from extension runner (includes session control methods)
948
+ const ctx = this._extensionRunner.createCommandContext();
949
+ try {
950
+ await command.handler(args, ctx);
951
+ return true;
952
+ }
953
+ catch (err) {
954
+ // Emit error via extension runner
955
+ this._extensionRunner.emitError({
956
+ extensionPath: `command:${commandName}`,
957
+ event: "command",
958
+ error: err instanceof Error ? err.message : String(err),
959
+ });
960
+ return true;
961
+ }
962
+ }
963
+ /**
964
+ * Expand skill commands (/skill:name args) to their full content.
965
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
966
+ * Emits errors via extension runner if file read fails.
967
+ */
968
+ _expandSkillCommand(text) {
969
+ if (!text.startsWith("/skill:"))
970
+ return text;
971
+ const spaceIndex = text.indexOf(" ");
972
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
973
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
974
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
975
+ if (!skill)
976
+ return text; // Unknown skill, pass through
977
+ try {
978
+ const content = readFileSync(skill.filePath, "utf-8");
979
+ const body = stripFrontmatter(content).trim();
980
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
981
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
982
+ }
983
+ catch (err) {
984
+ // Emit error like extension commands do
985
+ this._extensionRunner.emitError({
986
+ extensionPath: skill.filePath,
987
+ event: "skill_expansion",
988
+ error: err instanceof Error ? err.message : String(err),
989
+ });
990
+ return text; // Return original on error
991
+ }
992
+ }
993
+ /**
994
+ * Queue a steering message while the agent is running.
995
+ * Delivered after the current assistant turn finishes executing its tool calls,
996
+ * before the next LLM call.
997
+ * Expands skill commands and prompt templates. Errors on extension commands.
998
+ * @param images Optional image attachments to include with the message
999
+ * @throws Error if text is an extension command
1000
+ */
1001
+ async steer(text, images) {
1002
+ // Check for extension commands (cannot be queued)
1003
+ if (text.startsWith("/")) {
1004
+ this._throwIfExtensionCommand(text);
1005
+ }
1006
+ // Expand skill commands and prompt templates
1007
+ let expandedText = this._expandSkillCommand(text);
1008
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1009
+ await this._queueSteer(expandedText, images);
1010
+ }
1011
+ /**
1012
+ * Queue a follow-up message to be processed after the agent finishes.
1013
+ * Delivered only when agent has no more tool calls or steering messages.
1014
+ * Expands skill commands and prompt templates. Errors on extension commands.
1015
+ * @param images Optional image attachments to include with the message
1016
+ * @throws Error if text is an extension command
1017
+ */
1018
+ async followUp(text, images) {
1019
+ // Check for extension commands (cannot be queued)
1020
+ if (text.startsWith("/")) {
1021
+ this._throwIfExtensionCommand(text);
1022
+ }
1023
+ // Expand skill commands and prompt templates
1024
+ let expandedText = this._expandSkillCommand(text);
1025
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1026
+ await this._queueFollowUp(expandedText, images);
1027
+ }
1028
+ /**
1029
+ * Internal: Queue a steering message (already expanded, no extension command check).
1030
+ */
1031
+ async _queueSteer(text, images) {
1032
+ this._steeringMessages.push(text);
1033
+ this._emitQueueUpdate();
1034
+ const content = [{ type: "text", text }];
1035
+ if (images) {
1036
+ content.push(...images);
1037
+ }
1038
+ this.agent.steer({
1039
+ role: "user",
1040
+ content,
1041
+ timestamp: Date.now(),
1042
+ });
1043
+ }
1044
+ /**
1045
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
1046
+ */
1047
+ async _queueFollowUp(text, images) {
1048
+ this._followUpMessages.push(text);
1049
+ this._emitQueueUpdate();
1050
+ const content = [{ type: "text", text }];
1051
+ if (images) {
1052
+ content.push(...images);
1053
+ }
1054
+ this.agent.followUp({
1055
+ role: "user",
1056
+ content,
1057
+ timestamp: Date.now(),
1058
+ });
1059
+ }
1060
+ /**
1061
+ * Throw an error if the text is an extension command.
1062
+ */
1063
+ _throwIfExtensionCommand(text) {
1064
+ const spaceIndex = text.indexOf(" ");
1065
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1066
+ const command = this._extensionRunner.getCommand(commandName);
1067
+ if (command) {
1068
+ throw new Error(`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
1069
+ }
1070
+ }
1071
+ /**
1072
+ * Send a custom message to the session. Creates a CustomMessageEntry.
1073
+ *
1074
+ * Handles four cases:
1075
+ * - Streaming: queues message, processed when loop pulls from queue
1076
+ * - Streaming + triggerTurn false: appended to state/session once the current turn ends
1077
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
1078
+ * - Not streaming + no trigger: appends to state/session, no turn
1079
+ *
1080
+ * @param message Custom message with customType, content, display, details
1081
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
1082
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
1083
+ */
1084
+ async sendCustomMessage(message, options) {
1085
+ const appMessage = {
1086
+ role: "custom",
1087
+ customType: message.customType,
1088
+ // Untyped extensions can pass null/missing content; normalize at ingestion.
1089
+ content: message.content ?? [],
1090
+ display: message.display,
1091
+ details: message.details,
1092
+ timestamp: Date.now(),
1093
+ };
1094
+ if (options?.deliverAs === "nextTurn") {
1095
+ this._pendingNextTurnMessages.push(appMessage);
1096
+ }
1097
+ else if (this.isStreaming && options?.triggerTurn !== false) {
1098
+ if (options?.deliverAs === "followUp") {
1099
+ this.agent.followUp(appMessage);
1100
+ }
1101
+ else {
1102
+ this.agent.steer(appMessage);
1103
+ }
1104
+ }
1105
+ else if (options?.triggerTurn) {
1106
+ await this._runAgentPrompt(appMessage);
1107
+ }
1108
+ else if (this.isStreaming) {
1109
+ // Appending now would put the message between an assistant tool call and its
1110
+ // result, which providers that validate message order reject on replay. Defer
1111
+ // to the end of the turn. Nothing is emitted yet: message events must not
1112
+ // describe messages the session tree does not contain.
1113
+ this._pendingCustomMessages.push(appMessage);
1114
+ }
1115
+ else {
1116
+ this._appendCustomMessage(appMessage);
1117
+ }
1118
+ }
1119
+ _appendCustomMessage(appMessage) {
1120
+ this.agent.state.messages.push(appMessage);
1121
+ this.sessionManager.appendCustomMessageEntry(appMessage.customType, appMessage.content, appMessage.display, appMessage.details);
1122
+ this._emit({ type: "message_start", message: appMessage });
1123
+ this._emit({ type: "message_end", message: appMessage });
1124
+ }
1125
+ /**
1126
+ * Append custom messages queued while the agent was running.
1127
+ * Called once the current turn's tool results are in agent state and session history.
1128
+ */
1129
+ _flushPendingCustomMessages() {
1130
+ if (this._pendingCustomMessages.length === 0)
1131
+ return;
1132
+ const pending = this._pendingCustomMessages;
1133
+ this._pendingCustomMessages = [];
1134
+ for (const appMessage of pending) {
1135
+ this._appendCustomMessage(appMessage);
1136
+ }
1137
+ }
1138
+ /**
1139
+ * Send a user message to the agent. Always triggers a turn.
1140
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
1141
+ *
1142
+ * @param content User message content (string or content array)
1143
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
1144
+ * @param options.expandPromptTemplates Whether to dispatch extension commands and expand skill commands and prompt templates. Default: false.
1145
+ */
1146
+ async sendUserMessage(content, options) {
1147
+ // Normalize content to text string + optional images
1148
+ let text;
1149
+ let images;
1150
+ if (typeof content === "string") {
1151
+ text = content;
1152
+ }
1153
+ else {
1154
+ const textParts = [];
1155
+ images = [];
1156
+ for (const part of content) {
1157
+ if (part.type === "text") {
1158
+ textParts.push(part.text);
1159
+ }
1160
+ else {
1161
+ images.push(part);
1162
+ }
1163
+ }
1164
+ text = textParts.join("\n");
1165
+ if (images.length === 0)
1166
+ images = undefined;
1167
+ }
1168
+ await this.prompt(text, {
1169
+ expandPromptTemplates: options?.expandPromptTemplates ?? false,
1170
+ streamingBehavior: options?.deliverAs,
1171
+ images,
1172
+ source: "extension",
1173
+ });
1174
+ }
1175
+ /**
1176
+ * Clear all queued messages and return them.
1177
+ * Useful for restoring to editor when user aborts.
1178
+ * @returns Object with steering and followUp arrays
1179
+ */
1180
+ clearQueue() {
1181
+ const steering = [...this._steeringMessages];
1182
+ const followUp = [...this._followUpMessages];
1183
+ this._steeringMessages = [];
1184
+ this._followUpMessages = [];
1185
+ this.agent.clearAllQueues();
1186
+ this._emitQueueUpdate();
1187
+ return { steering, followUp };
1188
+ }
1189
+ /** Number of pending messages (includes both steering and follow-up) */
1190
+ get pendingMessageCount() {
1191
+ return this._steeringMessages.length + this._followUpMessages.length;
1192
+ }
1193
+ /** Get pending steering messages (read-only) */
1194
+ getSteeringMessages() {
1195
+ return this._steeringMessages;
1196
+ }
1197
+ /** Get pending follow-up messages (read-only) */
1198
+ getFollowUpMessages() {
1199
+ return this._followUpMessages;
1200
+ }
1201
+ get resourceLoader() {
1202
+ return this._resourceLoader;
1203
+ }
1204
+ /**
1205
+ * Abort current operation and wait for agent to become idle.
1206
+ */
1207
+ async abort() {
1208
+ this.abortRetry();
1209
+ this.agent.abort();
1210
+ await this.waitForIdle();
1211
+ }
1212
+ async waitForIdle() {
1213
+ if (this.isIdle) {
1214
+ return;
1215
+ }
1216
+ await this._getIdleWaitPromise();
1217
+ }
1218
+ // =========================================================================
1219
+ // Model Management
1220
+ // =========================================================================
1221
+ async _emitModelSelect(nextModel, previousModel, source) {
1222
+ if (modelsAreEqual(previousModel, nextModel))
1223
+ return;
1224
+ await this._extensionRunner.emit({
1225
+ type: "model_select",
1226
+ model: nextModel,
1227
+ previousModel,
1228
+ source,
1229
+ });
1230
+ }
1231
+ /**
1232
+ * Set model directly.
1233
+ * Validates that auth is configured and saves to the session transcript.
1234
+ * Persists to global defaults only when options.persist is true.
1235
+ * @throws Error if no auth is configured for the model
1236
+ */
1237
+ async setModel(model, options = {}) {
1238
+ if (!(await this._modelRuntime.checkAuth(model.provider))) {
1239
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
1240
+ }
1241
+ const previousModel = this.model;
1242
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(model);
1243
+ this.agent.state.model = model;
1244
+ this.sessionManager.appendModelChange(model.provider, model.id);
1245
+ if (options.persist) {
1246
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1247
+ this._addPersistedDefaultToNonEmptyScope(model);
1248
+ }
1249
+ // Apply thinking level for the new model.
1250
+ // Per-model thinking level overrides take priority over the global default.
1251
+ // Model persistence does not implicitly rewrite the global thinking default.
1252
+ this.setThinkingLevel(thinkingLevel);
1253
+ await this._emitModelSelect(model, previousModel, "set");
1254
+ }
1255
+ _addPersistedDefaultToNonEmptyScope(model) {
1256
+ if (this._scopedModels.length === 0)
1257
+ return;
1258
+ if (this._scopedModels.some((scoped) => modelsAreEqual(scoped.model, model)))
1259
+ return;
1260
+ this._scopedModels = [...this._scopedModels, { model }];
1261
+ const enabledModels = this.settingsManager.getEnabledModels();
1262
+ if (!enabledModels?.length)
1263
+ return;
1264
+ const modelReference = `${model.provider}/${model.id}`;
1265
+ if (enabledModels.some((pattern) => pattern.toLowerCase() === modelReference.toLowerCase()))
1266
+ return;
1267
+ this.settingsManager.setEnabledModels([...enabledModels, modelReference]);
1268
+ }
1269
+ /**
1270
+ * Cycle to next/previous model.
1271
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
1272
+ * @param direction - "forward" (default) or "backward"
1273
+ * @returns The new model info, or undefined if only one model available
1274
+ */
1275
+ async cycleModel(direction = "forward", options = {}) {
1276
+ if (this._scopedModels.length > 0) {
1277
+ return this._cycleScopedModel(direction, options);
1278
+ }
1279
+ return this._cycleAvailableModel(direction, options);
1280
+ }
1281
+ async _cycleScopedModel(direction, options) {
1282
+ const availableIds = new Set(this._modelRuntime.getAvailableSnapshot().map((model) => `${model.provider}\0${model.id}`));
1283
+ const scopedModels = this._scopedModels.filter((scoped) => availableIds.has(`${scoped.model.provider}\0${scoped.model.id}`));
1284
+ if (scopedModels.length <= 1)
1285
+ return undefined;
1286
+ const currentModel = this.model;
1287
+ let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
1288
+ if (currentIndex === -1)
1289
+ currentIndex = 0;
1290
+ const len = scopedModels.length;
1291
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1292
+ const next = scopedModels[nextIndex];
1293
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.model, next.thinkingLevel);
1294
+ // Apply model
1295
+ this.agent.state.model = next.model;
1296
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id);
1297
+ if (options.persist) {
1298
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1299
+ this._addPersistedDefaultToNonEmptyScope(next.model);
1300
+ }
1301
+ // Apply thinking level for the new model.
1302
+ // - Explicit scoped model thinking level overrides defaults
1303
+ // - Per-model thinking level overrides take priority over the global default
1304
+ // setThinkingLevel clamps to model capabilities.
1305
+ // Model persistence does not implicitly rewrite the global thinking default.
1306
+ this.setThinkingLevel(thinkingLevel);
1307
+ await this._emitModelSelect(next.model, currentModel, "cycle");
1308
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1309
+ }
1310
+ async _cycleAvailableModel(direction, options) {
1311
+ const availableModels = this._modelRuntime.getAvailableSnapshot();
1312
+ if (availableModels.length <= 1)
1313
+ return undefined;
1314
+ const currentModel = this.model;
1315
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
1316
+ if (currentIndex === -1)
1317
+ currentIndex = 0;
1318
+ const len = availableModels.length;
1319
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1320
+ const nextModel = availableModels[nextIndex];
1321
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(nextModel);
1322
+ this.agent.state.model = nextModel;
1323
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
1324
+ if (options.persist) {
1325
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1326
+ this._addPersistedDefaultToNonEmptyScope(nextModel);
1327
+ }
1328
+ // Apply thinking level for the new model.
1329
+ // Model persistence does not implicitly rewrite the global thinking default.
1330
+ this.setThinkingLevel(thinkingLevel);
1331
+ await this._emitModelSelect(nextModel, currentModel, "cycle");
1332
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
1333
+ }
1334
+ // =========================================================================
1335
+ // Thinking Level Management
1336
+ // =========================================================================
1337
+ /**
1338
+ * Set thinking level.
1339
+ * Clamps to model capabilities based on available thinking levels.
1340
+ * Saves the clamped level to the session transcript only if the level actually changes.
1341
+ * Persists the requested level to global defaults only when options.persist is true.
1342
+ */
1343
+ setThinkingLevel(level, options = {}) {
1344
+ const availableLevels = this.getAvailableThinkingLevels();
1345
+ const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1346
+ // Only persist if actually changing
1347
+ const previousLevel = this.agent.state.thinkingLevel;
1348
+ const isChanging = effectiveLevel !== previousLevel;
1349
+ this.agent.state.thinkingLevel = effectiveLevel;
1350
+ if (options.persist) {
1351
+ this.settingsManager.setDefaultThinkingLevel(level);
1352
+ }
1353
+ if (isChanging) {
1354
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1355
+ this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1356
+ void this._extensionRunner.emit({
1357
+ type: "thinking_level_select",
1358
+ level: effectiveLevel,
1359
+ previousLevel,
1360
+ });
1361
+ }
1362
+ }
1363
+ /**
1364
+ * Cycle to next thinking level.
1365
+ * @returns New level, or undefined if model doesn't support thinking
1366
+ */
1367
+ cycleThinkingLevel(options = {}) {
1368
+ if (!this.supportsThinking())
1369
+ return undefined;
1370
+ const levels = this.getAvailableThinkingLevels();
1371
+ const currentIndex = levels.indexOf(this.thinkingLevel);
1372
+ const nextIndex = (currentIndex + 1) % levels.length;
1373
+ const nextLevel = levels[nextIndex];
1374
+ this.setThinkingLevel(nextLevel, options);
1375
+ return nextLevel;
1376
+ }
1377
+ /**
1378
+ * Get available thinking levels for current model.
1379
+ * The provider will clamp to what the specific model supports internally.
1380
+ */
1381
+ getAvailableThinkingLevels() {
1382
+ if (!this.model)
1383
+ return [...THINKING_LEVEL_OPTIONS];
1384
+ return getSupportedThinkingLevels(this.model);
1385
+ }
1386
+ /**
1387
+ * Check if current model supports thinking/reasoning.
1388
+ */
1389
+ supportsThinking() {
1390
+ return !!this.model?.reasoning;
1391
+ }
1392
+ _getThinkingLevelForModelSwitch(targetModel, explicitLevel) {
1393
+ if (explicitLevel !== undefined) {
1394
+ return explicitLevel;
1395
+ }
1396
+ // Per-model default takes priority when switching to a model that has one
1397
+ if (targetModel) {
1398
+ const perModel = this.settingsManager.getModelThinkingLevel(targetModel.provider, targetModel.id);
1399
+ if (perModel !== undefined) {
1400
+ return perModel;
1401
+ }
1402
+ }
1403
+ return this.settingsManager.getDefaultThinkingLevel() ?? this.thinkingLevel ?? DEFAULT_THINKING_LEVEL;
1404
+ }
1405
+ _clampThinkingLevel(level, _availableLevels) {
1406
+ return this.model ? clampThinkingLevel(this.model, level) : "off";
1407
+ }
1408
+ // =========================================================================
1409
+ // Queue Mode Management
1410
+ // =========================================================================
1411
+ syncQueueModesFromSettings() {
1412
+ this.agent.steeringMode = this.settingsManager.getSteeringMode();
1413
+ this.agent.followUpMode = this.settingsManager.getFollowUpMode();
1414
+ }
1415
+ /**
1416
+ * Set steering message mode.
1417
+ * Saves to settings.
1418
+ */
1419
+ setSteeringMode(mode) {
1420
+ this.agent.steeringMode = mode;
1421
+ this.settingsManager.setSteeringMode(mode);
1422
+ }
1423
+ /**
1424
+ * Set follow-up message mode.
1425
+ * Saves to settings.
1426
+ */
1427
+ setFollowUpMode(mode) {
1428
+ this.agent.followUpMode = mode;
1429
+ this.settingsManager.setFollowUpMode(mode);
1430
+ }
1431
+ // =========================================================================
1432
+ // Compaction
1433
+ // =========================================================================
1434
+ /** Generate Pi's built-in compaction summary for manual and automatic compaction. */
1435
+ async _runDefaultCompaction(preparation, requestModel, apiKey, headers, customInstructions, signal, env, reason) {
1436
+ return compact(preparation, requestModel, apiKey, headers, customInstructions, signal, this.thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason }), undefined);
1437
+ }
1438
+ /**
1439
+ * Manually compact the session context.
1440
+ *
1441
+ * This is the manual entry point used by `/compact`, RPC, and extensions. It is
1442
+ * separate from automatic threshold/overflow compaction, which enters through
1443
+ * `_checkCompaction()` and `_runAutoCompaction()`. After preparation and the
1444
+ * `session_before_compact` hook, both paths call the lower-level `compact()`
1445
+ * function imported from `./compaction/index.ts`, unless the hook cancels or
1446
+ * supplies a custom result.
1447
+ *
1448
+ * Aborts the current agent operation first. Manual compaction never retries or
1449
+ * continues the interrupted agent turn.
1450
+ *
1451
+ * @param customInstructions Optional instructions for the compaction summary
1452
+ */
1453
+ async compact(customInstructions) {
1454
+ await this.abort();
1455
+ this._compactionAbortController = new AbortController();
1456
+ this._emit({ type: "compaction_start", reason: "manual" });
1457
+ let fromExtension = false;
1458
+ try {
1459
+ if (!this.model) {
1460
+ throw new Error(formatNoModelSelectedMessage());
1461
+ }
1462
+ const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
1463
+ const pathEntries = this.sessionManager.getBranch();
1464
+ const settings = this.settingsManager.getCompactionSettings();
1465
+ const preparation = prepareCompaction(pathEntries, settings);
1466
+ if (!preparation) {
1467
+ // Check why we can't compact
1468
+ const lastEntry = pathEntries[pathEntries.length - 1];
1469
+ if (lastEntry?.type === "compaction") {
1470
+ throw new Error("Already compacted");
1471
+ }
1472
+ throw new Error("Nothing to compact (session too small)");
1473
+ }
1474
+ let extensionCompaction;
1475
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1476
+ const result = (await this._extensionRunner.emit({
1477
+ type: "session_before_compact",
1478
+ preparation,
1479
+ branchEntries: pathEntries,
1480
+ customInstructions,
1481
+ reason: "manual",
1482
+ willRetry: false,
1483
+ signal: this._compactionAbortController.signal,
1484
+ }));
1485
+ if (result?.cancel) {
1486
+ throw new Error("Compaction cancelled");
1487
+ }
1488
+ if (result?.compaction) {
1489
+ extensionCompaction = result.compaction;
1490
+ fromExtension = true;
1491
+ }
1492
+ }
1493
+ let summary;
1494
+ let firstKeptEntryId;
1495
+ let tokensBefore;
1496
+ let usage;
1497
+ let details;
1498
+ if (extensionCompaction) {
1499
+ // Extension provided compaction content
1500
+ summary = extensionCompaction.summary;
1501
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1502
+ tokensBefore = extensionCompaction.tokensBefore;
1503
+ usage = extensionCompaction.usage;
1504
+ details = extensionCompaction.details;
1505
+ }
1506
+ else {
1507
+ // Shared default summary generator, also used by automatic compaction.
1508
+ const result = await this._runDefaultCompaction(preparation, requestModel, apiKey, headers, customInstructions, this._compactionAbortController.signal, env, "manual");
1509
+ summary = result.summary;
1510
+ firstKeptEntryId = result.firstKeptEntryId;
1511
+ tokensBefore = result.tokensBefore;
1512
+ usage = result.usage;
1513
+ details = result.details;
1514
+ }
1515
+ if (this._compactionAbortController.signal.aborted) {
1516
+ throw new Error("Compaction cancelled");
1517
+ }
1518
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1519
+ const newEntries = this.sessionManager.getEntries();
1520
+ const sessionContext = this.sessionManager.buildSessionContext();
1521
+ this.agent.state.messages = sessionContext.messages;
1522
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
1523
+ // Get the saved compaction entry for the extension event
1524
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1525
+ if (this._extensionRunner && savedCompactionEntry) {
1526
+ await this._extensionRunner.emit({
1527
+ type: "session_compact",
1528
+ compactionEntry: savedCompactionEntry,
1529
+ fromExtension,
1530
+ reason: "manual",
1531
+ willRetry: false,
1532
+ });
1533
+ }
1534
+ const compactionResult = {
1535
+ summary,
1536
+ firstKeptEntryId,
1537
+ tokensBefore,
1538
+ estimatedTokensAfter,
1539
+ usage,
1540
+ details,
1541
+ };
1542
+ // compaction_end listeners may submit queued prompts, so expose idle state before notifying them.
1543
+ this._compactionAbortController = undefined;
1544
+ this._emit({
1545
+ type: "compaction_end",
1546
+ reason: "manual",
1547
+ result: compactionResult,
1548
+ aborted: false,
1549
+ willRetry: false,
1550
+ });
1551
+ return compactionResult;
1552
+ }
1553
+ catch (error) {
1554
+ const message = error instanceof Error ? error.message : String(error);
1555
+ const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
1556
+ const errorMessage = aborted ? undefined : `Compaction failed: ${message}`;
1557
+ this._compactionAbortController = undefined;
1558
+ this._emit({
1559
+ type: "compaction_end",
1560
+ reason: "manual",
1561
+ result: undefined,
1562
+ aborted,
1563
+ willRetry: false,
1564
+ errorMessage,
1565
+ });
1566
+ await this._emitSessionCompactFailed({
1567
+ reason: "manual",
1568
+ errorMessage,
1569
+ aborted,
1570
+ willRetry: false,
1571
+ fromExtension,
1572
+ });
1573
+ throw error;
1574
+ }
1575
+ finally {
1576
+ this._compactionAbortController = undefined;
1577
+ }
1578
+ }
1579
+ /**
1580
+ * Cancel in-progress compaction (manual or auto).
1581
+ */
1582
+ abortCompaction() {
1583
+ this._compactionAbortController?.abort();
1584
+ this._autoCompactionAbortController?.abort();
1585
+ }
1586
+ /**
1587
+ * Cancel in-progress branch summarization.
1588
+ */
1589
+ abortBranchSummary() {
1590
+ this._branchSummaryAbortController?.abort();
1591
+ }
1592
+ /**
1593
+ * Dispatch automatic compaction after `agent_end` or before prompt submission.
1594
+ * Manual compaction does not call this method; it enters through `compact()`.
1595
+ *
1596
+ * Automatic cases:
1597
+ * 1. Overflow with retry: a context-overflow error or recoverable length stop;
1598
+ * remove the failed assistant message, compact, and retry the turn once.
1599
+ * 2. Overflow without retry: a successful response exceeded the configured
1600
+ * context window; compact but preserve the completed response.
1601
+ * 3. Threshold without retry: valid or estimated context usage crossed the
1602
+ * configured threshold; compact without retrying the completed response.
1603
+ *
1604
+ * Each case calls `_runAutoCompaction()`. After preparation and the
1605
+ * `session_before_compact` hook, that method calls the lower-level `compact()`
1606
+ * function imported from `./compaction/index.ts`, unless the hook cancels or
1607
+ * supplies a custom result.
1608
+ *
1609
+ * @param assistantMessage The assistant message to check
1610
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
1611
+ * @returns Whether the post-run loop should call `agent.continue()` for overflow recovery or queued messages
1612
+ */
1613
+ async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
1614
+ const settings = this.settingsManager.getCompactionSettings();
1615
+ if (!settings.enabled)
1616
+ return false;
1617
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1618
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
1619
+ return false;
1620
+ const contextWindow = this.model?.contextWindow ?? 0;
1621
+ // Skip overflow check if the message came from a different model.
1622
+ // This handles the case where user switched from a smaller-context model (e.g. opus)
1623
+ // to a larger-context model (e.g. codex) - the overflow error from the old model
1624
+ // shouldn't trigger compaction for the new model.
1625
+ const sameModel = this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
1626
+ // Skip compaction checks if this assistant message is older than the latest
1627
+ // compaction boundary. This prevents a stale pre-compaction usage/error
1628
+ // from retriggering compaction on the first prompt after compaction.
1629
+ const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
1630
+ const assistantIsFromBeforeCompaction = compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
1631
+ if (assistantIsFromBeforeCompaction) {
1632
+ return false;
1633
+ }
1634
+ // Automatic cases 1 and 2: context overflow.
1635
+ // A length stop is recoverable when output ended below the model's original desired limit,
1636
+ // independent of the configured context size or any context-clamped provider request limit.
1637
+ const contextOverflow = sameModel && isContextOverflow(assistantMessage, contextWindow);
1638
+ const recoverableLength = sameModel && isRecoverableLength(assistantMessage, this.model?.maxTokens ?? 0);
1639
+ if (contextOverflow || recoverableLength) {
1640
+ const willRetry = assistantMessage.stopReason !== "stop";
1641
+ // Case 2: the response completed successfully. Compact, but do not retry because
1642
+ // agent.continue() cannot continue from a completed assistant response.
1643
+ if (!willRetry) {
1644
+ return await this._runAutoCompaction("overflow", false);
1645
+ }
1646
+ if (this._overflowRecoveryAttempted) {
1647
+ const errorMessage = contextOverflow
1648
+ ? "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model."
1649
+ : "Truncated response recovery failed after one compact-and-retry attempt.";
1650
+ this._emit({
1651
+ type: "compaction_end",
1652
+ reason: "overflow",
1653
+ result: undefined,
1654
+ aborted: false,
1655
+ willRetry: false,
1656
+ errorMessage,
1657
+ });
1658
+ await this._emitSessionCompactFailed({
1659
+ reason: "overflow",
1660
+ errorMessage,
1661
+ aborted: false,
1662
+ willRetry: false,
1663
+ fromExtension: false,
1664
+ });
1665
+ return false;
1666
+ }
1667
+ // Case 1: remove the failed or truncated message from agent state, compact, and
1668
+ // retry once. The message remains in session history but is excluded from retry context.
1669
+ this._overflowRecoveryAttempted = true;
1670
+ const messages = this.agent.state.messages;
1671
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1672
+ this.agent.state.messages = messages.slice(0, -1);
1673
+ }
1674
+ return await this._runAutoCompaction("overflow", willRetry);
1675
+ }
1676
+ // Case 3: threshold compaction without retry.
1677
+ // For error messages or all-zero usage messages, estimate from the last valid response.
1678
+ // This ensures sessions that hit persistent API errors (e.g. 529) or malformed zero-usage
1679
+ // responses can still compact and do not reset context accounting.
1680
+ let contextTokens;
1681
+ const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;
1682
+ if (assistantMessage.stopReason === "error" || directContextTokens === 0) {
1683
+ const messages = this.agent.state.messages;
1684
+ const estimate = estimateContextTokens(messages);
1685
+ // Without provider usage, estimate.tokens is the pure message-size estimate.
1686
+ // Only usage-backed estimates need the stale pre-compaction check.
1687
+ if (estimate.lastUsageIndex !== null) {
1688
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
1689
+ // have stale usage reflecting the old (larger) context and would falsely
1690
+ // trigger compaction right after one just finished.
1691
+ const usageMsg = messages[estimate.lastUsageIndex];
1692
+ if (compactionEntry &&
1693
+ usageMsg.role === "assistant" &&
1694
+ usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
1695
+ return false;
1696
+ }
1697
+ }
1698
+ contextTokens = estimate.tokens;
1699
+ }
1700
+ else {
1701
+ contextTokens = directContextTokens;
1702
+ }
1703
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
1704
+ return await this._runAutoCompaction("threshold", false);
1705
+ }
1706
+ return false;
1707
+ }
1708
+ /**
1709
+ * Execute threshold or overflow compaction. Manual compaction uses
1710
+ * `AgentSession.compact()` instead. Both paths call the lower-level `compact()`
1711
+ * function imported from `./compaction/index.ts` after preparation and extension
1712
+ * interception.
1713
+ *
1714
+ * @param reason Automatic trigger selected by `_checkCompaction()`
1715
+ * @param willRetry Whether to continue the interrupted turn after overflow compaction
1716
+ * @returns Whether the post-run loop should call `agent.continue()`
1717
+ */
1718
+ async _runAutoCompaction(reason, willRetry) {
1719
+ const settings = this.settingsManager.getCompactionSettings();
1720
+ let started = false;
1721
+ let fromExtension = false;
1722
+ try {
1723
+ if (!this.model) {
1724
+ return false;
1725
+ }
1726
+ const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
1727
+ const pathEntries = this.sessionManager.getBranch();
1728
+ const preparation = prepareCompaction(pathEntries, settings);
1729
+ if (!preparation) {
1730
+ return false;
1731
+ }
1732
+ this._emit({ type: "compaction_start", reason });
1733
+ this._autoCompactionAbortController = new AbortController();
1734
+ started = true;
1735
+ let extensionCompaction;
1736
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1737
+ const extensionResult = (await this._extensionRunner.emit({
1738
+ type: "session_before_compact",
1739
+ preparation,
1740
+ branchEntries: pathEntries,
1741
+ customInstructions: undefined,
1742
+ reason,
1743
+ willRetry,
1744
+ signal: this._autoCompactionAbortController.signal,
1745
+ }));
1746
+ if (extensionResult?.cancel) {
1747
+ this._emit({
1748
+ type: "compaction_end",
1749
+ reason,
1750
+ result: undefined,
1751
+ aborted: true,
1752
+ willRetry: false,
1753
+ });
1754
+ await this._emitSessionCompactFailed({
1755
+ reason,
1756
+ aborted: true,
1757
+ willRetry: false,
1758
+ fromExtension: false,
1759
+ });
1760
+ return false;
1761
+ }
1762
+ if (extensionResult?.compaction) {
1763
+ extensionCompaction = extensionResult.compaction;
1764
+ fromExtension = true;
1765
+ }
1766
+ }
1767
+ let summary;
1768
+ let firstKeptEntryId;
1769
+ let tokensBefore;
1770
+ let usage;
1771
+ let details;
1772
+ if (extensionCompaction) {
1773
+ // Extension provided compaction content
1774
+ summary = extensionCompaction.summary;
1775
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1776
+ tokensBefore = extensionCompaction.tokensBefore;
1777
+ usage = extensionCompaction.usage;
1778
+ details = extensionCompaction.details;
1779
+ }
1780
+ else {
1781
+ // Shared default summary generator, also used by manual compaction.
1782
+ const compactResult = await this._runDefaultCompaction(preparation, requestModel, apiKey, headers, undefined, this._autoCompactionAbortController.signal, env, reason);
1783
+ summary = compactResult.summary;
1784
+ firstKeptEntryId = compactResult.firstKeptEntryId;
1785
+ tokensBefore = compactResult.tokensBefore;
1786
+ usage = compactResult.usage;
1787
+ details = compactResult.details;
1788
+ }
1789
+ if (this._autoCompactionAbortController.signal.aborted) {
1790
+ this._emit({
1791
+ type: "compaction_end",
1792
+ reason,
1793
+ result: undefined,
1794
+ aborted: true,
1795
+ willRetry: false,
1796
+ });
1797
+ await this._emitSessionCompactFailed({
1798
+ reason,
1799
+ aborted: true,
1800
+ willRetry: false,
1801
+ fromExtension,
1802
+ });
1803
+ return false;
1804
+ }
1805
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1806
+ const newEntries = this.sessionManager.getEntries();
1807
+ const sessionContext = this.sessionManager.buildSessionContext();
1808
+ this.agent.state.messages = sessionContext.messages;
1809
+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);
1810
+ // Get the saved compaction entry for the extension event
1811
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1812
+ if (this._extensionRunner && savedCompactionEntry) {
1813
+ await this._extensionRunner.emit({
1814
+ type: "session_compact",
1815
+ compactionEntry: savedCompactionEntry,
1816
+ fromExtension,
1817
+ reason,
1818
+ willRetry,
1819
+ });
1820
+ }
1821
+ const result = {
1822
+ summary,
1823
+ firstKeptEntryId,
1824
+ tokensBefore,
1825
+ estimatedTokensAfter,
1826
+ usage,
1827
+ details,
1828
+ };
1829
+ this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
1830
+ if (willRetry) {
1831
+ const messages = this.agent.state.messages;
1832
+ const lastMsg = messages[messages.length - 1];
1833
+ // The overflow response was persisted on message_end before _checkCompaction() removed it
1834
+ // from agent state. Rebuilding state from the new compaction can restore that kept entry,
1835
+ // leaving an assistant as the final message. agent.continue() rejects that state, so remove
1836
+ // the retriable error or truncated-length response again before continuing the interrupted turn.
1837
+ if (lastMsg?.role === "assistant" && (lastMsg.stopReason === "error" || lastMsg.stopReason === "length")) {
1838
+ this.agent.state.messages = messages.slice(0, -1);
1839
+ }
1840
+ return true;
1841
+ }
1842
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1843
+ // Continue once so queued messages are delivered.
1844
+ return this.agent.hasQueuedMessages();
1845
+ }
1846
+ catch (error) {
1847
+ const errorMessage = error instanceof Error ? error.message : "compaction failed";
1848
+ if (started) {
1849
+ const formattedErrorMessage = reason === "overflow"
1850
+ ? `Context overflow recovery failed: ${errorMessage}`
1851
+ : `Auto-compaction failed: ${errorMessage}`;
1852
+ this._emit({
1853
+ type: "compaction_end",
1854
+ reason,
1855
+ result: undefined,
1856
+ aborted: false,
1857
+ willRetry: false,
1858
+ errorMessage: formattedErrorMessage,
1859
+ });
1860
+ await this._emitSessionCompactFailed({
1861
+ reason,
1862
+ errorMessage: formattedErrorMessage,
1863
+ aborted: false,
1864
+ willRetry: false,
1865
+ fromExtension,
1866
+ });
1867
+ }
1868
+ return false;
1869
+ }
1870
+ finally {
1871
+ this._autoCompactionAbortController = undefined;
1872
+ }
1873
+ }
1874
+ /**
1875
+ * Toggle auto-compaction setting.
1876
+ */
1877
+ setAutoCompactionEnabled(enabled) {
1878
+ this.settingsManager.setCompactionEnabled(enabled);
1879
+ }
1880
+ /** Whether auto-compaction is enabled */
1881
+ get autoCompactionEnabled() {
1882
+ return this.settingsManager.getCompactionEnabled();
1883
+ }
1884
+ async bindExtensions(bindings) {
1885
+ if (bindings.uiContext !== undefined) {
1886
+ this._extensionUIContext = bindings.uiContext;
1887
+ }
1888
+ if (bindings.mode !== undefined) {
1889
+ this._extensionMode = bindings.mode;
1890
+ }
1891
+ if (bindings.commandContextActions !== undefined) {
1892
+ this._extensionCommandContextActions = bindings.commandContextActions;
1893
+ }
1894
+ if (bindings.abortHandler !== undefined) {
1895
+ this._extensionAbortHandler = bindings.abortHandler;
1896
+ }
1897
+ if (bindings.shutdownHandler !== undefined) {
1898
+ this._extensionShutdownHandler = bindings.shutdownHandler;
1899
+ }
1900
+ if (bindings.onError !== undefined) {
1901
+ this._extensionErrorListener = bindings.onError;
1902
+ }
1903
+ this._applyExtensionBindings(this._extensionRunner);
1904
+ await this._extensionRunner.emit(this._sessionStartEvent);
1905
+ await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
1906
+ }
1907
+ async extendResourcesFromExtensions(reason) {
1908
+ if (!this._extensionRunner.hasHandlers("resources_discover")) {
1909
+ return;
1910
+ }
1911
+ const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
1912
+ if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
1913
+ return;
1914
+ }
1915
+ const extensionPaths = {
1916
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
1917
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
1918
+ themePaths: this.buildExtensionResourcePaths(themePaths),
1919
+ };
1920
+ this._resourceLoader.extendResources(extensionPaths);
1921
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
1922
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
1923
+ }
1924
+ buildExtensionResourcePaths(entries) {
1925
+ return entries.map((entry) => {
1926
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
1927
+ const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
1928
+ return {
1929
+ path: entry.path,
1930
+ metadata: {
1931
+ source,
1932
+ scope: "temporary",
1933
+ origin: "top-level",
1934
+ baseDir,
1935
+ },
1936
+ };
1937
+ });
1938
+ }
1939
+ getExtensionSourceLabel(extensionPath) {
1940
+ if (extensionPath.startsWith("<")) {
1941
+ return `extension:${extensionPath.replace(/[<>]/g, "")}`;
1942
+ }
1943
+ const base = basename(extensionPath);
1944
+ const name = base.replace(/\.(ts|js)$/, "");
1945
+ return `extension:${name}`;
1946
+ }
1947
+ _applyExtensionBindings(runner) {
1948
+ runner.setUIContext(this._extensionUIContext, this._extensionMode);
1949
+ runner.bindCommandContext(this._extensionCommandContextActions);
1950
+ this._extensionErrorUnsubscriber?.();
1951
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
1952
+ ? runner.onError(this._extensionErrorListener)
1953
+ : undefined;
1954
+ }
1955
+ _refreshCurrentModelFromRegistry() {
1956
+ const currentModel = this.model;
1957
+ if (!currentModel) {
1958
+ return;
1959
+ }
1960
+ const refreshedModel = this._modelRuntime.getModel(currentModel.provider, currentModel.id);
1961
+ if (!refreshedModel || refreshedModel === currentModel) {
1962
+ return;
1963
+ }
1964
+ this.agent.state.model = refreshedModel;
1965
+ }
1966
+ _bindExtensionCore(runner) {
1967
+ const getCommands = () => {
1968
+ const extensionCommands = runner.getRegisteredCommands().map((command) => ({
1969
+ name: command.invocationName,
1970
+ description: command.description,
1971
+ source: "extension",
1972
+ sourceInfo: command.sourceInfo,
1973
+ }));
1974
+ const templates = this.promptTemplates.map((template) => ({
1975
+ name: template.name,
1976
+ description: template.description,
1977
+ source: "prompt",
1978
+ sourceInfo: template.sourceInfo,
1979
+ }));
1980
+ const skills = this._resourceLoader.getSkills().skills.map((skill) => ({
1981
+ name: `skill:${skill.name}`,
1982
+ description: skill.description,
1983
+ source: "skill",
1984
+ sourceInfo: skill.sourceInfo,
1985
+ }));
1986
+ return [...extensionCommands, ...templates, ...skills];
1987
+ };
1988
+ runner.bindCore({
1989
+ sendMessage: (message, options) => {
1990
+ this.sendCustomMessage(message, options).catch((err) => {
1991
+ runner.emitError({
1992
+ extensionPath: "<runtime>",
1993
+ event: "send_message",
1994
+ error: err instanceof Error ? err.message : String(err),
1995
+ });
1996
+ });
1997
+ },
1998
+ sendUserMessage: (content, options) => {
1999
+ this.sendUserMessage(content, options).catch((err) => {
2000
+ runner.emitError({
2001
+ extensionPath: "<runtime>",
2002
+ event: "send_user_message",
2003
+ error: err instanceof Error ? err.message : String(err),
2004
+ });
2005
+ });
2006
+ },
2007
+ appendEntry: (customType, data) => {
2008
+ const entryId = this.sessionManager.appendCustomEntry(customType, data);
2009
+ const entry = this.sessionManager.getEntry(entryId);
2010
+ if (entry) {
2011
+ this._emit({ type: "entry_appended", entry });
2012
+ }
2013
+ },
2014
+ setSessionName: (name) => {
2015
+ this.setSessionName(name);
2016
+ },
2017
+ getSessionName: () => {
2018
+ return this.sessionManager.getSessionName();
2019
+ },
2020
+ setLabel: (entryId, label) => {
2021
+ this.sessionManager.appendLabelChange(entryId, label);
2022
+ },
2023
+ getActiveTools: () => this.getActiveToolNames(),
2024
+ getAllTools: () => this.getAllTools(),
2025
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
2026
+ refreshTools: () => this._refreshToolRegistry(),
2027
+ getCommands,
2028
+ setModel: async (model) => {
2029
+ if (!this._modelRuntime.hasConfiguredAuth(model.provider))
2030
+ return false;
2031
+ await this.setModel(model);
2032
+ return true;
2033
+ },
2034
+ getThinkingLevel: () => this.thinkingLevel,
2035
+ setThinkingLevel: (level) => this.setThinkingLevel(level),
2036
+ }, {
2037
+ getModel: () => this.model,
2038
+ getScopedModels: () => this._scopedModels,
2039
+ isIdle: () => this.isIdle,
2040
+ isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
2041
+ getSignal: () => this.agent.signal,
2042
+ abort: () => {
2043
+ if (this._extensionAbortHandler) {
2044
+ this._extensionAbortHandler();
2045
+ return;
2046
+ }
2047
+ void this.abort();
2048
+ },
2049
+ hasPendingMessages: () => this.pendingMessageCount > 0,
2050
+ shutdown: () => {
2051
+ this._extensionShutdownHandler?.();
2052
+ },
2053
+ getContextUsage: () => this.getContextUsage(),
2054
+ compact: (options) => {
2055
+ void (async () => {
2056
+ try {
2057
+ const result = await this.compact(options?.customInstructions);
2058
+ options?.onComplete?.(result);
2059
+ }
2060
+ catch (error) {
2061
+ const err = error instanceof Error ? error : new Error(String(error));
2062
+ options?.onError?.(err);
2063
+ }
2064
+ })();
2065
+ },
2066
+ getSystemPrompt: () => this.systemPrompt,
2067
+ getSystemPromptOptions: () => this._baseSystemPromptOptions,
2068
+ }, {
2069
+ registerProvider: (name, config) => {
2070
+ this._modelRuntime.registerProvider(name, config);
2071
+ this._refreshCurrentModelFromRegistry();
2072
+ },
2073
+ registerNativeProvider: (provider) => {
2074
+ this._modelRuntime.registerNativeProvider(provider);
2075
+ this._refreshCurrentModelFromRegistry();
2076
+ },
2077
+ unregisterProvider: (name) => {
2078
+ this._modelRuntime.unregisterProvider(name);
2079
+ this._refreshCurrentModelFromRegistry();
2080
+ },
2081
+ });
2082
+ }
2083
+ _refreshToolRegistry(options) {
2084
+ const previousRegistryNames = new Set(this._toolRegistry.keys());
2085
+ const previousActiveToolNames = this.getActiveToolNames();
2086
+ const allowedToolNames = this._allowedToolNames;
2087
+ const excludedToolNames = this._excludedToolNames;
2088
+ const isAllowedTool = (name) => (!allowedToolNames || allowedToolNames.has(name)) && !excludedToolNames?.has(name);
2089
+ const registeredTools = this._extensionRunner.getAllRegisteredTools();
2090
+ const allCustomTools = [
2091
+ ...registeredTools,
2092
+ ...this._customTools.map((definition) => ({
2093
+ definition,
2094
+ sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
2095
+ })),
2096
+ ].filter((tool) => isAllowedTool(tool.definition.name));
2097
+ const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
2098
+ .filter(([name]) => isAllowedTool(name))
2099
+ .map(([name, definition]) => [
2100
+ name,
2101
+ {
2102
+ definition,
2103
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
2104
+ },
2105
+ ]));
2106
+ for (const tool of allCustomTools) {
2107
+ definitionRegistry.set(tool.definition.name, {
2108
+ definition: tool.definition,
2109
+ sourceInfo: tool.sourceInfo,
2110
+ });
2111
+ }
2112
+ this._toolDefinitions = definitionRegistry;
2113
+ this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
2114
+ .map(({ definition }) => {
2115
+ const snippet = this._normalizePromptSnippet(definition.promptSnippet);
2116
+ return snippet ? [definition.name, snippet] : undefined;
2117
+ })
2118
+ .filter((entry) => entry !== undefined));
2119
+ this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
2120
+ .map(({ definition }) => {
2121
+ const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
2122
+ return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
2123
+ })
2124
+ .filter((entry) => entry !== undefined));
2125
+ const runner = this._extensionRunner;
2126
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
2127
+ const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
2128
+ .filter((definition) => isAllowedTool(definition.name))
2129
+ .map((definition) => ({
2130
+ definition,
2131
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
2132
+ })), runner);
2133
+ const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
2134
+ for (const tool of wrappedExtensionTools) {
2135
+ toolRegistry.set(tool.name, tool);
2136
+ }
2137
+ this._toolRegistry = toolRegistry;
2138
+ const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
2139
+ if (allowedToolNames) {
2140
+ for (const toolName of this._toolRegistry.keys()) {
2141
+ if (allowedToolNames.has(toolName)) {
2142
+ nextActiveToolNames.push(toolName);
2143
+ }
2144
+ }
2145
+ }
2146
+ else if (options?.includeAllExtensionTools) {
2147
+ for (const tool of wrappedExtensionTools) {
2148
+ nextActiveToolNames.push(tool.name);
2149
+ }
2150
+ }
2151
+ else if (!options?.activeToolNames) {
2152
+ for (const toolName of this._toolRegistry.keys()) {
2153
+ if (!previousRegistryNames.has(toolName)) {
2154
+ nextActiveToolNames.push(toolName);
2155
+ }
2156
+ }
2157
+ }
2158
+ this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
2159
+ }
2160
+ _buildRuntime(options) {
2161
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
2162
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
2163
+ const shellPath = this.settingsManager.getShellPath();
2164
+ const baseToolDefinitions = this._baseToolsOverride
2165
+ ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
2166
+ name,
2167
+ createToolDefinitionFromAgentTool(tool),
2168
+ ]))
2169
+ : createAllToolDefinitions(this._cwd, {
2170
+ read: { autoResizeImages },
2171
+ bash: { commandPrefix: shellCommandPrefix, shellPath },
2172
+ });
2173
+ this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
2174
+ const extensionsResult = this._resourceLoader.getExtensions();
2175
+ if (options.flagValues) {
2176
+ for (const [name, value] of options.flagValues) {
2177
+ extensionsResult.runtime.flagValues.set(name, value);
2178
+ }
2179
+ }
2180
+ this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, new ModelRegistry(this._modelRuntime));
2181
+ if (this._extensionRunnerRef) {
2182
+ this._extensionRunnerRef.current = this._extensionRunner;
2183
+ }
2184
+ this._bindExtensionCore(this._extensionRunner);
2185
+ this._applyExtensionBindings(this._extensionRunner);
2186
+ const defaultActiveToolNames = this._baseToolsOverride
2187
+ ? Object.keys(this._baseToolsOverride)
2188
+ : ["read", "bash", "edit", "write"];
2189
+ const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
2190
+ this._refreshToolRegistry({
2191
+ activeToolNames: baseActiveToolNames,
2192
+ includeAllExtensionTools: options.includeAllExtensionTools,
2193
+ });
2194
+ }
2195
+ async reload(options) {
2196
+ const oldRunner = this._extensionRunner;
2197
+ const previousFlagValues = oldRunner.getFlagValues();
2198
+ await emitSessionShutdownEvent(oldRunner, { type: "session_shutdown", reason: "reload" });
2199
+ oldRunner.invalidate();
2200
+ await this.settingsManager.reload();
2201
+ this.syncQueueModesFromSettings();
2202
+ resetApiProviders();
2203
+ await this._resourceLoader.reload();
2204
+ this._buildRuntime({
2205
+ activeToolNames: this.getActiveToolNames(),
2206
+ flagValues: previousFlagValues,
2207
+ includeAllExtensionTools: true,
2208
+ });
2209
+ const hasBindings = this._extensionUIContext ||
2210
+ this._extensionCommandContextActions ||
2211
+ this._extensionShutdownHandler ||
2212
+ this._extensionErrorListener;
2213
+ if (hasBindings) {
2214
+ await options?.beforeSessionStart?.();
2215
+ await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
2216
+ await this.extendResourcesFromExtensions("reload");
2217
+ }
2218
+ }
2219
+ // =========================================================================
2220
+ // Auto-Retry
2221
+ // =========================================================================
2222
+ /**
2223
+ * Check if an error is retryable (overloaded, rate limit, server errors).
2224
+ * Context overflow errors are NOT retryable (handled by compaction instead).
2225
+ */
2226
+ _isRetryableError(message) {
2227
+ // Context overflow is handled by compaction, not retry.
2228
+ if (isContextOverflow(message, this.model?.contextWindow ?? 0))
2229
+ return false;
2230
+ return isRetryableAssistantError(message);
2231
+ }
2232
+ /**
2233
+ * Retry policy + callbacks shared by compaction and branch-summary summarization calls.
2234
+ * Uses the same `settings.retry` budget/backoff as agent-turn retries so a single transient
2235
+ * stream drop no longer fails the whole operation. `source` carries the context
2236
+ * the TUI needs to render the retry and recreate the underlying indicator.
2237
+ */
2238
+ _summarizationRetryCallbacks(source) {
2239
+ return {
2240
+ onRetryScheduled: (attempt, maxAttempts, delayMs, errorMessage) => {
2241
+ this._emit({
2242
+ type: "summarization_retry_scheduled",
2243
+ attempt,
2244
+ maxAttempts,
2245
+ delayMs,
2246
+ errorMessage,
2247
+ });
2248
+ },
2249
+ onRetryAttemptStart: () => {
2250
+ this._emit({
2251
+ type: "summarization_retry_attempt_start",
2252
+ ...source,
2253
+ });
2254
+ },
2255
+ onRetryFinished: () => {
2256
+ this._emit({ type: "summarization_retry_finished" });
2257
+ },
2258
+ };
2259
+ }
2260
+ /**
2261
+ * Prepare a retryable error for continuation with exponential backoff.
2262
+ * @returns true if the caller should continue the agent, false otherwise
2263
+ */
2264
+ async _prepareRetry(message) {
2265
+ const settings = this.settingsManager.getRetrySettings();
2266
+ if (!settings.enabled) {
2267
+ return false;
2268
+ }
2269
+ this._retryAttempt++;
2270
+ if (this._retryAttempt > settings.maxRetries) {
2271
+ // Preserve the completed attempt count so post-run handling can emit the final failure.
2272
+ this._retryAttempt--;
2273
+ return false;
2274
+ }
2275
+ const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
2276
+ this._emit({
2277
+ type: "auto_retry_start",
2278
+ attempt: this._retryAttempt,
2279
+ maxAttempts: settings.maxRetries,
2280
+ delayMs,
2281
+ errorMessage: message.errorMessage || "Unknown error",
2282
+ });
2283
+ // Remove error message from agent state (keep in session for history)
2284
+ const messages = this.agent.state.messages;
2285
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2286
+ this.agent.state.messages = messages.slice(0, -1);
2287
+ }
2288
+ // Wait with exponential backoff (abortable)
2289
+ this._retryAbortController = new AbortController();
2290
+ try {
2291
+ await sleep(delayMs, this._retryAbortController.signal);
2292
+ }
2293
+ catch {
2294
+ // Aborted during sleep - emit end event so UI can clean up
2295
+ const attempt = this._retryAttempt;
2296
+ this._retryAttempt = 0;
2297
+ this._emit({
2298
+ type: "auto_retry_end",
2299
+ success: false,
2300
+ attempt,
2301
+ finalError: "Retry cancelled",
2302
+ });
2303
+ return false;
2304
+ }
2305
+ finally {
2306
+ this._retryAbortController = undefined;
2307
+ }
2308
+ return true;
2309
+ }
2310
+ /**
2311
+ * Cancel in-progress retry.
2312
+ */
2313
+ abortRetry() {
2314
+ this._retryAbortController?.abort();
2315
+ }
2316
+ /** Whether auto-retry is currently in progress */
2317
+ get isRetrying() {
2318
+ return this._retryAbortController !== undefined;
2319
+ }
2320
+ /** Whether auto-retry is enabled */
2321
+ get autoRetryEnabled() {
2322
+ return this.settingsManager.getRetryEnabled();
2323
+ }
2324
+ /**
2325
+ * Toggle auto-retry setting.
2326
+ */
2327
+ setAutoRetryEnabled(enabled) {
2328
+ this.settingsManager.setRetryEnabled(enabled);
2329
+ }
2330
+ // =========================================================================
2331
+ // Bash Execution
2332
+ // =========================================================================
2333
+ /**
2334
+ * Execute a bash command.
2335
+ * Adds result to agent context and session.
2336
+ * @param command The bash command to execute
2337
+ * @param onChunk Optional streaming callback for output
2338
+ * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
2339
+ * @param options.id Optional identifier included in bash execution update events
2340
+ * @param options.operations Custom BashOperations for remote execution
2341
+ */
2342
+ async executeBash(command, onChunk, options) {
2343
+ const abortController = new AbortController();
2344
+ this._bashAbortControllers.add(abortController);
2345
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2346
+ const prefix = this.settingsManager.getShellCommandPrefix();
2347
+ const shellPath = this.settingsManager.getShellPath();
2348
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2349
+ try {
2350
+ const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
2351
+ onChunk: (delta) => {
2352
+ onChunk?.(delta);
2353
+ this._emit({ type: "bash_execution_update", id: options?.id, delta });
2354
+ },
2355
+ signal: abortController.signal,
2356
+ });
2357
+ this.recordBashResult(command, result, options);
2358
+ return result;
2359
+ }
2360
+ finally {
2361
+ this._bashAbortControllers.delete(abortController);
2362
+ }
2363
+ }
2364
+ /**
2365
+ * Record a bash execution result in session history.
2366
+ * Used by executeBash and by extensions that handle bash execution themselves.
2367
+ */
2368
+ recordBashResult(command, result, options) {
2369
+ const bashMessage = {
2370
+ role: "bashExecution",
2371
+ command,
2372
+ output: result.output,
2373
+ exitCode: result.exitCode,
2374
+ cancelled: result.cancelled,
2375
+ truncated: result.truncated,
2376
+ fullOutputPath: result.fullOutputPath,
2377
+ timestamp: Date.now(),
2378
+ excludeFromContext: options?.excludeFromContext,
2379
+ };
2380
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
2381
+ if (this.isStreaming) {
2382
+ // Queue for later - will be flushed on agent_end
2383
+ this._pendingBashMessages.push(bashMessage);
2384
+ }
2385
+ else {
2386
+ // Add to agent state immediately
2387
+ this.agent.state.messages.push(bashMessage);
2388
+ // Save to session
2389
+ this.sessionManager.appendMessage(bashMessage);
2390
+ }
2391
+ }
2392
+ /**
2393
+ * Cancel running bash command.
2394
+ */
2395
+ abortBash() {
2396
+ for (const abortController of [...this._bashAbortControllers]) {
2397
+ abortController.abort();
2398
+ }
2399
+ }
2400
+ /** Whether a bash command is currently running */
2401
+ get isBashRunning() {
2402
+ return this._bashAbortControllers.size > 0;
2403
+ }
2404
+ /** Whether there are pending bash messages waiting to be flushed */
2405
+ get hasPendingBashMessages() {
2406
+ return this._pendingBashMessages.length > 0;
2407
+ }
2408
+ /**
2409
+ * Flush pending bash messages to agent state and session.
2410
+ * Called after agent turn completes to maintain proper message ordering.
2411
+ */
2412
+ _flushPendingBashMessages() {
2413
+ if (this._pendingBashMessages.length === 0)
2414
+ return;
2415
+ for (const bashMessage of this._pendingBashMessages) {
2416
+ // Add to agent state
2417
+ this.agent.state.messages.push(bashMessage);
2418
+ // Save to session
2419
+ this.sessionManager.appendMessage(bashMessage);
2420
+ }
2421
+ this._pendingBashMessages = [];
2422
+ }
2423
+ // =========================================================================
2424
+ // Session Management
2425
+ // =========================================================================
2426
+ /**
2427
+ * Set a display name for the current session.
2428
+ */
2429
+ setSessionName(name) {
2430
+ this.sessionManager.appendSessionInfo(name);
2431
+ const event = { type: "session_info_changed", name: this.sessionManager.getSessionName() };
2432
+ this._emit(event);
2433
+ void this._extensionRunner.emit(event);
2434
+ }
2435
+ // =========================================================================
2436
+ // Tree Navigation
2437
+ // =========================================================================
2438
+ /**
2439
+ * Navigate to a different node in the session tree.
2440
+ * Unlike fork() which creates a new session file, this stays in the same file.
2441
+ *
2442
+ * @param targetId The entry ID to navigate to
2443
+ * @param options.summarize Whether user wants to summarize abandoned branch
2444
+ * @param options.customInstructions Custom instructions for summarizer
2445
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
2446
+ * @param options.label Label to attach to the branch summary entry
2447
+ * @returns Result with editorText (if user message) and cancelled status
2448
+ */
2449
+ async navigateTree(targetId, options = {}) {
2450
+ if (this.isStreaming) {
2451
+ throw new Error("Wait for the current response to finish before navigating the session tree.");
2452
+ }
2453
+ const oldLeafId = this.sessionManager.getLeafId();
2454
+ // No-op if already at target
2455
+ if (targetId === oldLeafId) {
2456
+ return { cancelled: false };
2457
+ }
2458
+ // Model required for summarization
2459
+ if (options.summarize && !this.model) {
2460
+ throw new Error("No model available for summarization");
2461
+ }
2462
+ const targetEntry = this.sessionManager.getEntry(targetId);
2463
+ if (!targetEntry) {
2464
+ throw new Error(`Entry ${targetId} not found`);
2465
+ }
2466
+ // Collect entries to summarize (from old leaf to common ancestor)
2467
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
2468
+ // Prepare event data - mutable so extensions can override
2469
+ let customInstructions = options.customInstructions;
2470
+ let replaceInstructions = options.replaceInstructions;
2471
+ let label = options.label;
2472
+ const preparation = {
2473
+ targetId,
2474
+ oldLeafId,
2475
+ commonAncestorId,
2476
+ entriesToSummarize,
2477
+ userWantsSummary: options.summarize ?? false,
2478
+ customInstructions,
2479
+ replaceInstructions,
2480
+ label,
2481
+ };
2482
+ // Set up abort controller for summarization
2483
+ this._branchSummaryAbortController = new AbortController();
2484
+ try {
2485
+ let extensionSummary;
2486
+ let fromExtension = false;
2487
+ // Emit session_before_tree event
2488
+ if (this._extensionRunner.hasHandlers("session_before_tree")) {
2489
+ const result = (await this._extensionRunner.emit({
2490
+ type: "session_before_tree",
2491
+ preparation,
2492
+ signal: this._branchSummaryAbortController.signal,
2493
+ }));
2494
+ if (result?.cancel) {
2495
+ return { cancelled: true };
2496
+ }
2497
+ if (result?.summary && options.summarize) {
2498
+ extensionSummary = result.summary;
2499
+ fromExtension = true;
2500
+ }
2501
+ // Allow extensions to override instructions and label
2502
+ if (result?.customInstructions !== undefined) {
2503
+ customInstructions = result.customInstructions;
2504
+ }
2505
+ if (result?.replaceInstructions !== undefined) {
2506
+ replaceInstructions = result.replaceInstructions;
2507
+ }
2508
+ if (result?.label !== undefined) {
2509
+ label = result.label;
2510
+ }
2511
+ }
2512
+ // Run default summarizer if needed
2513
+ let summaryText;
2514
+ let summaryDetails;
2515
+ let summaryUsage;
2516
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2517
+ const model = this.model;
2518
+ const { model: requestModel, apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
2519
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2520
+ const result = await generateBranchSummary(entriesToSummarize, {
2521
+ model: requestModel,
2522
+ apiKey,
2523
+ headers,
2524
+ env,
2525
+ signal: this._branchSummaryAbortController.signal,
2526
+ customInstructions,
2527
+ replaceInstructions,
2528
+ reserveTokens: branchSummarySettings.reserveTokens,
2529
+ streamFn: this.agent.streamFunction,
2530
+ retry: this.settingsManager.getRetrySettings(),
2531
+ callbacks: this._summarizationRetryCallbacks({ source: "branchSummary" }),
2532
+ });
2533
+ if (result.aborted) {
2534
+ return { cancelled: true, aborted: true };
2535
+ }
2536
+ if (result.error) {
2537
+ throw new Error(result.error);
2538
+ }
2539
+ summaryText = result.summary;
2540
+ summaryUsage = result.usage;
2541
+ summaryDetails = {
2542
+ readFiles: result.readFiles || [],
2543
+ modifiedFiles: result.modifiedFiles || [],
2544
+ };
2545
+ }
2546
+ else if (extensionSummary) {
2547
+ summaryText = extensionSummary.summary;
2548
+ summaryDetails = extensionSummary.details;
2549
+ summaryUsage = extensionSummary.usage;
2550
+ }
2551
+ // Determine the new leaf position based on target type
2552
+ let newLeafId;
2553
+ let editorText;
2554
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2555
+ // User message: leaf = parent (null if root), text goes to editor
2556
+ newLeafId = targetEntry.parentId;
2557
+ editorText = contentText(targetEntry.message.content, "");
2558
+ }
2559
+ else if (targetEntry.type === "custom_message") {
2560
+ // Custom message: leaf = parent (null if root), text goes to editor
2561
+ newLeafId = targetEntry.parentId;
2562
+ editorText = contentText(targetEntry.content, "");
2563
+ }
2564
+ else {
2565
+ // Non-user message: leaf = selected node
2566
+ newLeafId = targetId;
2567
+ }
2568
+ // Switch leaf (with or without summary)
2569
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
2570
+ let summaryEntry;
2571
+ if (summaryText) {
2572
+ // Create summary at target position (can be null for root)
2573
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension, summaryUsage);
2574
+ summaryEntry = this.sessionManager.getEntry(summaryId);
2575
+ // Attach label to the summary entry
2576
+ if (label) {
2577
+ this.sessionManager.appendLabelChange(summaryId, label);
2578
+ }
2579
+ }
2580
+ else if (newLeafId === null) {
2581
+ // No summary, navigating to root - reset leaf
2582
+ this.sessionManager.resetLeaf();
2583
+ }
2584
+ else {
2585
+ // No summary, navigating to non-root
2586
+ this.sessionManager.branch(newLeafId);
2587
+ }
2588
+ // Attach label to target entry when not summarizing (no summary entry to label)
2589
+ if (label && !summaryText) {
2590
+ this.sessionManager.appendLabelChange(targetId, label);
2591
+ }
2592
+ // Update agent state
2593
+ const sessionContext = this.sessionManager.buildSessionContext();
2594
+ this.agent.state.messages = sessionContext.messages;
2595
+ // Emit session_tree event
2596
+ await this._extensionRunner.emit({
2597
+ type: "session_tree",
2598
+ newLeafId: this.sessionManager.getLeafId(),
2599
+ oldLeafId,
2600
+ summaryEntry,
2601
+ fromExtension: summaryText ? fromExtension : undefined,
2602
+ });
2603
+ // Emit to custom tools
2604
+ return { editorText, cancelled: false, summaryEntry };
2605
+ }
2606
+ finally {
2607
+ this._branchSummaryAbortController = undefined;
2608
+ }
2609
+ }
2610
+ /**
2611
+ * Get all user messages from session for fork selector.
2612
+ */
2613
+ getUserMessagesForForking() {
2614
+ const entries = this.sessionManager.getEntries();
2615
+ const result = [];
2616
+ for (const entry of entries) {
2617
+ if (entry.type !== "message")
2618
+ continue;
2619
+ if (entry.message.role !== "user")
2620
+ continue;
2621
+ const text = contentText(entry.message.content, "");
2622
+ if (text) {
2623
+ result.push({ entryId: entry.id, text });
2624
+ }
2625
+ }
2626
+ return result;
2627
+ }
2628
+ /**
2629
+ * Get session statistics. Aggregates over ALL session entries (including
2630
+ * history that was compacted away), so token/cost totals reflect what was
2631
+ * actually billed across the session.
2632
+ */
2633
+ getSessionStats() {
2634
+ let userMessages = 0;
2635
+ let assistantMessages = 0;
2636
+ let toolResults = 0;
2637
+ let totalMessages = 0;
2638
+ let toolCalls = 0;
2639
+ const usageTotals = createUsageTotals();
2640
+ for (const entry of this.sessionManager.getEntries()) {
2641
+ if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
2642
+ addUsageToTotals(usageTotals, entry.usage);
2643
+ }
2644
+ if (entry.type !== "message")
2645
+ continue;
2646
+ totalMessages++;
2647
+ const message = entry.message;
2648
+ if (message.role === "user") {
2649
+ userMessages++;
2650
+ }
2651
+ else if (message.role === "toolResult") {
2652
+ toolResults++;
2653
+ if (message.usage) {
2654
+ addUsageToTotals(usageTotals, message.usage);
2655
+ }
2656
+ }
2657
+ else if (message.role === "assistant") {
2658
+ assistantMessages++;
2659
+ const assistantMsg = message;
2660
+ if (Array.isArray(assistantMsg.content)) {
2661
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
2662
+ }
2663
+ addUsageToTotals(usageTotals, assistantMsg.usage);
2664
+ }
2665
+ }
2666
+ return {
2667
+ sessionFile: this.sessionFile,
2668
+ sessionId: this.sessionId,
2669
+ userMessages,
2670
+ assistantMessages,
2671
+ toolCalls,
2672
+ toolResults,
2673
+ totalMessages,
2674
+ tokens: {
2675
+ input: usageTotals.input,
2676
+ output: usageTotals.output,
2677
+ cacheRead: usageTotals.cacheRead,
2678
+ cacheWrite: usageTotals.cacheWrite,
2679
+ total: usageTotals.input + usageTotals.output + usageTotals.cacheRead + usageTotals.cacheWrite,
2680
+ },
2681
+ cost: usageTotals.cost,
2682
+ contextUsage: this.getContextUsage(),
2683
+ };
2684
+ }
2685
+ getContextUsage() {
2686
+ const model = this.model;
2687
+ if (!model)
2688
+ return undefined;
2689
+ const contextWindow = model.contextWindow ?? 0;
2690
+ if (contextWindow <= 0)
2691
+ return undefined;
2692
+ // After compaction, the last assistant usage reflects pre-compaction context size.
2693
+ // We can only trust usage from an assistant that responded after the latest compaction.
2694
+ // If no such assistant exists, context token count is unknown until the next LLM response.
2695
+ const branchEntries = this.sessionManager.getBranch();
2696
+ const latestCompaction = getLatestCompactionEntry(branchEntries);
2697
+ if (latestCompaction) {
2698
+ // Check if there's a valid assistant usage after the compaction boundary
2699
+ const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
2700
+ let hasPostCompactionUsage = false;
2701
+ for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
2702
+ const entry = branchEntries[i];
2703
+ if (entry.type === "message" && entry.message.role === "assistant") {
2704
+ const assistant = entry.message;
2705
+ if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
2706
+ const contextTokens = calculateContextTokens(assistant.usage);
2707
+ if (contextTokens > 0) {
2708
+ hasPostCompactionUsage = true;
2709
+ break;
2710
+ }
2711
+ }
2712
+ }
2713
+ }
2714
+ if (!hasPostCompactionUsage) {
2715
+ return { tokens: null, contextWindow, percent: null };
2716
+ }
2717
+ }
2718
+ const estimate = estimateContextTokens(this.messages);
2719
+ const percent = (estimate.tokens / contextWindow) * 100;
2720
+ return {
2721
+ tokens: estimate.tokens,
2722
+ contextWindow,
2723
+ percent,
2724
+ };
2725
+ }
2726
+ /**
2727
+ * Export session to HTML.
2728
+ * @param outputPath Optional output path (defaults to session directory)
2729
+ * @param options Optional export presentation settings
2730
+ * @returns Path to exported file
2731
+ */
2732
+ async exportToHtml(outputPath, options = {}) {
2733
+ const themeName = [options.themeName, this.settingsManager.getTheme()].find((candidate) => candidate !== undefined && getThemeByName(candidate) !== undefined);
2734
+ // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
2735
+ const toolRenderer = createToolHtmlRenderer({
2736
+ getToolDefinition: (name) => this.getToolDefinition(name),
2737
+ theme,
2738
+ cwd: this.sessionManager.getCwd(),
2739
+ });
2740
+ return await exportSessionToHtml(this.sessionManager, this.state, {
2741
+ outputPath,
2742
+ themeName,
2743
+ toolRenderer,
2744
+ });
2745
+ }
2746
+ /**
2747
+ * Export the current session branch to a JSONL file.
2748
+ * Writes the session header followed by all entries on the current branch path.
2749
+ * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
2750
+ * @returns The resolved output file path.
2751
+ */
2752
+ exportToJsonl(outputPath) {
2753
+ return exportSessionToJsonl(this.sessionManager, outputPath);
2754
+ }
2755
+ // =========================================================================
2756
+ // Utilities
2757
+ // =========================================================================
2758
+ /**
2759
+ * Get text content of last assistant message.
2760
+ * Useful for /copy command.
2761
+ * @returns Text content, or undefined if no assistant message exists
2762
+ */
2763
+ getLastAssistantText() {
2764
+ const lastAssistant = this.messages
2765
+ .slice()
2766
+ .reverse()
2767
+ .find((m) => {
2768
+ if (m.role !== "assistant")
2769
+ return false;
2770
+ const msg = m;
2771
+ // Skip aborted messages with no content
2772
+ if (msg.stopReason === "aborted" && msg.content.length === 0)
2773
+ return false;
2774
+ return true;
2775
+ });
2776
+ if (!lastAssistant)
2777
+ return undefined;
2778
+ let text = "";
2779
+ for (const content of lastAssistant.content) {
2780
+ if (content.type === "text") {
2781
+ text += content.text;
2782
+ }
2783
+ }
2784
+ return text.trim() || undefined;
2785
+ }
2786
+ // =========================================================================
2787
+ // Extension System
2788
+ // =========================================================================
2789
+ createReplacedSessionContext() {
2790
+ const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
2791
+ context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
2792
+ context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
2793
+ return context;
2794
+ }
2795
+ /**
2796
+ * Check if extensions have handlers for a specific event type.
2797
+ */
2798
+ hasExtensionHandlers(eventType) {
2799
+ return this._extensionRunner.hasHandlers(eventType);
2800
+ }
2801
+ /**
2802
+ * Get the extension runner (for setting UI context and error handlers).
2803
+ */
2804
+ get extensionRunner() {
2805
+ return this._extensionRunner;
2806
+ }
2807
+ }
2808
+ //# sourceMappingURL=agent-session.js.map