zidane 9.1.1 → 9.1.4

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 (279) hide show
  1. package/dist/{acp-Di9WvMDF.js → acp-Cl4gCZN6.js} +7 -7
  2. package/dist/{acp-Di9WvMDF.js.map → acp-Cl4gCZN6.js.map} +1 -1
  3. package/dist/acp-cli.js +5 -5
  4. package/dist/acp.d.ts +2 -2
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-DJhpTS-B.js → agent-Dh_XZ7fj.js} +74 -19
  7. package/dist/agent-Dh_XZ7fj.js.map +1 -0
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{auth-store-port-DFgf22oo.js → auth-store-port-DBl2JUC6.js} +2 -2
  11. package/dist/{auth-store-port-DFgf22oo.js.map → auth-store-port-DBl2JUC6.js.map} +1 -1
  12. package/dist/{auto-update-restart-BFB7Ek87.js → auto-update-restart-CF_kjcJd.js} +277 -41
  13. package/dist/auto-update-restart-CF_kjcJd.js.map +1 -0
  14. package/dist/{browser-BcoCCB_n.js → browser-BkdeKnxO.js} +56 -2
  15. package/dist/browser-BkdeKnxO.js.map +1 -0
  16. package/dist/{browser-entry-ypi8CyE-.d.ts → browser-entry-BCwruqNa.d.ts} +10 -10
  17. package/dist/{browser-entry-ypi8CyE-.d.ts.map → browser-entry-BCwruqNa.d.ts.map} +1 -1
  18. package/dist/channels.d.ts +5 -5
  19. package/dist/chat/browser.d.ts +4 -4
  20. package/dist/chat/browser.js +6 -6
  21. package/dist/chat/pure.d.ts +5 -5
  22. package/dist/chat/pure.js +8 -8
  23. package/dist/chat.d.ts +5 -5
  24. package/dist/chat.js +55 -55
  25. package/dist/chat.js.map +1 -1
  26. package/dist/{cli-shared-CabruH8Z.js → cli-shared-DIV9c5Nr.js} +4 -4
  27. package/dist/{cli-shared-CabruH8Z.js.map → cli-shared-DIV9c5Nr.js.map} +1 -1
  28. package/dist/cli-style-DBEm6CyT.js +105 -0
  29. package/dist/cli-style-DBEm6CyT.js.map +1 -0
  30. package/dist/{client-core-CIixwznM.d.ts → client-core-C_4m_oL6.d.ts} +4 -4
  31. package/dist/{client-core-CIixwznM.d.ts.map → client-core-C_4m_oL6.d.ts.map} +1 -1
  32. package/dist/{client-CCaIXWue.d.ts → client-ygTASGis.d.ts} +2 -2
  33. package/dist/{client-CCaIXWue.d.ts.map → client-ygTASGis.d.ts.map} +1 -1
  34. package/dist/codemode-worker.js +8 -5
  35. package/dist/codemode-worker.js.map +1 -1
  36. package/dist/codemode.d.ts +16 -0
  37. package/dist/codemode.d.ts.map +1 -1
  38. package/dist/codemode.js +2 -2
  39. package/dist/{connection-loop-QmWL-fJf.d.ts → connection-loop-D_pRONCr.d.ts} +4 -4
  40. package/dist/{connection-loop-QmWL-fJf.d.ts.map → connection-loop-D_pRONCr.d.ts.map} +1 -1
  41. package/dist/contexts/daytona.d.ts +3 -3
  42. package/dist/contexts/docker.d.ts +1 -1
  43. package/dist/contexts/e2b.d.ts +2 -2
  44. package/dist/contexts/sandbox.d.ts +1 -1
  45. package/dist/{contexts-C72b0mMa.js → contexts-DLZTSRHU.js} +17 -106
  46. package/dist/contexts-DLZTSRHU.js.map +1 -0
  47. package/dist/contexts.d.ts +4 -4
  48. package/dist/contexts.js +2 -2
  49. package/dist/{credentials-wwETW8rI.js → credentials-D71duF64.js} +2 -2
  50. package/dist/{credentials-wwETW8rI.js.map → credentials-D71duF64.js.map} +1 -1
  51. package/dist/{cwd-picker-CcekODCt.js → cwd-picker-BsHA6HKv.js} +4 -4
  52. package/dist/{cwd-picker-CcekODCt.js.map → cwd-picker-BsHA6HKv.js.map} +1 -1
  53. package/dist/daemon-cli.js +4 -3
  54. package/dist/daemon-cli.js.map +1 -1
  55. package/dist/{decisions-CXmK0nz9.js → decisions-hsw5XS2g.js} +3 -1
  56. package/dist/decisions-hsw5XS2g.js.map +1 -0
  57. package/dist/{discovery-DycXFxdA.js → discovery-DD4wPWKS.js} +4 -4
  58. package/dist/{discovery-DycXFxdA.js.map → discovery-DD4wPWKS.js.map} +1 -1
  59. package/dist/durable/sqlite.d.ts +2 -2
  60. package/dist/durable.d.ts +1 -1
  61. package/dist/{engine-VQ86XGdG.js → engine-BDmtgr2O.js} +6 -6
  62. package/dist/{engine-VQ86XGdG.js.map → engine-BDmtgr2O.js.map} +1 -1
  63. package/dist/{eval-Bod0I1W_.js → eval-CfGUDAkN.js} +3 -3
  64. package/dist/{eval-Bod0I1W_.js.map → eval-CfGUDAkN.js.map} +1 -1
  65. package/dist/eval.d.ts +1 -1
  66. package/dist/eval.js +1 -1
  67. package/dist/{executor-C7RQrkEq.js → executor-EWOhLyd9.js} +4 -4
  68. package/dist/{executor-C7RQrkEq.js.map → executor-EWOhLyd9.js.map} +1 -1
  69. package/dist/{extension-mark-BqKdEZwF.js → extension-mark-_rhkDWL5.js} +9 -6
  70. package/dist/extension-mark-_rhkDWL5.js.map +1 -0
  71. package/dist/extensions/testing.d.ts +1 -1
  72. package/dist/extensions/testing.js +2 -2
  73. package/dist/{extensions-BCx4QuGB.js → extensions-DklXPjiq.js} +8 -8
  74. package/dist/{extensions-BCx4QuGB.js.map → extensions-DklXPjiq.js.map} +1 -1
  75. package/dist/{extensions-client-D8tEAcMw.d.ts → extensions-client-D4Q2XRKV.d.ts} +31 -5
  76. package/dist/extensions-client-D4Q2XRKV.d.ts.map +1 -0
  77. package/dist/extensions.d.ts +1 -1
  78. package/dist/extensions.js +6 -6
  79. package/dist/{fold-rules-DvLK8pbf.d.ts → fold-rules-1DpDwG9h.d.ts} +2 -2
  80. package/dist/{fold-rules-DvLK8pbf.d.ts.map → fold-rules-1DpDwG9h.d.ts.map} +1 -1
  81. package/dist/{google-Crva32sk.js → google-BtMW9KzL.js} +2 -2
  82. package/dist/{google-Crva32sk.js.map → google-BtMW9KzL.js.map} +1 -1
  83. package/dist/{headless-CCm-jLLT.js → headless-CQm19BL0.js} +4 -4
  84. package/dist/{headless-CCm-jLLT.js.map → headless-CQm19BL0.js.map} +1 -1
  85. package/dist/headless.d.ts +1 -1
  86. package/dist/headless.js +1 -1
  87. package/dist/history-worker.js +1 -1
  88. package/dist/{host-BHMs9jsN.js → host-DEoEzQal.js} +13 -4
  89. package/dist/host-DEoEzQal.js.map +1 -0
  90. package/dist/{host-scoped-settings-CrbcqOkP.js → host-scoped-settings-WBYaCork.js} +2 -2
  91. package/dist/{host-scoped-settings-CrbcqOkP.js.map → host-scoped-settings-WBYaCork.js.map} +1 -1
  92. package/dist/{host-signals-Jsjd_-4g.js → host-signals-91zyko_i.js} +5 -5
  93. package/dist/{host-signals-Jsjd_-4g.js.map → host-signals-91zyko_i.js.map} +1 -1
  94. package/dist/{host-wO_6GW0y.js → host-uP3t08w8.js} +276 -103
  95. package/dist/host-uP3t08w8.js.map +1 -0
  96. package/dist/{host-version-CNAr9pov.js → host-version-_RHlAB29.js} +2 -2
  97. package/dist/{host-version-CNAr9pov.js.map → host-version-_RHlAB29.js.map} +1 -1
  98. package/dist/{index-C6nnKu32.d.ts → index-B0PLo9jn.d.ts} +4 -4
  99. package/dist/{index-C6nnKu32.d.ts.map → index-B0PLo9jn.d.ts.map} +1 -1
  100. package/dist/{index-Djnc8Peh.d.ts → index-De4x-s76.d.ts} +14 -14
  101. package/dist/{index-Djnc8Peh.d.ts.map → index-De4x-s76.d.ts.map} +1 -1
  102. package/dist/{index-CGbOWa7y.d.ts → index-WlE93Q6d.d.ts} +411 -3
  103. package/dist/index-WlE93Q6d.d.ts.map +1 -0
  104. package/dist/{index-CCf_WeTQ.d.ts → index-f-XWIoYo.d.ts} +2 -2
  105. package/dist/{index-CCf_WeTQ.d.ts.map → index-f-XWIoYo.d.ts.map} +1 -1
  106. package/dist/index.d.ts +5 -5
  107. package/dist/index.js +17 -17
  108. package/dist/ipc/browser-types.d.ts +304 -7
  109. package/dist/ipc/browser-types.d.ts.map +1 -1
  110. package/dist/ipc/browser.d.ts +4 -4
  111. package/dist/ipc/browser.js +2 -2
  112. package/dist/ipc/remote.d.ts +6 -6
  113. package/dist/ipc/remote.js +3 -3
  114. package/dist/{ipc-BzWhIybr.js → ipc-CatnsVEd.js} +4 -4
  115. package/dist/{ipc-BzWhIybr.js.map → ipc-CatnsVEd.js.map} +1 -1
  116. package/dist/ipc.d.ts +10 -10
  117. package/dist/ipc.js +8 -8
  118. package/dist/{json-Dj-YATkZ.js → json-BjClr43H.js} +2 -20
  119. package/dist/json-BjClr43H.js.map +1 -0
  120. package/dist/{links-CJG_rFvf.js → links-a8C9eby4.js} +9 -9
  121. package/dist/{links-CJG_rFvf.js.map → links-a8C9eby4.js.map} +1 -1
  122. package/dist/{loaded-entry-DTURJo_R.js → loaded-entry-D6jzt5HQ.js} +2 -2
  123. package/dist/{loaded-entry-DTURJo_R.js.map → loaded-entry-D6jzt5HQ.js.map} +1 -1
  124. package/dist/mcp.d.ts +1 -1
  125. package/dist/{media-type-BtA0cbfI.d.ts → media-type-ZSmAGHvg.d.ts} +188 -7
  126. package/dist/media-type-ZSmAGHvg.d.ts.map +1 -0
  127. package/dist/{memory-DuVGrzbl.js → memory-CJy52DNi.js} +132 -31
  128. package/dist/memory-CJy52DNi.js.map +1 -0
  129. package/dist/model-test-CAtJ76kM.js.map +1 -1
  130. package/dist/{move-session-kylExJ5H.js → move-session-D7ILECs-.js} +4 -4
  131. package/dist/{move-session-kylExJ5H.js.map → move-session-D7ILECs-.js.map} +1 -1
  132. package/dist/{nested-call-record-DlzPeTB7.js → nested-call-record-OayszZBQ.js} +4 -3
  133. package/dist/nested-call-record-OayszZBQ.js.map +1 -0
  134. package/dist/output/stream-json.d.ts +1 -1
  135. package/dist/output/terminal.d.ts +1 -1
  136. package/dist/{path-display-COVV71Yu.js → path-display-CAWz-sMq.js} +3 -3
  137. package/dist/{path-display-COVV71Yu.js.map → path-display-CAWz-sMq.js.map} +1 -1
  138. package/dist/plugins.d.ts +1 -1
  139. package/dist/{prelude-CVKoUzV8.js → prelude-BwiSR1uA.js} +16 -5
  140. package/dist/prelude-BwiSR1uA.js.map +1 -0
  141. package/dist/{presets-CBt6rFfS.js → presets-CMY43nUP.js} +3 -3
  142. package/dist/{presets-CBt6rFfS.js.map → presets-CMY43nUP.js.map} +1 -1
  143. package/dist/presets.d.ts +1 -1
  144. package/dist/presets.js +1 -1
  145. package/dist/{protocol-CEVqBO-q.d.ts → protocol-C2lqKuMd.d.ts} +50 -7
  146. package/dist/protocol-C2lqKuMd.d.ts.map +1 -0
  147. package/dist/protocol-DOGyHgLQ.js.map +1 -1
  148. package/dist/protocol-NSllElLw.js.map +1 -1
  149. package/dist/providers/anthropic.d.ts +1 -1
  150. package/dist/providers/arcee.d.ts +1 -1
  151. package/dist/providers/baseten.d.ts +1 -1
  152. package/dist/providers/cerebras.d.ts +1 -1
  153. package/dist/providers/google.d.ts +1 -1
  154. package/dist/providers/google.js +1 -1
  155. package/dist/providers/local.d.ts +1 -1
  156. package/dist/providers/neuralwatt.d.ts +1 -1
  157. package/dist/providers/openai-compat.d.ts +1 -1
  158. package/dist/providers/openai.d.ts +1 -1
  159. package/dist/providers/openrouter.d.ts +1 -1
  160. package/dist/providers/xai.d.ts +1 -1
  161. package/dist/{providers-Z0TaBp1O.js → providers-zVRxiJDv.js} +5 -5
  162. package/dist/providers-zVRxiJDv.js.map +1 -0
  163. package/dist/providers.d.ts +1 -1
  164. package/dist/providers.js +1 -1
  165. package/dist/{readonly-db-D7Z-k0pQ.js → readonly-db-DrbT8tX6.js} +2 -2
  166. package/dist/{readonly-db-D7Z-k0pQ.js.map → readonly-db-DrbT8tX6.js.map} +1 -1
  167. package/dist/{registry-BKjeBnoy.js → registry-CBoYDIND.js} +2 -2
  168. package/dist/{registry-BKjeBnoy.js.map → registry-CBoYDIND.js.map} +1 -1
  169. package/dist/{registry-B6Ww76iW.js → registry-CQOU5jvF.js} +2 -2
  170. package/dist/{registry-B6Ww76iW.js.map → registry-CQOU5jvF.js.map} +1 -1
  171. package/dist/{registry-B9INJwJR.js → registry-YUUqbYGr.js} +324 -39
  172. package/dist/registry-YUUqbYGr.js.map +1 -0
  173. package/dist/{remote-hosts-BMWoHCWO.js → remote-hosts-CT8Q95dR.js} +4 -4
  174. package/dist/{remote-hosts-BMWoHCWO.js.map → remote-hosts-CT8Q95dR.js.map} +1 -1
  175. package/dist/{repo-url-D4Dr8NfZ.js → repo-url-DLjjuVk_.js} +169 -2
  176. package/dist/repo-url-DLjjuVk_.js.map +1 -0
  177. package/dist/restate.d.ts +2 -2
  178. package/dist/{sandbox-BwiPGKF7.d.ts → sandbox-B4OW6oNx.d.ts} +2 -2
  179. package/dist/{sandbox-BwiPGKF7.d.ts.map → sandbox-B4OW6oNx.d.ts.map} +1 -1
  180. package/dist/script-progress-CrZ507Qq.js +900 -0
  181. package/dist/script-progress-CrZ507Qq.js.map +1 -0
  182. package/dist/session/sqlite.d.ts +1 -1
  183. package/dist/session.d.ts +1 -1
  184. package/dist/{setting-BQBSyUq0.js → setting-_jh2OtiL.js} +6 -6
  185. package/dist/{setting-BQBSyUq0.js.map → setting-_jh2OtiL.js.map} +1 -1
  186. package/dist/{settings-catalog-4IU2i_jG.js → settings-catalog-DEZlXP51.js} +14 -2
  187. package/dist/settings-catalog-DEZlXP51.js.map +1 -0
  188. package/dist/{settings-keys-iI_Y-7MC.js → settings-keys-BT0_oKjO.js} +3 -3
  189. package/dist/{settings-keys-iI_Y-7MC.js.map → settings-keys-BT0_oKjO.js.map} +1 -1
  190. package/dist/{skills-CFXRItJ6.js → skills-CEbosUlM.js} +2 -2
  191. package/dist/{skills-CFXRItJ6.js.map → skills-CEbosUlM.js.map} +1 -1
  192. package/dist/skills.d.ts +1 -1
  193. package/dist/skills.js +1 -1
  194. package/dist/{source-Bl1Z501r.js → source-3ZnEPOSa.js} +3 -2
  195. package/dist/source-3ZnEPOSa.js.map +1 -0
  196. package/dist/{sqlite-runtime-BZ2L4RaG.d.ts → sqlite-runtime-CS_LBaAN.d.ts} +2 -2
  197. package/dist/sqlite-runtime-CS_LBaAN.d.ts.map +1 -0
  198. package/dist/{src-BY_ND2xn.js → src-BmTXDta8.js} +2 -2
  199. package/dist/{src-BY_ND2xn.js.map → src-BmTXDta8.js.map} +1 -1
  200. package/dist/{store-C6gI7FfZ.js → store-ByCDaKgJ.js} +14 -3
  201. package/dist/store-ByCDaKgJ.js.map +1 -0
  202. package/dist/{system-freeze-m5o1sGIM.js → system-freeze-DxJ-lRhu.js} +3 -3
  203. package/dist/{system-freeze-m5o1sGIM.js.map → system-freeze-DxJ-lRhu.js.map} +1 -1
  204. package/dist/{todo-edits-CbukbjyV.js → todo-edits-Dyj32ds6.js} +4 -3
  205. package/dist/todo-edits-Dyj32ds6.js.map +1 -0
  206. package/dist/tools/fetch-url.d.ts +1 -1
  207. package/dist/tools/web-search.d.ts +1 -1
  208. package/dist/{tools-CVTGhggj.js → tools-BsrGQ8K4.js} +2 -2
  209. package/dist/{tools-CVTGhggj.js.map → tools-BsrGQ8K4.js.map} +1 -1
  210. package/dist/tools.d.ts +1 -1
  211. package/dist/tools.js +3 -3
  212. package/dist/{transcript-anchors-CiSi_UBn.js → transcript-anchors-DMjvyUjk.js} +3 -3
  213. package/dist/{transcript-anchors-CiSi_UBn.js.map → transcript-anchors-DMjvyUjk.js.map} +1 -1
  214. package/dist/{transcript-reconcile-jbSBjLq2.js → transcript-reconcile-DpQO85wl.js} +3 -3
  215. package/dist/{transcript-reconcile-jbSBjLq2.js.map → transcript-reconcile-DpQO85wl.js.map} +1 -1
  216. package/dist/tui.d.ts +9 -9
  217. package/dist/tui.d.ts.map +1 -1
  218. package/dist/tui.js +289 -38
  219. package/dist/tui.js.map +1 -1
  220. package/dist/{types-bDQagoiL.d.ts → types-2HrgolQz.d.ts} +20 -8
  221. package/dist/types-2HrgolQz.d.ts.map +1 -0
  222. package/dist/types-4q1bFG53.js +122 -0
  223. package/dist/types-4q1bFG53.js.map +1 -0
  224. package/dist/{types-DnRd9_cA.d.ts → types-SXqk6hLD.d.ts} +3 -3
  225. package/dist/{types-DnRd9_cA.d.ts.map → types-SXqk6hLD.d.ts.map} +1 -1
  226. package/dist/types-myxheQkw.js.map +1 -1
  227. package/dist/types.d.ts +3 -3
  228. package/dist/{usage-summary-BfcXjiSM.js → usage-summary-BM7B3JdI.js} +2 -2
  229. package/dist/{usage-summary-BfcXjiSM.js.map → usage-summary-BM7B3JdI.js.map} +1 -1
  230. package/dist/{version-DqqqvHDP.js → version-DwQI12WA.js} +2 -2
  231. package/dist/{version-DqqqvHDP.js.map → version-DwQI12WA.js.map} +1 -1
  232. package/dist/{wait-task-BX4NcOOm.js → wait-task-BiI5UaZQ.js} +13 -3
  233. package/dist/wait-task-BiI5UaZQ.js.map +1 -0
  234. package/dist/{wire-CLm2rMK0.js → wire-Dxwxb7QQ.js} +2 -2
  235. package/dist/{wire-CLm2rMK0.js.map → wire-Dxwxb7QQ.js.map} +1 -1
  236. package/dist/{write-file-0E6TUJ9A.js → write-file-Dquu7MzB.js} +5 -3
  237. package/dist/write-file-Dquu7MzB.js.map +1 -0
  238. package/dist/{ws-DfGGYQ4W.js → ws-CA3o2nie.js} +4 -4
  239. package/dist/{ws-DfGGYQ4W.js.map → ws-CA3o2nie.js.map} +1 -1
  240. package/dist/{ws-client-CFMbhsNq.js → ws-client-C0iPAAzc.js} +2 -2
  241. package/dist/{ws-client-CFMbhsNq.js.map → ws-client-C0iPAAzc.js.map} +1 -1
  242. package/docs/CHAT.md +55 -0
  243. package/docs/CODEMODE.md +37 -0
  244. package/docs/EXTENSIONS.md +8 -6
  245. package/docs/RELEASE-NOTES-NEXT.md +48 -1
  246. package/docs/RELEASE.md +9 -1
  247. package/package.json +2 -3
  248. package/dist/agent-DJhpTS-B.js.map +0 -1
  249. package/dist/auto-update-restart-BFB7Ek87.js.map +0 -1
  250. package/dist/browser-BcoCCB_n.js.map +0 -1
  251. package/dist/contexts-C72b0mMa.js.map +0 -1
  252. package/dist/decisions-CXmK0nz9.js.map +0 -1
  253. package/dist/extension-mark-BqKdEZwF.js.map +0 -1
  254. package/dist/extensions-client-D8tEAcMw.d.ts.map +0 -1
  255. package/dist/host-BHMs9jsN.js.map +0 -1
  256. package/dist/host-wO_6GW0y.js.map +0 -1
  257. package/dist/index-CGbOWa7y.d.ts.map +0 -1
  258. package/dist/json-Dj-YATkZ.js.map +0 -1
  259. package/dist/media-type-BtA0cbfI.d.ts.map +0 -1
  260. package/dist/memory-DuVGrzbl.js.map +0 -1
  261. package/dist/nested-call-events-BYk8XvGX.js +0 -182
  262. package/dist/nested-call-events-BYk8XvGX.js.map +0 -1
  263. package/dist/nested-call-record-DlzPeTB7.js.map +0 -1
  264. package/dist/prelude-CVKoUzV8.js.map +0 -1
  265. package/dist/protocol-CEVqBO-q.d.ts.map +0 -1
  266. package/dist/providers-Z0TaBp1O.js.map +0 -1
  267. package/dist/registry-B9INJwJR.js.map +0 -1
  268. package/dist/repo-url-D4Dr8NfZ.js.map +0 -1
  269. package/dist/settings-catalog-4IU2i_jG.js.map +0 -1
  270. package/dist/source-Bl1Z501r.js.map +0 -1
  271. package/dist/sqlite-runtime-BZ2L4RaG.d.ts.map +0 -1
  272. package/dist/store-C6gI7FfZ.js.map +0 -1
  273. package/dist/todo-edits-CbukbjyV.js.map +0 -1
  274. package/dist/types-DTMEhKJO.js +0 -14
  275. package/dist/types-DTMEhKJO.js.map +0 -1
  276. package/dist/types-bDQagoiL.d.ts.map +0 -1
  277. package/dist/wait-task-BX4NcOOm.js.map +0 -1
  278. package/dist/write-file-0E6TUJ9A.js.map +0 -1
  279. package/scripts/eval.ts +0 -179
