@graphrefly/graphrefly 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (714) hide show
  1. package/README.md +1 -2
  2. package/dist/_internal-B23BagFd.d.cts +33 -0
  3. package/dist/_internal-B23BagFd.d.ts +33 -0
  4. package/dist/adaptive-rate-limiter-Dch_xYIi.d.cts +111 -0
  5. package/dist/adaptive-rate-limiter-Dch_xYIi.d.ts +111 -0
  6. package/dist/agents-C0Ji9ldU.d.cts +629 -0
  7. package/dist/agents-C9zexT7I.d.ts +629 -0
  8. package/dist/audit-BAXb3VOg.d.ts +246 -0
  9. package/dist/audit-C_bPfkqS.d.cts +246 -0
  10. package/dist/backoff-7KIK3WQW.js +24 -0
  11. package/dist/backoff-7KIK3WQW.js.map +1 -0
  12. package/dist/backoff-Bnb9OoPh.d.cts +6 -0
  13. package/dist/backoff-Bnb9OoPh.d.ts +6 -0
  14. package/dist/base/composition/index.cjs +811 -0
  15. package/dist/base/composition/index.cjs.map +1 -0
  16. package/dist/base/composition/index.d.cts +469 -0
  17. package/dist/base/composition/index.d.ts +469 -0
  18. package/dist/base/composition/index.js +40 -0
  19. package/dist/base/composition/index.js.map +1 -0
  20. package/dist/base/index.cjs +6336 -0
  21. package/dist/base/index.cjs.map +1 -0
  22. package/dist/base/index.d.cts +22 -0
  23. package/dist/base/index.d.ts +22 -0
  24. package/dist/base/index.js +259 -0
  25. package/dist/base/index.js.map +1 -0
  26. package/dist/base/io/index.cjs +3270 -0
  27. package/dist/base/io/index.cjs.map +1 -0
  28. package/dist/base/io/index.d.cts +2245 -0
  29. package/dist/base/io/index.d.ts +2245 -0
  30. package/dist/base/io/index.js +117 -0
  31. package/dist/base/io/index.js.map +1 -0
  32. package/dist/base/meta/index.cjs +43 -0
  33. package/dist/base/meta/index.cjs.map +1 -0
  34. package/dist/base/meta/index.d.cts +45 -0
  35. package/dist/base/meta/index.d.ts +45 -0
  36. package/dist/base/meta/index.js +13 -0
  37. package/dist/base/meta/index.js.map +1 -0
  38. package/dist/base/mutation/index.cjs +200 -0
  39. package/dist/base/mutation/index.cjs.map +1 -0
  40. package/dist/base/mutation/index.d.cts +177 -0
  41. package/dist/base/mutation/index.d.ts +177 -0
  42. package/dist/base/mutation/index.js +22 -0
  43. package/dist/base/mutation/index.js.map +1 -0
  44. package/dist/base/render/index.cjs +1120 -0
  45. package/dist/base/render/index.cjs.map +1 -0
  46. package/dist/base/render/index.d.cts +227 -0
  47. package/dist/base/render/index.d.ts +227 -0
  48. package/dist/base/render/index.js +24 -0
  49. package/dist/base/render/index.js.map +1 -0
  50. package/dist/base/sources/browser/index.cjs +172 -0
  51. package/dist/base/sources/browser/index.cjs.map +1 -0
  52. package/dist/base/sources/browser/index.d.cts +84 -0
  53. package/dist/base/sources/browser/index.d.ts +84 -0
  54. package/dist/base/sources/browser/index.js +151 -0
  55. package/dist/base/sources/browser/index.js.map +1 -0
  56. package/dist/base/sources/event/index.cjs +98 -0
  57. package/dist/base/sources/event/index.cjs.map +1 -0
  58. package/dist/base/sources/event/index.d.cts +91 -0
  59. package/dist/base/sources/event/index.d.ts +91 -0
  60. package/dist/base/sources/event/index.js +13 -0
  61. package/dist/base/sources/event/index.js.map +1 -0
  62. package/dist/base/sources/index.cjs +755 -0
  63. package/dist/base/sources/index.cjs.map +1 -0
  64. package/dist/base/sources/index.d.cts +357 -0
  65. package/dist/base/sources/index.d.ts +357 -0
  66. package/dist/base/sources/index.js +42 -0
  67. package/dist/base/sources/index.js.map +1 -0
  68. package/dist/base/sources/node/index.cjs +320 -0
  69. package/dist/base/sources/node/index.cjs.map +1 -0
  70. package/dist/base/sources/node/index.d.cts +185 -0
  71. package/dist/base/sources/node/index.d.ts +185 -0
  72. package/dist/base/sources/node/index.js +306 -0
  73. package/dist/base/sources/node/index.js.map +1 -0
  74. package/dist/base/utils/index.cjs +37 -0
  75. package/dist/base/utils/index.cjs.map +1 -0
  76. package/dist/base/utils/index.d.cts +37 -0
  77. package/dist/base/utils/index.d.ts +37 -0
  78. package/dist/base/utils/index.js +11 -0
  79. package/dist/base/utils/index.js.map +1 -0
  80. package/dist/base/worker/index.cjs +548 -0
  81. package/dist/base/worker/index.cjs.map +1 -0
  82. package/dist/base/worker/index.d.cts +207 -0
  83. package/dist/base/worker/index.d.ts +207 -0
  84. package/dist/base/worker/index.js +20 -0
  85. package/dist/base/worker/index.js.map +1 -0
  86. package/dist/breaker-C9skL3d8.d.ts +175 -0
  87. package/dist/breaker-ugSdq54q.d.cts +175 -0
  88. package/dist/cascading-CSSbKGrJ.d.ts +199 -0
  89. package/dist/cascading-baGkiihI.d.cts +199 -0
  90. package/dist/chunk-255UCBG4.js +58 -0
  91. package/dist/chunk-255UCBG4.js.map +1 -0
  92. package/dist/chunk-2LO3EL4W.js +1 -0
  93. package/dist/chunk-2LO3EL4W.js.map +1 -0
  94. package/dist/chunk-2OB3CEJS.js +1065 -0
  95. package/dist/chunk-2OB3CEJS.js.map +1 -0
  96. package/dist/chunk-36NMM65U.js +144 -0
  97. package/dist/chunk-36NMM65U.js.map +1 -0
  98. package/dist/chunk-3CEXCBN6.js +1 -0
  99. package/dist/chunk-3CEXCBN6.js.map +1 -0
  100. package/dist/chunk-3MUSLI6E.js +105 -0
  101. package/dist/chunk-3MUSLI6E.js.map +1 -0
  102. package/dist/chunk-3PSLNJDU.js +884 -0
  103. package/dist/chunk-3PSLNJDU.js.map +1 -0
  104. package/dist/chunk-3QZY5BI7.js +92 -0
  105. package/dist/chunk-3QZY5BI7.js.map +1 -0
  106. package/dist/chunk-42FQ27MQ.js +594 -0
  107. package/dist/chunk-42FQ27MQ.js.map +1 -0
  108. package/dist/chunk-4GYMCUDZ.js +1085 -0
  109. package/dist/chunk-4GYMCUDZ.js.map +1 -0
  110. package/dist/chunk-4S53H2KR.js +382 -0
  111. package/dist/chunk-4S53H2KR.js.map +1 -0
  112. package/dist/chunk-4XCHZRUJ.js +128 -0
  113. package/dist/chunk-4XCHZRUJ.js.map +1 -0
  114. package/dist/chunk-5THCXDWY.js +725 -0
  115. package/dist/chunk-5THCXDWY.js.map +1 -0
  116. package/dist/chunk-6XZYT4SW.js +256 -0
  117. package/dist/chunk-6XZYT4SW.js.map +1 -0
  118. package/dist/chunk-7EGRP2VX.js +76 -0
  119. package/dist/chunk-7EGRP2VX.js.map +1 -0
  120. package/dist/chunk-A7KV5UK4.js +150 -0
  121. package/dist/chunk-A7KV5UK4.js.map +1 -0
  122. package/dist/chunk-APY2SS5X.js +156 -0
  123. package/dist/chunk-APY2SS5X.js.map +1 -0
  124. package/dist/chunk-AZDQPQ3V.js +66 -0
  125. package/dist/chunk-AZDQPQ3V.js.map +1 -0
  126. package/dist/chunk-BU3SEFA5.js +90 -0
  127. package/dist/chunk-BU3SEFA5.js.map +1 -0
  128. package/dist/chunk-BXGZFGZ4.js +189 -0
  129. package/dist/chunk-BXGZFGZ4.js.map +1 -0
  130. package/dist/chunk-CGHORL6G.js +579 -0
  131. package/dist/chunk-CGHORL6G.js.map +1 -0
  132. package/dist/chunk-CXANAIZU.js +530 -0
  133. package/dist/chunk-CXANAIZU.js.map +1 -0
  134. package/dist/chunk-CZQHCKKG.js +1 -0
  135. package/dist/chunk-CZQHCKKG.js.map +1 -0
  136. package/dist/chunk-DKNHAICT.js +133 -0
  137. package/dist/chunk-DKNHAICT.js.map +1 -0
  138. package/dist/chunk-DM4OMPWK.js +584 -0
  139. package/dist/chunk-DM4OMPWK.js.map +1 -0
  140. package/dist/chunk-DMSNO6ZB.js +452 -0
  141. package/dist/chunk-DMSNO6ZB.js.map +1 -0
  142. package/dist/chunk-E5OZPDIW.js +229 -0
  143. package/dist/chunk-E5OZPDIW.js.map +1 -0
  144. package/dist/chunk-EVYY4X5A.js +509 -0
  145. package/dist/chunk-EVYY4X5A.js.map +1 -0
  146. package/dist/chunk-FDFD67UO.js +1 -0
  147. package/dist/chunk-FDFD67UO.js.map +1 -0
  148. package/dist/chunk-FMPF42Q4.js +13 -0
  149. package/dist/chunk-FMPF42Q4.js.map +1 -0
  150. package/dist/chunk-FR6RGA3B.js +1277 -0
  151. package/dist/chunk-FR6RGA3B.js.map +1 -0
  152. package/dist/chunk-FW23JYNQ.js +454 -0
  153. package/dist/chunk-FW23JYNQ.js.map +1 -0
  154. package/dist/chunk-GBCENOLN.js +1575 -0
  155. package/dist/chunk-GBCENOLN.js.map +1 -0
  156. package/dist/chunk-HL7HUJIX.js +1 -0
  157. package/dist/chunk-HL7HUJIX.js.map +1 -0
  158. package/dist/chunk-HULCUY35.js +2508 -0
  159. package/dist/chunk-HULCUY35.js.map +1 -0
  160. package/dist/chunk-IHTWQEDR.js +169 -0
  161. package/dist/chunk-IHTWQEDR.js.map +1 -0
  162. package/dist/chunk-IJRR6YAI.js +128 -0
  163. package/dist/chunk-IJRR6YAI.js.map +1 -0
  164. package/dist/chunk-JGFRAFDL.js +221 -0
  165. package/dist/chunk-JGFRAFDL.js.map +1 -0
  166. package/dist/chunk-KIIXR252.js +211 -0
  167. package/dist/chunk-KIIXR252.js.map +1 -0
  168. package/dist/chunk-KN3H5CNT.js +11 -0
  169. package/dist/chunk-KN3H5CNT.js.map +1 -0
  170. package/dist/chunk-KPG3DGLA.js +1 -0
  171. package/dist/chunk-KPG3DGLA.js.map +1 -0
  172. package/dist/chunk-KRNQ6RGQ.js +1 -0
  173. package/dist/chunk-KRNQ6RGQ.js.map +1 -0
  174. package/dist/chunk-LBAJK24K.js +1071 -0
  175. package/dist/chunk-LBAJK24K.js.map +1 -0
  176. package/dist/chunk-MLTPJMH6.js +417 -0
  177. package/dist/chunk-MLTPJMH6.js.map +1 -0
  178. package/dist/chunk-N3SZ7BMH.js +95 -0
  179. package/dist/chunk-N3SZ7BMH.js.map +1 -0
  180. package/dist/chunk-NDUD3IMO.js +540 -0
  181. package/dist/chunk-NDUD3IMO.js.map +1 -0
  182. package/dist/chunk-NY2PYHNC.js +873 -0
  183. package/dist/chunk-NY2PYHNC.js.map +1 -0
  184. package/dist/chunk-O3MT7DYI.js +225 -0
  185. package/dist/chunk-O3MT7DYI.js.map +1 -0
  186. package/dist/chunk-OCUDSN63.js +2386 -0
  187. package/dist/chunk-OCUDSN63.js.map +1 -0
  188. package/dist/chunk-OIWU3NYV.js +199 -0
  189. package/dist/chunk-OIWU3NYV.js.map +1 -0
  190. package/dist/chunk-OO5BM6CJ.js +1153 -0
  191. package/dist/chunk-OO5BM6CJ.js.map +1 -0
  192. package/dist/chunk-OQUIJT7A.js +1 -0
  193. package/dist/chunk-OQUIJT7A.js.map +1 -0
  194. package/dist/chunk-P5LBT622.js +105 -0
  195. package/dist/chunk-P5LBT622.js.map +1 -0
  196. package/dist/chunk-PKGQG5QQ.js +519 -0
  197. package/dist/chunk-PKGQG5QQ.js.map +1 -0
  198. package/dist/chunk-PKPO3JTZ.js +561 -0
  199. package/dist/chunk-PKPO3JTZ.js.map +1 -0
  200. package/dist/chunk-PL5UDIQ5.js +118 -0
  201. package/dist/chunk-PL5UDIQ5.js.map +1 -0
  202. package/dist/chunk-PZWISPIQ.js +432 -0
  203. package/dist/chunk-PZWISPIQ.js.map +1 -0
  204. package/dist/chunk-Q3EYOCZB.js +510 -0
  205. package/dist/chunk-Q3EYOCZB.js.map +1 -0
  206. package/dist/chunk-QMBYUVRL.js +15 -0
  207. package/dist/chunk-QMBYUVRL.js.map +1 -0
  208. package/dist/chunk-RAGGHLCV.js +200 -0
  209. package/dist/chunk-RAGGHLCV.js.map +1 -0
  210. package/dist/chunk-RGL53X5G.js +574 -0
  211. package/dist/chunk-RGL53X5G.js.map +1 -0
  212. package/dist/chunk-RJOG4IJU.js +1039 -0
  213. package/dist/chunk-RJOG4IJU.js.map +1 -0
  214. package/dist/chunk-SOOKUYVM.js +403 -0
  215. package/dist/chunk-SOOKUYVM.js.map +1 -0
  216. package/dist/chunk-T5BN5KG7.js +1 -0
  217. package/dist/chunk-T5BN5KG7.js.map +1 -0
  218. package/dist/chunk-TP7244Y6.js +207 -0
  219. package/dist/chunk-TP7244Y6.js.map +1 -0
  220. package/dist/chunk-TSBFTJKM.js +57 -0
  221. package/dist/chunk-TSBFTJKM.js.map +1 -0
  222. package/dist/chunk-URQ2CBBF.js +143 -0
  223. package/dist/chunk-URQ2CBBF.js.map +1 -0
  224. package/dist/chunk-W2BOPXTI.js +1 -0
  225. package/dist/chunk-W2BOPXTI.js.map +1 -0
  226. package/dist/chunk-WKSWLSCX.js +207 -0
  227. package/dist/chunk-WKSWLSCX.js.map +1 -0
  228. package/dist/chunk-Y52CS6YA.js +88 -0
  229. package/dist/chunk-Y52CS6YA.js.map +1 -0
  230. package/dist/chunk-YCBUWK77.js +92 -0
  231. package/dist/chunk-YCBUWK77.js.map +1 -0
  232. package/dist/chunk-YJ4U2D2C.js +314 -0
  233. package/dist/chunk-YJ4U2D2C.js.map +1 -0
  234. package/dist/chunk-Z4YXAUDN.js +239 -0
  235. package/dist/chunk-Z4YXAUDN.js.map +1 -0
  236. package/dist/chunk-Z6EGP5D7.js +92 -0
  237. package/dist/chunk-Z6EGP5D7.js.map +1 -0
  238. package/dist/compat/index.cjs +3083 -2
  239. package/dist/compat/index.cjs.map +1 -1
  240. package/dist/compat/index.d.cts +116 -1
  241. package/dist/compat/index.d.ts +116 -1
  242. package/dist/compat/index.js +175 -2
  243. package/dist/compat/index.js.map +1 -1
  244. package/dist/compat/jotai/index.cjs +130 -2
  245. package/dist/compat/jotai/index.cjs.map +1 -1
  246. package/dist/compat/jotai/index.d.cts +2 -1
  247. package/dist/compat/jotai/index.d.ts +2 -1
  248. package/dist/compat/jotai/index.js +7 -2
  249. package/dist/compat/jotai/index.js.map +1 -1
  250. package/dist/compat/nanostores/index.cjs +186 -2
  251. package/dist/compat/nanostores/index.cjs.map +1 -1
  252. package/dist/compat/nanostores/index.d.cts +2 -1
  253. package/dist/compat/nanostores/index.d.ts +2 -1
  254. package/dist/compat/nanostores/index.js +21 -2
  255. package/dist/compat/nanostores/index.js.map +1 -1
  256. package/dist/compat/nestjs/index.cjs +2224 -2
  257. package/dist/compat/nestjs/index.cjs.map +1 -1
  258. package/dist/compat/nestjs/index.d.cts +10 -1
  259. package/dist/compat/nestjs/index.d.ts +10 -1
  260. package/dist/compat/nestjs/index.js +77 -2
  261. package/dist/compat/nestjs/index.js.map +1 -1
  262. package/dist/compat/react/index.cjs +95 -2
  263. package/dist/compat/react/index.cjs.map +1 -1
  264. package/dist/compat/react/index.d.cts +2 -1
  265. package/dist/compat/react/index.d.ts +2 -1
  266. package/dist/compat/react/index.js +11 -2
  267. package/dist/compat/react/index.js.map +1 -1
  268. package/dist/compat/solid/index.cjs +82 -2
  269. package/dist/compat/solid/index.cjs.map +1 -1
  270. package/dist/compat/solid/index.d.cts +2 -1
  271. package/dist/compat/solid/index.d.ts +2 -1
  272. package/dist/compat/solid/index.js +11 -2
  273. package/dist/compat/solid/index.js.map +1 -1
  274. package/dist/compat/svelte/index.cjs +85 -2
  275. package/dist/compat/svelte/index.cjs.map +1 -1
  276. package/dist/compat/svelte/index.d.cts +2 -1
  277. package/dist/compat/svelte/index.d.ts +2 -1
  278. package/dist/compat/svelte/index.js +11 -2
  279. package/dist/compat/svelte/index.js.map +1 -1
  280. package/dist/compat/vue/index.cjs +100 -2
  281. package/dist/compat/vue/index.cjs.map +1 -1
  282. package/dist/compat/vue/index.d.cts +3 -1
  283. package/dist/compat/vue/index.d.ts +3 -1
  284. package/dist/compat/vue/index.js +11 -2
  285. package/dist/compat/vue/index.js.map +1 -1
  286. package/dist/compat/zustand/index.cjs +50 -2
  287. package/dist/compat/zustand/index.cjs.map +1 -1
  288. package/dist/compat/zustand/index.d.cts +2 -1
  289. package/dist/compat/zustand/index.d.ts +2 -1
  290. package/dist/compat/zustand/index.js +7 -2
  291. package/dist/compat/zustand/index.js.map +1 -1
  292. package/dist/distill-De6Rnn15.d.cts +48 -0
  293. package/dist/distill-De6Rnn15.d.ts +48 -0
  294. package/dist/external-register-CWyroXb_.d.cts +138 -0
  295. package/dist/external-register-CWyroXb_.d.ts +138 -0
  296. package/dist/fallback-Bx46zqky.d.cts +243 -0
  297. package/dist/fallback-pIWW8A2d.d.ts +243 -0
  298. package/dist/guarded-execution-BcdtxeBk.d.ts +207 -0
  299. package/dist/guarded-execution-C-3hnP6A.d.cts +207 -0
  300. package/dist/index-5SU_O78r.d.cts +754 -0
  301. package/dist/index-B6pxYJzO.d.cts +36 -0
  302. package/dist/index-B6pxYJzO.d.ts +36 -0
  303. package/dist/index-BFsng6v1.d.cts +44 -0
  304. package/dist/index-BFsng6v1.d.ts +44 -0
  305. package/dist/index-Bg-LwEt-.d.cts +45 -0
  306. package/dist/index-Bg-LwEt-.d.ts +45 -0
  307. package/dist/index-Brp888t0.d.cts +127 -0
  308. package/dist/index-Brp888t0.d.ts +127 -0
  309. package/dist/index-CDfk6jHN.d.cts +37 -0
  310. package/dist/index-CDfk6jHN.d.ts +37 -0
  311. package/dist/index-CEXCtYYJ.d.ts +754 -0
  312. package/dist/index-DLAxYaN5.d.cts +169 -0
  313. package/dist/index-DLAxYaN5.d.ts +169 -0
  314. package/dist/index-DeWbQzMe.d.cts +34 -0
  315. package/dist/index-DeWbQzMe.d.ts +34 -0
  316. package/dist/index-dX9IzPqj.d.cts +86 -0
  317. package/dist/index-dX9IzPqj.d.ts +86 -0
  318. package/dist/index.cjs +25950 -0
  319. package/dist/index.cjs.map +1 -1
  320. package/dist/index.d.cts +56 -42
  321. package/dist/index.d.ts +56 -42
  322. package/dist/index.js +849 -0
  323. package/dist/index.js.map +1 -1
  324. package/dist/layout-types-B5aiHYgk.d.cts +72 -0
  325. package/dist/layout-types-B5aiHYgk.d.ts +72 -0
  326. package/dist/memory-composers-BryDrRBX.d.cts +529 -0
  327. package/dist/memory-composers-CVQqPYEV.d.ts +529 -0
  328. package/dist/observable-BXQoW1P-.d.cts +36 -0
  329. package/dist/observable-BXQoW1P-.d.ts +36 -0
  330. package/dist/pipeline-graph-Ce47CB6Y.d.cts +145 -0
  331. package/dist/pipeline-graph-DXCwY9vG.d.ts +145 -0
  332. package/dist/presets/ai/index.cjs +4377 -0
  333. package/dist/presets/ai/index.cjs.map +1 -0
  334. package/dist/presets/ai/index.d.cts +98 -0
  335. package/dist/presets/ai/index.d.ts +98 -0
  336. package/dist/presets/ai/index.js +54 -0
  337. package/dist/presets/ai/index.js.map +1 -0
  338. package/dist/presets/harness/index.cjs +5929 -0
  339. package/dist/presets/harness/index.cjs.map +1 -0
  340. package/dist/presets/harness/index.d.cts +566 -0
  341. package/dist/presets/harness/index.d.ts +566 -0
  342. package/dist/presets/harness/index.js +71 -0
  343. package/dist/presets/harness/index.js.map +1 -0
  344. package/dist/presets/index.cjs +9782 -0
  345. package/dist/presets/index.cjs.map +1 -0
  346. package/dist/presets/index.d.cts +28 -0
  347. package/dist/presets/index.d.ts +28 -0
  348. package/dist/presets/index.js +129 -0
  349. package/dist/presets/index.js.map +1 -0
  350. package/dist/presets/inspect/index.cjs +1087 -0
  351. package/dist/presets/inspect/index.cjs.map +1 -0
  352. package/dist/presets/inspect/index.d.cts +172 -0
  353. package/dist/presets/inspect/index.d.ts +172 -0
  354. package/dist/presets/inspect/index.js +21 -0
  355. package/dist/presets/inspect/index.js.map +1 -0
  356. package/dist/presets/resilience/index.cjs +1593 -0
  357. package/dist/presets/resilience/index.cjs.map +1 -0
  358. package/dist/presets/resilience/index.d.cts +205 -0
  359. package/dist/presets/resilience/index.d.ts +205 -0
  360. package/dist/presets/resilience/index.js +18 -0
  361. package/dist/presets/resilience/index.js.map +1 -0
  362. package/dist/rate-limiter-CEALq4N1.d.ts +559 -0
  363. package/dist/rate-limiter-DpVbSYdH.d.cts +559 -0
  364. package/dist/reactive-layout-fswlBUvX.d.cts +195 -0
  365. package/dist/reactive-layout-fswlBUvX.d.ts +195 -0
  366. package/dist/retry-BDbRZ_gx.d.ts +125 -0
  367. package/dist/retry-DWuhjvsA.d.cts +125 -0
  368. package/dist/solutions/index.cjs +8200 -0
  369. package/dist/solutions/index.cjs.map +1 -0
  370. package/dist/solutions/index.d.cts +23 -0
  371. package/dist/solutions/index.d.ts +23 -0
  372. package/dist/solutions/index.js +55 -0
  373. package/dist/solutions/index.js.map +1 -0
  374. package/dist/spawnable-5mDY501F.d.cts +746 -0
  375. package/dist/spawnable-D3lR0oQu.d.ts +746 -0
  376. package/dist/status-U-rUI79b.d.cts +84 -0
  377. package/dist/status-U-rUI79b.d.ts +84 -0
  378. package/dist/timeout-U5O4ESK3.js +12 -0
  379. package/dist/timeout-U5O4ESK3.js.map +1 -0
  380. package/dist/types-BB5Lw-pB.d.cts +442 -0
  381. package/dist/types-BB5Lw-pB.d.ts +442 -0
  382. package/dist/types-CJWIMJiZ.d.ts +548 -0
  383. package/dist/types-vCq7ShIm.d.cts +548 -0
  384. package/dist/utils/ai/browser.cjs +2169 -0
  385. package/dist/utils/ai/browser.cjs.map +1 -0
  386. package/dist/utils/ai/browser.d.cts +129 -0
  387. package/dist/utils/ai/browser.d.ts +129 -0
  388. package/dist/utils/ai/browser.js +255 -0
  389. package/dist/utils/ai/browser.js.map +1 -0
  390. package/dist/utils/ai/index.cjs +8468 -0
  391. package/dist/utils/ai/index.cjs.map +1 -0
  392. package/dist/utils/ai/index.d.cts +1777 -0
  393. package/dist/utils/ai/index.d.ts +1777 -0
  394. package/dist/utils/ai/index.js +173 -0
  395. package/dist/utils/ai/index.js.map +1 -0
  396. package/dist/utils/ai/node.cjs +648 -0
  397. package/dist/utils/ai/node.cjs.map +1 -0
  398. package/dist/utils/ai/node.d.cts +57 -0
  399. package/dist/utils/ai/node.d.ts +57 -0
  400. package/dist/utils/ai/node.js +84 -0
  401. package/dist/utils/ai/node.js.map +1 -0
  402. package/dist/utils/cqrs/index.cjs +1036 -0
  403. package/dist/utils/cqrs/index.cjs.map +1 -0
  404. package/dist/utils/cqrs/index.d.cts +438 -0
  405. package/dist/utils/cqrs/index.d.ts +438 -0
  406. package/dist/utils/cqrs/index.js +18 -0
  407. package/dist/utils/cqrs/index.js.map +1 -0
  408. package/dist/utils/demo-shell/index.cjs +865 -0
  409. package/dist/utils/demo-shell/index.cjs.map +1 -0
  410. package/dist/utils/demo-shell/index.d.cts +90 -0
  411. package/dist/utils/demo-shell/index.d.ts +90 -0
  412. package/dist/utils/demo-shell/index.js +13 -0
  413. package/dist/utils/demo-shell/index.js.map +1 -0
  414. package/dist/utils/domain-templates/index.cjs +732 -0
  415. package/dist/utils/domain-templates/index.cjs.map +1 -0
  416. package/dist/utils/domain-templates/index.d.cts +214 -0
  417. package/dist/utils/domain-templates/index.d.ts +214 -0
  418. package/dist/utils/domain-templates/index.js +17 -0
  419. package/dist/utils/domain-templates/index.js.map +1 -0
  420. package/dist/utils/graphspec/index.cjs +1174 -0
  421. package/dist/utils/graphspec/index.cjs.map +1 -0
  422. package/dist/utils/graphspec/index.d.cts +449 -0
  423. package/dist/utils/graphspec/index.d.ts +449 -0
  424. package/dist/utils/graphspec/index.js +35 -0
  425. package/dist/utils/graphspec/index.js.map +1 -0
  426. package/dist/utils/harness/index.cjs +656 -0
  427. package/dist/utils/harness/index.cjs.map +1 -0
  428. package/dist/utils/harness/index.d.cts +542 -0
  429. package/dist/utils/harness/index.d.ts +542 -0
  430. package/dist/utils/harness/index.js +56 -0
  431. package/dist/utils/harness/index.js.map +1 -0
  432. package/dist/utils/index.cjs +17609 -0
  433. package/dist/utils/index.cjs.map +1 -0
  434. package/dist/utils/index.d.cts +96 -0
  435. package/dist/utils/index.d.ts +96 -0
  436. package/dist/utils/index.js +514 -0
  437. package/dist/utils/index.js.map +1 -0
  438. package/dist/utils/inspect/index.cjs +807 -0
  439. package/dist/utils/inspect/index.cjs.map +1 -0
  440. package/dist/utils/inspect/index.d.cts +123 -0
  441. package/dist/utils/inspect/index.d.ts +123 -0
  442. package/dist/utils/inspect/index.js +30 -0
  443. package/dist/utils/inspect/index.js.map +1 -0
  444. package/dist/utils/job-queue/index.cjs +717 -0
  445. package/dist/utils/job-queue/index.cjs.map +1 -0
  446. package/dist/utils/job-queue/index.d.cts +200 -0
  447. package/dist/utils/job-queue/index.d.ts +200 -0
  448. package/dist/utils/job-queue/index.js +18 -0
  449. package/dist/utils/job-queue/index.js.map +1 -0
  450. package/dist/utils/memory/index.cjs +1451 -0
  451. package/dist/utils/memory/index.cjs.map +1 -0
  452. package/dist/utils/memory/index.d.cts +582 -0
  453. package/dist/utils/memory/index.d.ts +582 -0
  454. package/dist/utils/memory/index.js +19 -0
  455. package/dist/utils/memory/index.js.map +1 -0
  456. package/dist/utils/messaging/index.cjs +666 -0
  457. package/dist/utils/messaging/index.cjs.map +1 -0
  458. package/dist/utils/messaging/index.d.cts +562 -0
  459. package/dist/utils/messaging/index.d.ts +562 -0
  460. package/dist/utils/messaging/index.js +50 -0
  461. package/dist/utils/messaging/index.js.map +1 -0
  462. package/dist/utils/orchestration/index.cjs +876 -0
  463. package/dist/utils/orchestration/index.cjs.map +1 -0
  464. package/dist/utils/orchestration/index.d.cts +233 -0
  465. package/dist/utils/orchestration/index.d.ts +233 -0
  466. package/dist/utils/orchestration/index.js +19 -0
  467. package/dist/utils/orchestration/index.js.map +1 -0
  468. package/dist/utils/process/index.cjs +743 -0
  469. package/dist/utils/process/index.cjs.map +1 -0
  470. package/dist/utils/process/index.d.cts +411 -0
  471. package/dist/utils/process/index.d.ts +411 -0
  472. package/dist/utils/process/index.js +14 -0
  473. package/dist/utils/process/index.js.map +1 -0
  474. package/dist/utils/reactive-layout/index.cjs +1607 -0
  475. package/dist/utils/reactive-layout/index.cjs.map +1 -0
  476. package/dist/utils/reactive-layout/index.d.cts +492 -0
  477. package/dist/utils/reactive-layout/index.d.ts +492 -0
  478. package/dist/utils/reactive-layout/index.js +52 -0
  479. package/dist/utils/reactive-layout/index.js.map +1 -0
  480. package/dist/utils/reduction/index.cjs +203 -0
  481. package/dist/utils/reduction/index.cjs.map +1 -0
  482. package/dist/utils/reduction/index.d.cts +102 -0
  483. package/dist/utils/reduction/index.d.ts +102 -0
  484. package/dist/utils/reduction/index.js +14 -0
  485. package/dist/utils/reduction/index.js.map +1 -0
  486. package/dist/utils/resilience/index.cjs +1617 -0
  487. package/dist/utils/resilience/index.cjs.map +1 -0
  488. package/dist/utils/resilience/index.d.cts +9 -0
  489. package/dist/utils/resilience/index.d.ts +9 -0
  490. package/dist/utils/resilience/index.js +44 -0
  491. package/dist/utils/resilience/index.js.map +1 -0
  492. package/dist/utils/surface/index.cjs +1070 -0
  493. package/dist/utils/surface/index.cjs.map +1 -0
  494. package/dist/utils/surface/index.d.cts +240 -0
  495. package/dist/utils/surface/index.d.ts +240 -0
  496. package/dist/utils/surface/index.js +30 -0
  497. package/dist/utils/surface/index.js.map +1 -0
  498. package/dist/utils/topology-view/index.cjs +620 -0
  499. package/dist/utils/topology-view/index.cjs.map +1 -0
  500. package/dist/utils/topology-view/index.d.cts +68 -0
  501. package/dist/utils/topology-view/index.d.ts +68 -0
  502. package/dist/utils/topology-view/index.js +11 -0
  503. package/dist/utils/topology-view/index.js.map +1 -0
  504. package/package.json +293 -237
  505. package/dist/core/index.cjs +0 -21
  506. package/dist/core/index.cjs.map +0 -1
  507. package/dist/core/index.d.cts +0 -1
  508. package/dist/core/index.d.ts +0 -1
  509. package/dist/core/index.js +0 -3
  510. package/dist/core/index.js.map +0 -1
  511. package/dist/extra/browser.cjs +0 -21
  512. package/dist/extra/browser.cjs.map +0 -1
  513. package/dist/extra/browser.d.cts +0 -1
  514. package/dist/extra/browser.d.ts +0 -1
  515. package/dist/extra/browser.js +0 -3
  516. package/dist/extra/browser.js.map +0 -1
  517. package/dist/extra/index.cjs +0 -21
  518. package/dist/extra/index.cjs.map +0 -1
  519. package/dist/extra/index.d.cts +0 -1
  520. package/dist/extra/index.d.ts +0 -1
  521. package/dist/extra/index.js +0 -3
  522. package/dist/extra/index.js.map +0 -1
  523. package/dist/extra/node.cjs +0 -21
  524. package/dist/extra/node.cjs.map +0 -1
  525. package/dist/extra/node.d.cts +0 -1
  526. package/dist/extra/node.d.ts +0 -1
  527. package/dist/extra/node.js +0 -3
  528. package/dist/extra/node.js.map +0 -1
  529. package/dist/extra/operators.cjs +0 -21
  530. package/dist/extra/operators.cjs.map +0 -1
  531. package/dist/extra/operators.d.cts +0 -1
  532. package/dist/extra/operators.d.ts +0 -1
  533. package/dist/extra/operators.js +0 -3
  534. package/dist/extra/operators.js.map +0 -1
  535. package/dist/extra/reactive.cjs +0 -21
  536. package/dist/extra/reactive.cjs.map +0 -1
  537. package/dist/extra/reactive.d.cts +0 -1
  538. package/dist/extra/reactive.d.ts +0 -1
  539. package/dist/extra/reactive.js +0 -3
  540. package/dist/extra/reactive.js.map +0 -1
  541. package/dist/extra/render/index.cjs +0 -21
  542. package/dist/extra/render/index.cjs.map +0 -1
  543. package/dist/extra/render/index.d.cts +0 -1
  544. package/dist/extra/render/index.d.ts +0 -1
  545. package/dist/extra/render/index.js +0 -3
  546. package/dist/extra/render/index.js.map +0 -1
  547. package/dist/extra/sources.cjs +0 -21
  548. package/dist/extra/sources.cjs.map +0 -1
  549. package/dist/extra/sources.d.cts +0 -1
  550. package/dist/extra/sources.d.ts +0 -1
  551. package/dist/extra/sources.js +0 -3
  552. package/dist/extra/sources.js.map +0 -1
  553. package/dist/extra/storage-browser.cjs +0 -21
  554. package/dist/extra/storage-browser.cjs.map +0 -1
  555. package/dist/extra/storage-browser.d.cts +0 -1
  556. package/dist/extra/storage-browser.d.ts +0 -1
  557. package/dist/extra/storage-browser.js +0 -3
  558. package/dist/extra/storage-browser.js.map +0 -1
  559. package/dist/extra/storage-core.cjs +0 -21
  560. package/dist/extra/storage-core.cjs.map +0 -1
  561. package/dist/extra/storage-core.d.cts +0 -1
  562. package/dist/extra/storage-core.d.ts +0 -1
  563. package/dist/extra/storage-core.js +0 -3
  564. package/dist/extra/storage-core.js.map +0 -1
  565. package/dist/extra/storage-node.cjs +0 -21
  566. package/dist/extra/storage-node.cjs.map +0 -1
  567. package/dist/extra/storage-node.d.cts +0 -1
  568. package/dist/extra/storage-node.d.ts +0 -1
  569. package/dist/extra/storage-node.js +0 -3
  570. package/dist/extra/storage-node.js.map +0 -1
  571. package/dist/extra/storage-tiers-browser.cjs +0 -21
  572. package/dist/extra/storage-tiers-browser.cjs.map +0 -1
  573. package/dist/extra/storage-tiers-browser.d.cts +0 -1
  574. package/dist/extra/storage-tiers-browser.d.ts +0 -1
  575. package/dist/extra/storage-tiers-browser.js +0 -3
  576. package/dist/extra/storage-tiers-browser.js.map +0 -1
  577. package/dist/extra/storage-tiers-node.cjs +0 -21
  578. package/dist/extra/storage-tiers-node.cjs.map +0 -1
  579. package/dist/extra/storage-tiers-node.d.cts +0 -1
  580. package/dist/extra/storage-tiers-node.d.ts +0 -1
  581. package/dist/extra/storage-tiers-node.js +0 -3
  582. package/dist/extra/storage-tiers-node.js.map +0 -1
  583. package/dist/extra/storage-tiers.cjs +0 -21
  584. package/dist/extra/storage-tiers.cjs.map +0 -1
  585. package/dist/extra/storage-tiers.d.cts +0 -1
  586. package/dist/extra/storage-tiers.d.ts +0 -1
  587. package/dist/extra/storage-tiers.js +0 -3
  588. package/dist/extra/storage-tiers.js.map +0 -1
  589. package/dist/extra/storage-wal.cjs +0 -21
  590. package/dist/extra/storage-wal.cjs.map +0 -1
  591. package/dist/extra/storage-wal.d.cts +0 -1
  592. package/dist/extra/storage-wal.d.ts +0 -1
  593. package/dist/extra/storage-wal.js +0 -3
  594. package/dist/extra/storage-wal.js.map +0 -1
  595. package/dist/graph/index.cjs +0 -21
  596. package/dist/graph/index.cjs.map +0 -1
  597. package/dist/graph/index.d.cts +0 -1
  598. package/dist/graph/index.d.ts +0 -1
  599. package/dist/graph/index.js +0 -3
  600. package/dist/graph/index.js.map +0 -1
  601. package/dist/patterns/ai/browser.cjs +0 -21
  602. package/dist/patterns/ai/browser.cjs.map +0 -1
  603. package/dist/patterns/ai/browser.d.cts +0 -1
  604. package/dist/patterns/ai/browser.d.ts +0 -1
  605. package/dist/patterns/ai/browser.js +0 -3
  606. package/dist/patterns/ai/browser.js.map +0 -1
  607. package/dist/patterns/ai/index.cjs +0 -21
  608. package/dist/patterns/ai/index.cjs.map +0 -1
  609. package/dist/patterns/ai/index.d.cts +0 -1
  610. package/dist/patterns/ai/index.d.ts +0 -1
  611. package/dist/patterns/ai/index.js +0 -3
  612. package/dist/patterns/ai/index.js.map +0 -1
  613. package/dist/patterns/ai/node.cjs +0 -21
  614. package/dist/patterns/ai/node.cjs.map +0 -1
  615. package/dist/patterns/ai/node.d.cts +0 -1
  616. package/dist/patterns/ai/node.d.ts +0 -1
  617. package/dist/patterns/ai/node.js +0 -3
  618. package/dist/patterns/ai/node.js.map +0 -1
  619. package/dist/patterns/cqrs/index.cjs +0 -21
  620. package/dist/patterns/cqrs/index.cjs.map +0 -1
  621. package/dist/patterns/cqrs/index.d.cts +0 -1
  622. package/dist/patterns/cqrs/index.d.ts +0 -1
  623. package/dist/patterns/cqrs/index.js +0 -3
  624. package/dist/patterns/cqrs/index.js.map +0 -1
  625. package/dist/patterns/demo-shell/index.cjs +0 -21
  626. package/dist/patterns/demo-shell/index.cjs.map +0 -1
  627. package/dist/patterns/demo-shell/index.d.cts +0 -1
  628. package/dist/patterns/demo-shell/index.d.ts +0 -1
  629. package/dist/patterns/demo-shell/index.js +0 -3
  630. package/dist/patterns/demo-shell/index.js.map +0 -1
  631. package/dist/patterns/domain-templates/index.cjs +0 -21
  632. package/dist/patterns/domain-templates/index.cjs.map +0 -1
  633. package/dist/patterns/domain-templates/index.d.cts +0 -1
  634. package/dist/patterns/domain-templates/index.d.ts +0 -1
  635. package/dist/patterns/domain-templates/index.js +0 -3
  636. package/dist/patterns/domain-templates/index.js.map +0 -1
  637. package/dist/patterns/graphspec/index.cjs +0 -21
  638. package/dist/patterns/graphspec/index.cjs.map +0 -1
  639. package/dist/patterns/graphspec/index.d.cts +0 -1
  640. package/dist/patterns/graphspec/index.d.ts +0 -1
  641. package/dist/patterns/graphspec/index.js +0 -3
  642. package/dist/patterns/graphspec/index.js.map +0 -1
  643. package/dist/patterns/harness/index.cjs +0 -21
  644. package/dist/patterns/harness/index.cjs.map +0 -1
  645. package/dist/patterns/harness/index.d.cts +0 -1
  646. package/dist/patterns/harness/index.d.ts +0 -1
  647. package/dist/patterns/harness/index.js +0 -3
  648. package/dist/patterns/harness/index.js.map +0 -1
  649. package/dist/patterns/inspect/index.cjs +0 -21
  650. package/dist/patterns/inspect/index.cjs.map +0 -1
  651. package/dist/patterns/inspect/index.d.cts +0 -1
  652. package/dist/patterns/inspect/index.d.ts +0 -1
  653. package/dist/patterns/inspect/index.js +0 -3
  654. package/dist/patterns/inspect/index.js.map +0 -1
  655. package/dist/patterns/job-queue/index.cjs +0 -21
  656. package/dist/patterns/job-queue/index.cjs.map +0 -1
  657. package/dist/patterns/job-queue/index.d.cts +0 -1
  658. package/dist/patterns/job-queue/index.d.ts +0 -1
  659. package/dist/patterns/job-queue/index.js +0 -3
  660. package/dist/patterns/job-queue/index.js.map +0 -1
  661. package/dist/patterns/memory/index.cjs +0 -21
  662. package/dist/patterns/memory/index.cjs.map +0 -1
  663. package/dist/patterns/memory/index.d.cts +0 -1
  664. package/dist/patterns/memory/index.d.ts +0 -1
  665. package/dist/patterns/memory/index.js +0 -3
  666. package/dist/patterns/memory/index.js.map +0 -1
  667. package/dist/patterns/messaging/index.cjs +0 -21
  668. package/dist/patterns/messaging/index.cjs.map +0 -1
  669. package/dist/patterns/messaging/index.d.cts +0 -1
  670. package/dist/patterns/messaging/index.d.ts +0 -1
  671. package/dist/patterns/messaging/index.js +0 -3
  672. package/dist/patterns/messaging/index.js.map +0 -1
  673. package/dist/patterns/orchestration/index.cjs +0 -21
  674. package/dist/patterns/orchestration/index.cjs.map +0 -1
  675. package/dist/patterns/orchestration/index.d.cts +0 -1
  676. package/dist/patterns/orchestration/index.d.ts +0 -1
  677. package/dist/patterns/orchestration/index.js +0 -3
  678. package/dist/patterns/orchestration/index.js.map +0 -1
  679. package/dist/patterns/process/index.cjs +0 -21
  680. package/dist/patterns/process/index.cjs.map +0 -1
  681. package/dist/patterns/process/index.d.cts +0 -1
  682. package/dist/patterns/process/index.d.ts +0 -1
  683. package/dist/patterns/process/index.js +0 -3
  684. package/dist/patterns/process/index.js.map +0 -1
  685. package/dist/patterns/reactive-layout/index.cjs +0 -21
  686. package/dist/patterns/reactive-layout/index.cjs.map +0 -1
  687. package/dist/patterns/reactive-layout/index.d.cts +0 -1
  688. package/dist/patterns/reactive-layout/index.d.ts +0 -1
  689. package/dist/patterns/reactive-layout/index.js +0 -3
  690. package/dist/patterns/reactive-layout/index.js.map +0 -1
  691. package/dist/patterns/reduction/index.cjs +0 -21
  692. package/dist/patterns/reduction/index.cjs.map +0 -1
  693. package/dist/patterns/reduction/index.d.cts +0 -1
  694. package/dist/patterns/reduction/index.d.ts +0 -1
  695. package/dist/patterns/reduction/index.js +0 -3
  696. package/dist/patterns/reduction/index.js.map +0 -1
  697. package/dist/patterns/surface/index.cjs +0 -21
  698. package/dist/patterns/surface/index.cjs.map +0 -1
  699. package/dist/patterns/surface/index.d.cts +0 -1
  700. package/dist/patterns/surface/index.d.ts +0 -1
  701. package/dist/patterns/surface/index.js +0 -3
  702. package/dist/patterns/surface/index.js.map +0 -1
  703. package/dist/patterns/topology-view/index.cjs +0 -21
  704. package/dist/patterns/topology-view/index.cjs.map +0 -1
  705. package/dist/patterns/topology-view/index.d.cts +0 -1
  706. package/dist/patterns/topology-view/index.d.ts +0 -1
  707. package/dist/patterns/topology-view/index.js +0 -3
  708. package/dist/patterns/topology-view/index.js.map +0 -1
  709. package/dist/testing/index.cjs +0 -21
  710. package/dist/testing/index.cjs.map +0 -1
  711. package/dist/testing/index.d.cts +0 -1
  712. package/dist/testing/index.d.ts +0 -1
  713. package/dist/testing/index.js +0 -3
  714. package/dist/testing/index.js.map +0 -1