@@ -1 +1 @@
1
- {"version":3,"file":"protocol-NSllElLw.js","names":[],"sources":["../src/codemode/runtime/protocol.ts"],"sourcesContent":["import type { CodemodeDeterminism, CodemodeOutputItem } from '../types'\nimport type { CodemodeWasmModule } from '../wasm'\n\n/**\n * Messages between the host (main thread) and the worker. Tool arguments,\n * results, and values cross as JSON strings: the worker passes them into and\n * out of the QuickJS VM as strings and never builds structured values itself.\n */\n\nexport interface WorkerData {\n code: string\n /**\n * `jsName` is the identifier the script uses; `description` is listed in `ALL_TOOLS`. A string\n * argument fills `stringArg`: `tools.shell(\"ls\")` is `tools.shell({ command: \"ls\" })`.\n */\n tools: { name: string, jsName: string, description: string, stringArg?: string }[]\n globals: { name: string, spread: boolean }[]\n /** Compiled `quickjs-wasi` module. Structured clone shares the compiled code with the worker. */\n wasm: CodemodeWasmModule\n memoryLimitBytes: number | undefined\n /** Snapshot for `load()`: key to JSON text. */\n store: Record<string, string>\n /**\n * One Int32 the host sets to non-zero before terminating the worker. The VM's interrupt handler\n * polls it, because Bun's `worker.terminate()` cannot stop a thread that is spinning in wasm.\n */\n interrupt: SharedArrayBuffer\n determinism: CodemodeDeterminism | undefined\n /** Advice for reading a tool the host keeps out of scripts, by member name. */\n toolHints?: Record<string, string>\n /** Global functions that call a tool, by function name: `{ sh: 'shell' }`. */\n shortcuts?: Record<string, string>\n}\n\n/** JSON-encoded `{ name?, message, stack? }` of an error thrown by the script. */\nexport type ScriptErrorJson = string\n\n/** One call. `id` is its issue sequence number (see `CodemodeToolContext.seq`). */\nexport interface CallMessage { id: number, target: 'tool' | 'global', name: string, args: string | undefined }\n\nexport type WorkerToHostMessage\n /** Every call issued during one drain of the VM's job queue, in issue order. */\n = | { type: 'calls', calls: CallMessage[] }\n | { type: 'output', item: CodemodeOutputItem }\n /** `writes` is a JSON array of `[key, json]` for `store()` and `[key]` for deletions. */\n | { type: 'done', ok: true, value: string | undefined, writes: string }\n | { type: 'done', ok: false, error: ScriptErrorJson }\n /** The VM failed outside the script's control, for example a wasm trap. */\n | { type: 'crash', message: string }\n\n/**\n * `payload` is the JSON result when `ok`, otherwise the error message. `text` is what printing\n * the result shows, for a tool that returned a `CodemodeValue`.\n */\nexport interface HostToWorkerMessage { type: 'result', id: number, ok: boolean, payload: string | undefined, text?: string }\n\nexport function isWorkerToHostMessage(value: unknown): value is WorkerToHostMessage {\n if (typeof value !== 'object' || value === null)\n return false\n const type = (value as { type?: unknown }).type\n return type === 'calls' || type === 'output' || type === 'done' || type === 'crash'\n}\n\nexport function isHostToWorkerMessage(value: unknown): value is HostToWorkerMessage {\n return typeof value === 'object' && value !== null && (value as { type?: unknown }).type === 'result'\n}\n"],"mappings":";AAwDA,SAAgB,sBAAsB,OAA8C;CAClF,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CACT,MAAM,OAAQ,MAA6B;CAC3C,OAAO,SAAS,WAAW,SAAS,YAAY,SAAS,UAAU,SAAS;AAC9E;AAEA,SAAgB,sBAAsB,OAA8C;CAClF,OAAO,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,SAAS;AAC/F"}
1
+ {"version":3,"file":"protocol-NSllElLw.js","names":[],"sources":["../src/codemode/runtime/protocol.ts"],"sourcesContent":["import type { CodemodeDeterminism, CodemodeOutputItem } from '../types'\nimport type { CodemodeWasmModule } from '../wasm'\n\n/**\n * Messages between the host (main thread) and the worker. Tool arguments,\n * results, and values cross as JSON strings: the worker passes them into and\n * out of the QuickJS VM as strings and never builds structured values itself.\n */\n\nexport interface WorkerData {\n code: string\n /**\n * `jsName` is the identifier the script uses; `description` is listed in `ALL_TOOLS`. A string\n * argument fills `stringArg`: `tools.shell(\"ls\")` is `tools.shell({ command: \"ls\" })`.\n */\n tools: { name: string, jsName: string, description: string, stringArg?: string }[]\n globals: { name: string, spread: boolean }[]\n /** Compiled `quickjs-wasi` module. Structured clone shares the compiled code with the worker. */\n wasm: CodemodeWasmModule\n memoryLimitBytes: number | undefined\n /** Snapshot for `load()`: key to JSON text. */\n store: Record<string, string>\n /**\n * One Int32 the host sets to non-zero before terminating the worker. The VM's interrupt handler\n * polls it, because Bun's `worker.terminate()` cannot stop a thread that is spinning in wasm.\n */\n interrupt: SharedArrayBuffer\n determinism: CodemodeDeterminism | undefined\n /** Advice for reading a tool the host keeps out of scripts, by member name. */\n toolHints?: Record<string, string>\n /** Global functions that call a tool, by function name: `{ sh: 'shell' }`. */\n shortcuts?: Record<string, string>\n /** Report the script line of each call (`CallMessage.line`). */\n trackLines?: boolean\n}\n\n/** JSON-encoded `{ name?, message, stack? }` of an error thrown by the script. */\nexport type ScriptErrorJson = string\n\n/**\n * One call. `id` is its issue sequence number (see `CodemodeToolContext.seq`). `line` is the\n * script line that made it, with `WorkerData.trackLines`.\n */\nexport interface CallMessage { id: number, target: 'tool' | 'global', name: string, args: string | undefined, line?: number }\n\nexport type WorkerToHostMessage\n /** Every call issued during one drain of the VM's job queue, in issue order. */\n = | { type: 'calls', calls: CallMessage[] }\n | { type: 'output', item: CodemodeOutputItem }\n /** `writes` is a JSON array of `[key, json]` for `store()` and `[key]` for deletions. */\n | { type: 'done', ok: true, value: string | undefined, writes: string }\n | { type: 'done', ok: false, error: ScriptErrorJson }\n /** The VM failed outside the script's control, for example a wasm trap. */\n | { type: 'crash', message: string }\n\n/**\n * `payload` is the JSON result when `ok`, otherwise the error message. `text` is what printing\n * the result shows, for a tool that returned a `CodemodeValue`.\n */\nexport interface HostToWorkerMessage { type: 'result', id: number, ok: boolean, payload: string | undefined, text?: string }\n\nexport function isWorkerToHostMessage(value: unknown): value is WorkerToHostMessage {\n if (typeof value !== 'object' || value === null)\n return false\n const type = (value as { type?: unknown }).type\n return type === 'calls' || type === 'output' || type === 'done' || type === 'crash'\n}\n\nexport function isHostToWorkerMessage(value: unknown): value is HostToWorkerMessage {\n return typeof value === 'object' && value !== null && (value as { type?: unknown }).type === 'result'\n}\n"],"mappings":";AA6DA,SAAgB,sBAAsB,OAA8C;CAClF,IAAI,OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CACT,MAAM,OAAQ,MAA6B;CAC3C,OAAO,SAAS,WAAW,SAAS,YAAY,SAAS,UAAU,SAAS;AAC9E;AAEA,SAAgB,sBAAsB,OAA8C;CAClF,OAAO,OAAO,UAAU,YAAY,UAAU,QAAS,MAA6B,SAAS;AAC/F"}
@@ -1,2 +1,2 @@
1
- import { $j as EXTENDED_CACHE_TTL_BETA, CM as planAnthropicThinking, Gj as cacheWriteTtlMultiplier, Jj as classifyAnthropicError, Kj as defaultAnthropicMaxTokens, Qj as resolveAnthropicBetas, SM as ThinkingBindingBehavior, Wj as anthropic, Xj as credentialIdentity, Yj as buildAnthropicClientOptions, Zj as resolveAnthropicAuthShape, bM as AnthropicThinkingPlan, eM as applyAnthropicCacheBreakpoints, nM as AnthropicContextManagement, qj as resolveAnthropicMaxOutput, rM as AnthropicParams, tM as AnthropicBedrockConfig, wM as resolveThinkingBinding, xM as THINKING_BINDING_SETTING_ENV } from "../index-CGbOWa7y.js";
1
+ import { AM as credentialIdentity, DM as resolveAnthropicMaxOutput, EM as defaultAnthropicMaxTokens, FM as AnthropicBedrockConfig, IM as AnthropicContextManagement, LM as AnthropicParams, MM as resolveAnthropicBetas, NM as EXTENDED_CACHE_TTL_BETA, OM as classifyAnthropicError, PM as applyAnthropicCacheBreakpoints, TM as cacheWriteTtlMultiplier, eN as AnthropicThinkingPlan, iN as resolveThinkingBinding, jM as resolveAnthropicAuthShape, kM as buildAnthropicClientOptions, nN as ThinkingBindingBehavior, rN as planAnthropicThinking, tN as THINKING_BINDING_SETTING_ENV, wM as anthropic } from "../index-WlE93Q6d.js";
2
2
  export { type AnthropicBedrockConfig, type AnthropicContextManagement, type AnthropicParams, type AnthropicThinkingPlan, EXTENDED_CACHE_TTL_BETA, THINKING_BINDING_SETTING_ENV, type ThinkingBindingBehavior, anthropic, applyAnthropicCacheBreakpoints, buildAnthropicClientOptions, cacheWriteTtlMultiplier, classifyAnthropicError, credentialIdentity, defaultAnthropicMaxTokens, planAnthropicThinking, resolveAnthropicAuthShape, resolveAnthropicBetas, resolveAnthropicMaxOutput, resolveThinkingBinding };
@@ -1,2 +1,2 @@
1
- import { Hj as ArceeParams, Uj as arcee } from "../index-CGbOWa7y.js";
1
+ import { CM as arcee, SM as ArceeParams } from "../index-WlE93Q6d.js";
2
2
  export { ArceeParams, arcee };
@@ -1,2 +1,2 @@
1
- import { Bj as baseten, Vj as planBasetenReasoning, zj as BasetenParams } from "../index-CGbOWa7y.js";
1
+ import { bM as baseten, xM as planBasetenReasoning, yM as BasetenParams } from "../index-WlE93Q6d.js";
2
2
  export { BasetenParams, baseten, planBasetenReasoning };
@@ -1,2 +1,2 @@
1
- import { Lj as CerebrasParams, Rj as cerebras } from "../index-CGbOWa7y.js";
1
+ import { _M as CerebrasParams, vM as cerebras } from "../index-WlE93Q6d.js";
2
2
  export { CerebrasParams, cerebras };
@@ -1,2 +1,2 @@
1
- import { Aj as GeminiRequest, Cj as resolveVertexAuth, Dj as GeminiFunctionDeclaration, Ej as GeminiContent, Mj as GeminiThinkingConfig, Nj as GeminiToolConfig, Oj as GeminiGenerationConfig, Pj as GoogleWireModel, Sj as resolveGoogleModel, Tj as toGeminiContents, _j as VertexRequestAuth, bj as googleCompatible, cj as GOOGLE_DEFAULT_MODEL, dj as GoogleExtraModel, fj as GoogleParams, gj as GoogleVertexParams, hj as GoogleTurnRequest, jj as GeminiResponseChunk, kj as GeminiPart, lj as GOOGLE_EXTRA_MODELS, mj as GoogleSharedParams, pj as GoogleRouteName, uj as GoogleCompatibleRoute, vj as classifyGoogleError, wj as GeminiTool, xj as googleVertex, yj as google } from "../index-CGbOWa7y.js";
1
+ import { $j as google, Gj as GoogleExtraModel, Hj as GOOGLE_DEFAULT_MODEL, Jj as GoogleSharedParams, Kj as GoogleParams, Qj as classifyGoogleError, Uj as GOOGLE_EXTRA_MODELS, Wj as GoogleCompatibleRoute, Xj as GoogleVertexParams, Yj as GoogleTurnRequest, Zj as VertexRequestAuth, aM as toGeminiContents, cM as GeminiGenerationConfig, dM as GeminiResponseChunk, eM as googleCompatible, fM as GeminiThinkingConfig, iM as GeminiTool, lM as GeminiPart, mM as GoogleWireModel, nM as resolveGoogleModel, oM as GeminiContent, pM as GeminiToolConfig, qj as GoogleRouteName, rM as resolveVertexAuth, sM as GeminiFunctionDeclaration, tM as googleVertex, uM as GeminiRequest } from "../index-WlE93Q6d.js";
2
2
  export { GOOGLE_DEFAULT_MODEL, GOOGLE_EXTRA_MODELS, type GeminiContent, type GeminiFunctionDeclaration, type GeminiGenerationConfig, type GeminiPart, type GeminiRequest, type GeminiResponseChunk, type GeminiThinkingConfig, type GeminiTool, type GeminiToolConfig, GoogleCompatibleRoute, GoogleExtraModel, GoogleParams, GoogleRouteName, GoogleSharedParams, GoogleTurnRequest, GoogleVertexParams, type GoogleWireModel, VertexRequestAuth, classifyGoogleError, google, googleCompatible, googleVertex, resolveGoogleModel, resolveVertexAuth, toGeminiContents };
@@ -1 +1 @@
1
- export { t as GOOGLE_DEFAULT_MODEL, n as GOOGLE_EXTRA_MODELS, r as classifyGoogleError, i as google, a as googleCompatible, o as googleVertex, s as resolveGoogleModel, c as resolveVertexAuth, u as toGeminiContents } from "../google-Crva32sk.js";
1
+ export { t as GOOGLE_DEFAULT_MODEL, n as GOOGLE_EXTRA_MODELS, r as classifyGoogleError, i as google, a as googleCompatible, o as googleVertex, s as resolveGoogleModel, c as resolveVertexAuth, u as toGeminiContents } from "../google-BtMW9KzL.js";
@@ -1,2 +1,2 @@
1
- import { oj as LocalParams, sj as local } from "../index-CGbOWa7y.js";
1
+ import { Bj as LocalParams, Vj as local } from "../index-WlE93Q6d.js";
2
2
  export { LocalParams, local };
@@ -1,2 +1,2 @@
1
- import { $A as NEURALWATT_DEFAULT_MODEL, ej as NeuralwattParams, nj as planNeuralwattReasoning, tj as neuralwatt } from "../index-CGbOWa7y.js";
1
+ import { Fj as neuralwatt, Ij as planNeuralwattReasoning, Nj as NEURALWATT_DEFAULT_MODEL, Pj as NeuralwattParams } from "../index-WlE93Q6d.js";
2
2
  export { NEURALWATT_DEFAULT_MODEL, NeuralwattParams, neuralwatt, planNeuralwattReasoning };
@@ -1,2 +1,2 @@
1
- import { AA as OpenAICompatAuthHeader, BA as mapOAIFinishReason, DA as ASSISTANT_TOOL_CALLS_TAG, FA as applyOAIToolCacheBreakpoint, GA as userMessage, HA as openaiCompat, IA as assistantMessage, KA as OpenAICompatStreamError, LA as buildAssistantContent, MA as OpenAICompatParams, NA as TOOL_RESULTS_TAG, OA as OAIMessage, PA as applyOAICacheBreakpoints, RA as classifyOpenAICompatError, UA as toOAIMessages, VA as openAICompatPromptMessage, WA as toolResultsMessage, jA as OpenAICompatHttpError, kA as OAITool, qA as consumeSSE, zA as formatTools } from "../index-CGbOWa7y.js";
1
+ import { Cj as toOAIMessages, Dj as consumeSSE, Ej as OpenAICompatStreamError, Sj as openaiCompat, Tj as userMessage, _j as buildAssistantContent, bj as mapOAIFinishReason, cj as OAIMessage, dj as OpenAICompatHttpError, fj as OpenAICompatParams, gj as assistantMessage, hj as applyOAIToolCacheBreakpoint, lj as OAITool, mj as applyOAICacheBreakpoints, pj as TOOL_RESULTS_TAG, sj as ASSISTANT_TOOL_CALLS_TAG, uj as OpenAICompatAuthHeader, vj as classifyOpenAICompatError, wj as toolResultsMessage, xj as openAICompatPromptMessage, yj as formatTools } from "../index-WlE93Q6d.js";
2
2
  export { ASSISTANT_TOOL_CALLS_TAG, OAIMessage, OAITool, OpenAICompatAuthHeader, OpenAICompatHttpError, OpenAICompatParams, OpenAICompatStreamError, TOOL_RESULTS_TAG, applyOAICacheBreakpoints, applyOAIToolCacheBreakpoint, assistantMessage, buildAssistantContent, classifyOpenAICompatError, consumeSSE, formatTools, mapOAIFinishReason, openAICompatPromptMessage, openaiCompat, toOAIMessages, toolResultsMessage, userMessage };
@@ -1,2 +1,2 @@
1
- import { JA as OpenAIParams, QA as toPiMessages, XA as mapCodexStopReason, YA as classifyOpenAIError, ZA as openai } from "../index-CGbOWa7y.js";
1
+ import { Aj as mapCodexStopReason, Mj as toPiMessages, Oj as OpenAIParams, jj as openai, kj as classifyOpenAIError } from "../index-WlE93Q6d.js";
2
2
  export { OpenAIParams, classifyOpenAIError, mapCodexStopReason, openai, toPiMessages };
@@ -1,2 +1,2 @@
1
- import { CA as OPENROUTER_DEFAULT_MODEL, EA as openrouter, TA as normalizeOpenRouterModelId, wA as OpenRouterParams } from "../index-CGbOWa7y.js";
1
+ import { aj as normalizeOpenRouterModelId, ij as OpenRouterParams, oj as openrouter, rj as OPENROUTER_DEFAULT_MODEL } from "../index-WlE93Q6d.js";
2
2
  export { OPENROUTER_DEFAULT_MODEL, OpenRouterParams, normalizeOpenRouterModelId, openrouter };
@@ -1,2 +1,2 @@
1
- import { _A as xai, gA as XaiParams } from "../index-CGbOWa7y.js";
1
+ import { XA as XaiParams, ZA as xai } from "../index-WlE93Q6d.js";
2
2
  export { XaiParams, xai };
@@ -1,5 +1,5 @@
1
1
  import { c as validateQuery, g as projectNameOf, l as validateSort } from "./validate-D--OhUFD.js";
2
- import { Jt as DisposedError, ot as assertAlive } from "./registry-B9INJwJR.js";
2
+ import { Zt as DisposedError, ct as assertUsable } from "./registry-YUUqbYGr.js";
3
3
  import { d as querySessions, x as SessionQueryError } from "./references-DZ5qTYDl.js";
4
4
  //#region src/extensions/runtime/domains/sessions.ts
5
5
  /**
@@ -121,12 +121,12 @@ function orchestrationRow(row) {
121
121
  *
122
122
  * @param deps - The extension's id, owner, guard and logger.
123
123
  * @param port - The host's session control and prompt bridge.
124
- * @returns The domain without `facets` (the context adds them). Every call rejects with `DisposedError` once the owner is disposed.
124
+ * @returns The domain without `facets` (the context adds them). Every call rejects with `DisposedError` once the owner is torn down (an unload waits for the calls in flight first).
125
125
  */