@@ -0,0 +1,2169 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // src/base/resilience/_internal.ts
34
+ function clampNonNegative(value) {
35
+ return value < 0 ? 0 : value;
36
+ }
37
+ function isNode(x) {
38
+ return x != null && typeof x === "object" && "cache" in x && typeof x.subscribe === "function";
39
+ }
40
+ var import_core13;
41
+ var init_internal = __esm({
42
+ "src/base/resilience/_internal.ts"() {
43
+ "use strict";
44
+ import_core13 = require("@graphrefly/pure-ts/core");
45
+ }
46
+ });
47
+
48
+ // src/base/resilience/backoff.ts
49
+ var NS_PER_SEC;
50
+ var init_backoff = __esm({
51
+ "src/base/resilience/backoff.ts"() {
52
+ "use strict";
53
+ NS_PER_SEC = 1e9;
54
+ }
55
+ });
56
+
57
+ // src/utils/ai/browser.ts
58
+ var browser_exports = {};
59
+ __export(browser_exports, {
60
+ chromeNanoAdapter: () => chromeNanoAdapter,
61
+ cloudFirstPreset: () => cloudFirstPreset,
62
+ localFirstPreset: () => localFirstPreset,
63
+ offlinePreset: () => offlinePreset,
64
+ webllmAdapter: () => webllmAdapter
65
+ });
66
+ module.exports = __toCommonJS(browser_exports);
67
+
68
+ // src/utils/ai/adapters/providers/browser/chrome-nano.ts
69
+ var import_core = require("@graphrefly/pure-ts/core");
70
+ function makeAbortError() {
71
+ const err = new Error("aborted");
72
+ err.name = "AbortError";
73
+ return err;
74
+ }
75
+ function chromeNanoAdapter(opts = {}) {
76
+ const streamMode = opts.streamMode ?? "accumulated";
77
+ const nav = opts.navigatorOverride ?? globalThis.navigator;
78
+ const getAi = () => {
79
+ const ai = nav?.ai;
80
+ if (!ai?.languageModel)
81
+ throw new Error(
82
+ "chromeNanoAdapter: Chrome AI languageModel not available (requires Chrome 131+ with flag/OT)."
83
+ );
84
+ return ai;
85
+ };
86
+ const session = async (invokeOpts) => {
87
+ const ai = getAi();
88
+ return ai.languageModel.create({
89
+ systemPrompt: invokeOpts?.systemPrompt ?? opts.systemPrompt,
90
+ temperature: invokeOpts?.temperature ?? opts.temperature,
91
+ topK: opts.topK,
92
+ signal: invokeOpts?.signal
93
+ });
94
+ };
95
+ const flatten = (messages) => {
96
+ const parts = [];
97
+ for (const m of messages) {
98
+ if (m.role === "system") continue;
99
+ parts.push(`${m.role}: ${m.content}`);
100
+ }
101
+ return parts.join("\n\n");
102
+ };
103
+ const zeroUsage = () => ({ input: { regular: 0 }, output: { regular: 0 } });
104
+ return {
105
+ provider: "chrome-nano",
106
+ model: "chrome-nano",
107
+ async invoke(messages, invokeOpts) {
108
+ const sess = await session(invokeOpts);
109
+ try {
110
+ const prompt = flatten(messages);
111
+ const start = (0, import_core.monotonicNs)();
112
+ const content = await sess.prompt(prompt, { signal: invokeOpts?.signal });
113
+ const latencyMs = Math.max(0, ((0, import_core.monotonicNs)() - start) / 1e6);
114
+ return {
115
+ content,
116
+ usage: zeroUsage(),
117
+ finishReason: "stop",
118
+ latencyMs,
119
+ model: "chrome-nano",
120
+ provider: "chrome-nano"
121
+ };
122
+ } finally {
123
+ sess.destroy?.();
124
+ }
125
+ },
126
+ async *stream(messages, invokeOpts) {
127
+ const sess = await session(invokeOpts);
128
+ try {
129
+ const prompt = flatten(messages);
130
+ if (streamMode === "delta") {
131
+ for await (const chunk of sess.promptStreaming(prompt, {
132
+ signal: invokeOpts?.signal
133
+ })) {
134
+ if (invokeOpts?.signal?.aborted) throw makeAbortError();
135
+ if (chunk) yield { type: "token", delta: chunk };
136
+ }
137
+ } else {
138
+ let last = "";
139
+ for await (const chunk of sess.promptStreaming(prompt, {
140
+ signal: invokeOpts?.signal
141
+ })) {
142
+ if (invokeOpts?.signal?.aborted) throw makeAbortError();
143
+ const delta = chunk.startsWith(last) ? chunk.slice(last.length) : chunk;
144
+ last = chunk;
145
+ if (delta) yield { type: "token", delta };
146
+ }
147
+ }
148
+ yield { type: "usage", usage: zeroUsage() };
149
+ yield { type: "finish", reason: "stop" };
150
+ } finally {
151
+ sess.destroy?.();
152
+ }
153
+ }
154
+ };
155
+ }
156
+
157
+ // src/utils/ai/adapters/providers/browser/webllm.ts
158
+ var import_core2 = require("@graphrefly/pure-ts/core");
159
+ function makeAbortError2() {
160
+ const err = new Error("aborted");
161
+ err.name = "AbortError";
162
+ return err;
163
+ }
164
+ function webllmAdapter(opts) {
165
+ let engine = opts.engine;
166
+ const ensureEngine = async () => {
167
+ if (engine) return engine;
168
+ if (!isWebGpuAvailable(opts.navigatorOverride))
169
+ throw new Error("webllmAdapter: WebGPU not available in this environment");
170
+ const mod = await import("@mlc-ai/web-llm").catch(() => {
171
+ throw new Error(
172
+ "webllmAdapter: @mlc-ai/web-llm not installed. Add it as a peer dependency or pass opts.engine."
173
+ );
174
+ });
175
+ const factory = mod.CreateMLCEngine;
176
+ if (!factory) throw new Error("webllmAdapter: @mlc-ai/web-llm missing CreateMLCEngine export");
177
+ engine = await factory(opts.model, { initProgressCallback: opts.initProgressCallback });
178
+ return engine;
179
+ };
180
+ const flatten = (messages, invokeOpts) => {
181
+ const flat = [];
182
+ if (invokeOpts?.systemPrompt) flat.push({ role: "system", content: invokeOpts.systemPrompt });
183
+ for (const m of messages)
184
+ flat.push({ role: m.role === "tool" ? "user" : m.role, content: m.content });
185
+ return flat;
186
+ };
187
+ const mapUsage4 = (u) => ({
188
+ input: { regular: u?.prompt_tokens ?? 0 },
189
+ output: { regular: u?.completion_tokens ?? 0 },
190
+ raw: u
191
+ });
192
+ return {
193
+ provider: "webllm",
194
+ model: opts.model,
195
+ async invoke(messages, invokeOpts) {
196
+ const eng = await ensureEngine();
197
+ const start = (0, import_core2.monotonicNs)();
198
+ const resp = await eng.chat.completions.create(
199
+ {
200
+ model: invokeOpts?.model ?? opts.model,
201
+ messages: flatten(messages, invokeOpts),
202
+ max_tokens: invokeOpts?.maxTokens,
203
+ temperature: invokeOpts?.temperature
204
+ },
205
+ { signal: invokeOpts?.signal }
206
+ );
207
+ const latencyMs = Math.max(0, ((0, import_core2.monotonicNs)() - start) / 1e6);
208
+ const choice = resp.choices?.[0];
209
+ return {
210
+ content: choice?.message?.content ?? "",
211
+ usage: mapUsage4(resp.usage),
212
+ finishReason: choice?.finish_reason,
213
+ latencyMs,
214
+ model: opts.model,
215
+ provider: "webllm"
216
+ };
217
+ },
218
+ async *stream(messages, invokeOpts) {
219
+ const eng = await ensureEngine();
220
+ const asyncIter = await eng.chat.completions.create(
221
+ {
222
+ model: invokeOpts?.model ?? opts.model,
223
+ messages: flatten(messages, invokeOpts),
224
+ max_tokens: invokeOpts?.maxTokens,
225
+ temperature: invokeOpts?.temperature,
226
+ stream: true
227
+ },
228
+ { signal: invokeOpts?.signal }
229
+ );
230
+ let finalUsage;
231
+ let finishReason;
232
+ for await (const chunk of asyncIter) {
233
+ if (invokeOpts?.signal?.aborted) throw makeAbortError2();
234
+ const c = chunk.choices?.[0];
235
+ if (c?.delta?.content) yield { type: "token", delta: c.delta.content };
236
+ if (c?.finish_reason) finishReason = c.finish_reason;
237
+ if (chunk.usage) finalUsage = chunk.usage;
238
+ }
239
+ if (finalUsage) yield { type: "usage", usage: mapUsage4(finalUsage) };
240
+ yield { type: "finish", reason: finishReason ?? "stop" };
241
+ }
242
+ };
243
+ }
244
+ function isWebGpuAvailable(navOverride) {
245
+ const nav = navOverride ?? globalThis.navigator;
246
+ return !!(nav && "gpu" in nav && nav.gpu);
247
+ }
248
+
249
+ // src/utils/ai/adapters/providers/anthropic.ts
250
+ var import_core4 = require("@graphrefly/pure-ts/core");
251
+
252
+ // src/base/io/http-error.ts
253
+ async function makeHttpError(resp, provider) {
254
+ let body;
255
+ try {
256
+ body = await resp.text();
257
+ } catch {
258
+ body = "";
259
+ }
260
+ const prefix = provider ?? "HTTP";
261
+ const err = new Error(
262
+ `${prefix} API ${resp.status}: ${resp.statusText}${body ? ` \u2014 ${body}` : ""}`
263
+ );
264
+ err.status = resp.status;
265
+ err.headers = resp.headers;
266
+ return err;
267
+ }
268
+
269
+ // src/base/io/sse.ts
270
+ var import_core3 = require("@graphrefly/pure-ts/core");
271
+ async function* parseSSEStream(source, opts) {
272
+ const parse = opts?.parse ?? ((raw) => raw);
273
+ const externalSignal = opts?.signal;
274
+ const decoder = new TextDecoder();
275
+ let buffer = "";
276
+ let currentEvent = "message";
277
+ let currentData = [];
278
+ let currentId;
279
+ let currentRetry;
280
+ const queue = [];
281
+ const flushEvent = () => {
282
+ if (currentData.length === 0 && currentEvent === "message" && currentId === void 0) {
283
+ currentData = [];
284
+ return;
285
+ }
286
+ const raw = currentData.join("\n");
287
+ queue.push({
288
+ event: currentEvent,
289
+ data: parse(raw),
290
+ id: currentId,
291
+ retry: currentRetry
292
+ });
293
+ currentEvent = "message";
294
+ currentData = [];
295
+ currentId = void 0;
296
+ currentRetry = void 0;
297
+ };
298
+ const processLine = (line) => {
299
+ if (line === "") {
300
+ flushEvent();
301
+ return;
302
+ }
303
+ if (line.startsWith(":")) return;
304
+ const colon = line.indexOf(":");
305
+ const field = colon < 0 ? line : line.slice(0, colon);
306
+ let value = colon < 0 ? "" : line.slice(colon + 1);
307
+ if (value.startsWith(" ")) value = value.slice(1);
308
+ switch (field) {
309
+ case "event":
310
+ currentEvent = value;
311
+ break;
312
+ case "data":
313
+ currentData.push(value);
314
+ break;
315
+ case "id":
316
+ if (!value.includes("\0")) currentId = value;
317
+ break;
318
+ case "retry": {
319
+ const n = Number(value);
320
+ if (Number.isFinite(n)) currentRetry = n;
321
+ break;
322
+ }
323
+ }
324
+ };
325
+ const processChunk = (chunk, done) => {
326
+ buffer += decoder.decode(chunk, { stream: !done });
327
+ const parts = buffer.split(/\r?\n/);
328
+ buffer = parts.pop() ?? "";
329
+ for (const line of parts) processLine(line);
330
+ };
331
+ const resp = source;
332
+ const stream = source instanceof ReadableStream ? source : resp && typeof resp === "object" && resp.body instanceof ReadableStream ? resp.body : null;
333
+ let reader;
334
+ let iter;
335
+ let cleanupDone = false;
336
+ const cleanupReader = () => {
337
+ if (cleanupDone) return;
338
+ cleanupDone = true;
339
+ if (reader) {
340
+ void reader.cancel().catch(() => void 0);
341
+ }
342
+ if (iter && typeof iter.return === "function") {
343
+ void Promise.resolve(iter.return()).catch(() => void 0);
344
+ }
345
+ };
346
+ const onAbort = () => {
347
+ cleanupReader();
348
+ };
349
+ if (externalSignal) {
350
+ if (externalSignal.aborted) return;
351
+ externalSignal.addEventListener("abort", onAbort, { once: true });
352
+ }
353
+ try {
354
+ if (stream) {
355
+ reader = stream.getReader();
356
+ while (!externalSignal?.aborted) {
357
+ const { value, done } = await reader.read();
358
+ if (done) break;
359
+ processChunk(value, false);
360
+ while (queue.length > 0) {
361
+ const ev = queue.shift();
362
+ yield ev;
363
+ }
364
+ }
365
+ processChunk(new Uint8Array(), true);
366
+ } else {
367
+ const asyncIter = source;
368
+ iter = asyncIter[Symbol.asyncIterator]();
369
+ while (!externalSignal?.aborted) {
370
+ const step = await iter.next();
371
+ if (step.done) break;
372
+ processChunk(step.value, false);
373
+ while (queue.length > 0) {
374
+ const ev = queue.shift();
375
+ yield ev;
376
+ }
377
+ }
378
+ processChunk(new Uint8Array(), true);
379
+ }
380
+ if (buffer.trim()) {
381
+ for (const line of buffer.split(/\r?\n/)) processLine(line);
382
+ flushEvent();
383
+ }
384
+ while (queue.length > 0) {
385
+ const ev = queue.shift();
386
+ yield ev;
387
+ }
388
+ } finally {
389
+ if (externalSignal) {
390
+ externalSignal.removeEventListener("abort", onAbort);
391
+ }
392
+ cleanupReader();
393
+ }
394
+ }
395
+
396
+ // src/utils/ai/adapters/providers/anthropic.ts
397
+ function anthropicAdapter(opts = {}) {
398
+ if (opts.sdk) return sdkBackedAnthropic(opts);
399
+ return fetchBackedAnthropic(opts);
400
+ }
401
+ function toAnthropicRequest(messages, invokeOpts, defaultModel, stream) {
402
+ const model = invokeOpts?.model ?? defaultModel;
403
+ if (!model)
404
+ throw new Error("anthropicAdapter: model must be set via options.model or invokeOpts.model");
405
+ const { system, chat } = partitionSystem(messages, invokeOpts?.systemPrompt);
406
+ const body = {
407
+ model,
408
+ messages: chat.map(toAnthropicMessage),
409
+ max_tokens: invokeOpts?.maxTokens ?? 4096
410
+ };
411
+ if (system) body.system = system;
412
+ if (invokeOpts?.temperature != null) body.temperature = invokeOpts.temperature;
413
+ if (invokeOpts?.tools && invokeOpts.tools.length > 0)
414
+ body.tools = invokeOpts.tools.map(toAnthropicTool);
415
+ if (invokeOpts?.maxReasoningTokens != null) {
416
+ body.thinking = { type: "enabled", budget_tokens: invokeOpts.maxReasoningTokens };
417
+ }
418
+ if (invokeOpts?.cacheHint) {
419
+ }
420
+ if (stream) body.stream = true;
421
+ if (invokeOpts?.providerExtras) Object.assign(body, invokeOpts.providerExtras);
422
+ return body;
423
+ }
424
+ function partitionSystem(messages, systemPrompt) {
425
+ const systemParts = [];
426
+ if (systemPrompt) systemParts.push(systemPrompt);
427
+ const chat = [];
428
+ for (const m of messages) {
429
+ if (m.role === "system") systemParts.push(m.content);
430
+ else chat.push(m);
431
+ }
432
+ return { system: systemParts.length > 0 ? systemParts.join("\n\n") : void 0, chat };
433
+ }
434
+ function toAnthropicMessage(m) {
435
+ if (m.role === "tool") {
436
+ return {
437
+ role: "user",
438
+ content: [
439
+ {
440
+ type: "tool_result",
441
+ tool_use_id: m.toolCallId,
442
+ content: m.content
443
+ }
444
+ ]
445
+ };
446
+ }
447
+ if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {
448
+ const blocks = [];
449
+ if (m.content) blocks.push({ type: "text", text: m.content });
450
+ for (const tc of m.toolCalls) {
451
+ blocks.push({ type: "tool_use", id: tc.id, name: tc.name, input: tc.arguments });
452
+ }
453
+ return { role: "assistant", content: blocks };
454
+ }
455
+ return { role: m.role, content: m.content };
456
+ }
457
+ function toAnthropicTool(t) {
458
+ return {
459
+ name: t.name,
460
+ description: t.description,
461
+ input_schema: t.parameters
462
+ };
463
+ }
464
+ function mergeAnthropicUsage(prev, next) {
465
+ if (!prev) return { ...next };
466
+ const merged = { ...prev };
467
+ if (next.input_tokens != null) merged.input_tokens = next.input_tokens;
468
+ if (next.output_tokens != null) merged.output_tokens = next.output_tokens;
469
+ if (next.cache_read_input_tokens != null)
470
+ merged.cache_read_input_tokens = next.cache_read_input_tokens;
471
+ if (next.cache_creation_input_tokens != null)
472
+ merged.cache_creation_input_tokens = next.cache_creation_input_tokens;
473
+ if (next.cache_creation) {
474
+ merged.cache_creation = {
475
+ ...prev.cache_creation ?? {},
476
+ ...next.cache_creation
477
+ };
478
+ }
479
+ if (next.server_tool_use) {
480
+ merged.server_tool_use = {
481
+ ...prev.server_tool_use ?? {},
482
+ ...next.server_tool_use
483
+ };
484
+ }
485
+ return merged;
486
+ }
487
+ function mapUsage(u) {
488
+ const usage = {
489
+ input: { regular: u?.input_tokens ?? 0 },
490
+ output: { regular: u?.output_tokens ?? 0 },
491
+ raw: u
492
+ };
493
+ if (u?.cache_read_input_tokens) usage.input.cacheRead = u.cache_read_input_tokens;
494
+ if (u?.cache_creation) {
495
+ if (u.cache_creation.ephemeral_5m_input_tokens)
496
+ usage.input.cacheWrite5m = u.cache_creation.ephemeral_5m_input_tokens;
497
+ if (u.cache_creation.ephemeral_1h_input_tokens)
498
+ usage.input.cacheWrite1h = u.cache_creation.ephemeral_1h_input_tokens;
499
+ } else if (u?.cache_creation_input_tokens) {
500
+ usage.input.cacheWrite5m = u.cache_creation_input_tokens;
501
+ }
502
+ if (u?.server_tool_use?.web_search_requests) {
503
+ usage.auxiliary = { webSearchRequests: u.server_tool_use.web_search_requests };
504
+ }
505
+ return usage;
506
+ }
507
+ function toLLMResponse(msg, latencyMs) {
508
+ const textParts = [];
509
+ const toolCalls = [];
510
+ for (const block of msg.content) {
511
+ if (block.type === "text" && typeof block.text === "string") {
512
+ textParts.push(block.text);
513
+ } else if (block.type === "tool_use") {
514
+ const tb = block;
515
+ toolCalls.push({ id: tb.id, name: tb.name, arguments: tb.input ?? {} });
516
+ }
517
+ }
518
+ return {
519
+ content: textParts.join(""),
520
+ toolCalls: toolCalls.length > 0 ? toolCalls : void 0,
521
+ usage: mapUsage(msg.usage),
522
+ finishReason: msg.stop_reason,
523
+ latencyMs,
524
+ model: msg.model,
525
+ provider: "anthropic"
526
+ };
527
+ }
528
+ function fetchBackedAnthropic(opts) {
529
+ const apiKey = opts.apiKey ?? globalThis.process?.env?.ANTHROPIC_API_KEY;
530
+ if (!apiKey) {
531
+ }
532
+ const baseURL = opts.baseURL ?? "https://api.anthropic.com";
533
+ const anthropicVersion = opts.anthropicVersion ?? "2023-06-01";
534
+ const fetchImpl = opts.fetchImpl ?? fetch;
535
+ const commonHeaders = () => {
536
+ if (!apiKey)
537
+ throw new Error("anthropicAdapter: apiKey required for invoke/stream (or provide opts.sdk)");
538
+ return {
539
+ "x-api-key": apiKey,
540
+ "anthropic-version": anthropicVersion,
541
+ "content-type": "application/json",
542
+ ...opts.headers ?? {}
543
+ };
544
+ };
545
+ return {
546
+ provider: "anthropic",
547
+ model: opts.model,
548
+ async invoke(messages, invokeOpts) {
549
+ const body = toAnthropicRequest(messages, invokeOpts, opts.model, false);
550
+ const start = (0, import_core4.monotonicNs)();
551
+ const resp = await fetchImpl(`${baseURL}/v1/messages`, {
552
+ method: "POST",
553
+ headers: commonHeaders(),
554
+ body: JSON.stringify(body),
555
+ signal: invokeOpts?.signal
556
+ });
557
+ if (!resp.ok) throw await makeHttpError(resp, "Anthropic");
558
+ const json = await resp.json();
559
+ const latencyMs = Math.max(0, ((0, import_core4.monotonicNs)() - start) / 1e6);
560
+ return toLLMResponse(json, latencyMs);
561
+ },
562
+ async *stream(messages, invokeOpts) {
563
+ const body = toAnthropicRequest(messages, invokeOpts, opts.model, true);
564
+ const resp = await fetchImpl(`${baseURL}/v1/messages`, {
565
+ method: "POST",
566
+ headers: { ...commonHeaders(), accept: "text/event-stream" },
567
+ body: JSON.stringify(body),
568
+ signal: invokeOpts?.signal
569
+ });
570
+ if (!resp.ok) throw await makeHttpError(resp, "Anthropic");
571
+ if (!resp.body) throw new Error("anthropicAdapter: streaming response has no body");
572
+ let finalUsage;
573
+ let finishReason;
574
+ const toolCallsByIndex = /* @__PURE__ */ new Map();
575
+ for await (const event of parseSSEStream(resp.body, { signal: invokeOpts?.signal })) {
576
+ const data = event.data;
577
+ if (!data) continue;
578
+ let parsed;
579
+ try {
580
+ parsed = JSON.parse(data);
581
+ } catch {
582
+ continue;
583
+ }
584
+ switch (parsed.type) {
585
+ case "message_start": {
586
+ const ms = parsed;
587
+ finalUsage = mergeAnthropicUsage(finalUsage, ms.message.usage);
588
+ break;
589
+ }
590
+ case "content_block_start": {
591
+ const cb = parsed;
592
+ const b = cb.content_block;
593
+ if (b.type === "tool_use") {
594
+ toolCallsByIndex.set(cb.index, {
595
+ id: String(b.id ?? ""),
596
+ name: String(b.name ?? ""),
597
+ argBuf: ""
598
+ });
599
+ yield {
600
+ type: "tool-call-delta",
601
+ delta: { id: String(b.id ?? ""), name: String(b.name ?? "") }
602
+ };
603
+ }
604
+ break;
605
+ }
606
+ case "content_block_delta": {
607
+ const cbd = parsed;
608
+ const d = cbd.delta;
609
+ if (d.type === "text_delta" && typeof d.text === "string") {
610
+ yield { type: "token", delta: d.text };
611
+ } else if (d.type === "input_json_delta" && typeof d.partial_json === "string") {
612
+ const existing = toolCallsByIndex.get(cbd.index);
613
+ if (existing) existing.argBuf += d.partial_json;
614
+ yield {
615
+ type: "tool-call-delta",
616
+ delta: { argumentsDelta: d.partial_json }
617
+ };
618
+ } else if (d.type === "thinking_delta" && typeof d.thinking === "string") {
619
+ yield { type: "thinking", delta: d.thinking };
620
+ }
621
+ break;
622
+ }
623
+ case "message_delta": {
624
+ const md = parsed;
625
+ if (md.delta.stop_reason) finishReason = md.delta.stop_reason;
626
+ if (md.delta.usage) {
627
+ finalUsage = mergeAnthropicUsage(finalUsage, md.delta.usage);
628
+ }
629
+ break;
630
+ }
631
+ case "message_stop":
632
+ break;
633
+ }
634
+ }
635
+ if (finalUsage) yield { type: "usage", usage: mapUsage(finalUsage) };
636
+ yield { type: "finish", reason: finishReason ?? "stop" };
637
+ }
638
+ };
639
+ }
640
+ function sdkBackedAnthropic(opts) {
641
+ const sdk = opts.sdk;
642
+ if (!sdk) throw new Error("sdkBackedAnthropic: sdk instance required");
643
+ return {
644
+ provider: "anthropic",
645
+ model: opts.model,
646
+ async invoke(messages, invokeOpts) {
647
+ const body = toAnthropicRequest(messages, invokeOpts, opts.model, false);
648
+ const start = (0, import_core4.monotonicNs)();
649
+ const resp = await sdk.messages.create(body, {
650
+ signal: invokeOpts?.signal
651
+ });
652
+ const latencyMs = Math.max(0, ((0, import_core4.monotonicNs)() - start) / 1e6);
653
+ return toLLMResponse(resp, latencyMs);
654
+ },
655
+ async *stream(messages, invokeOpts) {
656
+ if (!sdk.messages.stream) {
657
+ throw new Error("sdkBackedAnthropic: SDK instance does not expose .messages.stream");
658
+ }
659
+ const body = toAnthropicRequest(messages, invokeOpts, opts.model, true);
660
+ let finalUsage;
661
+ let finishReason;
662
+ for await (const event of sdk.messages.stream(body, { signal: invokeOpts?.signal })) {
663
+ switch (event.type) {
664
+ case "message_start":
665
+ finalUsage = mergeAnthropicUsage(
666
+ finalUsage,
667
+ event.message.usage
668
+ );
669
+ break;
670
+ case "content_block_delta": {
671
+ const d = event.delta;
672
+ if (d?.type === "text_delta" && typeof d.text === "string") {
673
+ yield { type: "token", delta: d.text };
674
+ } else if (d?.type === "input_json_delta" && typeof d.partial_json === "string") {
675
+ yield { type: "tool-call-delta", delta: { argumentsDelta: d.partial_json } };
676
+ } else if (d?.type === "thinking_delta" && typeof d.thinking === "string") {
677
+ yield { type: "thinking", delta: d.thinking };
678
+ }
679
+ break;
680
+ }
681
+ case "message_delta": {
682
+ const md = event;
683
+ if (md.delta.stop_reason) finishReason = md.delta.stop_reason;
684
+ if (md.delta.usage) finalUsage = mergeAnthropicUsage(finalUsage, md.delta.usage);
685
+ break;
686
+ }
687
+ }
688
+ }
689
+ if (finalUsage) yield { type: "usage", usage: mapUsage(finalUsage) };
690
+ yield { type: "finish", reason: finishReason ?? "stop" };
691
+ }
692
+ };
693
+ }
694
+
695
+ // src/utils/ai/adapters/providers/dry-run.ts
696
+ var import_core5 = require("@graphrefly/pure-ts/core");
697
+ function makeAbortError3() {
698
+ const err = new Error("aborted");
699
+ err.name = "AbortError";
700
+ return err;
701
+ }
702
+ function sleep(ms, signal) {
703
+ if (ms <= 0) return Promise.resolve();
704
+ if (signal?.aborted) return Promise.reject(makeAbortError3());
705
+ return new Promise((resolve, reject) => {
706
+ const timer = new import_core5.ResettableTimer();
707
+ let onAbort;
708
+ const cleanup = () => {
709
+ timer.cancel();
710
+ if (signal && onAbort) signal.removeEventListener("abort", onAbort);
711
+ };
712
+ timer.start(ms, () => {
713
+ cleanup();
714
+ resolve();
715
+ });
716
+ if (signal) {
717
+ onAbort = () => {
718
+ cleanup();
719
+ reject(makeAbortError3());
720
+ };
721
+ signal.addEventListener("abort", onAbort, { once: true });
722
+ }
723
+ });
724
+ }
725
+ function dryRunAdapter(opts = {}) {
726
+ const provider = opts.provider ?? "dry-run";
727
+ const model = opts.model ?? "dry-run-v1";
728
+ const latencyMs = opts.latencyMs ?? 0;
729
+ const streamChunkSize = Math.max(1, opts.streamChunkSize ?? 16);
730
+ const respondFn = opts.respond ?? ((msgs) => {
731
+ const lastUser = [...msgs].reverse().find((m) => m.role === "user");
732
+ return lastUser ? `echo: ${lastUser.content}` : "dry-run: no user message";
733
+ });
734
+ const usageFn = opts.usage ?? ((msgs, content) => {
735
+ const totalInput = msgs.reduce((s, m) => s + m.content.length, 0);
736
+ return {
737
+ input: { regular: Math.ceil(totalInput / 4) },
738
+ output: { regular: Math.ceil(content.length / 4) }
739
+ };
740
+ });
741
+ return {
742
+ provider,
743
+ model,
744
+ async invoke(messages, invokeOpts) {
745
+ await sleep(latencyMs, invokeOpts?.signal);
746
+ if (invokeOpts?.signal?.aborted) throw makeAbortError3();
747
+ const content = respondFn(messages, invokeOpts);
748
+ const usage = usageFn(messages, content);
749
+ return {
750
+ content,
751
+ usage,
752
+ finishReason: "stop",
753
+ model: invokeOpts?.model ?? model,
754
+ provider,
755
+ tier: invokeOpts?.tier,
756
+ metadata: { dryRun: true }
757
+ };
758
+ },
759
+ async *stream(messages, invokeOpts) {
760
+ const content = respondFn(messages, invokeOpts);
761
+ const usage = usageFn(messages, content);
762
+ const chunkCount = Math.ceil(content.length / streamChunkSize) || 1;
763
+ const perChunkMs = latencyMs > 0 ? latencyMs / chunkCount : 0;
764
+ for (let i = 0; i < content.length; i += streamChunkSize) {
765
+ if (invokeOpts?.signal?.aborted) throw makeAbortError3();
766
+ await sleep(perChunkMs, invokeOpts?.signal);
767
+ yield { type: "token", delta: content.slice(i, i + streamChunkSize) };
768
+ }
769
+ yield { type: "usage", usage };
770
+ yield { type: "finish", reason: "stop" };
771
+ }
772
+ };
773
+ }
774
+
775
+ // src/utils/ai/adapters/providers/fallback.ts
776
+ var import_core10 = require("@graphrefly/pure-ts/core");
777
+ var import_extra5 = require("@graphrefly/pure-ts/extra");
778
+
779
+ // src/utils/ai/adapters/middleware/replay-cache.ts
780
+ var import_core9 = require("@graphrefly/pure-ts/core");
781
+ var import_extra4 = require("@graphrefly/pure-ts/extra");
782
+
783
+ // src/base/composition/single-from-any.ts
784
+ var import_core7 = require("@graphrefly/pure-ts/core");
785
+ var import_extra = require("@graphrefly/pure-ts/extra");
786
+
787
+ // src/base/sources/settled.ts
788
+ var import_core6 = require("@graphrefly/pure-ts/core");
789
+ function firstValueFrom(source) {
790
+ return new Promise((resolve, reject) => {
791
+ let settled = false;
792
+ let shouldUnsub = false;
793
+ let unsub;
794
+ unsub = source.subscribe((msgs) => {
795
+ for (const m of msgs) {
796
+ if (settled) return;
797
+ if (m[0] === import_core6.DATA) {
798
+ settled = true;
799
+ resolve(m[1]);
800
+ if (unsub) {
801
+ unsub();
802
+ unsub = void 0;
803
+ } else shouldUnsub = true;
804
+ return;
805
+ }
806
+ if (m[0] === import_core6.ERROR) {
807
+ settled = true;
808
+ reject(m[1]);
809
+ if (unsub) {
810
+ unsub();
811
+ unsub = void 0;
812
+ } else shouldUnsub = true;
813
+ return;
814
+ }
815
+ if (m[0] === import_core6.COMPLETE) {
816
+ settled = true;
817
+ reject(new Error("completed without DATA"));
818
+ if (unsub) {
819
+ unsub();
820
+ unsub = void 0;
821
+ } else shouldUnsub = true;
822
+ return;
823
+ }
824
+ }
825
+ });
826
+ if (shouldUnsub) {
827
+ unsub?.();
828
+ unsub = void 0;
829
+ }
830
+ });
831
+ }
832
+
833
+ // src/base/composition/single-from-any.ts
834
+ function singleFromAny(factory, opts = {}) {
835
+ const keyFn = opts.keyFn ?? ((k) => String(k));
836
+ const inFlight = /* @__PURE__ */ new Map();
837
+ return (key) => {
838
+ const k = keyFn(key);
839
+ const existing = inFlight.get(k);
840
+ if (existing) return existing;
841
+ const input = factory(key);
842
+ let rawPromise;
843
+ if (input != null && typeof input.then === "function") {
844
+ rawPromise = Promise.resolve(input);
845
+ } else if (input != null && typeof input === "object" && "subscribe" in input && "cache" in input) {
846
+ rawPromise = firstValueFrom(input);
847
+ } else if (input != null && typeof input === "object" && Symbol.asyncIterator in input) {
848
+ rawPromise = (async () => {
849
+ const iter = input[Symbol.asyncIterator]();
850
+ try {
851
+ const { value, done } = await iter.next();
852
+ if (done) throw new Error("singleFromAny: factory returned empty async iterable");
853
+ return value;
854
+ } finally {
855
+ await iter.return?.();
856
+ }
857
+ })();
858
+ } else if (input != null && typeof input === "object" && Symbol.iterator in input) {
859
+ rawPromise = (async () => {
860
+ const iter = input[Symbol.iterator]();
861
+ try {
862
+ const { value, done } = iter.next();
863
+ if (done) throw new Error("singleFromAny: factory returned empty iterable");
864
+ return value;
865
+ } finally {
866
+ iter.return?.();
867
+ }
868
+ })();
869
+ } else {
870
+ rawPromise = Promise.resolve(input);
871
+ }
872
+ let tracked;
873
+ const cleanup = () => {
874
+ if (inFlight.get(k) === tracked) inFlight.delete(k);
875
+ };
876
+ tracked = rawPromise.then(
877
+ (v) => {
878
+ cleanup();
879
+ return v;
880
+ },
881
+ (e) => {
882
+ cleanup();
883
+ throw e;
884
+ }
885
+ );
886
+ inFlight.set(k, tracked);
887
+ return tracked;
888
+ };
889
+ }
890
+
891
+ // src/utils/ai/adapters/_internal/content-addressed-cache.ts
892
+ var import_extra2 = require("@graphrefly/pure-ts/extra");
893
+ function contentAddressedCache(opts) {
894
+ const { storage, mode = "read-write", keyFn, keyPrefix = "llm-replay" } = opts;
895
+ const substrateMode = mode === "read-strict" ? "read" : mode;
896
+ const substrate = (0, import_extra2.contentAddressedStorage)({
897
+ storage,
898
+ keyPrefix,
899
+ mode: substrateMode,
900
+ keyContext: ({ messages, opts: invokeOpts }) => {
901
+ const { signal: _signal, keyContext: _keyContext, ...rest } = invokeOpts ?? {};
902
+ return { messages, opts: rest };
903
+ }
904
+ });
905
+ async function keyFor(messages, invokeOpts) {
906
+ if (keyFn) {
907
+ if (keyFn.length <= 1) {
908
+ const ctx = {
909
+ messages,
910
+ opts: invokeOpts,
911
+ context: invokeOpts?.keyContext
912
+ };
913
+ const raw2 = await keyFn(ctx);
914
+ return `${keyPrefix}:${raw2}`;
915
+ }
916
+ const raw = await keyFn(messages, invokeOpts);
917
+ return `${keyPrefix}:${raw}`;
918
+ }
919
+ return substrate.keyFor({ messages, opts: invokeOpts });
920
+ }
921
+ return {
922
+ keyFor,
923
+ async lookup(messages, invokeOpts) {
924
+ if (mode === "write") return void 0;
925
+ if (keyFn) {
926
+ const key = await keyFor(messages, invokeOpts);
927
+ const raw = await storage.load(key);
928
+ if (raw === void 0) return void 0;
929
+ return raw;
930
+ }
931
+ return substrate.lookup({ messages, opts: invokeOpts });
932
+ },
933
+ async store(messages, invokeOpts, value) {
934
+ if (mode === "read") return;
935
+ if (keyFn) {
936
+ const key = await keyFor(messages, invokeOpts);
937
+ await storage.save(key, value);
938
+ return;
939
+ }
940
+ await substrate.store({ messages, opts: invokeOpts }, value);
941
+ },
942
+ async forget(messages, invokeOpts) {
943
+ if (mode === "read" || mode === "write") return;
944
+ if (!storage.delete) return;
945
+ if (keyFn) {
946
+ const key = await keyFor(messages, invokeOpts);
947
+ await storage.delete(key);
948
+ return;
949
+ }
950
+ await substrate.forget({ messages, opts: invokeOpts });
951
+ }
952
+ };
953
+ }
954
+
955
+ // src/utils/ai/adapters/_internal/wrappers.ts
956
+ var import_core8 = require("@graphrefly/pure-ts/core");
957
+ var import_extra3 = require("@graphrefly/pure-ts/extra");
958
+ function adapterWrapper(inner, impl, override) {
959
+ return {
960
+ provider: override?.provider ?? inner.provider,
961
+ model: override?.model ?? inner.model,
962
+ capabilities: override?.capabilities ?? inner.capabilities?.bind(inner),
963
+ invoke: impl.invoke,
964
+ stream: impl.stream
965
+ };
966
+ }
967
+ var MIDDLEWARE_LAYERS = /* @__PURE__ */ Symbol.for("graphrefly.adapter.middlewareLayers");
968
+ function withLayer(adapter, layerName, inner) {
969
+ const innerLayers = inner ? readLayers(inner) : [];
970
+ const chain = [...innerLayers, layerName];
971
+ Object.defineProperty(adapter, MIDDLEWARE_LAYERS, {
972
+ value: Object.freeze(chain),
973
+ enumerable: false,
974
+ writable: false,
975
+ configurable: false
976
+ });
977
+ return adapter;
978
+ }
979
+ function readLayers(adapter) {
980
+ const v = adapter[MIDDLEWARE_LAYERS];
981
+ return Array.isArray(v) ? v : [];
982
+ }
983
+
984
+ // src/utils/ai/adapters/middleware/replay-cache.ts
985
+ var ReplayCacheMissError = class extends Error {
986
+ constructor(key, method) {
987
+ super(`withReplayCache: no cached response for ${method} (key=${key}, mode=read-strict)`);
988
+ this.key = key;
989
+ this.method = method;
990
+ }
991
+ name = "ReplayCacheMissError";
992
+ };
993
+ function withReplayCache(inner, opts) {
994
+ const mode = opts.mode ?? "read-write";
995
+ const cacheStreaming = opts.cacheStreaming ?? false;
996
+ const captureStreamCadence = opts.captureStreamCadence ?? false;
997
+ const replaySpeed = opts.replaySpeed ?? 1;
998
+ const keyPrefix = opts.keyPrefix ?? "llm-replay";
999
+ const isReadOnly = mode === "read" || mode === "read-strict";
1000
+ const cache = contentAddressedCache({
1001
+ storage: opts.storage,
1002
+ mode: mode === "write-only" ? "write" : mode,
1003
+ keyFn: opts.keyFn,
1004
+ keyPrefix
1005
+ });
1006
+ const sleepMs = (ms) => ms <= 0 ? Promise.resolve() : new Promise((resolve) => {
1007
+ const t = new import_core9.ResettableTimer();
1008
+ t.start(ms, () => resolve());
1009
+ });
1010
+ const upstreamInFlight = singleFromAny(
1011
+ async ({ messages, invokeOpts }) => {
1012
+ return await firstValueFrom((0, import_extra4.fromAny)(inner.invoke(messages, invokeOpts)));
1013
+ },
1014
+ { keyFn: ({ _precomputedKey }) => _precomputedKey }
1015
+ );
1016
+ const wrap = adapterWrapper(inner, {
1017
+ async invoke(messages, invokeOpts) {
1018
+ const key = await cache.keyFor(messages, invokeOpts);
1019
+ const entry = await cache.lookup(messages, invokeOpts);
1020
+ if (entry?.response) {
1021
+ const cached = entry.response;
1022
+ return { ...cached, metadata: { ...cached.metadata ?? {}, replayCache: "hit" } };
1023
+ }
1024
+ if (mode === "read-strict") throw new ReplayCacheMissError(key, "invoke");
1025
+ const resp = await upstreamInFlight({ messages, invokeOpts, _precomputedKey: key });
1026
+ if (!isReadOnly) {
1027
+ await cache.store(messages, invokeOpts, { response: resp, storedAtNs: (0, import_core9.wallClockNs)() });
1028
+ }
1029
+ return resp;
1030
+ },
1031
+ async *stream(messages, invokeOpts) {
1032
+ if (!cacheStreaming) {
1033
+ for await (const delta of inner.stream(messages, invokeOpts)) yield delta;
1034
+ return;
1035
+ }
1036
+ const key = await cache.keyFor(messages, invokeOpts);
1037
+ const entry = await cache.lookup(messages, invokeOpts);
1038
+ if (entry) {
1039
+ const cached = entry.response;
1040
+ if (entry.streamChunks && entry.streamCadenceMs) {
1041
+ for (let i = 0; i < entry.streamChunks.length; i++) {
1042
+ const delay = entry.streamCadenceMs[i] ?? 0;
1043
+ const effective = replaySpeed > 0 ? delay / replaySpeed : 0;
1044
+ if (effective > 0) await sleepMs(effective);
1045
+ yield { type: "token", delta: entry.streamChunks[i]?.delta ?? "" };
1046
+ }
1047
+ } else if (cached.content) {
1048
+ yield { type: "token", delta: cached.content };
1049
+ }
1050
+ if (cached.usage) yield { type: "usage", usage: cached.usage };
1051
+ yield { type: "finish", reason: cached.finishReason ?? "stop" };
1052
+ return;
1053
+ }
1054
+ if (mode === "read-strict") throw new ReplayCacheMissError(key, "stream");
1055
+ let content = "";
1056
+ let usage;
1057
+ let finishReason;
1058
+ const chunks = [];
1059
+ const delaysMs = [];
1060
+ let lastNs;
1061
+ for await (const delta of inner.stream(messages, invokeOpts)) {
1062
+ if (delta.type === "token") {
1063
+ content += delta.delta;
1064
+ if (captureStreamCadence) {
1065
+ const now = (0, import_core9.monotonicNs)();
1066
+ const gap = lastNs === void 0 ? 0 : (now - lastNs) / 1e6;
1067
+ delaysMs.push(gap);
1068
+ lastNs = now;
1069
+ chunks.push({ delta: delta.delta });
1070
+ }
1071
+ }
1072
+ if (delta.type === "usage") usage = delta.usage;
1073
+ if (delta.type === "finish") finishReason = delta.reason;
1074
+ yield delta;
1075
+ }
1076
+ if ((content || usage) && !isReadOnly) {
1077
+ const resp = {
1078
+ content,
1079
+ usage: usage ?? { input: { regular: 0 }, output: { regular: 0 } },
1080
+ finishReason,
1081
+ model: inner.model ?? invokeOpts?.model ?? "",
1082
+ provider: inner.provider
1083
+ };
1084
+ const entryToStore = {
1085
+ response: resp,
1086
+ storedAtNs: (0, import_core9.wallClockNs)(),
1087
+ ...captureStreamCadence ? { streamChunks: chunks, streamCadenceMs: delaysMs } : {}
1088
+ };
1089
+ await cache.store(messages, invokeOpts, entryToStore);
1090
+ }
1091
+ }
1092
+ });
1093
+ withLayer(wrap, "withReplayCache", inner);
1094
+ return wrap;
1095
+ }
1096
+
1097
+ // src/utils/ai/adapters/providers/fallback.ts
1098
+ function degradedResponse(provider, model) {
1099
+ return {
1100
+ content: "[fallback: no cached response available for this request]",
1101
+ usage: { input: { regular: 0 }, output: { regular: 0 } },
1102
+ finishReason: "stop",
1103
+ model,
1104
+ provider,
1105
+ metadata: { degraded: true, reason: "no-fixture" }
1106
+ };
1107
+ }
1108
+ function normalizeRespondResult(raw, provider, model) {
1109
+ if (typeof raw === "string") {
1110
+ return {
1111
+ content: raw,
1112
+ usage: { input: { regular: 0 }, output: { regular: 0 } },
1113
+ finishReason: "stop",
1114
+ model,
1115
+ provider,
1116
+ metadata: { degraded: true, reason: "respond" }
1117
+ };
1118
+ }
1119
+ return raw;
1120
+ }
1121
+ async function fixtureKey(fixture, keyPrefix) {
1122
+ if ("key" in fixture) return fixture.key;
1123
+ const canonical = (0, import_extra5.canonicalJson)({ messages: fixture.messages, opts: fixture.invokeOpts ?? {} });
1124
+ const hex = await (0, import_core10.sha256Hex)(canonical);
1125
+ return `${keyPrefix}:${hex}`;
1126
+ }
1127
+ function toCachedEntry(fixture) {
1128
+ const base = {
1129
+ response: fixture.response,
1130
+ // Real timestamp so future TTL-aware tiers don't treat inline fixtures
1131
+ // as Epoch-old and evict them on first pass. Matches the wall-clock
1132
+ // write `withReplayCache` uses for disk-written entries.
1133
+ storedAtNs: (0, import_core10.wallClockNs)()
1134
+ };
1135
+ if ("key" in fixture && fixture.stream) {
1136
+ const tokenChunks = fixture.stream.chunks.filter(
1137
+ (c) => c.type === "token"
1138
+ );
1139
+ return {
1140
+ ...base,
1141
+ streamChunks: tokenChunks.map((c) => ({ delta: c.delta })),
1142
+ streamCadenceMs: fixture.stream.delaysMs ?? tokenChunks.map(() => 0)
1143
+ };
1144
+ }
1145
+ return base;
1146
+ }
1147
+ function resolveFixtureStorage(opts, keyPrefix) {
1148
+ const sources = [];
1149
+ if (opts.fixtures != null) sources.push("fixtures");
1150
+ if (opts.fixturesStorage != null) sources.push("fixturesStorage");
1151
+ if (sources.length > 1) {
1152
+ throw new TypeError(
1153
+ `fallbackAdapter: \`fixtures\` and \`fixturesStorage\` are mutually exclusive; got both ${sources.join(" and ")}. Pick one source. For filesystem directories use the node subpath's \`fallbackAdapter\`.`
1154
+ );
1155
+ }
1156
+ if (opts.fixtures) {
1157
+ const tier = (0, import_extra5.memoryKv)();
1158
+ const fixtures = opts.fixtures;
1159
+ const seedReady = (async () => {
1160
+ for (const fixture of fixtures) {
1161
+ const key = await fixtureKey(fixture, keyPrefix);
1162
+ await tier.save(key, toCachedEntry(fixture));
1163
+ }
1164
+ })();
1165
+ seedReady.catch(() => {
1166
+ });
1167
+ return { tier, seedReady };
1168
+ }
1169
+ if (opts.fixturesStorage) return { tier: opts.fixturesStorage, seedReady: Promise.resolve() };
1170
+ return { tier: void 0, seedReady: Promise.resolve() };
1171
+ }
1172
+ function fallbackAdapter(opts = {}) {
1173
+ const provider = opts.provider ?? "fallback";
1174
+ const model = opts.model ?? "fallback";
1175
+ const onMiss = opts.onMiss ?? "respond";
1176
+ const keyPrefix = opts.keyPrefix ?? "fallback";
1177
+ const leaf = (() => {
1178
+ if (opts.record) return opts.record.adapter;
1179
+ if (onMiss === "throw") {
1180
+ return dryRunAdapter({
1181
+ provider,
1182
+ model,
1183
+ respond: () => "[unreachable: read-strict mode throws on miss]"
1184
+ });
1185
+ }
1186
+ return {
1187
+ provider,
1188
+ model,
1189
+ async invoke(messages, invokeOpts) {
1190
+ const raw = opts.respond ? opts.respond(messages, invokeOpts) : degradedResponse(provider, model);
1191
+ return normalizeRespondResult(raw, provider, model);
1192
+ },
1193
+ async *stream(messages, invokeOpts) {
1194
+ const raw = opts.respond ? opts.respond(messages, invokeOpts) : degradedResponse(provider, model);
1195
+ const r = normalizeRespondResult(raw, provider, model);
1196
+ yield { type: "token", delta: r.content };
1197
+ if (r.usage) yield { type: "usage", usage: r.usage };
1198
+ yield { type: "finish", reason: r.finishReason ?? "stop" };
1199
+ }
1200
+ };
1201
+ })();
1202
+ let storage;
1203
+ let seedReady = Promise.resolve();
1204
+ if (opts.record) {
1205
+ if (!opts.record.storage) {
1206
+ throw new TypeError(
1207
+ "fallbackAdapter: `record.storage` is required in record mode. For filesystem `record.dir` convenience, use the node subpath's `fallbackAdapter`."
1208
+ );
1209
+ }
1210
+ storage = opts.record.storage;
1211
+ } else {
1212
+ const resolved = resolveFixtureStorage(opts, keyPrefix);
1213
+ storage = resolved.tier ?? (0, import_extra5.memoryKv)();
1214
+ seedReady = resolved.seedReady;
1215
+ }
1216
+ const mode = opts.record ? "read-write" : onMiss === "throw" ? "read-strict" : "read";
1217
+ const cached = withReplayCache(leaf, {
1218
+ storage,
1219
+ mode,
1220
+ keyPrefix,
1221
+ cacheStreaming: true,
1222
+ captureStreamCadence: true,
1223
+ replaySpeed: opts.replaySpeed,
1224
+ ...opts.keyFn ? { keyFn: opts.keyFn } : {}
1225
+ });
1226
+ return {
1227
+ provider,
1228
+ model,
1229
+ capabilities: cached.capabilities?.bind(cached),
1230
+ async invoke(messages, invokeOpts) {
1231
+ await seedReady;
1232
+ return cached.invoke(messages, invokeOpts);
1233
+ },
1234
+ async *stream(messages, invokeOpts) {
1235
+ await seedReady;
1236
+ for await (const delta of cached.stream(messages, invokeOpts)) yield delta;
1237
+ }
1238
+ };
1239
+ }
1240
+
1241
+ // src/utils/ai/adapters/providers/google.ts
1242
+ var import_core11 = require("@graphrefly/pure-ts/core");
1243
+ function googleAdapter(opts = {}) {
1244
+ if (opts.sdk) return sdkBackedGoogle(opts);
1245
+ return fetchBackedGoogle(opts);
1246
+ }
1247
+ function toGeminiRequest(messages, invokeOpts) {
1248
+ const systemParts = [];
1249
+ const contents = [];
1250
+ if (invokeOpts?.systemPrompt) systemParts.push(invokeOpts.systemPrompt);
1251
+ for (const m of messages) {
1252
+ if (m.role === "system") {
1253
+ systemParts.push(m.content);
1254
+ continue;
1255
+ }
1256
+ if (m.role === "tool") {
1257
+ contents.push({
1258
+ role: "user",
1259
+ parts: [
1260
+ {
1261
+ functionResponse: {
1262
+ name: m.name ?? m.toolCallId ?? "tool",
1263
+ response: { result: m.content }
1264
+ }
1265
+ }
1266
+ ]
1267
+ });
1268
+ continue;
1269
+ }
1270
+ if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {
1271
+ const parts = [];
1272
+ if (m.content) parts.push({ text: m.content });
1273
+ for (const tc of m.toolCalls) {
1274
+ parts.push({ functionCall: { name: tc.name, args: tc.arguments } });
1275
+ }
1276
+ contents.push({ role: "model", parts });
1277
+ continue;
1278
+ }
1279
+ contents.push({
1280
+ role: m.role === "assistant" ? "model" : "user",
1281
+ parts: [{ text: m.content }]
1282
+ });
1283
+ }
1284
+ const body = { contents };
1285
+ if (systemParts.length > 0) {
1286
+ body.systemInstruction = { role: "system", parts: [{ text: systemParts.join("\n\n") }] };
1287
+ }
1288
+ const genConfig = {};
1289
+ if (invokeOpts?.maxTokens != null) genConfig.maxOutputTokens = invokeOpts.maxTokens;
1290
+ if (invokeOpts?.temperature != null) genConfig.temperature = invokeOpts.temperature;
1291
+ if (invokeOpts?.maxReasoningTokens != null) {
1292
+ genConfig.thinkingConfig = { thinkingBudget: invokeOpts.maxReasoningTokens };
1293
+ }
1294
+ if (Object.keys(genConfig).length > 0) body.generationConfig = genConfig;
1295
+ if (invokeOpts?.tools && invokeOpts.tools.length > 0) {
1296
+ body.tools = [{ functionDeclarations: invokeOpts.tools.map(toGeminiTool) }];
1297
+ }
1298
+ if (invokeOpts?.providerExtras) Object.assign(body, invokeOpts.providerExtras);
1299
+ return body;
1300
+ }
1301
+ function toGeminiTool(t) {
1302
+ return {
1303
+ name: t.name,
1304
+ description: t.description,
1305
+ parameters: t.parameters
1306
+ };
1307
+ }
1308
+ function toSdkParams(body, model, signal) {
1309
+ const config = {};
1310
+ const gen = body.generationConfig;
1311
+ if (gen) {
1312
+ if (typeof gen.maxOutputTokens === "number") config.maxOutputTokens = gen.maxOutputTokens;
1313
+ if (typeof gen.temperature === "number") config.temperature = gen.temperature;
1314
+ if (gen.thinkingConfig) config.thinkingConfig = gen.thinkingConfig;
1315
+ }
1316
+ if (body.systemInstruction) config.systemInstruction = body.systemInstruction;
1317
+ if (body.tools) config.tools = body.tools;
1318
+ for (const [k, v] of Object.entries(body)) {
1319
+ if (k === "contents" || k === "generationConfig" || k === "systemInstruction" || k === "tools" || // Skip `abortSignal` so a caller-supplied entry in `providerExtras`
1320
+ // can't briefly land in `config.abortSignal` before being
1321
+ // overwritten — the canonical signal channel is the second
1322
+ // `signal` argument (set on `config.abortSignal` below).
1323
+ k === "abortSignal" || // Skip `model` so a stray `body.model` (not produced by
1324
+ // `toGeminiRequest` today, but defensively guarded) doesn't
1325
+ // duplicate the top-level `model` field on the SDK request.
1326
+ k === "model") {
1327
+ continue;
1328
+ }
1329
+ config[k] = v;
1330
+ }
1331
+ if (signal) config.abortSignal = signal;
1332
+ return {
1333
+ model,
1334
+ contents: body.contents,
1335
+ config: Object.keys(config).length > 0 ? config : void 0
1336
+ };
1337
+ }
1338
+ function mapUsage2(u) {
1339
+ const usage = {
1340
+ input: { regular: 0 },
1341
+ output: { regular: 0 },
1342
+ raw: u
1343
+ };
1344
+ if (!u) return usage;
1345
+ const promptTotal = u.promptTokenCount ?? 0;
1346
+ const cached = u.cachedContentTokenCount ?? 0;
1347
+ usage.input.regular = Math.max(0, promptTotal - cached);
1348
+ if (cached > 0) usage.input.cacheRead = cached;
1349
+ if (u.toolUsePromptTokenCount) usage.input.toolUse = u.toolUsePromptTokenCount;
1350
+ if (u.promptTokensDetails) {
1351
+ for (const d of u.promptTokensDetails) {
1352
+ const modality = d.modality?.toLowerCase();
1353
+ if (modality === "image") usage.input.image = (usage.input.image ?? 0) + d.tokenCount;
1354
+ else if (modality === "audio") usage.input.audio = (usage.input.audio ?? 0) + d.tokenCount;
1355
+ else if (modality === "video") usage.input.video = (usage.input.video ?? 0) + d.tokenCount;
1356
+ }
1357
+ }
1358
+ usage.output.regular = u.candidatesTokenCount ?? 0;
1359
+ if (u.thoughtsTokenCount) usage.output.reasoning = u.thoughtsTokenCount;
1360
+ return usage;
1361
+ }
1362
+ function toLLMResponse2(json, latencyMs) {
1363
+ const cand = json.candidates?.[0];
1364
+ const parts = cand?.content?.parts ?? [];
1365
+ const textParts = [];
1366
+ const toolCalls = [];
1367
+ let i = 0;
1368
+ for (const p of parts) {
1369
+ if (typeof p.text === "string") textParts.push(p.text);
1370
+ if (p.functionCall) {
1371
+ toolCalls.push({
1372
+ id: `${p.functionCall.name}-${i++}`,
1373
+ name: p.functionCall.name,
1374
+ arguments: p.functionCall.args ?? {}
1375
+ });
1376
+ }
1377
+ }
1378
+ return {
1379
+ content: textParts.join(""),
1380
+ toolCalls: toolCalls.length > 0 ? toolCalls : void 0,
1381
+ usage: mapUsage2(json.usageMetadata),
1382
+ finishReason: cand?.finishReason,
1383
+ latencyMs,
1384
+ model: json.modelVersion,
1385
+ provider: "google"
1386
+ };
1387
+ }
1388
+ function resolveApiKey(opts) {
1389
+ if (opts.apiKey) return opts.apiKey;
1390
+ const env = globalThis.process?.env;
1391
+ return env?.GOOGLE_API_KEY ?? env?.GEMINI_API_KEY;
1392
+ }
1393
+ function fetchBackedGoogle(opts) {
1394
+ const baseURL = opts.baseURL ?? "https://generativelanguage.googleapis.com/v1beta";
1395
+ const fetchImpl = opts.fetchImpl ?? fetch;
1396
+ const pickModel = (invokeOpts) => {
1397
+ const model = invokeOpts?.model ?? opts.model;
1398
+ if (!model)
1399
+ throw new Error("googleAdapter: model must be set via options.model or invokeOpts.model");
1400
+ return model;
1401
+ };
1402
+ const keyParam = () => {
1403
+ const key = resolveApiKey(opts);
1404
+ if (!key) throw new Error("googleAdapter: apiKey required for invoke/stream");
1405
+ return `key=${encodeURIComponent(key)}`;
1406
+ };
1407
+ return {
1408
+ provider: "google",
1409
+ model: opts.model,
1410
+ async invoke(messages, invokeOpts) {
1411
+ const model = pickModel(invokeOpts);
1412
+ const body = toGeminiRequest(messages, invokeOpts);
1413
+ const start = (0, import_core11.monotonicNs)();
1414
+ const url = `${baseURL}/models/${encodeURIComponent(model)}:generateContent?${keyParam()}`;
1415
+ const resp = await fetchImpl(url, {
1416
+ method: "POST",
1417
+ headers: { "content-type": "application/json", ...opts.headers ?? {} },
1418
+ body: JSON.stringify(body),
1419
+ signal: invokeOpts?.signal
1420
+ });
1421
+ if (!resp.ok) throw await makeHttpError(resp, "Google");
1422
+ const json = await resp.json();
1423
+ const latencyMs = Math.max(0, ((0, import_core11.monotonicNs)() - start) / 1e6);
1424
+ return toLLMResponse2(json, latencyMs);
1425
+ },
1426
+ async *stream(messages, invokeOpts) {
1427
+ const model = pickModel(invokeOpts);
1428
+ const body = toGeminiRequest(messages, invokeOpts);
1429
+ const url = `${baseURL}/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse&${keyParam()}`;
1430
+ const resp = await fetchImpl(url, {
1431
+ method: "POST",
1432
+ headers: {
1433
+ "content-type": "application/json",
1434
+ accept: "text/event-stream",
1435
+ ...opts.headers ?? {}
1436
+ },
1437
+ body: JSON.stringify(body),
1438
+ signal: invokeOpts?.signal
1439
+ });
1440
+ if (!resp.ok) throw await makeHttpError(resp, "Google");
1441
+ if (!resp.body) throw new Error("googleAdapter: streaming response has no body");
1442
+ let finalUsage;
1443
+ let finishReason;
1444
+ for await (const event of parseSSEStream(resp.body, { signal: invokeOpts?.signal })) {
1445
+ if (!event.data) continue;
1446
+ let parsed;
1447
+ try {
1448
+ parsed = JSON.parse(event.data);
1449
+ } catch {
1450
+ continue;
1451
+ }
1452
+ const cand = parsed.candidates?.[0];
1453
+ for (const p of cand?.content?.parts ?? []) {
1454
+ if (typeof p.text === "string") {
1455
+ if (p.thought) yield { type: "thinking", delta: p.text };
1456
+ else yield { type: "token", delta: p.text };
1457
+ }
1458
+ if (p.functionCall) {
1459
+ yield {
1460
+ type: "tool-call-delta",
1461
+ delta: {
1462
+ name: p.functionCall.name,
1463
+ argumentsDelta: JSON.stringify(p.functionCall.args ?? {})
1464
+ }
1465
+ };
1466
+ }
1467
+ }
1468
+ if (cand?.finishReason) finishReason = cand.finishReason;
1469
+ if (parsed.usageMetadata) finalUsage = parsed.usageMetadata;
1470
+ }
1471
+ if (finalUsage) yield { type: "usage", usage: mapUsage2(finalUsage) };
1472
+ yield { type: "finish", reason: finishReason ?? "stop" };
1473
+ }
1474
+ };
1475
+ }
1476
+ function sdkBackedGoogle(opts) {
1477
+ const sdk = opts.sdk;
1478
+ if (!sdk) throw new Error("sdkBackedGoogle: sdk instance required");
1479
+ return {
1480
+ provider: "google",
1481
+ model: opts.model,
1482
+ async invoke(messages, invokeOpts) {
1483
+ const body = toGeminiRequest(messages, invokeOpts);
1484
+ const model = invokeOpts?.model ?? opts.model;
1485
+ if (!model) throw new Error("googleAdapter: model required");
1486
+ const params = toSdkParams(body, model, invokeOpts?.signal);
1487
+ const start = (0, import_core11.monotonicNs)();
1488
+ const resp = await sdk.models.generateContent(params);
1489
+ const latencyMs = Math.max(0, ((0, import_core11.monotonicNs)() - start) / 1e6);
1490
+ return toLLMResponse2(resp, latencyMs);
1491
+ },
1492
+ async *stream(messages, invokeOpts) {
1493
+ if (!sdk.models.generateContentStream) {
1494
+ throw new Error("sdkBackedGoogle: SDK instance does not expose generateContentStream");
1495
+ }
1496
+ const body = toGeminiRequest(messages, invokeOpts);
1497
+ const model = invokeOpts?.model ?? opts.model;
1498
+ if (!model) throw new Error("googleAdapter: model required");
1499
+ const params = toSdkParams(body, model, invokeOpts?.signal);
1500
+ let finalUsage;
1501
+ let finishReason;
1502
+ const stream = await sdk.models.generateContentStream(params);
1503
+ for await (const chunk of stream) {
1504
+ const cand = chunk.candidates?.[0];
1505
+ for (const p of cand?.content?.parts ?? []) {
1506
+ if (typeof p.text === "string") {
1507
+ if (p.thought) yield { type: "thinking", delta: p.text };
1508
+ else yield { type: "token", delta: p.text };
1509
+ }
1510
+ if (p.functionCall) {
1511
+ yield {
1512
+ type: "tool-call-delta",
1513
+ delta: {
1514
+ name: p.functionCall.name,
1515
+ argumentsDelta: JSON.stringify(p.functionCall.args ?? {})
1516
+ }
1517
+ };
1518
+ }
1519
+ }
1520
+ if (cand?.finishReason) finishReason = cand.finishReason;
1521
+ if (chunk.usageMetadata) finalUsage = chunk.usageMetadata;
1522
+ }
1523
+ if (finalUsage) yield { type: "usage", usage: mapUsage2(finalUsage) };
1524
+ yield { type: "finish", reason: finishReason ?? "stop" };
1525
+ }
1526
+ };
1527
+ }
1528
+
1529
+ // src/utils/ai/adapters/providers/openai-compat.ts
1530
+ var import_core12 = require("@graphrefly/pure-ts/core");
1531
+ var PRESETS = {
1532
+ openai: { baseURL: "https://api.openai.com/v1", apiKeyEnv: "OPENAI_API_KEY", provider: "openai" },
1533
+ openrouter: {
1534
+ baseURL: "https://openrouter.ai/api/v1",
1535
+ apiKeyEnv: "OPENROUTER_API_KEY",
1536
+ provider: "openrouter"
1537
+ },
1538
+ groq: { baseURL: "https://api.groq.com/openai/v1", apiKeyEnv: "GROQ_API_KEY", provider: "groq" },
1539
+ ollama: { baseURL: "http://localhost:11434/v1", provider: "ollama" },
1540
+ deepseek: {
1541
+ baseURL: "https://api.deepseek.com/v1",
1542
+ apiKeyEnv: "DEEPSEEK_API_KEY",
1543
+ provider: "deepseek"
1544
+ },
1545
+ xai: { baseURL: "https://api.x.ai/v1", apiKeyEnv: "XAI_API_KEY", provider: "xai" }
1546
+ };
1547
+ function openAICompatAdapter(opts = {}) {
1548
+ if (opts.sdk) return sdkBackedOpenAI(opts);
1549
+ return fetchBackedOpenAI(opts);
1550
+ }
1551
+ function toOpenAIRequest(messages, invokeOpts, defaultModel, stream, bodyExtras) {
1552
+ const model = invokeOpts?.model ?? defaultModel;
1553
+ if (!model)
1554
+ throw new Error("openAICompatAdapter: model must be set via options.model or invokeOpts.model");
1555
+ const mapped = messages.map(toOpenAIMessage);
1556
+ if (invokeOpts?.systemPrompt && !messages.some((m) => m.role === "system")) {
1557
+ mapped.unshift({ role: "system", content: invokeOpts.systemPrompt });
1558
+ }
1559
+ const body = { model, messages: mapped };
1560
+ if (invokeOpts?.maxTokens != null) body.max_tokens = invokeOpts.maxTokens;
1561
+ if (invokeOpts?.temperature != null) body.temperature = invokeOpts.temperature;
1562
+ if (invokeOpts?.tools && invokeOpts.tools.length > 0) {
1563
+ body.tools = invokeOpts.tools.map(toOpenAITool);
1564
+ }
1565
+ if (invokeOpts?.maxReasoningTokens != null) {
1566
+ body.reasoning = { max_tokens: invokeOpts.maxReasoningTokens };
1567
+ }
1568
+ if (stream) {
1569
+ body.stream = true;
1570
+ body.stream_options = { include_usage: true };
1571
+ }
1572
+ if (bodyExtras) Object.assign(body, bodyExtras);
1573
+ if (invokeOpts?.providerExtras) Object.assign(body, invokeOpts.providerExtras);
1574
+ return body;
1575
+ }
1576
+ function toOpenAIMessage(m) {
1577
+ if (m.role === "tool") {
1578
+ return { role: "tool", tool_call_id: m.toolCallId, content: m.content };
1579
+ }
1580
+ if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {
1581
+ return {
1582
+ role: "assistant",
1583
+ content: m.content || null,
1584
+ tool_calls: m.toolCalls.map((tc) => ({
1585
+ id: tc.id,
1586
+ type: "function",
1587
+ function: { name: tc.name, arguments: JSON.stringify(tc.arguments) }
1588
+ }))
1589
+ };
1590
+ }
1591
+ return { role: m.role, content: m.content };
1592
+ }
1593
+ function toOpenAITool(t) {
1594
+ return {
1595
+ type: "function",
1596
+ function: {
1597
+ name: t.name,
1598
+ description: t.description,
1599
+ parameters: t.parameters
1600
+ }
1601
+ };
1602
+ }
1603
+ function mapUsage3(u) {
1604
+ const usage = {
1605
+ input: { regular: 0 },
1606
+ output: { regular: 0 },
1607
+ raw: u
1608
+ };
1609
+ if (!u) return usage;
1610
+ const inputTotal = u.prompt_tokens ?? 0;
1611
+ let cacheRead = u.prompt_tokens_details?.cached_tokens ?? 0;
1612
+ if (u.prompt_cache_hit_tokens != null) {
1613
+ cacheRead = u.prompt_cache_hit_tokens;
1614
+ usage.input.regular = u.prompt_cache_miss_tokens ?? Math.max(0, inputTotal - cacheRead);
1615
+ } else {
1616
+ usage.input.regular = Math.max(0, inputTotal - cacheRead);
1617
+ }
1618
+ if (cacheRead > 0) usage.input.cacheRead = cacheRead;
1619
+ if (u.prompt_tokens_details?.audio_tokens)
1620
+ usage.input.audio = u.prompt_tokens_details.audio_tokens;
1621
+ const outputTotal = u.completion_tokens ?? 0;
1622
+ const reasoning = u.completion_tokens_details?.reasoning_tokens ?? 0;
1623
+ usage.output.regular = Math.max(0, outputTotal - reasoning);
1624
+ if (reasoning > 0) usage.output.reasoning = reasoning;
1625
+ if (u.completion_tokens_details?.audio_tokens)
1626
+ usage.output.audio = u.completion_tokens_details.audio_tokens;
1627
+ if (u.completion_tokens_details?.accepted_prediction_tokens) {
1628
+ usage.output.predictionAccepted = u.completion_tokens_details.accepted_prediction_tokens;
1629
+ }
1630
+ if (u.completion_tokens_details?.rejected_prediction_tokens) {
1631
+ usage.output.predictionRejected = u.completion_tokens_details.rejected_prediction_tokens;
1632
+ }
1633
+ return usage;
1634
+ }
1635
+ function toLLMResponse3(json, latencyMs, provider) {
1636
+ const choice = json.choices[0];
1637
+ const msg = choice?.message;
1638
+ const content = msg?.content ?? "";
1639
+ const toolCalls = (msg?.tool_calls ?? []).map((tc) => ({
1640
+ id: tc.id,
1641
+ name: tc.function.name,
1642
+ arguments: safeJsonParse(tc.function.arguments)
1643
+ }));
1644
+ return {
1645
+ content,
1646
+ toolCalls: toolCalls.length > 0 ? toolCalls : void 0,
1647
+ usage: mapUsage3(json.usage),
1648
+ finishReason: choice?.finish_reason,
1649
+ latencyMs,
1650
+ model: json.model,
1651
+ provider
1652
+ };
1653
+ }
1654
+ function safeJsonParse(s) {
1655
+ try {
1656
+ const parsed = JSON.parse(s);
1657
+ return typeof parsed === "object" && parsed != null ? parsed : { _raw: s };
1658
+ } catch {
1659
+ return { _raw: s };
1660
+ }
1661
+ }
1662
+ function resolveConfig(opts) {
1663
+ const preset = opts.preset ?? "openai";
1664
+ const base = PRESETS[preset];
1665
+ const baseURL = opts.baseURL ?? base.baseURL;
1666
+ const provider = opts.provider ?? base.provider;
1667
+ const envKey = base.apiKeyEnv;
1668
+ const apiKey = opts.apiKey ?? (envKey ? globalThis.process?.env?.[envKey] : void 0);
1669
+ return { provider, baseURL, apiKey };
1670
+ }
1671
+ function fetchBackedOpenAI(opts) {
1672
+ const { provider, baseURL, apiKey } = resolveConfig(opts);
1673
+ const fetchImpl = opts.fetchImpl ?? fetch;
1674
+ const needsKey = provider !== "ollama";
1675
+ const commonHeaders = () => {
1676
+ const h = {
1677
+ "content-type": "application/json",
1678
+ ...opts.headers ?? {}
1679
+ };
1680
+ if (needsKey) {
1681
+ if (!apiKey)
1682
+ throw new Error(`openAICompatAdapter[${provider}]: apiKey required for invoke/stream`);
1683
+ h.authorization = `Bearer ${apiKey}`;
1684
+ }
1685
+ return h;
1686
+ };
1687
+ return {
1688
+ provider,
1689
+ model: opts.model,
1690
+ async invoke(messages, invokeOpts) {
1691
+ const body = toOpenAIRequest(messages, invokeOpts, opts.model, false, opts.bodyExtras);
1692
+ const start = (0, import_core12.monotonicNs)();
1693
+ const resp = await fetchImpl(`${baseURL}/chat/completions`, {
1694
+ method: "POST",
1695
+ headers: commonHeaders(),
1696
+ body: JSON.stringify(body),
1697
+ signal: invokeOpts?.signal
1698
+ });
1699
+ if (!resp.ok) throw await makeHttpError(resp, provider);
1700
+ const json = await resp.json();
1701
+ const latencyMs = Math.max(0, ((0, import_core12.monotonicNs)() - start) / 1e6);
1702
+ return toLLMResponse3(json, latencyMs, provider);
1703
+ },
1704
+ async *stream(messages, invokeOpts) {
1705
+ const body = toOpenAIRequest(messages, invokeOpts, opts.model, true, opts.bodyExtras);
1706
+ const resp = await fetchImpl(`${baseURL}/chat/completions`, {
1707
+ method: "POST",
1708
+ headers: { ...commonHeaders(), accept: "text/event-stream" },
1709
+ body: JSON.stringify(body),
1710
+ signal: invokeOpts?.signal
1711
+ });
1712
+ if (!resp.ok) throw await makeHttpError(resp, provider);
1713
+ if (!resp.body)
1714
+ throw new Error(`openAICompatAdapter[${provider}]: streaming response has no body`);
1715
+ let finalUsage;
1716
+ let finishReason;
1717
+ for await (const event of parseSSEStream(resp.body, { signal: invokeOpts?.signal })) {
1718
+ if (!event.data || event.data === "[DONE]") continue;
1719
+ let parsed;
1720
+ try {
1721
+ parsed = JSON.parse(event.data);
1722
+ } catch {
1723
+ continue;
1724
+ }
1725
+ const choices = parsed.choices;
1726
+ if (choices) {
1727
+ const c = choices[0];
1728
+ if (c?.delta?.content) yield { type: "token", delta: c.delta.content };
1729
+ if (c?.delta?.reasoning_content) {
1730
+ yield { type: "thinking", delta: c.delta.reasoning_content };
1731
+ }
1732
+ if (c?.delta?.tool_calls) {
1733
+ for (const tc of c.delta.tool_calls) {
1734
+ yield {
1735
+ type: "tool-call-delta",
1736
+ delta: {
1737
+ id: tc.id,
1738
+ name: tc.function?.name,
1739
+ argumentsDelta: tc.function?.arguments
1740
+ }
1741
+ };
1742
+ }
1743
+ }
1744
+ if (c?.finish_reason) finishReason = c.finish_reason;
1745
+ }
1746
+ if (parsed.usage) {
1747
+ finalUsage = parsed.usage;
1748
+ yield { type: "usage", usage: mapUsage3(finalUsage) };
1749
+ }
1750
+ }
1751
+ yield { type: "finish", reason: finishReason ?? "stop" };
1752
+ }
1753
+ };
1754
+ }
1755
+ function sdkBackedOpenAI(opts) {
1756
+ const sdk = opts.sdk;
1757
+ if (!sdk) throw new Error("sdkBackedOpenAI: sdk instance required");
1758
+ const { provider } = resolveConfig(opts);
1759
+ return {
1760
+ provider,
1761
+ model: opts.model,
1762
+ async invoke(messages, invokeOpts) {
1763
+ const body = toOpenAIRequest(messages, invokeOpts, opts.model, false, opts.bodyExtras);
1764
+ const start = (0, import_core12.monotonicNs)();
1765
+ const resp = await sdk.chat.completions.create(body, { signal: invokeOpts?.signal });
1766
+ const latencyMs = Math.max(0, ((0, import_core12.monotonicNs)() - start) / 1e6);
1767
+ return toLLMResponse3(resp, latencyMs, provider);
1768
+ },
1769
+ async *stream(messages, invokeOpts) {
1770
+ const body = toOpenAIRequest(messages, invokeOpts, opts.model, true, opts.bodyExtras);
1771
+ const stream = await sdk.chat.completions.create(body, {
1772
+ signal: invokeOpts?.signal
1773
+ });
1774
+ let finalUsage;
1775
+ let finishReason;
1776
+ for await (const chunk of stream) {
1777
+ const choices = chunk.choices;
1778
+ if (choices) {
1779
+ const c = choices[0];
1780
+ if (c?.delta?.content) yield { type: "token", delta: c.delta.content };
1781
+ if (c?.delta?.reasoning_content)
1782
+ yield { type: "thinking", delta: c.delta.reasoning_content };
1783
+ if (c?.delta?.tool_calls) {
1784
+ for (const tc of c.delta.tool_calls) {
1785
+ yield {
1786
+ type: "tool-call-delta",
1787
+ delta: {
1788
+ id: tc.id,
1789
+ name: tc.function?.name,
1790
+ argumentsDelta: tc.function?.arguments
1791
+ }
1792
+ };
1793
+ }
1794
+ }
1795
+ if (c?.finish_reason) finishReason = c.finish_reason;
1796
+ }
1797
+ const u = chunk.usage;
1798
+ if (u) {
1799
+ finalUsage = u;
1800
+ yield { type: "usage", usage: mapUsage3(u) };
1801
+ }
1802
+ }
1803
+ if (!finalUsage) {
1804
+ }
1805
+ yield { type: "finish", reason: finishReason ?? "stop" };
1806
+ }
1807
+ };
1808
+ }
1809
+
1810
+ // src/utils/ai/adapters/core/factory.ts
1811
+ function createAdapter(opts) {
1812
+ switch (opts.provider) {
1813
+ case "anthropic": {
1814
+ const a = {
1815
+ apiKey: opts.apiKey,
1816
+ model: opts.model,
1817
+ baseURL: opts.baseURL,
1818
+ headers: opts.headers,
1819
+ sdk: opts.sdk,
1820
+ fetchImpl: opts.fetchImpl,
1821
+ ...opts.extras
1822
+ };
1823
+ return anthropicAdapter(a);
1824
+ }
1825
+ case "google": {
1826
+ const g = {
1827
+ apiKey: opts.apiKey,
1828
+ model: opts.model,
1829
+ baseURL: opts.baseURL,
1830
+ headers: opts.headers,
1831
+ sdk: opts.sdk,
1832
+ fetchImpl: opts.fetchImpl,
1833
+ ...opts.extras
1834
+ };
1835
+ return googleAdapter(g);
1836
+ }
1837
+ case "dry-run": {
1838
+ const d = {
1839
+ model: opts.model,
1840
+ ...opts.extras
1841
+ };
1842
+ return dryRunAdapter(d);
1843
+ }
1844
+ case "fallback": {
1845
+ const f = {
1846
+ provider: opts.provider,
1847
+ model: opts.model,
1848
+ ...opts.extras
1849
+ };
1850
+ return fallbackAdapter(f);
1851
+ }
1852
+ // OpenAI-compat presets
1853
+ case "openai":
1854
+ case "openrouter":
1855
+ case "groq":
1856
+ case "ollama":
1857
+ case "deepseek":
1858
+ case "xai": {
1859
+ const c = {
1860
+ preset: opts.provider,
1861
+ apiKey: opts.apiKey,
1862
+ model: opts.model,
1863
+ baseURL: opts.baseURL,
1864
+ headers: opts.headers,
1865
+ bodyExtras: opts.bodyExtras,
1866
+ sdk: opts.sdk,
1867
+ fetchImpl: opts.fetchImpl,
1868
+ ...opts.extras
1869
+ };
1870
+ return openAICompatAdapter(c);
1871
+ }
1872
+ default: {
1873
+ const never = opts.provider;
1874
+ throw new Error(`createAdapter: unknown provider: ${String(never)}`);
1875
+ }
1876
+ }
1877
+ }
1878
+
1879
+ // src/utils/ai/adapters/routing/cascading.ts
1880
+ var import_extra6 = require("@graphrefly/pure-ts/extra");
1881
+
1882
+ // src/utils/resilience/breaker.ts
1883
+ var import_core14 = require("@graphrefly/pure-ts/core");
1884
+ init_internal();
1885
+ init_backoff();
1886
+ function circuitBreaker(options) {
1887
+ let threshold = 5;
1888
+ let baseCooldownNs = 30 * NS_PER_SEC;
1889
+ let cooldownStrategy = null;
1890
+ let halfOpenMax = 1;
1891
+ let now = import_core14.monotonicNs;
1892
+ function applyOptions(o) {
1893
+ threshold = Math.max(1, o?.failureThreshold ?? 5);
1894
+ baseCooldownNs = clampNonNegative(o?.cooldownNs ?? 30 * NS_PER_SEC);
1895
+ cooldownStrategy = o?.cooldown ?? null;
1896
+ halfOpenMax = Math.max(1, o?.halfOpenMax ?? 1);
1897
+ now = o?.now ?? import_core14.monotonicNs;
1898
+ }
1899
+ let _state = "closed";
1900
+ let _failureCount = 0;
1901
+ let _openCycle = 0;
1902
+ let _lastOpenedAt = 0;
1903
+ let _lastCooldownNs = baseCooldownNs;
1904
+ let _halfOpenAttempts = 0;
1905
+ let initialOpts;
1906
+ let optsUnsub;
1907
+ if (isNode(options)) {
1908
+ const optsNode = options;
1909
+ initialOpts = optsNode.cache;
1910
+ applyOptions(initialOpts);
1911
+ const lockedNow = initialOpts?.now;
1912
+ const hadInitialCache = initialOpts !== void 0;
1913
+ let firstEmit = hadInitialCache;
1914
+ optsUnsub = optsNode.subscribe((msgs) => {
1915
+ for (const m of msgs) {
1916
+ if (m[0] !== import_core14.DATA) continue;
1917
+ if (firstEmit) {
1918
+ firstEmit = false;
1919
+ continue;
1920
+ }
1921
+ const next = m[1];
1922
+ if (next == null || typeof next !== "object") continue;
1923
+ if (Object.keys(next).length === 0) continue;
1924
+ if ("now" in next && next.now !== lockedNow) {
1925
+ console.error(
1926
+ "circuitBreaker: ignoring mid-flight `now` change \u2014 clock override is mode-locked at construction. Prior `now` preserved."
1927
+ );
1928
+ continue;
1929
+ }
1930
+ const merged = {
1931
+ ...initialOpts ?? {},
1932
+ ...next,
1933
+ ...lockedNow !== void 0 ? { now: lockedNow } : {}
1934
+ };
1935
+ applyOptions(merged);
1936
+ initialOpts = merged;
1937
+ }
1938
+ });
1939
+ } else {
1940
+ applyOptions(options);
1941
+ }
1942
+ _lastCooldownNs = baseCooldownNs;
1943
+ function getCooldownNs() {
1944
+ if (!cooldownStrategy) return baseCooldownNs;
1945
+ const delayNs = cooldownStrategy(_openCycle);
1946
+ return delayNs !== null ? delayNs : baseCooldownNs;
1947
+ }
1948
+ function transitionToOpen() {
1949
+ _state = "open";
1950
+ _lastCooldownNs = getCooldownNs();
1951
+ _lastOpenedAt = now();
1952
+ _halfOpenAttempts = 0;
1953
+ }
1954
+ const breaker = {
1955
+ canExecute() {
1956
+ if (_state === "closed") return true;
1957
+ if (_state === "open") {
1958
+ const elapsed = now() - _lastOpenedAt;
1959
+ if (elapsed >= _lastCooldownNs) {
1960
+ _state = "half-open";
1961
+ _halfOpenAttempts = 1;
1962
+ return true;
1963
+ }
1964
+ return false;
1965
+ }
1966
+ if (_halfOpenAttempts < halfOpenMax) {
1967
+ _halfOpenAttempts++;
1968
+ return true;
1969
+ }
1970
+ return false;
1971
+ },
1972
+ recordSuccess() {
1973
+ if (_state === "half-open") {
1974
+ _state = "closed";
1975
+ _failureCount = 0;
1976
+ _openCycle = 0;
1977
+ } else if (_state === "closed") {
1978
+ _failureCount = 0;
1979
+ }
1980
+ },
1981
+ recordFailure(_error) {
1982
+ if (_state === "half-open") {
1983
+ _openCycle++;
1984
+ transitionToOpen();
1985
+ return;
1986
+ }
1987
+ if (_state === "closed") {
1988
+ _failureCount++;
1989
+ if (_failureCount >= threshold) {
1990
+ transitionToOpen();
1991
+ }
1992
+ }
1993
+ },
1994
+ get state() {
1995
+ return _state;
1996
+ },
1997
+ get failureCount() {
1998
+ return _failureCount;
1999
+ },
2000
+ reset() {
2001
+ _state = "closed";
2002
+ _failureCount = 0;
2003
+ _openCycle = 0;
2004
+ _halfOpenAttempts = 0;
2005
+ },
2006
+ dispose() {
2007
+ optsUnsub?.();
2008
+ }
2009
+ // Internal accessors used by withBreaker for the BreakerState
2010
+ // companion (DS-13.5.B). Not part of the public CircuitBreaker
2011
+ // interface but exposed for the bundle wiring.
2012
+ };
2013
+ breaker._stateSnapshot = () => ({
2014
+ status: _state,
2015
+ failureCount: _failureCount,
2016
+ openCycle: _openCycle,
2017
+ lastOpenedAtNs: _lastOpenedAt,
2018
+ halfOpenAttempts: _halfOpenAttempts,
2019
+ lastCooldownNs: _lastCooldownNs
2020
+ });
2021
+ return breaker;
2022
+ }
2023
+
2024
+ // src/utils/ai/adapters/routing/cascading.ts
2025
+ var AllTiersExhaustedError = class extends Error {
2026
+ name = "AllTiersExhaustedError";
2027
+ skipped;
2028
+ failed;
2029
+ constructor(report) {
2030
+ const parts = [];
2031
+ if (report.failed.size > 0) parts.push(`failed=[${[...report.failed.keys()].join(",")}]`);
2032
+ if (report.skipped.length > 0) {
2033
+ parts.push(`skipped=[${report.skipped.map((s) => `${s.name}(${s.reason})`).join(",")}]`);
2034
+ }
2035
+ super(`All LLM adapter tiers exhausted: ${parts.join(" ")}`);
2036
+ this.skipped = report.skipped;
2037
+ this.failed = report.failed;
2038
+ }
2039
+ };
2040
+ function cascadingLlmAdapter(tiers, opts = {}) {
2041
+ if (tiers.length === 0) throw new RangeError("cascadingLlmAdapter: tiers must be non-empty");
2042
+ const resolved = tiers.map((t) => ({
2043
+ name: t.name,
2044
+ adapter: t.adapter,
2045
+ filter: t.filter,
2046
+ breaker: t.breaker ? "canExecute" in t.breaker ? t.breaker : circuitBreaker(t.breaker) : void 0
2047
+ }));
2048
+ const streamRetryBeforeFirstChunk = opts.streamRetryBeforeFirstChunk ?? true;
2049
+ const cascade = {
2050
+ provider: "cascading",
2051
+ model: void 0,
2052
+ async invoke(messages, invokeOpts) {
2053
+ const skipped = [];
2054
+ const failed = /* @__PURE__ */ new Map();
2055
+ for (let i = 0; i < resolved.length; i++) {
2056
+ const t = resolved[i];
2057
+ if (t.filter && !t.filter(messages, invokeOpts)) {
2058
+ skipped.push({ name: t.name, reason: "filter" });
2059
+ continue;
2060
+ }
2061
+ if (t.breaker && !t.breaker.canExecute()) {
2062
+ skipped.push({ name: t.name, reason: "breaker" });
2063
+ continue;
2064
+ }
2065
+ try {
2066
+ const resp = await firstValueFrom((0, import_extra6.fromAny)(t.adapter.invoke(messages, invokeOpts)));
2067
+ t.breaker?.recordSuccess();
2068
+ return { ...resp, metadata: { ...resp.metadata ?? {}, tier: t.name } };
2069
+ } catch (err) {
2070
+ failed.set(t.name, err);
2071
+ t.breaker?.recordFailure(err);
2072
+ const next = resolved[i + 1];
2073
+ if (next) opts.onFallback?.(t.name, next.name, err);
2074
+ }
2075
+ }
2076
+ const report = { skipped, failed };
2077
+ opts.onExhausted?.(report);
2078
+ throw new AllTiersExhaustedError(report);
2079
+ },
2080
+ async *stream(messages, invokeOpts) {
2081
+ const skipped = [];
2082
+ const failed = /* @__PURE__ */ new Map();
2083
+ for (let i = 0; i < resolved.length; i++) {
2084
+ const t = resolved[i];
2085
+ if (t.filter && !t.filter(messages, invokeOpts)) {
2086
+ skipped.push({ name: t.name, reason: "filter" });
2087
+ continue;
2088
+ }
2089
+ if (t.breaker && !t.breaker.canExecute()) {
2090
+ skipped.push({ name: t.name, reason: "breaker" });
2091
+ continue;
2092
+ }
2093
+ let yieldedAny = false;
2094
+ try {
2095
+ for await (const delta of t.adapter.stream(messages, invokeOpts)) {
2096
+ yieldedAny = true;
2097
+ yield delta;
2098
+ }
2099
+ t.breaker?.recordSuccess();
2100
+ return;
2101
+ } catch (err) {
2102
+ failed.set(t.name, err);
2103
+ t.breaker?.recordFailure(err);
2104
+ if (yieldedAny || !streamRetryBeforeFirstChunk) {
2105
+ throw err;
2106
+ }
2107
+ const next = resolved[i + 1];
2108
+ if (next) opts.onFallback?.(t.name, next.name, err);
2109
+ }
2110
+ }
2111
+ const report = { skipped, failed };
2112
+ opts.onExhausted?.(report);
2113
+ throw new AllTiersExhaustedError(report);
2114
+ }
2115
+ };
2116
+ withLayer(cascade, `cascade[${resolved.map((t) => t.name).join(",")}]`);
2117
+ return cascade;
2118
+ }
2119
+
2120
+ // src/utils/ai/adapters/routing/browser-presets.ts
2121
+ function cloudFirstPreset(opts) {
2122
+ const tiers = [{ name: "cloud", adapter: createAdapter(opts.cloud) }];
2123
+ if (opts.webllmModel) {
2124
+ tiers.push({ name: "webllm", adapter: webllmAdapter({ model: opts.webllmModel }) });
2125
+ }
2126
+ if (opts.chromeNano !== false) {
2127
+ tiers.push({
2128
+ name: "chrome-nano",
2129
+ adapter: chromeNanoAdapter(),
2130
+ filter: (_msgs, iOpts) => !iOpts?.tools || iOpts.tools.length === 0
2131
+ });
2132
+ }
2133
+ return cascadingLlmAdapter(tiers, opts.cascade);
2134
+ }
2135
+ function localFirstPreset(opts) {
2136
+ const tiers = [
2137
+ {
2138
+ name: "ollama",
2139
+ adapter: createAdapter({
2140
+ provider: "ollama",
2141
+ model: opts.ollamaModel,
2142
+ baseURL: opts.ollamaBaseURL
2143
+ })
2144
+ }
2145
+ ];
2146
+ if (opts.webllmModel) {
2147
+ tiers.push({ name: "webllm", adapter: webllmAdapter({ model: opts.webllmModel }) });
2148
+ }
2149
+ if (opts.chromeNano !== false) {
2150
+ tiers.push({
2151
+ name: "chrome-nano",
2152
+ adapter: chromeNanoAdapter(),
2153
+ filter: (_msgs, iOpts) => !iOpts?.tools || iOpts.tools.length === 0
2154
+ });
2155
+ }
2156
+ return cascadingLlmAdapter(tiers, opts.cascade);
2157
+ }
2158
+ function offlinePreset(opts) {
2159
+ const tiers = [{ name: "webllm", adapter: webllmAdapter({ model: opts.webllmModel }) }];
2160
+ if (opts.chromeNano !== false) {
2161
+ tiers.push({
2162
+ name: "chrome-nano",
2163
+ adapter: chromeNanoAdapter(),
2164
+ filter: (_msgs, iOpts) => !iOpts?.tools || iOpts.tools.length === 0
2165
+ });
2166
+ }
2167
+ return cascadingLlmAdapter(tiers, opts.cascade);
2168
+ }
2169
+ //# sourceMappingURL=browser.cjs.map