126
126
  function createSessionsDomain(deps, port) {
127
127
  const { extensionId, owner } = deps;
128
128
  const verbs = (method) => {
129
- assertAlive(owner, `sessions.${method}`);
129
+ assertUsable(owner, `sessions.${method}`);
130
130
  const control = port.sessionControl();
131
131
  if (!control) throw new Error(`sessions.${method}: no chat host is attached (extension "${extensionId}").`);
132
132
  return control.verbs(extensionId);
@@ -179,7 +179,7 @@ function createSessionsDomain(deps, port) {
179
179
  submit: async (text, opts = {}) => {
180
180
  const delivery = opts.delivery ? { delivery: opts.delivery } : void 0;
181
181
  if (opts.sessionId !== void 0) return lifecycle("submit")(opts.sessionId, text, delivery);
182
- assertAlive(owner, "sessions.submit");
182
+ assertUsable(owner, "sessions.submit");
183
183
  if (!port.promptBridge) throw new Error(`sessions.submit: this host has no prompt pipeline; pass a sessionId (extension "${extensionId}").`);
184
184
  return port.promptBridge.submit(text, delivery);
185
185
  }
@@ -805,4 +805,4 @@ function watchProviderAccounts(catalog, integrations, sources = []) {
805
805
  //#endregion
806
806
  export { createModelsCatalog as a, addTransform as c, reloadWith as d, createCatalogSet as f, fieldsReadBy as g, createSessionsDomain as h, watchProviderAccounts as i, extensionOrigin as l, clonePlain as m, createProvidersCatalog as n, createModelsDomain as o, once as p, createProvidersDomain as r, modelKey as s, accountModelKey as t, owned as u };
807
807
 
808
- //# sourceMappingURL=providers-Z0TaBp1O.js.map
808
+ //# sourceMappingURL=providers-zVRxiJDv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"providers-zVRxiJDv.js","names":[],"sources":["../src/extensions/runtime/domains/sessions.ts","../src/extensions/catalog/clone.ts","../src/extensions/catalog/engine.ts","../src/extensions/catalog/domain.ts","../src/extensions/catalog/models.ts","../src/extensions/catalog/providers.ts"],"sourcesContent":["/**\n * `ctx.sessions` (extension API): the orchestration verbs mapped 1:1,\n * plus the lifecycle verbs. Everything goes through the host's\n * session control, acting as the extension, so what it creates is tagged\n * with the extension id. Without a host, or when the host lacks a verb, the\n * call rejects with a message naming both.\n */\n\nimport type { CommandOutputBlock } from '../../../chat/commands'\nimport type { SessionQuery, SessionQueryIssue, SessionSort } from '../../../chat/session-query'\nimport type { SessionListQuery, SessionListRow, SessionsDomain } from '../../api/sessions'\nimport type { ExtensionSessionLifecycleVerbs, ExtensionSessionRow, ExtensionSessionVerbs } from '../../host-runtime'\nimport type { DomainDeps } from '../deps'\nimport type { SessionsPort } from './ports'\nimport { projectNameOf, querySessions, SessionQueryError, validateQuery, validateSort } from '../../../chat/session-query'\nimport { assertUsable } from '../owner'\n\ntype Verbs = ExtensionSessionVerbs & ExtensionSessionLifecycleVerbs\n\n/**\n * Prefixes bare renderer ids of `custom` blocks with the extension id, as\n * `ctx.appendNote` does.\n */\nfunction namespaceBlocks(extensionId: string, blocks: readonly CommandOutputBlock[]): CommandOutputBlock[] {\n return blocks.map(block =>\n block.custom && !block.custom.renderer.includes('/')\n ? { ...block, custom: { ...block.custom, renderer: `${extensionId}/${block.custom.renderer}` } }\n : block)\n}\n\n/** Rows per page of `ctx.sessions.list` when the query names none, and the most it hands out. */\nexport const SESSION_LIST_DEFAULT_LIMIT = 30\n/** The most rows one `ctx.sessions.list` page holds. */\nexport const SESSION_LIST_MAX_LIMIT = 100\n\n/** A list query with its defaults filled, as the host's `query` verb gets it. */\nexport type NormalizedSessionListQuery = Parameters<NonNullable<ExtensionSessionLifecycleVerbs['query']>>[0]\n\n/**\n * Checks a `ctx.sessions.list` query and fills its defaults. Throws a\n * `SessionQueryError` naming every problem.\n *\n * @param query - The query as the extension gave it.\n */\nexport function normalizeSessionListQuery(query: unknown): NormalizedSessionListQuery {\n if (query === undefined)\n query = {}\n if (typeof query === 'number')\n throw new SessionQueryError([{ path: 'query', message: `list takes a query object now: call list({ limit: ${query} })` }])\n if (!query || typeof query !== 'object' || Array.isArray(query))\n throw new SessionQueryError([{ path: 'query', message: 'must be { where?, sort?, limit?, cursor?, archived? }' }])\n const q = query as Record<string, unknown>\n const issues: SessionQueryIssue[] = []\n for (const key of Object.keys(q)) {\n if (!['where', 'sort', 'limit', 'cursor', 'archived'].includes(key))\n issues.push({ path: key, message: 'unknown key; a list query holds where, sort, limit, cursor and archived' })\n }\n if (q.where !== undefined)\n issues.push(...validateQuery(q.where))\n if (q.sort !== undefined)\n issues.push(...validateSort(q.sort))\n const limit = q.limit ?? SESSION_LIST_DEFAULT_LIMIT\n if (!Number.isInteger(limit) || (limit as number) < 1 || (limit as number) > SESSION_LIST_MAX_LIMIT)\n issues.push({ path: 'limit', message: `must be a whole number from 1 to ${SESSION_LIST_MAX_LIMIT}` })\n if (q.cursor !== undefined && (typeof q.cursor !== 'string' || q.cursor.length === 0))\n issues.push({ path: 'cursor', message: 'must be the cursor of a previous page' })\n if (q.archived !== undefined && typeof q.archived !== 'boolean' && q.archived !== 'all')\n issues.push({ path: 'archived', message: 'must be true, false or \\'all\\'' })\n if (issues.length > 0)\n throw new SessionQueryError(issues)\n return {\n ...(q.where !== undefined ? { where: q.where as NonNullable<SessionListQuery['where']> } : {}),\n sort: (q.sort as SessionListQuery['sort']) ?? [{ field: 'updatedAt', dir: 'desc' }],\n limit: limit as number,\n ...(q.cursor !== undefined ? { cursor: q.cursor as string } : {}),\n archived: (q.archived as SessionListQuery['archived']) ?? false,\n }\n}\n\n/**\n * Every field path a query reads (conditions at any depth) and a sort reads,\n * as written (`facet.<ext>.<key>` paths whole).\n *\n * @param where - The query.\n * @param sort - The sort keys.\n */\nexport function fieldsReadBy(where: SessionQuery | undefined, sort: readonly SessionSort[] = []): Set<string> {\n const out = new Set<string>(sort.map(s => s.field))\n const walk = (q: SessionQuery): void => {\n if ('field' in q)\n out.add(q.field)\n else if ('all' in q)\n q.all.forEach(walk)\n else if ('any' in q)\n q.any.forEach(walk)\n else if ('not' in q)\n walk(q.not)\n }\n if (where)\n walk(where)\n return out\n}\n\n/** The fields an orchestration row fills (`orchestrationRow`): what a host without the `query` verb can filter and sort on. */\nconst ORCHESTRATION_FIELDS: ReadonlySet<string> = new Set(['id', 'title', 'cwd', 'projectName', 'status', 'updatedAt', 'archived'])\n\nfunction isDefaultSort(sort: readonly SessionSort[]): boolean {\n return sort.length === 1 && sort[0]!.field === 'updatedAt' && sort[0]!.dir === 'desc'\n}\n\n/** An orchestration row as a list row: the fields it has, no facets. */\nfunction orchestrationRow(row: ExtensionSessionRow): SessionListRow {\n return { id: row.sessionId, title: row.title, projectRoot: null, projectName: projectNameOf({ cwd: row.cwd }) ?? '', cwd: row.cwd, status: row.state, updatedAt: row.updatedAt, archived: false, worker: row.worker, facets: {} }\n}\n\n/**\n * Creates one extension's `ctx.sessions`.\n *\n * @param deps - The extension's id, owner, guard and logger.\n * @param port - The host's session control and prompt bridge.\n * @returns The domain without `facets` (the context adds them). Every call rejects with `DisposedError` once the owner is torn down (an unload waits for the calls in flight first).\n */\nexport function createSessionsDomain(deps: DomainDeps, port: SessionsPort): Omit<SessionsDomain, 'facets'> {\n const { extensionId, owner } = deps\n\n const verbs = (method: string): Verbs => {\n assertUsable(owner, `sessions.${method}`)\n const control = port.sessionControl()\n if (!control)\n throw new Error(`sessions.${method}: no chat host is attached (extension \"${extensionId}\").`)\n return control.verbs(extensionId)\n }\n\n /** The lifecycle verb `method`, or a rejection when the host does not implement it. */\n const lifecycle = <K extends keyof ExtensionSessionLifecycleVerbs>(method: K): NonNullable<Verbs[K]> => {\n const all = verbs(method)\n const verb = all[method]\n if (typeof verb !== 'function')\n throw new Error(`sessions.${method}: this host does not support it (extension \"${extensionId}\").`)\n return verb.bind(all) as NonNullable<Verbs[K]>\n }\n\n return {\n create: async params => verbs('create').create(params),\n list: async (query) => {\n const all = verbs('list')\n const q = normalizeSessionListQuery(query)\n if (typeof all.query === 'function')\n return all.query(q)\n // A host without the query verb: its newest orchestration rows, filtered here. A query that needs more fails rather than answering wrong.\n const unsupported = (why: string): Error => new Error(`sessions.list: this host does not support queries (extension \"${extensionId}\"): ${why}.`)\n const missing = [...fieldsReadBy(q.where, q.sort)].filter(f => !ORCHESTRATION_FIELDS.has(f))\n if (missing.length > 0)\n throw unsupported(`it lists only ${[...ORCHESTRATION_FIELDS].join(', ')}, not ${missing.join(', ')}`)\n if (q.archived !== false)\n throw unsupported('it lists no archived sessions')\n const listed = await all.list(SESSION_LIST_MAX_LIMIT)\n const truncated = listed.length >= SESSION_LIST_MAX_LIMIT\n if (truncated && (q.where !== undefined || !isDefaultSort(q.sort)))\n throw unsupported(`it lists only its ${SESSION_LIST_MAX_LIMIT} newest sessions, so it can only page them newest first, unfiltered`)\n const page = querySessions(listed.map(orchestrationRow), { ...q, scope: q.archived })\n // A page that ends exactly at the last listed row is whole (no cursor); one cut short by the end of the list may miss older sessions.\n if (truncated && page.cursor === undefined && page.rows.length < q.limit)\n throw unsupported(`it lists only its ${SESSION_LIST_MAX_LIMIT} newest sessions; this page reaches past them`)\n return page\n },\n read: async sessionId => verbs('read').read(sessionId),\n send: async (sessionId, prompt) => verbs('send').send(sessionId, prompt),\n steer: async (sessionId, message) => verbs('steer').steer(sessionId, message),\n cancel: async sessionId => verbs('cancel').cancel(sessionId),\n transcript: async (sessionId, limit) => verbs('transcript').transcript(sessionId, limit),\n wait: async (sessionId, timeoutSec) => verbs('wait').wait(sessionId, timeoutSec),\n events: async query => verbs('events').events(query),\n pending: async sessionId => verbs('pending').pending(sessionId),\n answer: async (requestId, response) => verbs('answer').answer(requestId, response),\n approve: async (requestId, decision) => verbs('approve').approve(requestId, decision),\n\n get: async sessionId => lifecycle('get')(sessionId),\n remove: async sessionId => lifecycle('remove')(sessionId),\n compact: async sessionId => lifecycle('compact')(sessionId),\n switchModel: async (sessionId, model) => lifecycle('switchModel')(sessionId, model),\n switchAgent: async (sessionId, agentId) => lifecycle('switchAgent')(sessionId, agentId),\n setThinking: async (sessionId, level) => lifecycle('setThinking')(sessionId, level),\n synthetic: async (sessionId, message) => lifecycle('synthetic')(sessionId, message),\n note: async (sessionId, blocks) => lifecycle('note')(sessionId, namespaceBlocks(extensionId, blocks)),\n\n submit: async (text, opts = {}) => {\n const delivery = opts.delivery ? { delivery: opts.delivery } : undefined\n if (opts.sessionId !== undefined)\n return lifecycle('submit')(opts.sessionId, text, delivery)\n // The session in view: the host's prompt pipeline, as `ctx.submitPrompt`.\n assertUsable(owner, 'sessions.submit')\n if (!port.promptBridge)\n throw new Error(`sessions.submit: this host has no prompt pipeline; pass a sessionId (extension \"${extensionId}\").`)\n return port.promptBridge.submit(text, delivery)\n },\n }\n}\n","/**\n * Copy-on-edit cloning for catalog items. Items mix plain data (specs,\n * presets, labels) with functions and class instances (`execute`,\n * `factory`, OAuth providers, zod schemas). Only the plain data is copied;\n * everything else is shared by reference, so an edit never reaches a value\n * an earlier read handed out.\n */\n\n/** `true` for arrays and objects whose prototype is `Object.prototype` or `null`. */\nfunction isPlain(value: unknown): value is Record<string, unknown> | unknown[] {\n if (Array.isArray(value))\n return true\n if (value === null || typeof value !== 'object')\n return false\n const proto = Object.getPrototypeOf(value)\n return proto === Object.prototype || proto === null\n}\n\n/**\n * Deep-copies arrays and plain objects. Functions, class instances, Maps,\n * Sets and primitives are kept as they are. Cycles are preserved.\n */\nexport function clonePlain<T>(value: T): T {\n const seen = new Map<object, unknown>()\n const walk = (v: unknown): unknown => {\n if (!isPlain(v))\n return v\n const hit = seen.get(v)\n if (hit !== undefined)\n return hit\n if (Array.isArray(v)) {\n const out: unknown[] = []\n seen.set(v, out)\n for (const item of v)\n out.push(walk(item))\n return out\n }\n const out: Record<string, unknown> = Object.create(Object.getPrototypeOf(v))\n seen.set(v, out)\n for (const key of Object.keys(v))\n out[key] = walk(v[key])\n return out\n }\n return walk(value) as T\n}\n","/**\n * The catalog transform engine shared by every extension catalog (tools, agents,\n * models, providers, MCP servers, skills).\n *\n * A catalog value is rebuilt by replay: the base items (built-ins, config),\n * then registrations in the order they were made, then every transform in\n * extension load order. The result is memoized until a registration,\n * transform or `reload()` changes it. Each item records who added,\n * modified or removed it, so Settings can name the extension, and disposing\n * the extension's registrations restores the item on the next read.\n *\n * Edits are copy-on-edit: `update` clones the item before the transform\n * sees it, so a value an earlier read handed out is never mutated. A\n * transform that throws is rolled back as a whole and reported.\n */\n\nimport type { Disposable, ItemOrigin } from '../api'\nimport type { Guard } from '../runtime/deps'\nimport { clonePlain } from './clone'\n\n/** An item with the origin a base or registration gives it. */\nexport interface Sourced<T> {\n /** The item. */\n readonly item: T\n /** Who put it in the catalog. */\n readonly origin: ItemOrigin\n}\n\n/** One keyed collection inside a catalog. */\nexport interface SectionSpec<T, C> {\n /** The id of an item. Must be a non-empty string. */\n key: (item: T) => string\n /** The base items for a context: built-ins and config. Cached until `reload()`. */\n base: (context: C) => readonly Sourced<T>[]\n /** Copy used by `update`. Default: {@link clonePlain}. */\n clone?: (item: T) => T\n}\n\n/** Catalog-wide state beside the sections (a default id, auto-invoked names). */\nexport interface StateSpec<X, C> {\n /** The state before any transform. */\n base: (context: C) => X\n /** Copy taken before each transform, restored when it throws. */\n clone: (state: X) => X\n}\n\n/** Who touched one id. Removed ids keep theirs with `removedBy`. */\nexport interface Provenance {\n /** The item id. */\n readonly id: string\n /** Who put the item in the catalog. A transform's `add` makes it `{ kind: 'extension' }`. */\n readonly origin: ItemOrigin\n /** The origin of an item this one replaced at registration (same id). */\n readonly replaced?: ItemOrigin\n /** The extension whose transform added the item. */\n readonly addedBy?: string\n /** Extensions whose transforms edited the item, in replay order. */\n readonly modifiedBy: readonly string[]\n /** The extension whose transform removed the item. */\n readonly removedBy?: string\n}\n\n/** A transform that threw during replay; its edits were rolled back. */\nexport interface TransformFailure {\n /** The extension that registered the transform. */\n readonly extensionId: string\n /** The guard label it ran under. */\n readonly label: string\n}\n\n/** One section of a replayed catalog value. Frozen. */\nexport interface SectionValue<T> {\n /** The items, in insertion order. */\n readonly items: readonly T[]\n /** The item with this id. */\n get: (id: string) => T | undefined\n /** The origin of a present item. */\n origin: (id: string) => ItemOrigin | undefined\n /** Who touched an id, present or removed. */\n provenance: (id: string) => Provenance | undefined\n /** Provenance of every id, present ones first, then removed ones. */\n readonly entries: readonly Provenance[]\n}\n\n/** A replayed catalog value. Never mutated after it is returned. */\nexport interface CatalogValue<S extends Sections, X> {\n /** Every section after replay. */\n readonly sections: { readonly [K in keyof S]: SectionValue<S[K]> }\n /** The state after replay. */\n readonly state: Readonly<X>\n /** Transforms that threw and were skipped. */\n readonly failures: readonly TransformFailure[]\n}\n\n/** The section item types of a catalog, by section name (an object type such as `{ tools: NamedTool }`). */\nexport type Sections = object\n\n/** The editable form of a section that a transform works on. */\nexport interface SectionDraft<T> {\n /** Present items, in order. Treat them as read-only; edit through `update`. */\n list: () => readonly T[]\n /** The item with this id. Read-only, like `list`. */\n get: (id: string) => T | undefined\n /** Origin of a present item. */\n origin: (id: string) => ItemOrigin | undefined\n /** Adds an item, or replaces the one with the same id. */\n add: (item: T) => void\n /** Edits a clone of the item. A missing id is a no-op. The edit must keep the id. */\n update: (id: string, edit: (item: T) => void) => void\n /** Puts `item` in place of the item with its id (or adds it), marking it modified. */\n replace: (item: T) => void\n /** Removes an item. A missing id is a no-op. */\n remove: (id: string) => void\n /** A clone of an item, for callbacks that may mutate what they get. */\n cloneOf: (id: string) => T | undefined\n}\n\n/** What a transform gets: every section, the state, and who is editing. */\nexport interface CatalogDraft<S extends Sections, X, C> {\n /** The sections. */\n readonly sections: { readonly [K in keyof S]: SectionDraft<S[K]> }\n /** The state. Replace or mutate it; it is cloned before each transform. */\n state: X\n /** The context the catalog is read for. */\n readonly context: C\n /** The extension whose transform is running. */\n readonly extensionId: string\n /** Throws when the transform already returned (an editor kept past its call). */\n assertOpen: () => void\n}\n\n/** A transform registration. */\nexport interface TransformRegistration<S extends Sections, X, C> {\n /** The extension that owns the transform (orders replay and attributes edits). */\n extensionId: string\n /** Runs the transform with error attribution. */\n guard: Guard\n /** Guard label. Default: `<catalog>.transform`. */\n label?: string\n /** Edits the draft. */\n apply: (draft: CatalogDraft<S, X, C>) => void\n}\n\n/** Options shared by every catalog. */\nexport interface CatalogOptions {\n /** Load-order rank of an extension; lower replays first. Ties keep registration order. */\n order?: (extensionId: string) => number\n /** Most memoized values kept (one per context key). Default 32. */\n cacheSize?: number\n}\n\n/** Spec of a multi-section catalog. */\nexport interface CatalogSetSpec<S extends Sections, X, C> extends CatalogOptions {\n /** Name used in guard labels and errors. */\n name: string\n /** The sections. */\n sections: { [K in keyof S]: SectionSpec<S[K], C> }\n /** Optional catalog-wide state. */\n state?: StateSpec<X, C>\n /** Memo key of a context. `undefined` means \"don't memoize\". Default: one key for all. */\n contextKey?: (context: C) => string | undefined\n}\n\n/** A shared catalog: registrations, transforms, replayed reads. */\nexport interface CatalogSet<S extends Sections, X, C> {\n /** Catalog name. */\n readonly name: string\n /** Adds an item to a section after the base. A later registration of the same id replaces an earlier one. */\n register: <K extends keyof S>(section: K, item: S[K], origin: ItemOrigin) => Disposable\n /** Adds a transform. Replays in `order`, then registration order. */\n transform: (registration: TransformRegistration<S, X, C>) => Disposable\n /** Drops the cached base and every memoized value, then notifies. */\n reload: () => void\n /** The replayed value for a context, memoized until the next change. */\n read: (context: C) => CatalogValue<S, X>\n /** Calls `listener` after each change (the next `read` replays). Returns the unsubscribe. */\n subscribe: (listener: () => void) => () => void\n}\n\ninterface Entry<T> extends Provenance { readonly item: T }\n\ninterface Gate { open: boolean, extensionId: string }\n\nconst BUILTIN: ItemOrigin = Object.freeze({ kind: 'builtin' })\n\nfunction withExtension(list: readonly string[], extensionId: string): readonly string[] {\n return list.includes(extensionId) ? list : [...list, extensionId]\n}\n\nfunction provenanceOf<T>(entry: Entry<T>): Provenance {\n const { item: _item, ...rest } = entry\n return rest\n}\n\nclass SectionDraftImpl<T> implements SectionDraft<T> {\n entries = new Map<string, Entry<T>>()\n removed = new Map<string, Provenance>()\n\n constructor(private readonly name: string, private readonly spec: SectionSpec<T, unknown>, private readonly gate: Gate) {}\n\n idOf(item: T): string {\n const id = this.spec.key(item)\n if (typeof id !== 'string' || id.length === 0)\n throw new TypeError(`${this.name}: item needs a non-empty string id`)\n return id\n }\n\n seed(item: T, origin: ItemOrigin): void {\n const id = this.idOf(item)\n const prev = this.entries.get(id)\n this.entries.set(id, { id, item, origin, modifiedBy: [], ...(prev ? { replaced: prev.origin } : {}) })\n }\n\n private check(): void {\n if (!this.gate.open)\n throw new Error(`${this.name}: the editor was used after its transform returned`)\n }\n\n private cloneItem(item: T): T {\n return (this.spec.clone ?? clonePlain)(item)\n }\n\n list = (): readonly T[] => {\n this.check()\n return [...this.entries.values()].map(entry => entry.item)\n }\n\n get = (id: string): T | undefined => {\n this.check()\n return this.entries.get(id)?.item\n }\n\n origin = (id: string): ItemOrigin | undefined => {\n this.check()\n return this.entries.get(id)?.origin\n }\n\n cloneOf = (id: string): T | undefined => {\n this.check()\n const entry = this.entries.get(id)\n return entry ? this.cloneItem(entry.item) : undefined\n }\n\n add = (item: T): void => {\n this.check()\n const id = this.idOf(item)\n const ext = this.gate.extensionId\n const prev = this.entries.get(id) ?? this.removed.get(id)\n this.removed.delete(id)\n if (prev) {\n const { removedBy: _removedBy, ...rest } = provenanceOf(prev as Entry<T>)\n this.entries.set(id, { ...rest, item, modifiedBy: withExtension(prev.modifiedBy, ext) })\n return\n }\n this.entries.set(id, { id, item, origin: { kind: 'extension', id: ext }, addedBy: ext, modifiedBy: [] })\n }\n\n update = (id: string, edit: (item: T) => void): void => {\n this.check()\n const prev = this.entries.get(id)\n if (!prev)\n return\n const copy = this.cloneItem(prev.item)\n edit(copy)\n if (this.idOf(copy) !== id)\n throw new Error(`${this.name}: update must not change the id of \"${id}\"`)\n this.entries.set(id, { ...prev, item: copy, modifiedBy: withExtension(prev.modifiedBy, this.gate.extensionId) })\n }\n\n replace = (item: T): void => {\n this.check()\n const id = this.idOf(item)\n const prev = this.entries.get(id)\n if (!prev) {\n this.add(item)\n return\n }\n this.entries.set(id, { ...prev, item, modifiedBy: withExtension(prev.modifiedBy, this.gate.extensionId) })\n }\n\n remove = (id: string): void => {\n this.check()\n const prev = this.entries.get(id)\n if (!prev)\n return\n this.entries.delete(id)\n this.removed.set(id, { ...provenanceOf(prev), removedBy: this.gate.extensionId })\n }\n\n checkpoint(): () => void {\n const entries = new Map(this.entries)\n const removed = new Map(this.removed)\n return () => {\n this.entries = entries\n this.removed = removed\n }\n }\n\n freeze(): SectionValue<T> {\n const entries = new Map(this.entries)\n const provenance = new Map<string, Provenance>()\n for (const [id, entry] of entries)\n provenance.set(id, Object.freeze(provenanceOf(entry)))\n for (const [id, prov] of this.removed)\n provenance.set(id, Object.freeze(prov))\n return Object.freeze({\n items: Object.freeze([...entries.values()].map(entry => entry.item)),\n get: (id: string) => entries.get(id)?.item,\n origin: (id: string) => entries.get(id)?.origin,\n provenance: (id: string) => provenance.get(id),\n entries: Object.freeze([...provenance.values()]),\n })\n }\n}\n\ninterface StoredRegistration { seq: number, section: PropertyKey, item: unknown, origin: ItemOrigin }\ninterface StoredTransform<S extends Sections, X, C> extends TransformRegistration<S, X, C> { seq: number }\n\n/** Creates a catalog with several sections and optional state. */\nexport function createCatalogSet<S extends Sections, X = undefined, C = void>(spec: CatalogSetSpec<S, X, C>): CatalogSet<S, X, C> {\n const sectionNames = Object.keys(spec.sections) as (keyof S & string)[]\n const registrations: StoredRegistration[] = []\n const transforms: StoredTransform<S, X, C>[] = []\n const baseCache = new Map<string, { [K in keyof S]: readonly Sourced<S[K]>[] }>()\n const valueCache = new Map<string, CatalogValue<S, X>>()\n const listeners = new Set<() => void>()\n const cacheSize = spec.cacheSize ?? 32\n let seq = 0\n\n const notify = (): void => {\n for (const listener of [...listeners]) {\n try {\n listener()\n }\n catch {\n // A host listener must not break other listeners or the registration.\n }\n }\n }\n\n const invalidate = (): void => {\n valueCache.clear()\n notify()\n }\n\n const baseFor = (context: C, key: string | undefined): { [K in keyof S]: readonly Sourced<S[K]>[] } => {\n const hit = key === undefined ? undefined : baseCache.get(key)\n if (hit)\n return hit\n const base = {} as { [K in keyof S]: readonly Sourced<S[K]>[] }\n for (const name of sectionNames)\n base[name] = spec.sections[name].base(context)\n if (key !== undefined)\n baseCache.set(key, base)\n return base\n }\n\n const rank = (extensionId: string): number => {\n const value = spec.order?.(extensionId)\n return typeof value === 'number' && Number.isFinite(value) ? value : Number.MAX_SAFE_INTEGER\n }\n\n const build = (context: C, key: string | undefined): CatalogValue<S, X> => {\n const gate: Gate = { open: false, extensionId: '' }\n const drafts = {} as { [K in keyof S]: SectionDraftImpl<S[K]> }\n const base = baseFor(context, key)\n for (const name of sectionNames) {\n const draft = new SectionDraftImpl<S[typeof name]>(`${spec.name}.${name}`, spec.sections[name] as SectionSpec<S[typeof name], unknown>, gate)\n for (const { item, origin } of base[name])\n draft.seed(item, origin ?? BUILTIN)\n drafts[name] = draft\n }\n for (const reg of registrations)\n (drafts[reg.section as keyof S] as SectionDraftImpl<unknown>).seed(reg.item, reg.origin)\n\n const draft: CatalogDraft<S, X, C> = {\n sections: drafts,\n state: (spec.state ? spec.state.base(context) : undefined) as X,\n context,\n get extensionId() { return gate.extensionId },\n assertOpen: () => {\n if (!gate.open)\n throw new Error(`${spec.name}: the editor was used after its transform returned`)\n },\n }\n\n const failures: TransformFailure[] = []\n const ordered = [...transforms].sort((a, b) => rank(a.extensionId) - rank(b.extensionId) || a.seq - b.seq)\n for (const transform of ordered) {\n const restores = sectionNames.map(name => drafts[name].checkpoint())\n const savedState = spec.state ? spec.state.clone(draft.state) : draft.state\n const label = transform.label ?? `${spec.name}.transform`\n gate.open = true\n gate.extensionId = transform.extensionId\n let ok = false\n try {\n ok = transform.guard.callSync(label, () => {\n transform.apply(draft)\n return true\n }, { fallback: false }) === true\n }\n catch {\n ok = false\n }\n finally {\n gate.open = false\n }\n if (!ok) {\n for (const restore of restores)\n restore()\n draft.state = savedState\n failures.push(Object.freeze({ extensionId: transform.extensionId, label }))\n }\n }\n\n const sections = {} as { [K in keyof S]: SectionValue<S[K]> }\n for (const name of sectionNames)\n sections[name] = drafts[name].freeze()\n return Object.freeze({ sections: Object.freeze(sections), state: draft.state, failures: Object.freeze(failures) })\n }\n\n return {\n name: spec.name,\n register(section, item, origin) {\n if (!sectionNames.includes(section as keyof S & string))\n throw new TypeError(`${spec.name}: unknown section \"${String(section)}\"`)\n const id = spec.sections[section].key(item)\n if (typeof id !== 'string' || id.length === 0)\n throw new TypeError(`${spec.name}.${String(section)}: item needs a non-empty string id`)\n const stored: StoredRegistration = { seq: seq++, section, item, origin }\n registrations.push(stored)\n invalidate()\n return once(() => {\n const index = registrations.indexOf(stored)\n if (index >= 0) {\n registrations.splice(index, 1)\n invalidate()\n }\n })\n },\n transform(registration) {\n if (typeof registration.apply !== 'function')\n throw new TypeError(`${spec.name}: transform must be a function`)\n const stored: StoredTransform<S, X, C> = { ...registration, seq: seq++ }\n transforms.push(stored)\n invalidate()\n return once(() => {\n const index = transforms.indexOf(stored)\n if (index >= 0) {\n transforms.splice(index, 1)\n invalidate()\n }\n })\n },\n reload() {\n baseCache.clear()\n invalidate()\n },\n read(context) {\n const key = spec.contextKey ? spec.contextKey(context) : ''\n if (key !== undefined) {\n const hit = valueCache.get(key)\n if (hit)\n return hit\n }\n const value = build(context, key)\n if (key !== undefined) {\n valueCache.set(key, value)\n if (valueCache.size > cacheSize)\n valueCache.delete(valueCache.keys().next().value as string)\n }\n return value\n },\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n }\n}\n\n/** Spec of a single-section catalog. */\nexport interface CatalogSpec<T> extends CatalogOptions {\n /** Name used in guard labels and errors. Default `'catalog'`. */\n name?: string\n /** The id of an item. */\n key: (item: T) => string\n /** The base items. Plain items are `builtin`; give `Sourced` entries for another origin. */\n base: () => readonly (T | Sourced<T>)[]\n /** Copy used by `update`. Default: {@link clonePlain}. */\n clone?: (item: T) => T\n /** Tells a `Sourced` entry from a plain item. Default: an object with exactly `item` and `origin`. */\n isSourced?: (entry: T | Sourced<T>) => entry is Sourced<T>\n}\n\n/** A single-section catalog. */\nexport interface Catalog<T> {\n /** Adds an item after the base. */\n register: (item: T, origin: ItemOrigin) => Disposable\n /** Adds a transform owned by `extensionId`, run through `guard`. */\n transform: (fn: (editor: SectionDraft<T>) => void, extensionId: string, guard: Guard) => Disposable\n /** Re-reads the base and replays. */\n reload: () => void\n /** The replayed items, memoized until the next change. */\n read: () => readonly T[]\n /** The replayed section, with provenance. */\n value: () => SectionValue<T>\n /** Transforms that threw on the last replay. */\n failures: () => readonly TransformFailure[]\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n}\n\nfunction defaultIsSourced<T>(entry: T | Sourced<T>): entry is Sourced<T> {\n if (entry === null || typeof entry !== 'object')\n return false\n const keys = Object.keys(entry)\n return keys.length === 2 && keys.includes('item') && keys.includes('origin')\n}\n\n/** Creates a catalog with one keyed collection: the generic transform engine. */\nexport function createCatalog<T>(spec: CatalogSpec<T>): Catalog<T> {\n const isSourced = spec.isSourced ?? defaultIsSourced\n const set = createCatalogSet<{ items: T }, undefined, void>({\n name: spec.name ?? 'catalog',\n order: spec.order,\n cacheSize: spec.cacheSize,\n sections: {\n items: {\n key: spec.key,\n clone: spec.clone,\n base: () => spec.base().map(entry => isSourced(entry) ? entry : { item: entry, origin: BUILTIN }),\n },\n },\n })\n return {\n register: (item, origin) => set.register('items', item, origin),\n transform: (fn, extensionId, guard) => set.transform({ extensionId, guard, apply: draft => fn(draft.sections.items) }),\n reload: set.reload,\n read: () => set.read().sections.items.items,\n value: () => set.read().sections.items,\n failures: () => set.read().failures,\n subscribe: set.subscribe,\n }\n}\n\n/** Wraps a function so it runs at most once: the Disposable contract. */\nexport function once(fn: () => void): Disposable {\n let done = false\n return {\n dispose() {\n if (done)\n return\n done = true\n fn()\n },\n }\n}\n","/**\n * Glue between the shared catalogs and one extension's domain: owner\n * binding, guarded transforms, extension origins.\n */\n\nimport type { Disposable, ItemOrigin, Transform } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { CatalogDraft, CatalogSet, Sections } from './engine'\nimport { DisposedError } from '../api'\nimport { once } from './engine'\n\n/** A host port that can re-read external data before a catalog replays. */\nexport interface RefreshablePort {\n /** Re-reads the base (config files, a server list). `reload()` awaits it before replaying. */\n refresh?: () => Promise<void>\n}\n\n/** The origin of items the extension registers. */\nexport function extensionOrigin(deps: DomainDeps): ItemOrigin {\n return { kind: 'extension', id: deps.extensionId }\n}\n\n/**\n * Makes a registration through the extension's owner: refused once the owner\n * is disposed, withdrawn when it is, and withdrawable on its own.\n */\nexport function owned(deps: DomainDeps, what: string, make: () => Disposable): Disposable {\n if (deps.owner.disposed)\n throw new DisposedError(what)\n const inner = make()\n let cleanup: Disposable | undefined\n const handle = once(() => {\n cleanup?.dispose()\n inner.dispose()\n })\n cleanup = deps.owner.onCleanup(() => handle.dispose())\n return handle\n}\n\n/** Registers `fn` as a guarded transform of `set`, with the editor `makeEditor` builds. */\nexport function addTransform<S extends Sections, X, C, E>(\n deps: DomainDeps,\n set: CatalogSet<S, X, C>,\n what: string,\n makeEditor: (draft: CatalogDraft<S, X, C>) => E,\n fn: Transform<E>,\n): Disposable {\n if (typeof fn !== 'function')\n throw new TypeError(`${what}: transform must be a function`)\n return owned(deps, what, () => set.transform({\n extensionId: deps.extensionId,\n guard: deps.guard,\n label: what,\n apply: draft => fn(makeEditor(draft)),\n }))\n}\n\n/** `reload()` of a catalog domain: refresh the port, then drop the cached base. */\nexport function reloadWith(set: { reload: () => void }, port: RefreshablePort): () => Promise<void> {\n return async () => {\n await port.refresh?.()\n set.reload()\n }\n}\n","/**\n * The models catalog: `ctx.models`. Models of the active providers, keyed\n * by provider and model id, plus the default selection. Models are not added\n * here: a provider brings them (see `ctx.providers`).\n */\n\nimport type { Disposable, ItemOrigin, ModelEditor, ModelInfo, ModelsDomain } from '../api'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogDraft, CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\n\n/** The catalog id of a model: `<providerId>/<modelId>`. */\nexport function modelKey(providerId: string, modelId: string): string {\n return `${providerId}/${modelId}`\n}\n\n/** A model selection. */\nexport interface ModelSelection {\n /** Provider id. */\n readonly providerId: string\n /** Model id. */\n readonly modelId: string\n}\n\n/** Supplies the base models and default. The host connects the active providers (after `providers` transforms). */\nexport interface ModelsCatalogPort extends RefreshablePort {\n /** Models of the active providers. */\n models: () => readonly Sourced<ModelInfo>[]\n /** The configured default selection. */\n default?: () => ModelSelection | undefined\n}\n\n/** Catalog-wide model state. */\nexport interface ModelsState {\n /** The default selection. */\n default?: ModelSelection\n /** The extension whose transform set it. */\n defaultSetBy?: string\n}\n\n/** Section item types of the models catalog. */\nexport interface ModelsSections {\n /** Models, by {@link modelKey}. */\n models: ModelInfo\n}\n\n/** A replayed models value. `state.default` is cleared when its model is gone. */\nexport type ModelsValue = CatalogValue<ModelsSections, ModelsState>\n\n/** The shared models catalog a host builds once. */\nexport interface ModelsCatalog {\n /** The replayed value. */\n read: () => ModelsValue\n /** Adds a model outside the provider base (host use; extensions go through providers). */\n register: (model: ModelInfo, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createModelsEngine>\n}\n\nfunction createModelsEngine(port: ModelsCatalogPort, options: CatalogOptions) {\n return createCatalogSet<ModelsSections, ModelsState, void>({\n ...options,\n name: 'models',\n sections: { models: { key: model => modelKey(model.providerId, model.id), base: () => port.models() } },\n state: {\n base: () => {\n const selection = port.default?.()\n return selection ? { default: { ...selection } } : {}\n },\n clone: state => ({ ...state }),\n },\n })\n}\n\nfunction modelEditor(draft: CatalogDraft<ModelsSections, ModelsState, void>): ModelEditor {\n const models = draft.sections.models\n return {\n list: providerId => providerId === undefined ? models.list() : models.list().filter(model => model.providerId === providerId),\n get: (providerId, modelId) => models.get(modelKey(providerId, modelId)),\n update: (providerId, modelId, edit) => models.update(modelKey(providerId, modelId), edit),\n remove: (providerId, modelId) => models.remove(modelKey(providerId, modelId)),\n default: {\n get: () => {\n draft.assertOpen()\n return draft.state.default ? { ...draft.state.default } : undefined\n },\n set: (providerId, modelId) => {\n draft.assertOpen()\n if (!models.get(modelKey(providerId, modelId)))\n throw new Error(`models.default.set: no model \"${modelKey(providerId, modelId)}\"`)\n draft.state = { default: { providerId, modelId }, defaultSetBy: draft.extensionId }\n },\n },\n }\n}\n\n/** Creates the shared models catalog. */\nexport function createModelsCatalog(port: ModelsCatalogPort, options: CatalogOptions = {}): ModelsCatalog {\n const engine = createModelsEngine(port, options)\n return {\n engine,\n read: () => {\n const value = engine.read()\n const selection = value.state.default\n if (!selection || value.sections.models.get(modelKey(selection.providerId, selection.modelId)))\n return value\n return Object.freeze({ ...value, state: Object.freeze({}) })\n },\n register: (model, origin) => engine.register('models', model, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.models` over the shared catalog. */\nexport function createModelsDomain(deps: DomainDeps, catalog: ModelsCatalog): ModelsDomain {\n return {\n transform: fn => addTransform(deps, catalog.engine, 'models.transform', modelEditor, fn),\n reload: catalog.reload,\n list: () => catalog.read().sections.models.items,\n default: () => {\n const selection = catalog.read().state.default\n return selection ? { providerId: selection.providerId, modelId: selection.modelId } : undefined\n },\n }\n}\n","/**\n * The providers catalog: `ctx.providers`. Provider descriptors (active or\n * not) and the models each provider offers, edited together by one\n * {@link ProviderEditor} per transform. Removing a provider removes its\n * models. The host feeds the models of active providers into the models catalog.\n *\n * A provider can also hold a model list per account (`models.set(id, list,\n * { account })`): the list a picker shows for that account. Accounts without\n * one fall back to the provider's own list. Provider transforms read accounts,\n * so hosts re-run them when accounts change ({@link watchProviderAccounts}).\n */\n\nimport type { ProviderDescriptor } from '../../chat/providers'\nimport type { Disposable, ItemOrigin, ModelInfo, ProviderEditor, ProvidersDomain } from '../api'\nimport type { IntegrationRegistry } from '../integrations/registry'\nimport type { DomainDeps } from '../runtime/deps'\nimport type { RefreshablePort } from './domain'\nimport type { CatalogDraft, CatalogOptions, CatalogValue, Sourced } from './engine'\nimport { addTransform, extensionOrigin, owned, reloadWith } from './domain'\nimport { createCatalogSet } from './engine'\nimport { modelKey } from './models'\n\n/** Supplies the base descriptors and their models. The host connects the provider registry. */\nexport interface ProvidersCatalogPort extends RefreshablePort {\n /** Built-in and config provider descriptors. */\n providers: () => readonly Sourced<ProviderDescriptor>[]\n /** Models of those providers. */\n models?: () => readonly Sourced<ModelInfo>[]\n}\n\n/** Section item types of the providers catalog. */\nexport interface ProvidersSections {\n /** Descriptors, by `key`. */\n providers: ProviderDescriptor\n /** Models, by `<providerId>/<modelId>` (see {@link modelKey}). */\n models: ModelInfo\n /** Account-scoped models, by {@link accountModelKey}. */\n accountModels: AccountModelInfo\n}\n\n/** A model of one account's list (`models.set(providerId, list, { account })`). */\nexport interface AccountModelInfo extends ModelInfo {\n /** The account whose list holds it. */\n account: string\n}\n\n/**\n * The catalog id of an account-scoped model: `<providerId>@<account>/<modelId>`.\n *\n * @param providerId - Provider id.\n * @param account - The account the list belongs to.\n * @param modelId - Model id.\n */\nexport function accountModelKey(providerId: string, account: string, modelId: string): string {\n return `${providerId}@${account}/${modelId}`\n}\n\n/** A replayed providers value. */\nexport type ProvidersValue = CatalogValue<ProvidersSections, undefined>\n\n/** The shared providers catalog a host builds once. */\nexport interface ProvidersCatalog {\n /** The replayed value. */\n read: () => ProvidersValue\n /**\n * Models of one provider (or all), after transforms. With `account` (and a\n * provider): that account's own list when it has one, else the provider's.\n */\n models: (providerId?: string, opts?: { account?: string }) => readonly ModelInfo[]\n /** The accounts of a provider that have their own model list, in insertion order. */\n accounts: (providerId: string) => readonly string[]\n /** Adds a descriptor. */\n register: (descriptor: ProviderDescriptor, origin: ItemOrigin) => Disposable\n /** Re-reads the base and replays. */\n reload: () => Promise<void>\n /** Calls `listener` after each change. */\n subscribe: (listener: () => void) => () => void\n /**\n * Engine access for the domain factory.\n *\n * @internal\n */\n readonly engine: ReturnType<typeof createProvidersEngine>\n}\n\nfunction createProvidersEngine(port: ProvidersCatalogPort, options: CatalogOptions) {\n return createCatalogSet<ProvidersSections, undefined, void>({\n ...options,\n name: 'providers',\n sections: {\n providers: { key: descriptor => descriptor.key, base: () => port.providers() },\n models: { key: model => modelKey(model.providerId, model.id), base: () => port.models?.() ?? [] },\n accountModels: { key: model => accountModelKey(model.providerId, model.account, model.id), base: () => [] },\n },\n })\n}\n\nfunction providerEditor(draft: CatalogDraft<ProvidersSections, undefined, void>): ProviderEditor {\n const providers = draft.sections.providers\n const models = draft.sections.models\n const accountModels = draft.sections.accountModels\n const modelsOf = (providerId: string) => models.list().filter(model => model.providerId === providerId)\n const accountModelsOf = (providerId: string, account?: string) => accountModels.list().filter(model => model.providerId === providerId && (account === undefined || model.account === account))\n const checkOwner = (providerId: string, next: readonly ModelInfo[]): void => {\n for (const model of next) {\n if (model.providerId !== providerId)\n throw new Error(`providers.models.set: model \"${model.id}\" belongs to \"${model.providerId}\", not \"${providerId}\"`)\n }\n }\n return {\n list: providers.list,\n get: providers.get,\n origin: providers.origin,\n add: providers.add,\n update: providers.update,\n remove: (id) => {\n providers.remove(id)\n for (const model of modelsOf(id))\n models.remove(modelKey(id, model.id))\n for (const model of accountModelsOf(id))\n accountModels.remove(accountModelKey(id, model.account, model.id))\n },\n models: {\n set: (providerId, next, opts) => {\n checkOwner(providerId, next)\n const wanted = new Set(next.map(model => model.id))\n const account = opts?.account\n if (account !== undefined) {\n if (typeof account !== 'string' || account.length === 0)\n throw new TypeError('providers.models.set: account must be a non-empty string')\n for (const model of accountModelsOf(providerId, account)) {\n if (!wanted.has(model.id))\n accountModels.remove(accountModelKey(providerId, account, model.id))\n }\n for (const model of next)\n accountModels.replace({ ...model, account })\n return\n }\n for (const model of modelsOf(providerId)) {\n if (!wanted.has(model.id))\n models.remove(modelKey(providerId, model.id))\n }\n for (const model of next)\n models.replace(model)\n },\n // An edit by id applies to every list that holds the model: the provider's and each account's.\n update: (providerId, modelId, edit) => {\n models.update(modelKey(providerId, modelId), edit)\n for (const model of accountModelsOf(providerId)) {\n if (model.id === modelId)\n accountModels.update(accountModelKey(providerId, model.account, modelId), edit)\n }\n },\n remove: (providerId, modelId) => {\n models.remove(modelKey(providerId, modelId))\n for (const model of accountModelsOf(providerId)) {\n if (model.id === modelId)\n accountModels.remove(accountModelKey(providerId, model.account, modelId))\n }\n },\n },\n }\n}\n\n/** Creates the shared providers catalog. */\nexport function createProvidersCatalog(port: ProvidersCatalogPort, options: CatalogOptions = {}): ProvidersCatalog {\n const engine = createProvidersEngine(port, options)\n return {\n engine,\n read: () => engine.read(),\n models: (providerId, opts) => {\n const value = engine.read()\n if (providerId === undefined)\n return value.sections.models.items\n const account = opts?.account\n if (account !== undefined) {\n const own = value.sections.accountModels.items.filter(model => model.providerId === providerId && model.account === account)\n if (own.length > 0)\n return own.map(({ account: _account, ...model }) => model)\n }\n return value.sections.models.items.filter(model => model.providerId === providerId)\n },\n accounts: (providerId) => {\n const out = new Set<string>()\n for (const model of engine.read().sections.accountModels.items) {\n if (model.providerId === providerId)\n out.add(model.account)\n }\n return [...out]\n },\n register: (descriptor, origin) => engine.register('providers', descriptor, origin),\n reload: reloadWith(engine, port),\n subscribe: engine.subscribe,\n }\n}\n\n/** Creates one extension's `ctx.providers` over the shared catalog. */\nexport function createProvidersDomain(deps: DomainDeps, catalog: ProvidersCatalog): ProvidersDomain {\n return {\n register(descriptor) {\n if (!descriptor || typeof descriptor.key !== 'string' || descriptor.key.length === 0)\n throw new TypeError('providers.register: descriptor needs a non-empty key')\n if (typeof descriptor.factory !== 'function')\n throw new TypeError(`providers.register: \"${descriptor.key}\" needs a factory`)\n return owned(deps, 'providers.register', () => catalog.register(descriptor, extensionOrigin(deps)))\n },\n transform: fn => addTransform(deps, catalog.engine, 'providers.transform', providerEditor, fn),\n reload: catalog.reload,\n list: () => catalog.read().sections.providers.items,\n }\n}\n\n/** Something that says when provider accounts change. Returns the unsubscribe. */\nexport type AccountChangeSource = (listener: () => void) => () => void\n\n/**\n * Re-runs provider transforms (`catalog.reload()`) when accounts change: any\n * integration connection (connect, disconnect, a new default) and any other\n * source the host passes (its stored provider accounts). Changes in one turn\n * of the event loop reload once. Returns the unsubscribe.\n *\n * @param catalog - The providers catalog.\n * @param integrations - The integration registry, when the host has one.\n * @param sources - Other account change sources (the credentials file).\n */\nexport function watchProviderAccounts(catalog: Pick<ProvidersCatalog, 'reload'>, integrations: Pick<IntegrationRegistry, 'subscribe'> | undefined, sources: readonly AccountChangeSource[] = []): () => void {\n let queued = false\n let stopped = false\n const changed = (): void => {\n if (queued || stopped)\n return\n queued = true\n queueMicrotask(() => {\n queued = false\n if (!stopped)\n void catalog.reload()\n })\n }\n const offs = [...(integrations ? [integrations.subscribe(changed)] : []), ...sources.map(source => source(changed))]\n return () => {\n stopped = true\n for (const off of offs)\n off()\n }\n}\n"],"mappings":";;;;;;;;AAuBA,SAAS,gBAAgB,aAAqB,QAA6D;CACzG,OAAO,OAAO,KAAI,UAChB,MAAM,UAAU,CAAC,MAAM,OAAO,SAAS,SAAS,GAAG,IAC/C;EAAE,GAAG;EAAO,QAAQ;GAAE,GAAG,MAAM;GAAQ,UAAU,GAAG,YAAY,GAAG,MAAM,OAAO;EAAW;CAAE,IAC7F,KAAK;AACb;;;;;;;AAgBA,SAAgB,0BAA0B,OAA4C;CACpF,IAAI,UAAU,KAAA,GACZ,QAAQ,CAAC;CACX,IAAI,OAAO,UAAU,UACnB,MAAM,IAAI,kBAAkB,CAAC;EAAE,MAAM;EAAS,SAAS,qDAAqD,MAAM;CAAK,CAAC,CAAC;CAC3H,IAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAC5D,MAAM,IAAI,kBAAkB,CAAC;EAAE,MAAM;EAAS,SAAS;CAAwD,CAAC,CAAC;CACnH,MAAM,IAAI;CACV,MAAM,SAA8B,CAAC;CACrC,KAAK,MAAM,OAAO,OAAO,KAAK,CAAC,GAC7B,IAAI,CAAC;EAAC;EAAS;EAAQ;EAAS;EAAU;CAAU,CAAC,CAAC,SAAS,GAAG,GAChE,OAAO,KAAK;EAAE,MAAM;EAAK,SAAS;CAA0E,CAAC;CAEjH,IAAI,EAAE,UAAU,KAAA,GACd,OAAO,KAAK,GAAG,cAAc,EAAE,KAAK,CAAC;CACvC,IAAI,EAAE,SAAS,KAAA,GACb,OAAO,KAAK,GAAG,aAAa,EAAE,IAAI,CAAC;CACrC,MAAM,QAAQ,EAAE,SAAA;CAChB,IAAI,CAAC,OAAO,UAAU,KAAK,KAAM,QAAmB,KAAM,QAAA,KACxD,OAAO,KAAK;EAAE,MAAM;EAAS,SAAS;CAA6D,CAAC;CACtG,IAAI,EAAE,WAAW,KAAA,MAAc,OAAO,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GACnB,SAAS;GACT,IAAI,CAAC,SACH,QAAa,OAAO;EACxB,CAAC;CACH;CACA,MAAM,OAAO,CAAC,GAAI,eAAe,CAAC,aAAa,UAAU,OAAO,CAAC,IAAI,CAAC,GAAI,GAAG,QAAQ,KAAI,WAAU,OAAO,OAAO,CAAC,CAAC;CACnH,aAAa;EACX,UAAU;EACV,KAAK,MAAM,OAAO,MAChB,IAAI;CACR;AACF"}
@@ -1,3 +1,3 @@
1
- import { $A as NEURALWATT_DEFAULT_MODEL, $k as Provider, AA as OpenAICompatAuthHeader, AM as ImageAspectRatio, Aj as GeminiRequest, BA as mapOAIFinishReason, Bj as baseten, DM as OPENAI_IMAGE_MODELS, Dj as GeminiFunctionDeclaration, EA as openrouter, EM as openrouterImageModels, Ej as GeminiContent, FM as ProviderImageRequest, Fj as CursorParams, HA as openaiCompat, Hj as ArceeParams, IM as ProviderImageResponse, Ij as cursor, JA as OpenAIParams, JI as ModelCatalogEntry, LM as ProviderImages, Lj as CerebrasParams, MA as OpenAICompatParams, MM as ImageModelInfo, Mj as GeminiThinkingConfig, NM as MAX_IMAGES_PER_REQUEST, Nj as GeminiToolConfig, OM as GOOGLE_IMAGE_MODELS, Oj as GeminiGenerationConfig, PM as ProviderImageAvailability, Pj as GoogleWireModel, QI as setModelCatalog, Qk as InputTransformation, RA as classifyOpenAICompatError, Rj as cerebras, SA as sanitizeToolSpecs, TM as XAI_IMAGE_MODELS, Uj as arcee, Vj as planBasetenReasoning, Wj as anthropic, XI as ModelTier, YI as ModelCatalogSource, ZA as openai, ZI as getModelCatalog, Zk as HistoryRepair, _A as xai, _M as registerCustomOAuthProvider, aA as ProviderMeta, aM as PromptCacheKeyOption, aj as planMistralReasoning, bA as SchemaSanitizeResult, bj as googleCompatible, cA as TokenCountPayload, cM as OAuthParams, dA as ToolSpec, dM as credentialsFromParams, eA as ProviderCapabilities, eM as applyAnthropicCacheBreakpoints, ej as NeuralwattParams, fA as TurnResult, fM as extractRuntimeCredentials, fj as GoogleParams, gA as XaiParams, gM as readOAuthCredentials, gj as GoogleVertexParams, hA as zai, hM as readAccountOAuthCredential, hj as GoogleTurnRequest, iA as ProviderDecisions, iM as PromptCacheKeyContext, ij as mistral, jA as OpenAICompatHttpError, jM as ImageData, jj as GeminiResponseChunk, kM as IMAGE_ASPECT_RATIOS, kj as GeminiPart, lA as ToolCall, lM as ResolveOAuthApiKeyOptions, mA as planZaiReasoning, mM as pinnedAccountMissingError, mj as GoogleSharedParams, nA as ProviderDecisionRequest, nj as planNeuralwattReasoning, oA as StreamCallbacks, oM as derivePromptCacheKey, oj as LocalParams, pA as ZaiParams, pM as isOAuthAccessToken, qI as ModelCatalog, rA as ProviderDecisionResponse, rM as AnthropicParams, rj as MistralParams, sA as StreamOptions, sM as resolvePromptCacheKey, sj as local, tA as ProviderDecisionAvailability, tj as neuralwatt, uA as ToolResult, uM as credentialsFilePath, uj as GoogleCompatibleRoute, vA as SchemaSanitizeOptions, vM as resolveOAuthApiKey, vj as classifyGoogleError, wA as OpenRouterParams, wj as GeminiTool, xA as sanitizeToolSchema, xj as googleVertex, yA as SchemaSanitizeProfile, yM as writeOAuthCredentials, yj as google, zj as BasetenParams } from "./index-CGbOWa7y.js";
1
+ import { $A as SchemaSanitizeProfile, $M as writeOAuthCredentials, $j as google, AL as ModelCatalogSource, BA as StreamCallbacks, BM as derivePromptCacheKey, Bj as LocalParams, CM as arcee, FA as ProviderDecisionAvailability, Fj as neuralwatt, GA as ToolSpec, GM as credentialsFromParams, HA as TokenCountPayload, HM as OAuthParams, IA as ProviderDecisionRequest, Ij as planNeuralwattReasoning, JA as planZaiReasoning, JM as pinnedAccountMissingError, Jj as GoogleSharedParams, KA as TurnResult, KM as extractRuntimeCredentials, Kj as GoogleParams, LA as ProviderDecisionResponse, LM as AnthropicParams, Lj as MistralParams, MA as InputTransformation, ML as getModelCatalog, NA as Provider, NL as setModelCatalog, Nj as NEURALWATT_DEFAULT_MODEL, OL as ModelCatalog, Oj as OpenAIParams, PA as ProviderCapabilities, PM as applyAnthropicCacheBreakpoints, Pj as NeuralwattParams, QA as SchemaSanitizeOptions, QM as resolveOAuthApiKey, Qj as classifyGoogleError, RA as ProviderDecisions, RM as PromptCacheKeyContext, Rj as mistral, SM as ArceeParams, Sj as openaiCompat, UA as ToolCall, UM as ResolveOAuthApiKeyOptions, VA as StreamOptions, VM as resolvePromptCacheKey, Vj as local, WA as ToolResult, WM as credentialsFilePath, Wj as GoogleCompatibleRoute, XA as XaiParams, XM as readOAuthCredentials, Xj as GoogleVertexParams, YA as zai, YM as readAccountOAuthCredential, Yj as GoogleTurnRequest, ZA as xai, ZM as registerCustomOAuthProvider, _M as CerebrasParams, _N as ProviderImages, aN as XAI_IMAGE_MODELS, bM as baseten, bj as mapOAIFinishReason, cM as GeminiGenerationConfig, cN as GOOGLE_IMAGE_MODELS, dM as GeminiResponseChunk, dN as ImageData, dj as OpenAICompatHttpError, eM as googleCompatible, ej as SchemaSanitizeResult, fM as GeminiThinkingConfig, fN as ImageModelInfo, fj as OpenAICompatParams, gM as cursor, gN as ProviderImageResponse, hM as CursorParams, hN as ProviderImageRequest, iM as GeminiTool, ij as OpenRouterParams, jA as HistoryRepair, jL as ModelTier, jj as openai, kL as ModelCatalogEntry, lM as GeminiPart, lN as IMAGE_ASPECT_RATIOS, mM as GoogleWireModel, mN as ProviderImageAvailability, nj as sanitizeToolSpecs, oM as GeminiContent, oN as openrouterImageModels, oj as openrouter, pM as GeminiToolConfig, pN as MAX_IMAGES_PER_REQUEST, qA as ZaiParams, qM as isOAuthAccessToken, sM as GeminiFunctionDeclaration, sN as OPENAI_IMAGE_MODELS, tM as googleVertex, tj as sanitizeToolSchema, uM as GeminiRequest, uN as ImageAspectRatio, uj as OpenAICompatAuthHeader, vM as cerebras, vj as classifyOpenAICompatError, wM as anthropic, xM as planBasetenReasoning, yM as BasetenParams, zA as ProviderMeta, zM as PromptCacheKeyOption, zj as planMistralReasoning } from "./index-WlE93Q6d.js";
2
2
  import { a as getOAuthApiKey, c as refreshOpenAICodexToken, i as ensureBundledOAuthFlows, l as registerOAuthProvider, o as getOAuthProvider, r as OAuthProviderInterface, s as refreshAnthropicToken } from "./oauth-callback-page-DMxIgurj.js";
3
3
  export { type AnthropicParams, type ArceeParams, type BasetenParams, type CerebrasParams, type CursorParams, GOOGLE_IMAGE_MODELS, type GeminiContent, type GeminiFunctionDeclaration, type GeminiGenerationConfig, type GeminiPart, type GeminiRequest, type GeminiResponseChunk, type GeminiThinkingConfig, type GeminiTool, type GeminiToolConfig, type GoogleCompatibleRoute, type GoogleParams, type GoogleSharedParams, type GoogleTurnRequest, type GoogleVertexParams, type GoogleWireModel, HistoryRepair, IMAGE_ASPECT_RATIOS, type ImageAspectRatio, type ImageData, type ImageModelInfo, InputTransformation, type LocalParams, MAX_IMAGES_PER_REQUEST, type MistralParams, type ModelCatalog, type ModelCatalogEntry, type ModelCatalogSource, type ModelTier, NEURALWATT_DEFAULT_MODEL, type NeuralwattParams, type OAuthParams, type OAuthProviderInterface, OPENAI_IMAGE_MODELS, type OpenAICompatAuthHeader, OpenAICompatHttpError, type OpenAICompatParams, type OpenAIParams, type OpenRouterParams, type PromptCacheKeyContext, type PromptCacheKeyOption, Provider, ProviderCapabilities, ProviderDecisionAvailability, ProviderDecisionRequest, ProviderDecisionResponse, ProviderDecisions, type ProviderImageAvailability, type ProviderImageRequest, type ProviderImageResponse, type ProviderImages, ProviderMeta, type ResolveOAuthApiKeyOptions, type SchemaSanitizeOptions, type SchemaSanitizeProfile, type SchemaSanitizeResult, StreamCallbacks, StreamOptions, TokenCountPayload, ToolCall, ToolResult, ToolSpec, TurnResult, XAI_IMAGE_MODELS, type XaiParams, type ZaiParams, anthropic, applyAnthropicCacheBreakpoints, arcee, baseten, cerebras, classifyGoogleError, classifyOpenAICompatError, credentialsFilePath, credentialsFromParams, cursor, derivePromptCacheKey, ensureBundledOAuthFlows, extractRuntimeCredentials, getModelCatalog, getOAuthApiKey, getOAuthProvider, google, googleCompatible, googleVertex, isOAuthAccessToken, local, mapOAIFinishReason, mistral, neuralwatt, openai, openaiCompat, openrouter, openrouterImageModels, pinnedAccountMissingError, planBasetenReasoning, planMistralReasoning, planNeuralwattReasoning, planZaiReasoning, readAccountOAuthCredential, readOAuthCredentials, refreshAnthropicToken, refreshOpenAICodexToken, registerCustomOAuthProvider, registerOAuthProvider, resolveOAuthApiKey, resolvePromptCacheKey, sanitizeToolSchema, sanitizeToolSpecs, setModelCatalog, writeOAuthCredentials, xai, zai };
package/dist/providers.js CHANGED
@@ -5,7 +5,7 @@ import { arcee } from "./providers/arcee.js";
5
5
  import { baseten, planBasetenReasoning } from "./providers/baseten.js";
6
6
  import { cerebras } from "./providers/cerebras.js";
7
7
  import { a as cursor, i as planMistralReasoning, n as zai, r as mistral, t as planZaiReasoning } from "./providers-CShv3UgY.js";
8
- import { a as googleCompatible, i as google, l as GOOGLE_IMAGE_MODELS, o as googleVertex, r as classifyGoogleError } from "./google-Crva32sk.js";
8
+ import { a as googleCompatible, i as google, l as GOOGLE_IMAGE_MODELS, o as googleVertex, r as classifyGoogleError } from "./google-BtMW9KzL.js";
9
9
  import { n as MAX_IMAGES_PER_REQUEST, t as IMAGE_ASPECT_RATIOS } from "./types-JzccL5GE.js";
10
10
  import { o as OPENAI_IMAGE_MODELS, r as openai } from "./openai-CQw3EVu6.js";
11
11
  import { a as openrouterImageModels, r as openrouter } from "./openrouter-CgBpQR6G.js";
@@ -1,6 +1,6 @@
1
1
  import { s as loadSession } from "./session-BORxmqlM.js";
2
2
  import { n as createSqliteDriver, t as OPEN_BUSY_TIMEOUT_MS } from "./sqlite-driver-Xc4U0PRB.js";
3
- import { h as replayTurns } from "./store-C6gI7FfZ.js";
3
+ import { h as replayTurns } from "./store-ByCDaKgJ.js";
4
4
  import { i as LOAD_EVENTS_MAX_PAGE_TURNS } from "./protocol-DOGyHgLQ.js";
5
5
  //#region src/ipc/daemon/handlers/params.ts
6
6
  /**
@@ -432,4 +432,4 @@ async function openReadonlySqlite(path) {
432
432
  //#endregion
433
433
  export { exchangeBoundaries as a, turnCutPoints as c, checkParams as d, nonNegativeInt as f, sessionIdOf as h, WHOLE_RUN_PAGES as i, loadOrThrow as l, requiredString as m, changedSessionOf as n, isPagedLoad as o, optionalString as p, createTranscriptReplayCache as r, transcriptPage as s, openReadonlySqlite as t, InvalidParamsError as u };
434
434
 
435
- //# sourceMappingURL=readonly-db-D7Z-k0pQ.js.map
435
+ //# sourceMappingURL=readonly-db-DrbT8tX6.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"readonly-db-D7Z-k0pQ.js","names":[],"sources":["../src/ipc/daemon/handlers/params.ts","../src/ipc/daemon/handlers/session-load.ts","../src/ipc/daemon/handlers/transcript-page.ts","../src/ipc/daemon/handlers/transcript-cache.ts","../src/ipc/history/readonly-db.ts"],"sourcesContent":["/**\n * Shape checks for request params: they arrive as untrusted JSON (the\n * `IpcMethods` types are not a runtime guarantee). The dispatcher runs\n * {@link checkParams} on every request and notification before its handler;\n * handlers use the field checks for what they require. A failed check is an\n * {@link InvalidParamsError}, answered as JSON-RPC \"invalid params\".\n */\n\nexport class InvalidParamsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidParamsError'\n }\n}\n\n/** Longest session id accepted (minted ids are under 64 characters). */\nconst MAX_SESSION_ID_LENGTH = 1024\n\n/**\n * A session id: a non-empty string that is one plain path segment. Ids name\n * directories on disk (`<data dir>/sessions/<id>/`, removed recursively on\n * delete), so `..`, separators and NUL are refused.\n */\nexport function checkSessionId(value: unknown, name = 'sessionId'): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_SESSION_ID_LENGTH)\n throw new InvalidParamsError(`${name} must be a non-empty string of at most ${MAX_SESSION_ID_LENGTH} characters.`)\n if (value === '.' || value === '..' || /[/\\\\\\0]/.test(value))\n throw new InvalidParamsError(`${name} must not be a path (no \"/\", \"\\\\\", \".\" or \"..\").`)\n return value\n}\n\n/** The required `sessionId` of `params`. */\nexport function sessionIdOf(params: { sessionId?: unknown } | null | undefined): string {\n return checkSessionId(params?.sessionId)\n}\n\n/** An optional non-negative integer; `undefined` when absent. */\nexport function nonNegativeInt(value: unknown, name: string): number | undefined {\n if (value === undefined)\n return undefined\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)\n throw new InvalidParamsError(`${name} must be a non-negative integer.`)\n return value\n}\n\n/** A non-empty string. */\nexport function requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.length === 0)\n throw new InvalidParamsError(`${name} must be a non-empty string.`)\n return value\n}\n\n/** An optional string; `undefined` when absent. */\nexport function optionalString(value: unknown, name: string): string | undefined {\n if (value !== undefined && typeof value !== 'string')\n throw new InvalidParamsError(`${name} must be a string.`)\n return value\n}\n\n/**\n * What every method's params must be: absent, `null`, or an object (never an\n * array or a scalar), whose `sessionId` / `sessionIds`, when present, name\n * sessions ({@link checkSessionId}).\n */\nexport function checkParams(params: unknown): void {\n if (params === undefined || params === null)\n return\n if (typeof params !== 'object' || Array.isArray(params))\n throw new InvalidParamsError('params must be an object.')\n const { sessionId, sessionIds } = params as { sessionId?: unknown, sessionIds?: unknown }\n if (sessionId !== undefined)\n checkSessionId(sessionId)\n if (sessionIds !== undefined) {\n if (!Array.isArray(sessionIds))\n throw new InvalidParamsError('sessionIds must be an array.')\n for (const id of sessionIds)\n checkSessionId(id, 'sessionIds[]')\n }\n}\n","/** A stored session or a \"not found\" error: kept apart from `./sessions` so the history worker loads without the chat host's graph. */\nimport type { SessionData, SessionStore } from '../../../session/index'\n\nexport async function loadOrThrow(store: Pick<SessionStore, 'load'>, sessionId: string): Promise<SessionData> {\n const data = await store.load(sessionId)\n if (!data)\n throw new Error(`Session \"${sessionId}\" not found.`)\n return data\n}\n","/**\n * One page of a transcript for `sessions.loadEvents` paging, in whole runs:\n * everything from a user message to the turn before the next one. The run\n * the page ends in is always whole, and the runs before it join while the\n * page stays within `limit` turns, so scrolling back brings the previous\n * run (or a few small ones) at a time, never part of one. A run longer than\n * {@link WHOLE_RUN_PAGES} pages on its own is the one exception: it comes in\n * pieces of that size, each starting on a turn that keeps a tool call with\n * its result. The GUI's local pager cuts with the same rule.\n */\nimport type { SessionRun } from '../../../session/index'\nimport type { SessionTurn } from '../../../types'\nimport type { LoadEventsPaging } from '../../protocol'\nimport { LOAD_EVENTS_MAX_PAGE_TURNS, LOAD_EVENTS_PAGE_TURNS } from '../../protocol'\nimport { InvalidParamsError, nonNegativeInt, optionalString } from './params'\n\n/**\n * A run longer than this many pages is split (by `limit`, so the client's\n * halving retry on a reply too large still converges).\n */\nexport const WHOLE_RUN_PAGES = 5\n\nexport function isPagedLoad(p: LoadEventsPaging | undefined): boolean {\n return p?.before !== undefined || p?.limit !== undefined || p?.beforeTurnId !== undefined\n}\n\n/**\n * Per turn: does a run start there (a parent-run user turn carrying no tool result, not loop-injected)?\n * @param turns - Turns of the session, in order.\n * @param runs - Runs of the session, used to tell child runs from parent runs.\n * @returns One flag per turn.\n */\nexport function exchangeBoundaries(turns: readonly SessionTurn[], runs: readonly SessionRun[]): boolean[] {\n const childRuns = new Set(runs.filter(run => (run.depth ?? 0) > 0 || run.parentRunId !== undefined).map(run => run.id))\n return turns.map(turn => turn.role === 'user'\n && !turn.injected\n && !(turn.runId !== undefined && childRuns.has(turn.runId))\n && !turn.content.some(block => block.type === 'tool_result'))\n}\n\n/**\n * Per turn: can a page start there without leaving a tool call's result behind (not a tool-result turn)?\n * @param turns - Turns of the session, in order.\n * @returns One flag per turn.\n */\nexport function turnCutPoints(turns: readonly SessionTurn[]): boolean[] {\n return turns.map(turn => !(turn.role === 'user' && turn.content.some(block => block.type === 'tool_result')))\n}\n\n/**\n * `[from, to)` of the page, and the cursor of the one before it, over the\n * turns' {@link exchangeBoundaries} (run starts) and {@link turnCutPoints}\n * (where a run too long to send whole may be split; run starts when absent).\n * @param boundaries - Run starts per turn, from {@link exchangeBoundaries}.\n * @param paging - The `before` cursor and `limit` of the request.\n * @param cuts - Allowed cut points per turn, from {@link turnCutPoints}.\n * @param turnIds - Id per turn: where a `beforeTurnId` anchor sits (it wins over `before`).\n * @returns The turn range of the page and the cursor of the page before it.\n */\nexport function transcriptPage(\n boundaries: readonly boolean[],\n paging: LoadEventsPaging,\n cuts: readonly boolean[] = boundaries,\n turnIds?: readonly string[],\n): { from: number, to: number, cursor?: number } {\n const before = anchorIndex(paging.beforeTurnId, turnIds) ?? nonNegativeInt(paging.before, 'before')\n const limit = Math.min(Math.max(nonNegativeInt(paging.limit, 'limit') ?? LOAD_EVENTS_PAGE_TURNS, 1), LOAD_EVENTS_MAX_PAGE_TURNS)\n const to = Math.min(before ?? boundaries.length, boundaries.length)\n if (to === 0)\n return { from: 0, to: 0 }\n /** Where the run holding turn `end - 1` starts (0 when no run start precedes it). */\n const runStart = (end: number): number => {\n let i = end - 1\n while (i > 0 && !boundaries[i])\n i--\n return i\n }\n let from = runStart(to)\n const ceiling = limit * WHOLE_RUN_PAGES\n if (to - from > ceiling) {\n // One run too long to send whole: its last `ceiling` turns, from a turn\n // that keeps a tool call with its result.\n from = to - ceiling\n while (from < to - 1 && !cuts[from])\n from++\n }\n else {\n // The runs before it too, whole, while the page stays within `limit`.\n while (from > 0) {\n const previous = runStart(from)\n if (to - previous > limit)\n break\n from = previous\n }\n }\n return { from, to, ...(from > 0 ? { cursor: from } : {}) }\n}\n\n/** The position of the turn `beforeTurnId` names; `undefined` without one. A turn the transcript doesn't hold is invalid params. */\nfunction anchorIndex(beforeTurnId: unknown, turnIds: readonly string[] | undefined): number | undefined {\n const anchor = optionalString(beforeTurnId, 'beforeTurnId')\n if (anchor === undefined)\n return undefined\n const at = turnIds?.indexOf(anchor) ?? -1\n if (at < 0)\n throw new InvalidParamsError(`beforeTurnId \"${anchor.slice(0, 128)}\" is not a turn of this session.`)\n return at\n}\n","/**\n * Whole-session reads a client pages through, kept per session content\n * version so N pages cost one read of the session, not N:\n *\n * - the replay behind `sessions.loadEvents` pages (each page is a slice of\n * the WHOLE replay: see `replayTurns`);\n * - the document behind `sessions.getTurns` pages and the `sessions.get`\n * `turns: false` head (`document`): loaded, healed and copied once.\n * Every page carries its version, so a client that sees it change\n * mid-load starts over instead of mixing two versions\n * (`loadSessionDocument`).\n *\n * The version: a store with `getMeta` answers it without parsing turns\n * (its change counter `rev`, `updatedAt`, the turn and run counts; a hit\n * then skips the load too). `rev` grows on every write, so a version never\n * comes back after a change, whatever `updatedAt` a writer stamps (another\n * process on the same sessions.db included, which no host signal covers).\n * The version is read again after a miss's load: when it moved meanwhile,\n * what was loaded is of no known version, so it is served under a label no\n * other read gets, and not kept. A store without `rev` keeps the older\n * rule: a version stamped in the millisecond the read started is served\n * but not kept. Any other store's loaded document is fingerprinted (turn\n * ids, roles, block shapes and text lengths, the runs), and so is a live\n * session's in-memory copy (plus its metadata and status). The host's own\n * writes also drop entries by their signals (`observe`), which covers the\n * edits a version cannot see.\n *\n * A client that pages a session itself (the GUI main process over its own\n * store: `replay`) shares this cache with its own load, a version variant\n * for what else that load depends on, and background reads that never evict.\n *\n * Bounded: a few sessions per kind, least recently used first out, and a\n * byte budget (a document over it is served, not kept; a replay over it is\n * kept alone, so a long session's scroll-back still replays once). Besides the entries,\n * a session is tracked only while a read of it is in flight (so a drop\n * meanwhile stops that read's result from being kept): a session that is\n * dropped, forgotten or signalled leaves nothing behind.\n */\nimport type { StreamEvent } from '../../../chat/index'\nimport type { Session, SessionData, SessionRun, SessionStore } from '../../../session/index'\nimport type { SessionTurn } from '../../../types'\nimport type { HostSignal, LoadEventsPaging, SessionEventsPage } from '../../protocol'\nimport { replayTurns } from '../../../chat/store'\nimport { loadSession } from '../../../session/index'\nimport { loadOrThrow } from './session-load'\nimport { exchangeBoundaries, transcriptPage, turnCutPoints } from './transcript-page'\n\nconst DEFAULT_MAX_SESSIONS = 4\nconst DEFAULT_MAX_BYTES = 64 * 1024 * 1024\n\n/** Signals that follow a change to a session's turns or runs. */\nconst CHANGE_SIGNALS = new Set<HostSignal['kind']>(['sessions:changed', 'run:start', 'run:end', 'turn:end', 'compacting:end', 'prompt-turns'])\n\ninterface Versioned {\n version: string\n bytes: number\n}\n\n/** A whole-session replay: pages are `transcriptPage` slices of it. */\nexport interface TranscriptReplay extends Versioned {\n /** Every turn's events, in order: what a whole `sessions.loadEvents` returns. */\n events: StreamEvent[]\n /** Where each turn's events start (`[turns]` = the end). */\n turnStarts: number[]\n /** Where each run starts (`exchangeBoundaries`): where a page may start. */\n boundaries: boolean[]\n /** Where a run too long for one page may be split (`turnCutPoints`). */\n cuts: boolean[]\n /** Each turn's id: where a `beforeTurnId` anchor sits. */\n turnIds: string[]\n /** The loaded `seqs`, when the load gave them. */\n seqs?: number[]\n}\n\n/** What a client's own load gives `replay`. */\nexport interface ReplayData {\n /** The session's turns, in order. */\n turns: SessionTurn[]\n /** The session's runs (they tell child runs from parent runs). */\n runs: SessionRun[]\n /** A per-turn position the client keeps with the replay (the GUI store's `seq`). */\n seqs?: number[]\n}\n\n/** A client's own read of a stored session, for `replay`. */\nexport interface ReplayRead {\n /** Loads the session on a miss; `null` when it is unknown. */\n load: () => Promise<ReplayData | null> | ReplayData | null\n /** Appended to the version: what else the load depends on. */\n variant?: string\n /** A read ahead of the user: a hit leaves the order as is, a miss is kept only when that evicts nothing. */\n background?: boolean\n}\n\ninterface ReadOptions {\n variant?: string\n background?: boolean\n}\n\n/** One version of a session's document, as `sessions.get` would send it. */\nexport interface DocumentSnapshot extends Versioned {\n data: SessionData\n}\n\n/** Whole-session replays and documents, kept per session version (see the module header). */\nexport interface TranscriptReplayCache {\n /**\n * One `sessions.loadEvents` page of a stored session, sliced from its replay. Throws when the session is unknown, `InvalidParamsError` for bad paging.\n * `load`: reads the session on a miss instead of `store.load` (`null`: unknown).\n */\n page: (store: Pick<SessionStore, 'load' | 'getMeta'>, sessionId: string, paging: LoadEventsPaging, load?: () => ReplayData | null) => Promise<SessionEventsPage>\n /** A stored session's replay from the client's own `read.load`, versioned like `page`'s; `null` when unknown. */\n replay: (store: Pick<SessionStore, 'getMeta'>, sessionId: string, read: ReplayRead) => Promise<TranscriptReplay | null>\n /** The replay kept for a session, whatever its version; `touch` counts it as used. */\n cached: (sessionId: string, touch?: boolean) => TranscriptReplay | undefined\n /** The document (the live copy when `live` is given, else the stored one, healed in memory), and its version; `null` when unknown. */\n document: (store: SessionStore, sessionId: string, live: Session | null) => Promise<DocumentSnapshot | null>\n /** A host signal: one that follows a change to a session drops its entries. */\n observe: (signal: HostSignal) => void\n /** Drops the session's entries (it is gone); a read in flight is served but not kept. */\n forget: (sessionId: string) => void\n /** Entries kept and sessions with a read in flight, across both kinds: what the cache holds. */\n sizes: () => { entries: number, inFlight: number }\n}\n\n/** The session a host signal says changed (its turns or runs), if any: its cached entries are stale. */\nexport function changedSessionOf(signal: HostSignal): string | undefined {\n return CHANGE_SIGNALS.has(signal.kind) && 'sessionId' in signal && typeof signal.sessionId === 'string' ? signal.sessionId : undefined\n}\n\n/** A read in flight: a drop of its session meanwhile marks it, and its result is then served but not kept. */\ninterface InFlightRead { dropped: boolean }\n\n/**\n * One kind of entry (replays, documents): LRU by insertion order, bounded by\n * count and bytes. `keepOversized`: an entry over the byte budget on its own\n * is still kept, alone (it evicts every other), until the next one is kept.\n */\nfunction createLru<T extends Versioned>(maxSessions: number, maxBytes: number, keepOversized = false) {\n const entries = new Map<string, T>()\n let totalBytes = 0\n const drop = (sessionId: string): void => {\n const entry = entries.get(sessionId)\n if (entry) {\n totalBytes -= entry.bytes\n entries.delete(sessionId)\n }\n }\n return {\n size: () => entries.size,\n peek(sessionId: string, touch: boolean): T | undefined {\n const entry = entries.get(sessionId)\n if (entry && touch) {\n entries.delete(sessionId)\n entries.set(sessionId, entry)\n }\n return entry\n },\n hit(sessionId: string, version: string, touch = true): T | undefined {\n const entry = entries.get(sessionId)\n if (!entry || entry.version !== version)\n return undefined\n if (touch) {\n entries.delete(sessionId)\n entries.set(sessionId, entry)\n }\n return entry\n },\n drop,\n /** Replaces the session's entry. `evict: false`: kept only when that pushes nothing out. */\n keep(sessionId: string, entry: T, evict = true): void {\n drop(sessionId)\n if (entry.bytes > maxBytes && (!keepOversized || !evict))\n return\n if (!evict && (entries.size >= maxSessions || totalBytes + entry.bytes > maxBytes))\n return\n entries.set(sessionId, entry)\n totalBytes += entry.bytes\n for (const [id, oldest] of entries) {\n // The entry just kept is the newest: an oversized one stays, alone.\n if ((entries.size <= maxSessions && totalBytes <= maxBytes) || id === sessionId)\n break\n entries.delete(id)\n totalBytes -= oldest.bytes\n }\n },\n }\n}\n\n/**\n * A replay and document cache.\n * @param options - Bounds and a seam.\n * @param options.maxSessions - Entries kept per kind (replays, documents). Default 4.\n * @param options.maxBytes - Byte budget per kind, by {@link approxJsonBytes}. Default 64 MiB.\n * @param options.replay - Builds a replay from turns and runs. Default `replayTurns`.\n */\nexport function createTranscriptReplayCache(options: {\n maxSessions?: number\n maxBytes?: number\n /** The replay (a seam for counting it). */\n replay?: typeof replayTurns\n} = {}): TranscriptReplayCache {\n const maxSessions = options.maxSessions ?? DEFAULT_MAX_SESSIONS\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES\n const replay = options.replay ?? replayTurns\n // A long session's replay can outgrow the budget alone (a 25k-turn agentic\n // session replays to ~90 MiB). Not kept, every page of its scroll-back\n // loaded and replayed the whole session again: hundreds of ms per page.\n const replays = createLru<TranscriptReplay>(maxSessions, maxBytes, true)\n const documents = createLru<DocumentSnapshot>(maxSessions, maxBytes)\n const inFlight = new Map<string, Set<InFlightRead>>()\n /** Labels a read of no known version: never equal to another read's. */\n let unversioned = 0\n\n function drop(sessionId: string): void {\n for (const read of inFlight.get(sessionId) ?? [])\n read.dropped = true\n replays.drop(sessionId)\n documents.drop(sessionId)\n }\n\n /** Run `fn` as an in-flight read of `sessionId`, tracked only while it runs. */\n async function tracked<R>(sessionId: string, fn: (read: InFlightRead) => Promise<R>): Promise<R> {\n const read: InFlightRead = { dropped: false }\n const reads = inFlight.get(sessionId) ?? new Set<InFlightRead>()\n inFlight.set(sessionId, reads.add(read))\n try {\n return await fn(read)\n }\n finally {\n reads.delete(read)\n if (reads.size === 0 && inFlight.get(sessionId) === reads)\n inFlight.delete(sessionId)\n }\n }\n\n /**\n * A stored session's entry of `lru`, built from `load` on a miss. The\n * version comes from `getMeta` when the store has it (see the header),\n * else from the loaded data (`fingerprintOf`).\n */\n function stored<T extends Versioned, D>(\n lru: ReturnType<typeof createLru<T>>,\n store: Pick<SessionStore, 'getMeta'>,\n sessionId: string,\n load: () => Promise<D | null> | D | null,\n build: (data: D, version: string) => T,\n fingerprintOf: (data: D) => string,\n { variant = '', background = false }: ReadOptions = {},\n ): Promise<T | null> {\n return tracked(sessionId, async (read) => {\n if (store.getMeta) {\n const readAt = Date.now()\n const meta = await store.getMeta(sessionId)\n if (!meta)\n return null\n const version = storeVersion(meta) + variant\n const cached = lru.hit(sessionId, version, !background)\n if (cached)\n return cached\n const data = await load()\n if (data === null)\n return null\n let settled: boolean\n if (meta.rev !== undefined) {\n const after = await store.getMeta(sessionId)\n settled = after !== null && storeVersion(after) + variant === version\n }\n else {\n settled = meta.updatedAt < readAt\n }\n const entry = build(data, settled ? version : `${version}~${++unversioned}`)\n // A stale entry goes either way: its version cannot come back. A\n // background read leaves it to the foreground, which may hold a newer one.\n if (settled && !read.dropped)\n lru.keep(sessionId, entry, !background)\n else if (!background)\n lru.drop(sessionId)\n return entry\n }\n const data = await load()\n if (data === null)\n return null\n const version = fingerprintOf(data) + variant\n const cached = lru.hit(sessionId, version, !background)\n if (cached)\n return cached\n const entry = build(data, version)\n if (!read.dropped)\n lru.keep(sessionId, entry, !background)\n return entry\n })\n }\n\n function buildReplay(data: ReplayData, version: string): TranscriptReplay {\n const { events, turnStarts } = replay(data.turns, data.runs)\n return {\n version,\n events,\n turnStarts,\n boundaries: exchangeBoundaries(data.turns, data.runs),\n cuts: turnCutPoints(data.turns),\n turnIds: data.turns.map(turn => turn.id),\n bytes: approxJsonBytes(events),\n ...(data.seqs ? { seqs: data.seqs } : {}),\n }\n }\n\n const snapshotOf = (data: SessionData, version: string): DocumentSnapshot => ({ version, data, bytes: approxJsonBytes(data) })\n\n return {\n async page(store, sessionId, paging, load) {\n const entry = load\n ? await stored(replays, store, sessionId, load, buildReplay, data => fingerprint(0, data.turns, data.runs))\n : await stored(replays, store, sessionId, () => loadOrThrow(store, sessionId), buildReplay, data => fingerprint(data.updatedAt, data.turns, data.runs))\n if (!entry)\n throw new Error(`Session \"${sessionId}\" not found.`)\n const { from, to, cursor } = transcriptPage(entry.boundaries, paging, entry.cuts, entry.turnIds)\n const events = entry.events.slice(entry.turnStarts[from], entry.turnStarts[to])\n return {\n events,\n exact: true,\n start: entry.turnStarts[from]!,\n ...(cursor !== undefined ? { cursor } : {}),\n ...(paging.beforeTurnId !== undefined ? { beforeTurnId: paging.beforeTurnId } : {}),\n }\n },\n replay(store, sessionId, read) {\n const options = { variant: read.variant, background: read.background }\n return stored(replays, store, sessionId, read.load, buildReplay, data => fingerprint(0, data.turns, data.runs), options)\n },\n cached: (sessionId, touch = false) => replays.peek(sessionId, touch),\n async document(store, sessionId, live) {\n if (live) {\n // The live copy: ahead of the store mid-run, and holding the todos.\n const version = `live:${fingerprint(0, live.turns, live.runs)}:${hashText(JSON.stringify([live.status, live.metadata]))}`\n return tracked(sessionId, async (read) => {\n const cached = documents.hit(sessionId, version)\n if (cached)\n return cached\n const entry = snapshotOf(live.toJSON(), version)\n if (!read.dropped)\n documents.keep(sessionId, entry)\n return entry\n })\n }\n // A reader: a load-time pairing heal stays in memory, the host's own agent persists the document.\n const load = async (): Promise<SessionData | null> => (await loadSession(store, sessionId, { persistHeal: false }))?.toJSON() ?? null\n return stored(documents, store, sessionId, load, snapshotOf, data => fingerprint(data.updatedAt, data.turns, data.runs))\n },\n observe(signal) {\n const sessionId = changedSessionOf(signal)\n if (sessionId !== undefined)\n drop(sessionId)\n },\n forget: drop,\n sizes: () => ({ entries: replays.size() + documents.size(), inFlight: inFlight.size }),\n }\n}\n\n/**\n * About the length of `JSON.stringify(value)`: what an entry holds, for the\n * byte budget. Walks the value without building the string (several times\n * cheaper on a long session); the budget is a heuristic, exact bytes are not\n * needed.\n */\nexport function approxJsonBytes(value: unknown): number {\n if (typeof value === 'string')\n return value.length + 2\n if (typeof value !== 'object' || value === null)\n return 8\n let bytes = 2\n if (Array.isArray(value)) {\n for (const item of value)\n bytes += approxJsonBytes(item) + 1\n return bytes\n }\n for (const key in value)\n bytes += key.length + 4 + approxJsonBytes((value as Record<string, unknown>)[key])\n return bytes\n}\n\nfunction storeVersion(meta: { rev?: number, updatedAt: number, turnCount: number, runCount: number }): string {\n return `meta:${meta.rev ?? '-'}:${meta.updatedAt}:${meta.turnCount}:${meta.runCount}`\n}\n\n/** A 32-bit FNV-1a: `mix` values in, `digest` (base 36) out. */\nfunction fnv1a() {\n let hash = 0x811C9DC5\n const add = (text: string): void => {\n for (let i = 0; i < text.length; i++)\n hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193)\n }\n return {\n add,\n /** One value, then a separator: `ab` + `c` never hashes as `a` + `bc`. */\n mix: (value: string | number | undefined): void => {\n add(String(value))\n hash = Math.imul(hash ^ 0x1F, 0x01000193)\n },\n digest: (): string => (hash >>> 0).toString(36),\n }\n}\n\nfunction hashText(text: string): string {\n const hash = fnv1a()\n hash.add(text)\n return hash.digest()\n}\n\n/** FNV-1a over the document's shape: what changes when a turn or run is added, removed, or rewritten. */\nfunction fingerprint(updatedAt: number, turns: readonly SessionTurn[], runs: readonly SessionRun[]): string {\n const { mix, digest } = fnv1a()\n for (const turn of turns) {\n mix(turn.id)\n mix(turn.role)\n mix(turn.runId)\n mix(typeof turn.display === 'string' ? turn.display : '')\n mix(typeof turn.injected === 'string' ? turn.injected : '')\n mix(turn.content.length)\n for (const block of turn.content) {\n mix(block.type)\n const fields = block as { text?: unknown, output?: unknown, summary?: unknown }\n for (const field of [fields.text, fields.output, fields.summary])\n mix(typeof field === 'string' ? field.length : Array.isArray(field) ? field.length : '')\n }\n }\n mix(JSON.stringify(runs))\n return `doc:${updatedAt}:${turns.length}:${runs.length}:${digest()}`\n}\n","/**\n * A read-only connection to a sessions database, from whichever runtime runs\n * the caller: `bun:sqlite` under Bun, `node:sqlite` under Node. The history\n * worker reads on one (`./worker.ts`); the host thread opens one when the\n * worker can't serve a usage scan (`./transcript.ts`).\n */\nimport type { SqliteDriver } from '../../session/sqlite-driver'\nimport { createSqliteDriver, OPEN_BUSY_TIMEOUT_MS } from '../../session/sqlite-driver'\n\n/**\n * Opens `path` read-only. A long wait on a writer's lock is bounded by the store's busy timeout.\n *\n * @param path - The sessions database.\n */\nexport async function openReadonlySqlite(path: string): Promise<SqliteDriver> {\n if (typeof Bun !== 'undefined') {\n const { Database } = await import('bun:sqlite')\n const db = new Database(path, { readonly: true })\n db.exec(`PRAGMA busy_timeout = ${OPEN_BUSY_TIMEOUT_MS}`)\n return createSqliteDriver(db, { close: () => db.close(false) })\n }\n const { DatabaseSync } = await import('node:sqlite')\n const db = new DatabaseSync(path, { readOnly: true })\n db.exec(`PRAGMA busy_timeout = ${OPEN_BUSY_TIMEOUT_MS}`)\n return createSqliteDriver(db)\n}\n"],"mappings":";;;;;;;;;;;;AAQA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,MAAM,wBAAwB;;;;;;AAO9B,SAAgB,eAAe,OAAgB,OAAO,aAAqB;CACzE,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,uBACpE,MAAM,IAAI,mBAAmB,GAAG,KAAK,yCAAyC,sBAAsB,aAAa;CACnH,IAAI,UAAU,OAAO,UAAU,QAAQ,UAAU,KAAK,KAAK,GACzD,MAAM,IAAI,mBAAmB,GAAG,KAAK,iDAAiD;CACxF,OAAO;AACT;;AAGA,SAAgB,YAAY,QAA4D;CACtF,OAAO,eAAe,QAAQ,SAAS;AACzC;;AAGA,SAAgB,eAAe,OAAgB,MAAkC;CAC/E,IAAI,UAAU,KAAA,GACZ,OA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AClC,MAAM,KAAK,IAAI,SAAS,MAAM,EAAE,UAAU,KAAK,CAAC;EAChD,GAAG,KAAK,yBAAyB,sBAAsB;EACvD,OAAO,mBAAmB,IAAI,EAAE,aAAa,GAAG,MAAM,KAAK,EAAE,CAAC;CAChE;CACA,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,MAAM,KAAK,IAAI,aAAa,MAAM,EAAE,UAAU,KAAK,CAAC;CACpD,GAAG,KAAK,yBAAyB,sBAAsB;CACvD,OAAO,mBAAmB,EAAE;AAC9B"}
1
+ {"version":3,"file":"readonly-db-DrbT8tX6.js","names":[],"sources":["../src/ipc/daemon/handlers/params.ts","../src/ipc/daemon/handlers/session-load.ts","../src/ipc/daemon/handlers/transcript-page.ts","../src/ipc/daemon/handlers/transcript-cache.ts","../src/ipc/history/readonly-db.ts"],"sourcesContent":["/**\n * Shape checks for request params: they arrive as untrusted JSON (the\n * `IpcMethods` types are not a runtime guarantee). The dispatcher runs\n * {@link checkParams} on every request and notification before its handler;\n * handlers use the field checks for what they require. A failed check is an\n * {@link InvalidParamsError}, answered as JSON-RPC \"invalid params\".\n */\n\nexport class InvalidParamsError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'InvalidParamsError'\n }\n}\n\n/** Longest session id accepted (minted ids are under 64 characters). */\nconst MAX_SESSION_ID_LENGTH = 1024\n\n/**\n * A session id: a non-empty string that is one plain path segment. Ids name\n * directories on disk (`<data dir>/sessions/<id>/`, removed recursively on\n * delete), so `..`, separators and NUL are refused.\n */\nexport function checkSessionId(value: unknown, name = 'sessionId'): string {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_SESSION_ID_LENGTH)\n throw new InvalidParamsError(`${name} must be a non-empty string of at most ${MAX_SESSION_ID_LENGTH} characters.`)\n if (value === '.' || value === '..' || /[/\\\\\\0]/.test(value))\n throw new InvalidParamsError(`${name} must not be a path (no \"/\", \"\\\\\", \".\" or \"..\").`)\n return value\n}\n\n/** The required `sessionId` of `params`. */\nexport function sessionIdOf(params: { sessionId?: unknown } | null | undefined): string {\n return checkSessionId(params?.sessionId)\n}\n\n/** An optional non-negative integer; `undefined` when absent. */\nexport function nonNegativeInt(value: unknown, name: string): number | undefined {\n if (value === undefined)\n return undefined\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0)\n throw new InvalidParamsError(`${name} must be a non-negative integer.`)\n return value\n}\n\n/** A non-empty string. */\nexport function requiredString(value: unknown, name: string): string {\n if (typeof value !== 'string' || value.length === 0)\n throw new InvalidParamsError(`${name} must be a non-empty string.`)\n return value\n}\n\n/** An optional string; `undefined` when absent. */\nexport function optionalString(value: unknown, name: string): string | undefined {\n if (value !== undefined && typeof value !== 'string')\n throw new InvalidParamsError(`${name} must be a string.`)\n return value\n}\n\n/**\n * What every method's params must be: absent, `null`, or an object (never an\n * array or a scalar), whose `sessionId` / `sessionIds`, when present, name\n * sessions ({@link checkSessionId}).\n */\nexport function checkParams(params: unknown): void {\n if (params === undefined || params === null)\n return\n if (typeof params !== 'object' || Array.isArray(params))\n throw new InvalidParamsError('params must be an object.')\n const { sessionId, sessionIds } = params as { sessionId?: unknown, sessionIds?: unknown }\n if (sessionId !== undefined)\n checkSessionId(sessionId)\n if (sessionIds !== undefined) {\n if (!Array.isArray(sessionIds))\n throw new InvalidParamsError('sessionIds must be an array.')\n for (const id of sessionIds)\n checkSessionId(id, 'sessionIds[]')\n }\n}\n","/** A stored session or a \"not found\" error: kept apart from `./sessions` so the history worker loads without the chat host's graph. */\nimport type { SessionData, SessionStore } from '../../../session/index'\n\nexport async function loadOrThrow(store: Pick<SessionStore, 'load'>, sessionId: string): Promise<SessionData> {\n const data = await store.load(sessionId)\n if (!data)\n throw new Error(`Session \"${sessionId}\" not found.`)\n return data\n}\n","/**\n * One page of a transcript for `sessions.loadEvents` paging, in whole runs:\n * everything from a user message to the turn before the next one. The run\n * the page ends in is always whole, and the runs before it join while the\n * page stays within `limit` turns, so scrolling back brings the previous\n * run (or a few small ones) at a time, never part of one. A run longer than\n * {@link WHOLE_RUN_PAGES} pages on its own is the one exception: it comes in\n * pieces of that size, each starting on a turn that keeps a tool call with\n * its result. The GUI's local pager cuts with the same rule.\n */\nimport type { SessionRun } from '../../../session/index'\nimport type { SessionTurn } from '../../../types'\nimport type { LoadEventsPaging } from '../../protocol'\nimport { LOAD_EVENTS_MAX_PAGE_TURNS, LOAD_EVENTS_PAGE_TURNS } from '../../protocol'\nimport { InvalidParamsError, nonNegativeInt, optionalString } from './params'\n\n/**\n * A run longer than this many pages is split (by `limit`, so the client's\n * halving retry on a reply too large still converges).\n */\nexport const WHOLE_RUN_PAGES = 5\n\nexport function isPagedLoad(p: LoadEventsPaging | undefined): boolean {\n return p?.before !== undefined || p?.limit !== undefined || p?.beforeTurnId !== undefined\n}\n\n/**\n * Per turn: does a run start there (a parent-run user turn carrying no tool result, not loop-injected)?\n * @param turns - Turns of the session, in order.\n * @param runs - Runs of the session, used to tell child runs from parent runs.\n * @returns One flag per turn.\n */\nexport function exchangeBoundaries(turns: readonly SessionTurn[], runs: readonly SessionRun[]): boolean[] {\n const childRuns = new Set(runs.filter(run => (run.depth ?? 0) > 0 || run.parentRunId !== undefined).map(run => run.id))\n return turns.map(turn => turn.role === 'user'\n && !turn.injected\n && !(turn.runId !== undefined && childRuns.has(turn.runId))\n && !turn.content.some(block => block.type === 'tool_result'))\n}\n\n/**\n * Per turn: can a page start there without leaving a tool call's result behind (not a tool-result turn)?\n * @param turns - Turns of the session, in order.\n * @returns One flag per turn.\n */\nexport function turnCutPoints(turns: readonly SessionTurn[]): boolean[] {\n return turns.map(turn => !(turn.role === 'user' && turn.content.some(block => block.type === 'tool_result')))\n}\n\n/**\n * `[from, to)` of the page, and the cursor of the one before it, over the\n * turns' {@link exchangeBoundaries} (run starts) and {@link turnCutPoints}\n * (where a run too long to send whole may be split; run starts when absent).\n * @param boundaries - Run starts per turn, from {@link exchangeBoundaries}.\n * @param paging - The `before` cursor and `limit` of the request.\n * @param cuts - Allowed cut points per turn, from {@link turnCutPoints}.\n * @param turnIds - Id per turn: where a `beforeTurnId` anchor sits (it wins over `before`).\n * @returns The turn range of the page and the cursor of the page before it.\n */\nexport function transcriptPage(\n boundaries: readonly boolean[],\n paging: LoadEventsPaging,\n cuts: readonly boolean[] = boundaries,\n turnIds?: readonly string[],\n): { from: number, to: number, cursor?: number } {\n const before = anchorIndex(paging.beforeTurnId, turnIds) ?? nonNegativeInt(paging.before, 'before')\n const limit = Math.min(Math.max(nonNegativeInt(paging.limit, 'limit') ?? LOAD_EVENTS_PAGE_TURNS, 1), LOAD_EVENTS_MAX_PAGE_TURNS)\n const to = Math.min(before ?? boundaries.length, boundaries.length)\n if (to === 0)\n return { from: 0, to: 0 }\n /** Where the run holding turn `end - 1` starts (0 when no run start precedes it). */\n const runStart = (end: number): number => {\n let i = end - 1\n while (i > 0 && !boundaries[i])\n i--\n return i\n }\n let from = runStart(to)\n const ceiling = limit * WHOLE_RUN_PAGES\n if (to - from > ceiling) {\n // One run too long to send whole: its last `ceiling` turns, from a turn\n // that keeps a tool call with its result.\n from = to - ceiling\n while (from < to - 1 && !cuts[from])\n from++\n }\n else {\n // The runs before it too, whole, while the page stays within `limit`.\n while (from > 0) {\n const previous = runStart(from)\n if (to - previous > limit)\n break\n from = previous\n }\n }\n return { from, to, ...(from > 0 ? { cursor: from } : {}) }\n}\n\n/** The position of the turn `beforeTurnId` names; `undefined` without one. A turn the transcript doesn't hold is invalid params. */\nfunction anchorIndex(beforeTurnId: unknown, turnIds: readonly string[] | undefined): number | undefined {\n const anchor = optionalString(beforeTurnId, 'beforeTurnId')\n if (anchor === undefined)\n return undefined\n const at = turnIds?.indexOf(anchor) ?? -1\n if (at < 0)\n throw new InvalidParamsError(`beforeTurnId \"${anchor.slice(0, 128)}\" is not a turn of this session.`)\n return at\n}\n","/**\n * Whole-session reads a client pages through, kept per session content\n * version so N pages cost one read of the session, not N:\n *\n * - the replay behind `sessions.loadEvents` pages (each page is a slice of\n * the WHOLE replay: see `replayTurns`);\n * - the document behind `sessions.getTurns` pages and the `sessions.get`\n * `turns: false` head (`document`): loaded, healed and copied once.\n * Every page carries its version, so a client that sees it change\n * mid-load starts over instead of mixing two versions\n * (`loadSessionDocument`).\n *\n * The version: a store with `getMeta` answers it without parsing turns\n * (its change counter `rev`, `updatedAt`, the turn and run counts; a hit\n * then skips the load too). `rev` grows on every write, so a version never\n * comes back after a change, whatever `updatedAt` a writer stamps (another\n * process on the same sessions.db included, which no host signal covers).\n * The version is read again after a miss's load: when it moved meanwhile,\n * what was loaded is of no known version, so it is served under a label no\n * other read gets, and not kept. A store without `rev` keeps the older\n * rule: a version stamped in the millisecond the read started is served\n * but not kept. Any other store's loaded document is fingerprinted (turn\n * ids, roles, block shapes and text lengths, the runs), and so is a live\n * session's in-memory copy (plus its metadata and status). The host's own\n * writes also drop entries by their signals (`observe`), which covers the\n * edits a version cannot see.\n *\n * A client that pages a session itself (the GUI main process over its own\n * store: `replay`) shares this cache with its own load, a version variant\n * for what else that load depends on, and background reads that never evict.\n *\n * Bounded: a few sessions per kind, least recently used first out, and a\n * byte budget (a document over it is served, not kept; a replay over it is\n * kept alone, so a long session's scroll-back still replays once). Besides the entries,\n * a session is tracked only while a read of it is in flight (so a drop\n * meanwhile stops that read's result from being kept): a session that is\n * dropped, forgotten or signalled leaves nothing behind.\n */\nimport type { StreamEvent } from '../../../chat/index'\nimport type { Session, SessionData, SessionRun, SessionStore } from '../../../session/index'\nimport type { SessionTurn } from '../../../types'\nimport type { HostSignal, LoadEventsPaging, SessionEventsPage } from '../../protocol'\nimport { replayTurns } from '../../../chat/store'\nimport { loadSession } from '../../../session/index'\nimport { loadOrThrow } from './session-load'\nimport { exchangeBoundaries, transcriptPage, turnCutPoints } from './transcript-page'\n\nconst DEFAULT_MAX_SESSIONS = 4\nconst DEFAULT_MAX_BYTES = 64 * 1024 * 1024\n\n/** Signals that follow a change to a session's turns or runs. */\nconst CHANGE_SIGNALS = new Set<HostSignal['kind']>(['sessions:changed', 'run:start', 'run:end', 'turn:end', 'compacting:end', 'prompt-turns'])\n\ninterface Versioned {\n version: string\n bytes: number\n}\n\n/** A whole-session replay: pages are `transcriptPage` slices of it. */\nexport interface TranscriptReplay extends Versioned {\n /** Every turn's events, in order: what a whole `sessions.loadEvents` returns. */\n events: StreamEvent[]\n /** Where each turn's events start (`[turns]` = the end). */\n turnStarts: number[]\n /** Where each run starts (`exchangeBoundaries`): where a page may start. */\n boundaries: boolean[]\n /** Where a run too long for one page may be split (`turnCutPoints`). */\n cuts: boolean[]\n /** Each turn's id: where a `beforeTurnId` anchor sits. */\n turnIds: string[]\n /** The loaded `seqs`, when the load gave them. */\n seqs?: number[]\n}\n\n/** What a client's own load gives `replay`. */\nexport interface ReplayData {\n /** The session's turns, in order. */\n turns: SessionTurn[]\n /** The session's runs (they tell child runs from parent runs). */\n runs: SessionRun[]\n /** A per-turn position the client keeps with the replay (the GUI store's `seq`). */\n seqs?: number[]\n}\n\n/** A client's own read of a stored session, for `replay`. */\nexport interface ReplayRead {\n /** Loads the session on a miss; `null` when it is unknown. */\n load: () => Promise<ReplayData | null> | ReplayData | null\n /** Appended to the version: what else the load depends on. */\n variant?: string\n /** A read ahead of the user: a hit leaves the order as is, a miss is kept only when that evicts nothing. */\n background?: boolean\n}\n\ninterface ReadOptions {\n variant?: string\n background?: boolean\n}\n\n/** One version of a session's document, as `sessions.get` would send it. */\nexport interface DocumentSnapshot extends Versioned {\n data: SessionData\n}\n\n/** Whole-session replays and documents, kept per session version (see the module header). */\nexport interface TranscriptReplayCache {\n /**\n * One `sessions.loadEvents` page of a stored session, sliced from its replay. Throws when the session is unknown, `InvalidParamsError` for bad paging.\n * `load`: reads the session on a miss instead of `store.load` (`null`: unknown).\n */\n page: (store: Pick<SessionStore, 'load' | 'getMeta'>, sessionId: string, paging: LoadEventsPaging, load?: () => ReplayData | null) => Promise<SessionEventsPage>\n /** A stored session's replay from the client's own `read.load`, versioned like `page`'s; `null` when unknown. */\n replay: (store: Pick<SessionStore, 'getMeta'>, sessionId: string, read: ReplayRead) => Promise<TranscriptReplay | null>\n /** The replay kept for a session, whatever its version; `touch` counts it as used. */\n cached: (sessionId: string, touch?: boolean) => TranscriptReplay | undefined\n /** The document (the live copy when `live` is given, else the stored one, healed in memory), and its version; `null` when unknown. */\n document: (store: SessionStore, sessionId: string, live: Session | null) => Promise<DocumentSnapshot | null>\n /** A host signal: one that follows a change to a session drops its entries. */\n observe: (signal: HostSignal) => void\n /** Drops the session's entries (it is gone); a read in flight is served but not kept. */\n forget: (sessionId: string) => void\n /** Entries kept and sessions with a read in flight, across both kinds: what the cache holds. */\n sizes: () => { entries: number, inFlight: number }\n}\n\n/** The session a host signal says changed (its turns or runs), if any: its cached entries are stale. */\nexport function changedSessionOf(signal: HostSignal): string | undefined {\n return CHANGE_SIGNALS.has(signal.kind) && 'sessionId' in signal && typeof signal.sessionId === 'string' ? signal.sessionId : undefined\n}\n\n/** A read in flight: a drop of its session meanwhile marks it, and its result is then served but not kept. */\ninterface InFlightRead { dropped: boolean }\n\n/**\n * One kind of entry (replays, documents): LRU by insertion order, bounded by\n * count and bytes. `keepOversized`: an entry over the byte budget on its own\n * is still kept, alone (it evicts every other), until the next one is kept.\n */\nfunction createLru<T extends Versioned>(maxSessions: number, maxBytes: number, keepOversized = false) {\n const entries = new Map<string, T>()\n let totalBytes = 0\n const drop = (sessionId: string): void => {\n const entry = entries.get(sessionId)\n if (entry) {\n totalBytes -= entry.bytes\n entries.delete(sessionId)\n }\n }\n return {\n size: () => entries.size,\n peek(sessionId: string, touch: boolean): T | undefined {\n const entry = entries.get(sessionId)\n if (entry && touch) {\n entries.delete(sessionId)\n entries.set(sessionId, entry)\n }\n return entry\n },\n hit(sessionId: string, version: string, touch = true): T | undefined {\n const entry = entries.get(sessionId)\n if (!entry || entry.version !== version)\n return undefined\n if (touch) {\n entries.delete(sessionId)\n entries.set(sessionId, entry)\n }\n return entry\n },\n drop,\n /** Replaces the session's entry. `evict: false`: kept only when that pushes nothing out. */\n keep(sessionId: string, entry: T, evict = true): void {\n drop(sessionId)\n if (entry.bytes > maxBytes && (!keepOversized || !evict))\n return\n if (!evict && (entries.size >= maxSessions || totalBytes + entry.bytes > maxBytes))\n return\n entries.set(sessionId, entry)\n totalBytes += entry.bytes\n for (const [id, oldest] of entries) {\n // The entry just kept is the newest: an oversized one stays, alone.\n if ((entries.size <= maxSessions && totalBytes <= maxBytes) || id === sessionId)\n break\n entries.delete(id)\n totalBytes -= oldest.bytes\n }\n },\n }\n}\n\n/**\n * A replay and document cache.\n * @param options - Bounds and a seam.\n * @param options.maxSessions - Entries kept per kind (replays, documents). Default 4.\n * @param options.maxBytes - Byte budget per kind, by {@link approxJsonBytes}. Default 64 MiB.\n * @param options.replay - Builds a replay from turns and runs. Default `replayTurns`.\n */\nexport function createTranscriptReplayCache(options: {\n maxSessions?: number\n maxBytes?: number\n /** The replay (a seam for counting it). */\n replay?: typeof replayTurns\n} = {}): TranscriptReplayCache {\n const maxSessions = options.maxSessions ?? DEFAULT_MAX_SESSIONS\n const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES\n const replay = options.replay ?? replayTurns\n // A long session's replay can outgrow the budget alone (a 25k-turn agentic\n // session replays to ~90 MiB). Not kept, every page of its scroll-back\n // loaded and replayed the whole session again: hundreds of ms per page.\n const replays = createLru<TranscriptReplay>(maxSessions, maxBytes, true)\n const documents = createLru<DocumentSnapshot>(maxSessions, maxBytes)\n const inFlight = new Map<string, Set<InFlightRead>>()\n /** Labels a read of no known version: never equal to another read's. */\n let unversioned = 0\n\n function drop(sessionId: string): void {\n for (const read of inFlight.get(sessionId) ?? [])\n read.dropped = true\n replays.drop(sessionId)\n documents.drop(sessionId)\n }\n\n /** Run `fn` as an in-flight read of `sessionId`, tracked only while it runs. */\n async function tracked<R>(sessionId: string, fn: (read: InFlightRead) => Promise<R>): Promise<R> {\n const read: InFlightRead = { dropped: false }\n const reads = inFlight.get(sessionId) ?? new Set<InFlightRead>()\n inFlight.set(sessionId, reads.add(read))\n try {\n return await fn(read)\n }\n finally {\n reads.delete(read)\n if (reads.size === 0 && inFlight.get(sessionId) === reads)\n inFlight.delete(sessionId)\n }\n }\n\n /**\n * A stored session's entry of `lru`, built from `load` on a miss. The\n * version comes from `getMeta` when the store has it (see the header),\n * else from the loaded data (`fingerprintOf`).\n */\n function stored<T extends Versioned, D>(\n lru: ReturnType<typeof createLru<T>>,\n store: Pick<SessionStore, 'getMeta'>,\n sessionId: string,\n load: () => Promise<D | null> | D | null,\n build: (data: D, version: string) => T,\n fingerprintOf: (data: D) => string,\n { variant = '', background = false }: ReadOptions = {},\n ): Promise<T | null> {\n return tracked(sessionId, async (read) => {\n if (store.getMeta) {\n const readAt = Date.now()\n const meta = await store.getMeta(sessionId)\n if (!meta)\n return null\n const version = storeVersion(meta) + variant\n const cached = lru.hit(sessionId, version, !background)\n if (cached)\n return cached\n const data = await load()\n if (data === null)\n return null\n let settled: boolean\n if (meta.rev !== undefined) {\n const after = await store.getMeta(sessionId)\n settled = after !== null && storeVersion(after) + variant === version\n }\n else {\n settled = meta.updatedAt < readAt\n }\n const entry = build(data, settled ? version : `${version}~${++unversioned}`)\n // A stale entry goes either way: its version cannot come back. A\n // background read leaves it to the foreground, which may hold a newer one.\n if (settled && !read.dropped)\n lru.keep(sessionId, entry, !background)\n else if (!background)\n lru.drop(sessionId)\n return entry\n }\n const data = await load()\n if (data === null)\n return null\n const version = fingerprintOf(data) + variant\n const cached = lru.hit(sessionId, version, !background)\n if (cached)\n return cached\n const entry = build(data, version)\n if (!read.dropped)\n lru.keep(sessionId, entry, !background)\n return entry\n })\n }\n\n function buildReplay(data: ReplayData, version: string): TranscriptReplay {\n const { events, turnStarts } = replay(data.turns, data.runs)\n return {\n version,\n events,\n turnStarts,\n boundaries: exchangeBoundaries(data.turns, data.runs),\n cuts: turnCutPoints(data.turns),\n turnIds: data.turns.map(turn => turn.id),\n bytes: approxJsonBytes(events),\n ...(data.seqs ? { seqs: data.seqs } : {}),\n }\n }\n\n const snapshotOf = (data: SessionData, version: string): DocumentSnapshot => ({ version, data, bytes: approxJsonBytes(data) })\n\n return {\n async page(store, sessionId, paging, load) {\n const entry = load\n ? await stored(replays, store, sessionId, load, buildReplay, data => fingerprint(0, data.turns, data.runs))\n : await stored(replays, store, sessionId, () => loadOrThrow(store, sessionId), buildReplay, data => fingerprint(data.updatedAt, data.turns, data.runs))\n if (!entry)\n throw new Error(`Session \"${sessionId}\" not found.`)\n const { from, to, cursor } = transcriptPage(entry.boundaries, paging, entry.cuts, entry.turnIds)\n const events = entry.events.slice(entry.turnStarts[from], entry.turnStarts[to])\n return {\n events,\n exact: true,\n start: entry.turnStarts[from]!,\n ...(cursor !== undefined ? { cursor } : {}),\n ...(paging.beforeTurnId !== undefined ? { beforeTurnId: paging.beforeTurnId } : {}),\n }\n },\n replay(store, sessionId, read) {\n const options = { variant: read.variant, background: read.background }\n return stored(replays, store, sessionId, read.load, buildReplay, data => fingerprint(0, data.turns, data.runs), options)\n },\n cached: (sessionId, touch = false) => replays.peek(sessionId, touch),\n async document(store, sessionId, live) {\n if (live) {\n // The live copy: ahead of the store mid-run, and holding the todos.\n const version = `live:${fingerprint(0, live.turns, live.runs)}:${hashText(JSON.stringify([live.status, live.metadata]))}`\n return tracked(sessionId, async (read) => {\n const cached = documents.hit(sessionId, version)\n if (cached)\n return cached\n const entry = snapshotOf(live.toJSON(), version)\n if (!read.dropped)\n documents.keep(sessionId, entry)\n return entry\n })\n }\n // A reader: a load-time pairing heal stays in memory, the host's own agent persists the document.\n const load = async (): Promise<SessionData | null> => (await loadSession(store, sessionId, { persistHeal: false }))?.toJSON() ?? null\n return stored(documents, store, sessionId, load, snapshotOf, data => fingerprint(data.updatedAt, data.turns, data.runs))\n },\n observe(signal) {\n const sessionId = changedSessionOf(signal)\n if (sessionId !== undefined)\n drop(sessionId)\n },\n forget: drop,\n sizes: () => ({ entries: replays.size() + documents.size(), inFlight: inFlight.size }),\n }\n}\n\n/**\n * About the length of `JSON.stringify(value)`: what an entry holds, for the\n * byte budget. Walks the value without building the string (several times\n * cheaper on a long session); the budget is a heuristic, exact bytes are not\n * needed.\n */\nexport function approxJsonBytes(value: unknown): number {\n if (typeof value === 'string')\n return value.length + 2\n if (typeof value !== 'object' || value === null)\n return 8\n let bytes = 2\n if (Array.isArray(value)) {\n for (const item of value)\n bytes += approxJsonBytes(item) + 1\n return bytes\n }\n for (const key in value)\n bytes += key.length + 4 + approxJsonBytes((value as Record<string, unknown>)[key])\n return bytes\n}\n\nfunction storeVersion(meta: { rev?: number, updatedAt: number, turnCount: number, runCount: number }): string {\n return `meta:${meta.rev ?? '-'}:${meta.updatedAt}:${meta.turnCount}:${meta.runCount}`\n}\n\n/** A 32-bit FNV-1a: `mix` values in, `digest` (base 36) out. */\nfunction fnv1a() {\n let hash = 0x811C9DC5\n const add = (text: string): void => {\n for (let i = 0; i < text.length; i++)\n hash = Math.imul(hash ^ text.charCodeAt(i), 0x01000193)\n }\n return {\n add,\n /** One value, then a separator: `ab` + `c` never hashes as `a` + `bc`. */\n mix: (value: string | number | undefined): void => {\n add(String(value))\n hash = Math.imul(hash ^ 0x1F, 0x01000193)\n },\n digest: (): string => (hash >>> 0).toString(36),\n }\n}\n\nfunction hashText(text: string): string {\n const hash = fnv1a()\n hash.add(text)\n return hash.digest()\n}\n\n/** FNV-1a over the document's shape: what changes when a turn or run is added, removed, or rewritten. */\nfunction fingerprint(updatedAt: number, turns: readonly SessionTurn[], runs: readonly SessionRun[]): string {\n const { mix, digest } = fnv1a()\n for (const turn of turns) {\n mix(turn.id)\n mix(turn.role)\n mix(turn.runId)\n mix(typeof turn.display === 'string' ? turn.display : '')\n mix(typeof turn.injected === 'string' ? turn.injected : '')\n mix(turn.content.length)\n for (const block of turn.content) {\n mix(block.type)\n const fields = block as { text?: unknown, output?: unknown, summary?: unknown }\n for (const field of [fields.text, fields.output, fields.summary])\n mix(typeof field === 'string' ? field.length : Array.isArray(field) ? field.length : '')\n }\n }\n mix(JSON.stringify(runs))\n return `doc:${updatedAt}:${turns.length}:${runs.length}:${digest()}`\n}\n","/**\n * A read-only connection to a sessions database, from whichever runtime runs\n * the caller: `bun:sqlite` under Bun, `node:sqlite` under Node. The history\n * worker reads on one (`./worker.ts`); the host thread opens one when the\n * worker can't serve a usage scan (`./transcript.ts`).\n */\nimport type { SqliteDriver } from '../../session/sqlite-driver'\nimport { createSqliteDriver, OPEN_BUSY_TIMEOUT_MS } from '../../session/sqlite-driver'\n\n/**\n * Opens `path` read-only. A long wait on a writer's lock is bounded by the store's busy timeout.\n *\n * @param path - The sessions database.\n */\nexport async function openReadonlySqlite(path: string): Promise<SqliteDriver> {\n if (typeof Bun !== 'undefined') {\n const { Database } = await import('bun:sqlite')\n const db = new Database(path, { readonly: true })\n db.exec(`PRAGMA busy_timeout = ${OPEN_BUSY_TIMEOUT_MS}`)\n return createSqliteDriver(db, { close: () => db.close(false) })\n }\n const { DatabaseSync } = await import('node:sqlite')\n const db = new DatabaseSync(path, { readOnly: true })\n db.exec(`PRAGMA busy_timeout = ${OPEN_BUSY_TIMEOUT_MS}`)\n return createSqliteDriver(db)\n}\n"],"mappings":";;;;;;;;;;;;AAQA,IAAa,qBAAb,cAAwC,MAAM;CAC5C,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,MAAM,wBAAwB;;;;;;AAO9B,SAAgB,eAAe,OAAgB,OAAO,aAAqB;CACzE,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,uBACpE,MAAM,IAAI,mBAAmB,GAAG,KAAK,yCAAyC,sBAAsB,aAAa;CACnH,IAAI,UAAU,OAAO,UAAU,QAAQ,UAAU,KAAK,KAAK,GACzD,MAAM,IAAI,mBAAmB,GAAG,KAAK,iDAAiD;CACxF,OAAO;AACT;;AAGA,SAAgB,YAAY,QAA4D;CACtF,OAAO,eAAe,QAAQ,SAAS;AACzC;;AAGA,SAAgB,eAAe,OAAgB,MAAkC;CAC/E,IAAI,UAA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Aa,MAAM,OAAO;EAClC,MAAM,KAAK,IAAI,SAAS,MAAM,EAAE,UAAU,KAAK,CAAC;EAChD,GAAG,KAAK,yBAAyB,sBAAsB;EACvD,OAAO,mBAAmB,IAAI,EAAE,aAAa,GAAG,MAAM,KAAK,EAAE,CAAC;CAChE;CACA,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,MAAM,KAAK,IAAI,aAAa,MAAM,EAAE,UAAU,KAAK,CAAC;CACpD,GAAG,KAAK,yBAAyB,sBAAsB;CACvD,OAAO,mBAAmB,EAAE;AAC9B"}
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.js";
2
2
  import { p as errorMessage } from "./errors-C3z7pmOx.js";
3
3
  import { l as resolveOAuthApiKey } from "./oauth-7IvbubTT.js";
4
- import "./auth-store-port-DFgf22oo.js";
4
+ import "./auth-store-port-DBl2JUC6.js";
5
5
  //#region src/extensions/integrations/oauth.ts
6
6
  /** A token endpoint refused a request. */
7
7
  var OAuthTokenError = class extends Error {
@@ -1024,4 +1024,4 @@ function integrationRegistry() {
1024
1024
  //#endregion
1025
1025
  export { integrationRegistry as n, registry_exports as r, createIntegrationRegistry as t };
1026
1026
 
1027
- //# sourceMappingURL=registry-BKjeBnoy.js.map
1027
+ //# sourceMappingURL=registry-CBoYDIND.js.map