sliccy 5.59.2 → 5.60.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 (310) hide show
  1. package/dist/ui/assets/__vite-browser-external-DZX1xHt-.js +1 -0
  2. package/dist/ui/assets/account-store-BddNCTSm.js +98 -0
  3. package/dist/ui/assets/account-store-dvAfa3y8.js +38 -0
  4. package/dist/ui/assets/adobe-C0iTCwW2.js +1 -0
  5. package/dist/ui/assets/adobe-DC5UT0ZJ.js +2 -0
  6. package/dist/ui/assets/adobe-oauth-state-Csa5ciQS.js +1 -0
  7. package/dist/ui/assets/{adobe-oauth-state-BeQ7T3Vk.js → adobe-oauth-state-Vbbfo7gR.js} +1 -1
  8. package/dist/ui/assets/agent-message-to-chat-QyCEPmi8.js +7 -0
  9. package/dist/ui/assets/{anthropic-messages-BP_xL8Mh.js → anthropic-messages-CIsUSIzG.js} +3 -3
  10. package/dist/ui/assets/{anthropic-messages-BwBPoNP0.js → anthropic-messages-_fPAePlR.js} +3 -3
  11. package/dist/ui/assets/{apps-9o4o-h1Z.js → apps-ztx90XZQ.js} +1 -1
  12. package/dist/ui/assets/attachments-CByeG2Ru.js +1 -0
  13. package/dist/ui/assets/{azure-openai-BifOYnRZ.js → azure-openai-BKnOwPkT.js} +1 -1
  14. package/dist/ui/assets/{azure-openai-BvAdt1td.js → azure-openai-Y9U14npX.js} +1 -1
  15. package/dist/ui/assets/{azure-openai-responses-BXDkTtSH.js → azure-openai-responses-DhzbC_tL.js} +1 -1
  16. package/dist/ui/assets/{azure-openai-responses-De9pJjBR.js → azure-openai-responses-bHfWNMbx.js} +1 -1
  17. package/dist/ui/assets/base64-DpPqYZJF.js +1 -0
  18. package/dist/ui/assets/bedrock-camp-BEi8MYUS.js +1 -0
  19. package/dist/ui/assets/bedrock-camp-CvxD6hHk.js +1 -0
  20. package/dist/ui/assets/bridge-launch-params-jegYRGJ6.js +1 -0
  21. package/dist/ui/assets/{browser-2wdq8OwU.js → browser-COVn7LPD.js} +6 -6
  22. package/dist/ui/assets/{cdp-Bwq6NLAx.js → cdp-7evcrxxP.js} +1 -1
  23. package/dist/ui/assets/cerebras-D_u7JsxU.js +1 -0
  24. package/dist/ui/assets/cerebras-ZAPHCT6L.js +1 -0
  25. package/dist/ui/assets/client-CpLUc-P8.js +4 -0
  26. package/dist/ui/assets/clipboard-Bd1Wp2vH.js +1 -0
  27. package/dist/ui/assets/compat-DyT25qXb.js +2 -0
  28. package/dist/ui/assets/{completionchunk-B2eUYPOo.js → completionchunk-D8ek1SQ-.js} +1 -1
  29. package/dist/ui/assets/{composer-speech-CgPswGW1.js → composer-speech-BWsih2Nz.js} +1 -1
  30. package/dist/ui/assets/{connect-surface-CnYXozQ2.js → connect-surface-YVJhSwyb.js} +1 -1
  31. package/dist/ui/assets/{context-compaction-LYFtS2_f.js → context-compaction-dcYYajWb.js} +6 -6
  32. package/dist/ui/assets/cost-command-Cpg2Em0Q.js +1613 -0
  33. package/dist/ui/assets/db-DjAqlQ2I.js +1 -0
  34. package/dist/ui/assets/db-ysOO0kLr.js +1 -0
  35. package/dist/ui/assets/dictation-priming-DGpw1lUV.js +1 -0
  36. package/dist/ui/assets/dip-BumXS1a9.js +233 -0
  37. package/dist/ui/assets/discovery-preference-DCtfbqw1.js +1 -0
  38. package/dist/ui/assets/dist-0FRaZO2z.js +12 -0
  39. package/dist/ui/assets/{dist-cYpTkQqJ.js → dist-BhEJb2Dl.js} +1 -1
  40. package/dist/ui/assets/{dist-DD6YY4Ks2.js → dist-Bj10RLrf.js} +1 -1
  41. package/dist/ui/assets/{dist-BHXb30bf.js → dist-Bq5i9FMJ.js} +4 -4
  42. package/dist/ui/assets/dist-CJ6ilPeJ.js +18 -0
  43. package/dist/ui/assets/{dist-D58cmC11.js → dist-Cc2eS9kS.js} +1 -1
  44. package/dist/ui/assets/{dist-CC_gNVTb.js → dist-DB-MlM2G.js} +1 -1
  45. package/dist/ui/assets/{dist-Bw2SRiP7.js → dist-DuLHpm2f.js} +1 -1
  46. package/dist/ui/assets/dist-DvjiIrEx.js +23 -0
  47. package/dist/ui/assets/{dist-D1pcMg_U.js → dist-d2CXjMIs.js} +3 -3
  48. package/dist/ui/assets/electron-overlay-route-CjT6k9Df.js +1 -0
  49. package/dist/ui/assets/ensure-speech-assets-D2Pclall.js +1 -0
  50. package/dist/ui/assets/es-CP2z28j0.js +53 -0
  51. package/dist/ui/assets/esp8266-CkAPDkuz.js +1 -0
  52. package/dist/ui/assets/esptool-operations-C0DUkD34.js +13 -0
  53. package/dist/ui/assets/esptool-operations-iCYPdIRA.js +12 -0
  54. package/dist/ui/assets/extension-bridge-transport-DHBo-K6K.js +1 -0
  55. package/dist/ui/assets/{follower-navigate-watcher-CRVUcrQz.js → follower-navigate-watcher-Cn5RjYxg.js} +1 -1
  56. package/dist/ui/assets/{fs-CHAFLJ_u.js → fs-BVM9dzPP.js} +1 -1
  57. package/dist/ui/assets/fs-CMpdIYZs.js +2 -0
  58. package/dist/ui/assets/git-config-Lj0BT7Oc.js +7 -0
  59. package/dist/ui/assets/github-CmX1lUH3.js +2 -0
  60. package/dist/ui/assets/github-copilot-C9loxoyp.js +1 -0
  61. package/dist/ui/assets/github-copilot-JdvDIR67.js +2 -0
  62. package/dist/ui/assets/github-ndbvNRbv.js +1 -0
  63. package/dist/ui/assets/global-db-DvmmimLY.js +1 -0
  64. package/dist/ui/assets/{google-generative-ai-C58ldv83.js → google-generative-ai-CyS9qbzb.js} +1 -1
  65. package/dist/ui/assets/{google-generative-ai-Eq6eGS5h.js → google-generative-ai-DkRyuoBH.js} +1 -1
  66. package/dist/ui/assets/{google-shared-DQbld86Z.js → google-shared-CCJkdw81.js} +2 -2
  67. package/dist/ui/assets/{google-shared-DwCjfFnw.js → google-shared-p5XdfI6c.js} +3 -3
  68. package/dist/ui/assets/{google-vertex-C18Xl3dV.js → google-vertex-Cp9ldPyE.js} +1 -1
  69. package/dist/ui/assets/{google-vertex-CkkAgSFr.js → google-vertex-D7VRnbrL.js} +1 -1
  70. package/dist/ui/assets/{handoff-link-CLvhqfpd.js → handoff-link-CfgH86mb.js} +1 -1
  71. package/dist/ui/assets/hear-D7srqY_7.js +1 -0
  72. package/dist/ui/assets/hear-acxY6mf0.js +1 -0
  73. package/dist/ui/assets/hid-device-registry-DboUgvzI.js +1 -0
  74. package/dist/ui/assets/hid-picker-Bhoh8hxy.js +1 -0
  75. package/dist/ui/assets/installer-D7LGGQGy.js +3 -0
  76. package/dist/ui/assets/{js-realm-worker-CeYHBMC5.js → js-realm-worker-B4uCLm52.js} +3 -3
  77. package/dist/ui/assets/{json-parse-B51EftGA.js → json-parse-CpLf0aqK.js} +1 -1
  78. package/dist/ui/assets/{json-parse-C7d6hyOc.js → json-parse-rb7sUwcH.js} +1 -1
  79. package/dist/ui/assets/kernel-worker-DMnEeTNU.js +8759 -0
  80. package/dist/ui/assets/{kokoro-C-DxSDte.js → kokoro-CGDCwNNA.js} +2 -2
  81. package/dist/ui/assets/{kokoro-BFFlHn4y.js → kokoro-D3TYeL2z.js} +2 -2
  82. package/dist/ui/assets/{kokoro-engine-uXKuCuNf.js → kokoro-engine-DLKTuHMR.js} +2 -2
  83. package/dist/ui/assets/legacy-api-aliases-BQSsmFIS.js +1 -0
  84. package/dist/ui/assets/legacy-api-aliases-DWJHPSiz.js +1 -0
  85. package/dist/ui/assets/{legacy-styles-kYboUbpI.js → legacy-styles-DcRu2WCJ.js} +1 -1
  86. package/dist/ui/assets/lick-manager-Ct3WOtut.js +2 -0
  87. package/dist/ui/assets/lick-ws-bridge-C_bJMGw6.js +1 -0
  88. package/dist/ui/assets/{lick-ws-bridge-Cbwcxuba.js → lick-ws-bridge-SPFIXhG2.js} +1 -1
  89. package/dist/ui/assets/llm-session-id-ZObKEXzb.js +1 -0
  90. package/dist/ui/assets/local-llm-B5vPCdpH.js +2 -0
  91. package/dist/ui/assets/{local-llm-Bn1XrCIn.js → local-llm-DS8tu43V.js} +1 -1
  92. package/dist/ui/assets/magick-wasm-B-rybRPb.js +43 -0
  93. package/dist/ui/assets/main-D8Y-cnmF.js +22 -0
  94. package/dist/ui/assets/{main-cherry-d-KDlb8k.js → main-cherry-CGm5knH6.js} +1 -1
  95. package/dist/ui/assets/{mime-types-BqLkKWa7.js → mime-types-D7IV6i7k.js} +1 -1
  96. package/dist/ui/assets/mistral-conversations-CLDzxp2F.js +8 -0
  97. package/dist/ui/assets/mistral-conversations-DbKikZnf.js +7 -0
  98. package/dist/ui/assets/{models-ByRUWfA-.js → models-CzSI8IsT.js} +1 -1
  99. package/dist/ui/assets/{mount-vMc2lWlc.js → mount-C4XESP9i.js} +1 -1
  100. package/dist/ui/assets/mount-Hr9QXuwp.js +2 -0
  101. package/dist/ui/assets/{mount-bridge-client-0Afn2H9Y.js → mount-bridge-client-BVLVI9yX.js} +1 -1
  102. package/dist/ui/assets/mount-recovery-BHHDw9yC.js +2 -0
  103. package/dist/ui/assets/mount-table-store-CTrzlrNn.js +1 -0
  104. package/dist/ui/assets/navigation-watcher-BoJS9hdc.js +1 -0
  105. package/dist/ui/assets/new-session-u-78FCPG.js +2 -0
  106. package/dist/ui/assets/oauth-bootstrap-DHKASsxn.js +2 -0
  107. package/dist/ui/assets/{oauth-service-w5HZt7Xx.js → oauth-service-CmM0tZSO.js} +1 -1
  108. package/dist/ui/assets/oauth-service-DSuwOpMz.js +1 -0
  109. package/dist/ui/assets/{openai-BeH6aC_-.js → openai-BxFF4GUL.js} +2 -2
  110. package/dist/ui/assets/{openai-BvKpRLAG.js → openai-CmTnPr9N.js} +2 -2
  111. package/dist/ui/assets/openai-codex-Djc_-qM9.js +1 -0
  112. package/dist/ui/assets/openai-codex-gi-RyKX_.js +1 -0
  113. package/dist/ui/assets/{openai-codex-responses-BDYh8ojD.js → openai-codex-responses-B_k2rCqO.js} +1 -1
  114. package/dist/ui/assets/{openai-codex-responses-C7QnNmC0.js → openai-codex-responses-RviMslSH.js} +1 -1
  115. package/dist/ui/assets/{openai-completions-t-glszMQ.js → openai-completions-CGLtJfv2.js} +1 -1
  116. package/dist/ui/assets/{openai-completions-BnAjXzgN.js → openai-completions-COYKlBqA.js} +1 -1
  117. package/dist/ui/assets/{openai-responses-o9_kr7GP.js → openai-responses-C4mUX6jK.js} +1 -1
  118. package/dist/ui/assets/{openai-responses-BofM6cmY.js → openai-responses-D02gU0ey.js} +1 -1
  119. package/dist/ui/assets/{openai-responses-shared-79gch22X.js → openai-responses-shared-CCTyKL6A.js} +2 -2
  120. package/dist/ui/assets/{openai-responses-shared-DKPwc9Eh.js → openai-responses-shared-bVKJbQt9.js} +2 -2
  121. package/dist/ui/assets/{openrouter-images-PT0FZmkM.js → openrouter-images-BrQDTa3_.js} +1 -1
  122. package/dist/ui/assets/{openrouter-images-D0dgD5eX.js → openrouter-images-DtvjLeGK.js} +1 -1
  123. package/dist/ui/assets/otel-C1NYdIbe.js +3 -0
  124. package/dist/ui/assets/otel-joHgpnL_.js +3 -0
  125. package/dist/ui/assets/page-follower-tray-DFeLlotx.js +5 -0
  126. package/dist/ui/assets/panel-rpc-handlers-CTZqBsvr.js +2 -0
  127. package/dist/ui/assets/{pdfjs-BdCnB7P8.js → pdfjs-B1saeD0h.js} +5 -5
  128. package/dist/ui/assets/{port-bridge-client-Btb0CfZS.js → port-bridge-client-CdvMlimf.js} +1 -1
  129. package/dist/ui/assets/{port-bridge-client-BtsJUDjt.js → port-bridge-client-CsrXhMWo.js} +1 -1
  130. package/dist/ui/assets/preload-helper-Czpn1I53.js +1 -0
  131. package/dist/ui/assets/process-manager-B5dz0PkO.js +1 -0
  132. package/dist/ui/assets/provider-DeZ3vGbS.js +2 -0
  133. package/dist/ui/assets/provider-POdkeNpc.js +1 -0
  134. package/dist/ui/assets/provider-settings-3FoUN196.js +1 -0
  135. package/dist/ui/assets/provider-settings-BraIAAA7.js +2 -0
  136. package/dist/ui/assets/provider-store-access-B_pR-9Xx.js +2 -0
  137. package/dist/ui/assets/provider-store-access-BkJ_SWbe.js +1 -0
  138. package/dist/ui/assets/providers-B26DtTJa.js +1 -0
  139. package/dist/ui/assets/providers-CvODsjGm.js +2 -0
  140. package/dist/ui/assets/proxied-fetch-DETjVL-j.js +2 -0
  141. package/dist/ui/assets/proxied-fetch-sbHa3Tte.js +1 -0
  142. package/dist/ui/assets/{py-realm-worker-C5_FcpVv.js → py-realm-worker-VuYxvTG9.js} +2 -2
  143. package/dist/ui/assets/{pyodide-CVuZVKDU.js → pyodide-BahZNzwn.js} +2 -2
  144. package/dist/ui/assets/{quick-llm-D_B5T-_G.js → quick-llm-DzhE1JW0.js} +1 -1
  145. package/dist/ui/assets/{readline-D4m_9EmN.js → readline-0OE_8qoR.js} +1 -1
  146. package/dist/ui/assets/remote-cdp-transport-DOoXIxy3.js +1 -0
  147. package/dist/ui/assets/{remote-terminal-view-BOSJ_t1v.js → remote-terminal-view-C7x7cM1d.js} +2 -2
  148. package/dist/ui/assets/runtime-mode-M-qJL9jF.js +1 -0
  149. package/dist/ui/assets/safe-buffer-C0pSmFaz.js +12 -0
  150. package/dist/ui/assets/script-catalog-BYXhqRAc.js +2 -0
  151. package/dist/ui/assets/{secret-env-CGjJCzwN.js → secret-env-1E2r2H5F.js} +1 -1
  152. package/dist/ui/assets/{secret-topology-_rfIhUjY.js → secret-topology-D2k1IxFk.js} +1 -1
  153. package/dist/ui/assets/{secrets-bridge-client-a5aLwwny.js → secrets-bridge-client-CONYX8PU.js} +1 -1
  154. package/dist/ui/assets/serial-picker-CUd91lje.js +1 -0
  155. package/dist/ui/assets/session-freezer-CUzeQ9yz.js +21 -0
  156. package/dist/ui/assets/{setup-sprinkle-exec-P2hO-taT.js → setup-sprinkle-exec-DD6jqggr.js} +1 -1
  157. package/dist/ui/assets/setup-sudo-cXyK0NGW.js +2 -0
  158. package/dist/ui/assets/{shared-Cq5Q0noX.js → shared-Dwjvg8S5.js} +1 -1
  159. package/dist/ui/assets/shared-X5SFnyK-.js +4 -0
  160. package/dist/ui/assets/skills-otSlGBFl.js +6 -0
  161. package/dist/ui/assets/{slicc-editor-DKckizoI.js → slicc-editor-BoIEeofq.js} +2 -2
  162. package/dist/ui/assets/{speak-DG2fJcBd.js → speak-WMi1eHMn.js} +3 -3
  163. package/dist/ui/assets/{speak-D1O_Xrcr.js → speak-YEgNUk4w.js} +1 -1
  164. package/dist/ui/assets/{sprinkle-bridge-C0ycYX8f.js → sprinkle-bridge-CmJpELpy.js} +1 -1
  165. package/dist/ui/assets/sprinkle-manager-DXrwoVHS.js +1 -0
  166. package/dist/ui/assets/{sprinkle-renderer-Bk_e6Kbr.js → sprinkle-renderer-B0y9_9py.js} +2 -2
  167. package/dist/ui/assets/{wc-shell-BUIX3UPq.js → src-6TqoULh8.js} +94 -211
  168. package/dist/ui/assets/src-CS5gSDhT.js +1 -0
  169. package/dist/ui/assets/src-Dk1QVJRd.js +1 -0
  170. package/dist/ui/assets/store-BfzctFJC.js +1 -0
  171. package/dist/ui/assets/{sudo-tWv6esvM.js → sudo-LN3PJp6v.js} +1 -1
  172. package/dist/ui/assets/telemetry-C8rZr13D.js +3 -0
  173. package/dist/ui/assets/timestamp-preference-DgrTvVNx.js +2 -0
  174. package/dist/ui/assets/transcript-limits-D0M7bLr9.js +1 -0
  175. package/dist/ui/assets/{transform-messages-ZX8cvJiJ.js → transform-messages-CVIV-EgO.js} +1 -1
  176. package/dist/ui/assets/transform-messages-fFaW-DLG.js +1 -0
  177. package/dist/ui/assets/transformers-env-8w05vuhN.js +1 -0
  178. package/dist/ui/assets/{transformers-env-w-btTDFl.js → transformers-env-sL29_hFb.js} +1 -1
  179. package/dist/ui/assets/{transformers.web-C6PlPLR-.js → transformers.web-CrioJkWG.js} +4 -4
  180. package/dist/ui/assets/{transformers.web-DkJGoARp.js → transformers.web-D6viRW2X.js} +5 -5
  181. package/dist/ui/assets/tray-follower-status-CyJIKXH4.js +1 -0
  182. package/dist/ui/assets/tray-join-url-BIvzbiFR.js +1 -0
  183. package/dist/ui/assets/tray-leader-DcLymd_E.js +1 -0
  184. package/dist/ui/assets/tray-leave-runtime-lJcLlwtm.js +1 -0
  185. package/dist/ui/assets/tray-runtime-config-DJIIJaBR.js +1 -0
  186. package/dist/ui/assets/tray-runtime-config-DlPGhxQs.js +1 -0
  187. package/dist/ui/assets/tray-sync-protocol-CVdiCvfU.js +1 -0
  188. package/dist/ui/assets/upgrade-detection-DIIyklC5.js +1 -0
  189. package/dist/ui/assets/usb-device-registry-BOGfZXgp.js +1 -0
  190. package/dist/ui/assets/{usb-operations-D-YdmmuG.js → usb-operations-BQbhk96u.js} +1 -1
  191. package/dist/ui/assets/usb-picker-Cl6Cwuv9.js +1 -0
  192. package/dist/ui/assets/voice-reply-DHV6R4En.js +1 -0
  193. package/dist/ui/assets/wc-attach-DU0svqb7.js +13 -0
  194. package/dist/ui/assets/wc-extension-oy0LEz26.js +2 -0
  195. package/dist/ui/assets/{wc-float-label-CNeJqRLg.js → wc-float-label-DeQPr3pd.js} +1 -1
  196. package/dist/ui/assets/wc-follower-DcQtc8YB.js +17 -0
  197. package/dist/ui/assets/wc-live-D7BaYtR7.js +8 -0
  198. package/dist/ui/assets/wc-nav-BqxVwvjV.js +2 -0
  199. package/dist/ui/assets/wc-onboarding-D9lPUOm-.js +2 -0
  200. package/dist/ui/assets/{wc-permissions-CAEOwurQ.js → wc-permissions-DW60QZxV.js} +3 -3
  201. package/dist/ui/assets/wc-permissions-providers-DMTDytlu.js +2 -0
  202. package/dist/ui/assets/wc-placeholder-C0wfdFBG.js +4 -0
  203. package/dist/ui/assets/wc-scoop-color-CByZNEJo.js +1 -0
  204. package/dist/ui/assets/wc-settings-qEE2zwaO.js +51 -0
  205. package/dist/ui/assets/wc-shell-BHZzK20y.js +117 -0
  206. package/dist/ui/assets/wc-sprinkles-DlE9uQTj.js +2 -0
  207. package/dist/ui/assets/wc-tray-BdFq9TlZ.js +2 -0
  208. package/dist/ui/assets/{whisper-engine-BHlrRP_X.js → whisper-engine-C0mT2z02.js} +1 -1
  209. package/dist/ui/assets/whisper-session-DvjyTCj0.js +2 -0
  210. package/dist/ui/assets/xai-grok-Bx0idvJc.js +1 -0
  211. package/dist/ui/assets/xai-grok-CemZ8tZD.js +1 -0
  212. package/dist/ui/assets/xterm-DX7Hb5S-.js +47 -0
  213. package/dist/ui/assets/xterm-U4TA8lIC.js +35 -0
  214. package/dist/ui/index.html +24 -15
  215. package/dist/ui/packages/webapp/index.html +24 -15
  216. package/package.json +2 -2
  217. package/dist/ui/assets/__vite-browser-external-s4_sx6bN.js +0 -1
  218. package/dist/ui/assets/account-store-B8fkPmC7.js +0 -103
  219. package/dist/ui/assets/account-store-VWDFUG4w.js +0 -38
  220. package/dist/ui/assets/adobe-Cq8jcHMI.js +0 -1
  221. package/dist/ui/assets/adobe-Dd07woZ4.js +0 -2
  222. package/dist/ui/assets/adobe-oauth-state-UjunBhEy.js +0 -1
  223. package/dist/ui/assets/agent-message-to-chat-B5QkdBqr.js +0 -7
  224. package/dist/ui/assets/bedrock-camp-CZFsedRI.js +0 -1
  225. package/dist/ui/assets/bedrock-camp-Czep_VHL.js +0 -1
  226. package/dist/ui/assets/cdp-bridge-CUqQUcaF.js +0 -1
  227. package/dist/ui/assets/cerebras-BvIwtmYU.js +0 -1
  228. package/dist/ui/assets/cerebras-CtDsI5t_.js +0 -1
  229. package/dist/ui/assets/clipboard-DYJRGAtu.js +0 -1
  230. package/dist/ui/assets/compat-FrhC6T45.js +0 -2
  231. package/dist/ui/assets/dip-C3FVgAp9.js +0 -1
  232. package/dist/ui/assets/discovery-preference-ChE43Rww.js +0 -1
  233. package/dist/ui/assets/dist-0c-Ms6jt.js +0 -23
  234. package/dist/ui/assets/dist-C30gQBcj2.js +0 -12
  235. package/dist/ui/assets/dist-ClEUNLR-.js +0 -18
  236. package/dist/ui/assets/ensure-speech-assets-DstqSdfZ.js +0 -1
  237. package/dist/ui/assets/es-kEo2Tmh4.js +0 -53
  238. package/dist/ui/assets/esp8266-DhxGJGHR.js +0 -1
  239. package/dist/ui/assets/esp8266-dt3vHImh.js +0 -1
  240. package/dist/ui/assets/esptool-operations-BBtDOaij.js +0 -12
  241. package/dist/ui/assets/esptool-operations-wGO-l9-a.js +0 -13
  242. package/dist/ui/assets/extension-bridge-transport-Bi9JIuzJ.js +0 -1
  243. package/dist/ui/assets/fs-Bkm8VZTn.js +0 -2
  244. package/dist/ui/assets/github-BeBf_tPt.js +0 -1
  245. package/dist/ui/assets/github-DVGask0m.js +0 -2
  246. package/dist/ui/assets/github-copilot-C_189pyB.js +0 -2
  247. package/dist/ui/assets/github-copilot-D_2n36Iv.js +0 -1
  248. package/dist/ui/assets/hear-B6LfLMgq.js +0 -1
  249. package/dist/ui/assets/hear-tL55Pr9X.js +0 -1
  250. package/dist/ui/assets/hid-device-registry-6w-g8ZpF.js +0 -1
  251. package/dist/ui/assets/hid-picker-Cp7Sp5N-.js +0 -1
  252. package/dist/ui/assets/kernel-worker-Yib4X2rK.js +0 -10443
  253. package/dist/ui/assets/lick-ws-bridge-DcIF2ReT.js +0 -1
  254. package/dist/ui/assets/main-CN--RCWy.js +0 -24
  255. package/dist/ui/assets/mistral-conversations-DKqvekSA.js +0 -7
  256. package/dist/ui/assets/mistral-conversations-szVW8BsU.js +0 -8
  257. package/dist/ui/assets/mount-D4hso6oU.js +0 -2
  258. package/dist/ui/assets/mount-id-nJcx05eu.js +0 -1
  259. package/dist/ui/assets/mount-table-store-s20mtVA3.js +0 -1
  260. package/dist/ui/assets/navigation-watcher-DTSw-td6.js +0 -1
  261. package/dist/ui/assets/new-session-Xv5Kw8-N.js +0 -2
  262. package/dist/ui/assets/oauth-bootstrap-C1TvVgVm.js +0 -2
  263. package/dist/ui/assets/oauth-service-Cf0jA8F5.js +0 -1
  264. package/dist/ui/assets/openai-codex-CEstk2ir.js +0 -1
  265. package/dist/ui/assets/openai-codex-wHLeOM3p.js +0 -1
  266. package/dist/ui/assets/otel-BvlmHUjk.js +0 -3
  267. package/dist/ui/assets/otel-CCT7TRJr.js +0 -3
  268. package/dist/ui/assets/page-follower-tray-B6HRGJrV.js +0 -5
  269. package/dist/ui/assets/panel-rpc-handlers-DKYTrToh.js +0 -2
  270. package/dist/ui/assets/preload-helper-CZgWQFsJ.js +0 -1
  271. package/dist/ui/assets/provider-DN6we75z.js +0 -1
  272. package/dist/ui/assets/provider-settings-CrHdjWRY.js +0 -1
  273. package/dist/ui/assets/provider-store-access-24wOseEM.js +0 -1
  274. package/dist/ui/assets/provider-store-access-C92IYCEl.js +0 -1
  275. package/dist/ui/assets/provider-zLIF1UQc.js +0 -2
  276. package/dist/ui/assets/providers-CmWab6F3.js +0 -1
  277. package/dist/ui/assets/providers-D2g-3ix9.js +0 -2
  278. package/dist/ui/assets/proxied-fetch-CQqrhHlW.js +0 -1
  279. package/dist/ui/assets/proxied-fetch-D3wsof0i.js +0 -2
  280. package/dist/ui/assets/remote-cdp-transport-DspFAFy_.js +0 -1
  281. package/dist/ui/assets/serial-picker-bJGym01W.js +0 -1
  282. package/dist/ui/assets/session-freezer-DtJb5_ro.js +0 -1
  283. package/dist/ui/assets/sprinkle-manager-CSCqntix.js +0 -1
  284. package/dist/ui/assets/src-BQoW5KdD.js +0 -1
  285. package/dist/ui/assets/src-BvERX0WZ.js +0 -1
  286. package/dist/ui/assets/store-2nS5H77F.js +0 -1
  287. package/dist/ui/assets/transform-messages-DwI5R8if.js +0 -1
  288. package/dist/ui/assets/transformers-env-D9qkXm3g.js +0 -1
  289. package/dist/ui/assets/tray-leader-CqFDvcNH.js +0 -1
  290. package/dist/ui/assets/tray-leave-runtime-C4sJoGLD.js +0 -1
  291. package/dist/ui/assets/upgrade-detection-Ba_0YKaQ.js +0 -1
  292. package/dist/ui/assets/usb-device-registry-k6vTKonT.js +0 -1
  293. package/dist/ui/assets/usb-picker-DJjZemi7.js +0 -1
  294. package/dist/ui/assets/voice-reply-DQhloSOU.js +0 -1
  295. package/dist/ui/assets/wc-attach-BhQT8ZHR.js +0 -13
  296. package/dist/ui/assets/wc-extension-C4UUKHE1.js +0 -2
  297. package/dist/ui/assets/wc-follower-yEiXLTkQ.js +0 -17
  298. package/dist/ui/assets/wc-live-CVqsJqLB.js +0 -258
  299. package/dist/ui/assets/wc-nav-CIhQdld0.js +0 -2
  300. package/dist/ui/assets/wc-onboarding-ByJ2OTEx.js +0 -2
  301. package/dist/ui/assets/wc-permissions-providers-CbkqRh4J.js +0 -2
  302. package/dist/ui/assets/wc-placeholder-BzfJm5K3.js +0 -4
  303. package/dist/ui/assets/wc-settings-CZ9BR9F3.js +0 -51
  304. package/dist/ui/assets/wc-sprinkles-aeMd0T-B.js +0 -2
  305. package/dist/ui/assets/wc-tray-D34gP9Uw.js +0 -2
  306. package/dist/ui/assets/whisper-session-C8cizjJD.js +0 -2
  307. package/dist/ui/assets/xai-grok-ltyrVlT-.js +0 -1
  308. package/dist/ui/assets/xai-grok-p0W6Xjk5.js +0 -1
  309. package/dist/ui/assets/xterm-DMlKjmUi.js +0 -36
  310. package/dist/ui/assets/xterm-Dwh1I9AE.js +0 -48
@@ -1 +1 @@
1
- import{t as e}from"./preload-helper-CZgWQFsJ.js";var t=class{queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise(e=>{this.resolveFinalResult=e})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));let t=this.waiting.shift();t?t({value:e,done:!1}):this.queue.push(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let e=await new Promise(e=>this.waiting.push(e));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}},n=class extends t{constructor(){super(e=>e.type===`done`||e.type===`error`,e=>{if(e.type===`done`)return e.message;if(e.type===`error`)return e.error;throw Error(`Unexpected event type for final result`)})}};function r(){return new n}function i(e,t){return{role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function a(e,t){(async()=>{for await(let n of t)e.push(n);e.end()})()}function o(e,t){let r=new n;return t().then(e=>{a(r,e)}).catch(t=>{let n=i(e,t);r.push({type:`error`,reason:`error`,error:n}),r.end(n)}),r}function s(e){return{stream:(t,n,r)=>o(t,async()=>(await e()).stream(t,n,r)),streamSimple:(t,n,r)=>o(t,async()=>(await e()).streamSimple(t,n,r))}}var c=function(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e},l=t=>e(()=>import(c(t)),[]);function u(){return globalThis.process?.env}function d(){return{async env(e){let t=u()?.[e];return typeof t==`string`&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await l(`node:fs/promises`),n=e;return n.startsWith(`~`)&&(n=(await l(`node:os`)).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var f=class{credentials=new Map;chains=new Map;enqueue(e,t){let n=this.chains.get(e)??Promise.resolve(),r=(async()=>(await n.catch(()=>{}),t()))();return this.chains.set(e,r.catch(()=>{})),r}async read(e){return this.credentials.get(e)}modify(e,t){return this.enqueue(e,async()=>{let n=this.credentials.get(e),r=await t(n);return r!==void 0&&this.credentials.set(e,r),r??n})}delete(e){return this.enqueue(e,async()=>{this.credentials.delete(e)})}},p=class extends Error{code;constructor(e,t,n){super(t,n),this.name=`ModelsError`,this.code=e}};async function m(e,t,n,r,i){let a=i?.env?h(r,i.env):r;if(i?.apiKey!==void 0&&e.auth.apiKey)return _(a,e.auth.apiKey,t,{type:`api_key`,key:i.apiKey,env:i.env});let o=await v(n,e.id);if(o){if(o.type===`oauth`&&e.auth.oauth)return g(n,e.id,e.auth.oauth,o);if(o.type===`api_key`&&e.auth.apiKey){let n=i?.env?{...o,env:{...o.env,...i.env}}:o;return _(a,e.auth.apiKey,t,n)}return}return e.auth.apiKey?_(a,e.auth.apiKey,t,void 0):void 0}function h(e,t){return{env:async n=>t[n]||await e.env(n),fileExists:t=>e.fileExists(t)}}async function g(e,t,n,r){let i=r;if(Date.now()>=i.expires){let r;try{r=await e.modify(t,async e=>{if(e?.type===`oauth`&&!(Date.now()<e.expires))try{return await n.refresh(e)}catch(e){throw new p(`oauth`,`OAuth refresh failed for ${t}`,{cause:e})}})}catch(e){throw e instanceof p?e:new p(`auth`,`Credential store modify failed for ${t}`,{cause:e})}if(r?.type!==`oauth`)return;i=r}try{return{auth:await n.toAuth(i),source:`OAuth`}}catch(e){throw new p(`oauth`,`OAuth auth derivation failed for ${t}`,{cause:e})}}async function _(e,t,n,r){try{return await t.resolve({model:n,ctx:e,credential:r})}catch(e){throw new p(`auth`,`API key auth failed for provider ${n.provider}`,{cause:e})}}async function v(e,t){try{return await e.read(t)}catch(e){throw new p(`auth`,`Credential store read failed for ${t}`,{cause:e})}}var y=class{providers=new Map;credentials;authContext;constructor(e){this.credentials=e?.credentials??new f,this.authContext=e?.authContext??d()}setProvider(e){this.providers.set(e.id,e)}deleteProvider(e){this.providers.delete(e)}clearProviders(){this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let t=this.providers.get(e);if(!t)return[];try{return t.getModels()}catch{return[]}}let t=[];for(let e of this.providers.values())try{t.push(...e.getModels())}catch{}return t}getModel(e,t){return this.getModels(e).find(e=>e.id===t)}async refresh(e){if(e!==void 0){let t=this.providers.get(e);if(!t?.refreshModels)return;try{await t.refreshModels()}catch(t){throw t instanceof p?t:new p(`model_source`,`Model refresh failed for ${e}`,{cause:t})}return}await Promise.allSettled(Array.from(this.providers.values(),async e=>e.refreshModels?.()))}async getAuth(e){let t=this.providers.get(e.provider);if(t)return m(t,e,this.credentials,this.authContext)}requireProvider(e){let t=this.providers.get(e.provider);if(!t)throw new p(`provider`,`Unknown provider: ${e.provider}`);return t}async applyAuth(e,t){let n=await m(this.requireProvider(e),e,this.credentials,this.authContext,{apiKey:t?.apiKey,env:t?.env}),r=n?.auth;if(!r)return{requestModel:e,requestOptions:t};let i=r.baseUrl?{...e,baseUrl:r.baseUrl}:e,a=t?.apiKey??r.apiKey,o=r.headers||t?.headers?{...r.headers,...t?.headers}:void 0,s=n.env||t?.env?{...n.env??{},...t?.env??{}}:void 0;return{requestModel:i,requestOptions:{...t,apiKey:a,headers:o,env:s}}}stream(e,t,n){return o(e,async()=>{let r=this.requireProvider(e),{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return r.stream(i,t,a)})}async complete(e,t,n){return this.stream(e,t,n).result()}streamSimple(e,t,n){return o(e,async()=>{let r=this.requireProvider(e),{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return r.streamSimple(i,t,a)})}async completeSimple(e,t,n){return this.streamSimple(e,t,n).result()}};function b(e){return new y(e)}function x(e){let t=e.models,n,r=e.refreshModels,i=typeof e.api.stream==`function`?e.api:void 0,a=i?void 0:e.api,s=e=>i??a?.[e.api],c=(t,n)=>{let r=s(t);return r?n(r):o(t,async()=>{throw new p(`stream`,`Provider ${e.id} has no API implementation for "${t.api}"`)})};return{id:e.id,name:e.name??e.id,baseUrl:e.baseUrl,headers:e.headers,auth:e.auth,getModels:()=>t,refreshModels:r?()=>(n??=(async()=>{try{t=await r()}finally{n=void 0}})(),n):void 0,stream:(e,t,n)=>c(e,r=>r.stream(e,t,n)),streamSimple:(e,t,n)=>c(e,r=>r.streamSimple(e,t,n))}}function S(e,t){let n=t.cacheWrite1h??0,r=t.cacheWrite-n;return t.cost.input=e.cost.input/1e6*t.input,t.cost.output=e.cost.output/1e6*t.output,t.cost.cacheRead=e.cost.cacheRead/1e6*t.cacheRead,t.cost.cacheWrite=(e.cost.cacheWrite*r+e.cost.input*2*n)/1e6,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite,t.cost}var C=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function w(e){return e.reasoning?C.filter(t=>{let n=e.thinkingLevelMap?.[t];return n===null?!1:t===`xhigh`?n!==void 0:!0}):[`off`]}function T(e,t){let n=w(e);if(n.includes(t))return t;let r=C.indexOf(t);if(r===-1)return n[0]??`off`;for(let e=r;e<C.length;e++){let t=C[e];if(n.includes(t))return t}for(let e=r-1;e>=0;e--){let t=C[e];if(n.includes(t))return t}return n[0]??`off`}export{s as a,x as i,T as n,n as o,b as r,r as s,S as t};
1
+ import{t as e}from"./preload-helper-Czpn1I53.js";var t=class{queue=[];waiting=[];done=!1;finalResultPromise;resolveFinalResult;isComplete;extractResult;constructor(e,t){this.isComplete=e,this.extractResult=t,this.finalResultPromise=new Promise(e=>{this.resolveFinalResult=e})}push(e){if(this.done)return;this.isComplete(e)&&(this.done=!0,this.resolveFinalResult(this.extractResult(e)));let t=this.waiting.shift();t?t({value:e,done:!1}):this.queue.push(e)}end(e){for(this.done=!0,e!==void 0&&this.resolveFinalResult(e);this.waiting.length>0;)this.waiting.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let e=await new Promise(e=>this.waiting.push(e));if(e.done)return;yield e.value}}result(){return this.finalResultPromise}},n=class extends t{constructor(){super(e=>e.type===`done`||e.type===`error`,e=>{if(e.type===`done`)return e.message;if(e.type===`error`)return e.error;throw Error(`Unexpected event type for final result`)})}};function r(){return new n}function i(e,t){return{role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function a(e,t){(async()=>{for await(let n of t)e.push(n);e.end()})()}function o(e,t){let r=new n;return t().then(e=>{a(r,e)}).catch(t=>{let n=i(e,t);r.push({type:`error`,reason:`error`,error:n}),r.end(n)}),r}function s(e){return{stream:(t,n,r)=>o(t,async()=>(await e()).stream(t,n,r)),streamSimple:(t,n,r)=>o(t,async()=>(await e()).streamSimple(t,n,r))}}var c=function(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e},l=t=>e(()=>import(c(t)),[]);function u(){return globalThis.process?.env}function d(){return{async env(e){let t=u()?.[e];return typeof t==`string`&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await l(`node:fs/promises`),n=e;return n.startsWith(`~`)&&(n=(await l(`node:os`)).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}var f=class{credentials=new Map;chains=new Map;enqueue(e,t){let n=this.chains.get(e)??Promise.resolve(),r=(async()=>(await n.catch(()=>{}),t()))();return this.chains.set(e,r.catch(()=>{})),r}async read(e){return this.credentials.get(e)}modify(e,t){return this.enqueue(e,async()=>{let n=this.credentials.get(e),r=await t(n);return r!==void 0&&this.credentials.set(e,r),r??n})}delete(e){return this.enqueue(e,async()=>{this.credentials.delete(e)})}},p=class extends Error{code;constructor(e,t,n){super(t,n),this.name=`ModelsError`,this.code=e}};async function m(e,t,n,r,i){let a=i?.env?h(r,i.env):r;if(i?.apiKey!==void 0&&e.auth.apiKey)return _(a,e.auth.apiKey,t,{type:`api_key`,key:i.apiKey,env:i.env});let o=await v(n,e.id);if(o){if(o.type===`oauth`&&e.auth.oauth)return g(n,e.id,e.auth.oauth,o);if(o.type===`api_key`&&e.auth.apiKey){let n=i?.env?{...o,env:{...o.env,...i.env}}:o;return _(a,e.auth.apiKey,t,n)}return}return e.auth.apiKey?_(a,e.auth.apiKey,t,void 0):void 0}function h(e,t){return{env:async n=>t[n]||await e.env(n),fileExists:t=>e.fileExists(t)}}async function g(e,t,n,r){let i=r;if(Date.now()>=i.expires){let r;try{r=await e.modify(t,async e=>{if(e?.type===`oauth`&&!(Date.now()<e.expires))try{return await n.refresh(e)}catch(e){throw new p(`oauth`,`OAuth refresh failed for ${t}`,{cause:e})}})}catch(e){throw e instanceof p?e:new p(`auth`,`Credential store modify failed for ${t}`,{cause:e})}if(r?.type!==`oauth`)return;i=r}try{return{auth:await n.toAuth(i),source:`OAuth`}}catch(e){throw new p(`oauth`,`OAuth auth derivation failed for ${t}`,{cause:e})}}async function _(e,t,n,r){try{return await t.resolve({model:n,ctx:e,credential:r})}catch(e){throw new p(`auth`,`API key auth failed for provider ${n.provider}`,{cause:e})}}async function v(e,t){try{return await e.read(t)}catch(e){throw new p(`auth`,`Credential store read failed for ${t}`,{cause:e})}}var y=class{providers=new Map;credentials;authContext;constructor(e){this.credentials=e?.credentials??new f,this.authContext=e?.authContext??d()}setProvider(e){this.providers.set(e.id,e)}deleteProvider(e){this.providers.delete(e)}clearProviders(){this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let t=this.providers.get(e);if(!t)return[];try{return t.getModels()}catch{return[]}}let t=[];for(let e of this.providers.values())try{t.push(...e.getModels())}catch{}return t}getModel(e,t){return this.getModels(e).find(e=>e.id===t)}async refresh(e){if(e!==void 0){let t=this.providers.get(e);if(!t?.refreshModels)return;try{await t.refreshModels()}catch(t){throw t instanceof p?t:new p(`model_source`,`Model refresh failed for ${e}`,{cause:t})}return}await Promise.allSettled(Array.from(this.providers.values(),async e=>e.refreshModels?.()))}async getAuth(e){let t=this.providers.get(e.provider);if(t)return m(t,e,this.credentials,this.authContext)}requireProvider(e){let t=this.providers.get(e.provider);if(!t)throw new p(`provider`,`Unknown provider: ${e.provider}`);return t}async applyAuth(e,t){let n=await m(this.requireProvider(e),e,this.credentials,this.authContext,{apiKey:t?.apiKey,env:t?.env}),r=n?.auth;if(!r)return{requestModel:e,requestOptions:t};let i=r.baseUrl?{...e,baseUrl:r.baseUrl}:e,a=t?.apiKey??r.apiKey,o=r.headers||t?.headers?{...r.headers,...t?.headers}:void 0,s=n.env||t?.env?{...n.env??{},...t?.env??{}}:void 0;return{requestModel:i,requestOptions:{...t,apiKey:a,headers:o,env:s}}}stream(e,t,n){return o(e,async()=>{let r=this.requireProvider(e),{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return r.stream(i,t,a)})}async complete(e,t,n){return this.stream(e,t,n).result()}streamSimple(e,t,n){return o(e,async()=>{let r=this.requireProvider(e),{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return r.streamSimple(i,t,a)})}async completeSimple(e,t,n){return this.streamSimple(e,t,n).result()}};function b(e){return new y(e)}function x(e){let t=e.models,n,r=e.refreshModels,i=typeof e.api.stream==`function`?e.api:void 0,a=i?void 0:e.api,s=e=>i??a?.[e.api],c=(t,n)=>{let r=s(t);return r?n(r):o(t,async()=>{throw new p(`stream`,`Provider ${e.id} has no API implementation for "${t.api}"`)})};return{id:e.id,name:e.name??e.id,baseUrl:e.baseUrl,headers:e.headers,auth:e.auth,getModels:()=>t,refreshModels:r?()=>(n??=(async()=>{try{t=await r()}finally{n=void 0}})(),n):void 0,stream:(e,t,n)=>c(e,r=>r.stream(e,t,n)),streamSimple:(e,t,n)=>c(e,r=>r.streamSimple(e,t,n))}}function S(e,t){let n=t.cacheWrite1h??0,r=t.cacheWrite-n;return t.cost.input=e.cost.input/1e6*t.input,t.cost.output=e.cost.output/1e6*t.output,t.cost.cacheRead=e.cost.cacheRead/1e6*t.cacheRead,t.cost.cacheWrite=(e.cost.cacheWrite*r+e.cost.input*2*n)/1e6,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite,t.cost}var C=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`];function w(e){return e.reasoning?C.filter(t=>{let n=e.thinkingLevelMap?.[t];return n===null?!1:t!==`xhigh`||n!==void 0}):[`off`]}function T(e,t){let n=w(e);if(n.includes(t))return t;let r=C.indexOf(t);if(r===-1)return n[0]??`off`;for(let e=r;e<C.length;e++){let t=C[e];if(n.includes(t))return t}for(let e=r-1;e>=0;e--){let t=C[e];if(n.includes(t))return t}return n[0]??`off`}export{s as a,x as i,T as n,n as o,b as r,r as s,S as t};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{c as t,s as n}from"./src-BQoW5KdD.js";import"./backend-local-J_dSen8g.js";import{t as r}from"./runtime-env-byAg9ij-.js";import{t as i}from"./types-idfTVsM8.js";import{t as a}from"./mime-types-BqLkKWa7.js";import{o,r as s,t as c}from"./proxied-fetch-CQqrhHlW.js";import{t as l}from"./remote-cache-D59F5FOx.js";import{t as u}from"./port-bridge-client-BtsJUDjt.js";function d(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function f(e){return e.split(`/`).pop()||`data`}function p(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var m=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=p(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new i(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let a=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(a.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(a.status===404)throw await this.cache.invalidateBody(t),new i(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new i(`EACCES`,`da access denied`,e);if(a.status>=400)throw new i(`EIO`,`da readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new i(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new i(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,t){if(this.assertOpen(e),t.byteLength>this.maxBodyBytes)throw new i(`EFBIG`,`body exceeds maxBodyBytes`,e);let n=this.toMountRelative(e),r=await this.cache.getBody(n),o=d(f(e),a(e),t),s={"content-type":o.contentType,"content-length":String(o.body.byteLength)};r?.etag?s[`if-match`]=r.etag.startsWith(`W/`)?r.etag.slice(2):r.etag:r||(s[`if-none-match`]=`*`);let c=()=>this.transport({method:`POST`,path:this.toSourcePath(n),headers:s,body:o.body}),l,u=1;try{l=await c()}catch{u=2,l=await c()}if(l.status===412){if(u===2){let r=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(r.status>=400)throw new i(`EIO`,`da reconcile HEAD failed: ${r.status}`,e);let a=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,a);let o=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new i(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new i(`EACCES`,`da write denied`,e);if(l.status>=400)throw new i(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(n,t,p);let m=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new i(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new i(`EIO`,`da list failed: ${r.status}`,e);let a=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,a),a}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),a=r.pop()??``,o=r.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===a);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new i(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===a&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(o,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new i(`ENOENT`,`no such file or directory`,e)}throw new i(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new i(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new i(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new i(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function h(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new i(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let a=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(a.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(a.status===404)throw await this.cache.invalidateBody(t),new i(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new i(`EACCES`,`s3 access denied`,e);if(a.status>=400)throw new i(`EIO`,`s3 readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new i(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new i(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new i(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),a={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?a[`if-match`]=r.etag:a[`if-none-match`]=`*`;let o=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:a,body:t}),s,c=1;try{s=await o()}catch{c=2,s=await o()}if(s.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new i(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let a=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,a);let o=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new i(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new i(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new i(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new i(`EIO`,`s3 list failed: ${r.status}`,`/`);let a=await r.text(),o=this.parseListingXml(a);e.push(...o.contents),t=o.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),a=r.pop()??``,o=r.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===a);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new i(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new i(`ENOENT`,`no such file or directory`,e)}throw new i(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new i(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new i(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new i(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new i(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},_=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function v(){let{getAccounts:e}=await import(`./account-store-B8fkPmC7.js`).then(e=>e.n),t=e().find(e=>e.providerId===`adobe`);if(!t?.accessToken)throw new _(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}const y=u({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new i(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function b(e,t){return y({type:e,envelope:t})}const x=n,S=t,C=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),w=new Set([101,103,204,205,304]);function T(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new i(`EACCES`,e.error):e.errorCode===`invalid_request`?new i(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||C.has(String(e.errorCode))?new i(`EIO`,e.error):new i(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=x(e.bodyBase64)}catch(e){throw new i(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=w.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function E(e,t){let n;try{n=await fetch(o(e),{method:`POST`,headers:c({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new i(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new i(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function D(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new i(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function O(e,t,n){return r()?D(e,n):s()?b(e,n):E(t,n)}function k(e){return async t=>T(await O(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?S(t.body):void 0}))}function A(e){let t=e?.getImsToken??(async()=>(await v()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new i(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return T(await O(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?S(e.body):void 0}))}}var j=e({DaMountBackend:()=>m,RemoteMountCache:()=>l,S3MountBackend:()=>g,makeSignedFetchDa:()=>A,makeSignedFetchS3:()=>k});export{m as a,g as i,A as n,k as r,j as t};
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{m as t,o as n,p as r,r as i,t as a}from"./proxied-fetch-sbHa3Tte.js";import"./src-Dk1QVJRd.js";import"./backend-local-J_dSen8g.js";import{t as o}from"./runtime-env-byAg9ij-.js";import{t as s}from"./types-idfTVsM8.js";import{t as c}from"./mime-types-D7IV6i7k.js";import{t as l}from"./remote-cache-D59F5FOx.js";import{t as u}from"./port-bridge-client-CsrXhMWo.js";function d(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function f(e){return e.split(`/`).pop()||`data`}function p(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var m=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=p(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`da access denied`,e);if(i.status>=400)throw new s(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,c,u),c}async writeFile(e,t){if(this.assertOpen(e),t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let n=this.toMountRelative(e),r=await this.cache.getBody(n),i=d(f(e),c(e),t),a={"content-type":i.contentType,"content-length":String(i.body.byteLength)};r?.etag?a[`if-match`]=r.etag.startsWith(`W/`)?r.etag.slice(2):r.etag:r||(a[`if-none-match`]=`*`);let o=()=>this.transport({method:`POST`,path:this.toSourcePath(n),headers:a,body:i.body}),l,u=1;try{l=await o()}catch{u=2,l=await o()}if(l.status===412){if(u===2){let r=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(r.status>=400)throw new s(`EIO`,`da reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new s(`EACCES`,`da write denied`,e);if(l.status>=400)throw new s(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(n,t,p);let m=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new s(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new s(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new s(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new s(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new s(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function h(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new s(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new s(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new s(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new s(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await i.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new s(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,c=1;try{o=await a()}catch{c=2,o=await a()}if(o.status===412){if(c===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new s(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new s(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new s(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new s(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new s(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new s(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new s(`ENOENT`,`no such file or directory`,e)}throw new s(`EIO`,`s3 stat failed: ${c.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new s(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new s(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new s(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new s(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},_=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function v(){let{getAccounts:e}=await import(`./account-store-BddNCTSm.js`).then(e=>e.n),t=e().find(e=>e.providerId===`adobe`);if(!t?.accessToken)throw new _(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}const y=u({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new s(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function b(e,t){return y({type:e,envelope:t})}const x=r,S=t,C=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),w=new Set([101,103,204,205,304]);function T(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new s(`EACCES`,e.error):e.errorCode===`invalid_request`?new s(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||C.has(String(e.errorCode))?new s(`EIO`,e.error):new s(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=x(e.bodyBase64)}catch(e){throw new s(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=w.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function E(e,t){let r;try{r=await fetch(n(e),{method:`POST`,headers:a({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await r.json()}catch(e){throw new s(`EIO`,`mount transport: response is not a JSON envelope (status ${r.status}): ${e instanceof Error?e.message:String(e)}`)}}async function D(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new s(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function O(e,t,n){return o()?D(e,n):i()?b(e,n):E(t,n)}function k(e){return async t=>T(await O(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?S(t.body):void 0}))}function A(e){let t=e?.getImsToken??(async()=>(await v()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new s(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return T(await O(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?S(e.body):void 0}))}}var j=e({DaMountBackend:()=>m,RemoteMountCache:()=>l,S3MountBackend:()=>g,makeSignedFetchDa:()=>A,makeSignedFetchS3:()=>k});export{m as a,g as i,A as n,k as r,j as t};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/account-store-dvAfa3y8.js","assets/rolldown-runtime-aKtaBQYM.js","assets/preload-helper-Czpn1I53.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-CvODsjGm.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{t}from"./mime-types-ugOWOUZ9.js";import{n,t as r}from"./base64-DpPqYZJF.js";import"./src-CS5gSDhT.js";import{o as i,r as a,t as o}from"./proxied-fetch-DETjVL-j.js";import{n as s}from"./runtime-env-DH4NDw4t.js";import{t as c}from"./types-idfTVsM8.js";import"./backend-local-smcj-_Ox.js";import"./mount-table-store-CfQUN_2R.js";import{t as l}from"./mount-bridge-client-BVLVI9yX.js";function u(e,t,n){let r=`----DaMount${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`,i=new TextEncoder,a=i.encode(`--${r}\r\nContent-Disposition: form-data; name="data"; filename="${e}"\r\nContent-Type: ${t}\r\n\r\n`),o=i.encode(`\r\n--${r}--\r\n`),s=new Uint8Array(a.byteLength+n.byteLength+o.byteLength);return s.set(a,0),s.set(n,a.byteLength),s.set(o,a.byteLength+n.byteLength),{contentType:`multipart/form-data; boundary=${r}`,body:s}}function d(e){return e.split(`/`).pop()||`data`}function f(e){let t=e.match(/^da:\/\/([^/]+)\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid DA source '${e}' — expected da://org/repo[/path]`);return{org:t[1],repo:t[2],path:(t[3]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var p=5*1024*1024,m=class{kind=`da`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=f(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??p,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new c(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toSourcePath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/source/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}toListPath(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``),n=[this.parsed.path,t].filter(e=>e.length>0).join(`/`);return`/list/${this.parsed.org}/${this.parsed.repo}${n?`/${n}`:``}`}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new c(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new c(`EACCES`,`da access denied`,e);if(i.status>=400)throw new c(`EIO`,`da readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let s=new Uint8Array(await i.arrayBuffer());if(s.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``,u=l.startsWith(`W/`)?l.slice(2):l;return await this.cache.putBody(t,s,u),s}async writeFile(e,n){if(this.assertOpen(e),n.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=this.toMountRelative(e),i=await this.cache.getBody(r),a=u(d(e),t(e),n),o={"content-type":a.contentType,"content-length":String(a.body.byteLength)};i?.etag?o[`if-match`]=i.etag.startsWith(`W/`)?i.etag.slice(2):i.etag:i||(o[`if-none-match`]=`*`);let s=()=>this.transport({method:`POST`,path:this.toSourcePath(r),headers:o,body:a.body}),l,f=1;try{l=await s()}catch{f=2,l=await s()}if(l.status===412){if(f===2){let t=await this.transport({method:`HEAD`,path:this.toSourcePath(r)});if(t.status>=400)throw new c(`EIO`,`da reconcile HEAD failed: ${t.status}`,e);let i=t.headers.get(`etag`)??``;await this.cache.putBody(r,n,i);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new c(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new c(`EACCES`,`da write denied`,e);if(l.status>=400)throw new c(`EIO`,`da writeFile failed: ${l.status}`,e);let p=l.headers.get(`etag`)??``;await this.cache.putBody(r,n,p);let m=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.transport({method:`GET`,path:this.toListPath(t)});if(r.status===404)throw new c(`ENOENT`,`no such directory`,e);if(r.status>=400)throw new c(`EIO`,`da list failed: ${r.status}`,e);let i=(await r.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,i),i}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new c(`ENOENT`,`no such file or directory`,e)}let s=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(s.status===200){let e=Number(s.headers.get(`content-length`)??`0`),t=s.headers.get(`etag`)??``,n=s.headers.get(`last-modified`),r=n?Date.parse(n):0;if(o){let n=o.entries.map(n=>n.name===i&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(a,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(s.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new c(`ENOENT`,`no such file or directory`,e)}throw new c(`EIO`,`da stat failed: ${s.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.transport({method:`DELETE`,path:this.toSourcePath(t)});if(n.status===404)throw new c(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new c(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new c(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let r=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(r)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{await this.refreshDir(e,t,n)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}return e?.bodies&&await this.refreshBodies(t),t}async classifyFile(e,t,n){let r=await this.cache.getBody(e);r?t&&r.etag!==t?(await this.cache.invalidateBody(e),n.changed.push(e)):n.unchanged++:n.added.push(e)}async refreshDir(e,t,n){let r=await this.transport({method:`GET`,path:this.toListPath(e)});if(r.status>=400){t.errors.push({path:e,message:`list failed: ${r.status}`});return}let i=await r.json(),a=[];for(let r of i)if(r.ext){let n=e?`${e}/${r.name}.${r.ext}`:`${r.name}.${r.ext}`;a.push({name:`${r.name}.${r.ext}`,kind:`file`,etag:r.etag,lastModified:r.lastModified}),await this.classifyFile(n,r.etag,t)}else a.push({name:r.name,kind:`directory`}),n.push(e?`${e}/${r.name}`:r.name);await this.cache.putListing(e,a)}async refreshBodies(e){for(let t of e.changed)try{await this.readFile(t)}catch(n){e.errors.push({path:t,message:n instanceof Error?n.message:String(n)})}}describe(){return{displayName:`${this.parsed.org}/${this.parsed.repo}${this.parsed.path?`/${this.parsed.path}`:``}`,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function h(e){let t=e.match(/^s3:\/\/([^/]+)(?:\/(.*))?$/);if(!t)throw Error(`invalid S3 source '${e}' — expected s3://bucket[/prefix]`);return{bucket:t[1],prefix:(t[2]??``).replace(/^\/+/,``).replace(/\/+$/,``)}}var g=25*1024*1024,_=class{kind=`s3`;source;profile;mountId;parsed;cache;maxBodyBytes;transport;closed=!1;constructor(e){this.source=e.source,this.profile=e.profile,this.mountId=e.mountId??crypto.randomUUID(),this.parsed=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??g,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new c(`EBADF`,`mount closed`,e)}toMountRelative(e){return e.replace(/^\/+/,``)}toS3Key(e){let t=e.replace(/^\/+/,``).replace(/\/+$/,``);return[this.parsed.prefix,t].filter(e=>e.length>0).join(`/`)}toMountRelativeKey(e){return this.parsed.prefix?e.slice(this.parsed.prefix.length+1):e}async readFile(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n&&!this.cache.isStale(n.cachedAt))return n.body;let r={};n&&(r[`if-none-match`]=n.etag);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:r});if(i.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(i.status===404)throw await this.cache.invalidateBody(t),new c(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new c(`EACCES`,`s3 access denied`,e);if(i.status>=400)throw new c(`EIO`,`s3 readFile failed: ${i.status}`,e);let a=i.headers.get(`content-length`),o=a?Number(a):void 0;if(o!==void 0&&o>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes (${o} > ${this.maxBodyBytes})`,e);let s=new Uint8Array(await i.arrayBuffer());if(s.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=i.headers.get(`etag`)??``;return await this.cache.putBody(t,s,l),s}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new c(`EFBIG`,`body exceeds maxBodyBytes`,e);let r=await this.cache.getBody(n),i={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};r?i[`if-match`]=r.etag:i[`if-none-match`]=`*`;let a=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i,body:t}),o,s=1;try{o=await a()}catch{s=2,o=await a()}if(o.status===412){if(s===2){let r=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status>=400)throw new c(`EIO`,`s3 reconcile HEAD failed: ${r.status}`,e);let i=r.headers.get(`etag`)??``;await this.cache.putBody(n,t,i);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new c(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(o.status===401||o.status===403)throw new c(`EACCES`,`s3 write denied`,e);if(o.status>=400)throw new c(`EIO`,`s3 writeFile failed: ${o.status}`,e);let l=o.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let r=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(r.status>=400)throw new c(`EIO`,`s3 list failed: ${r.status}`,`/`);let i=await r.text(),a=this.parseListingXml(i);e.push(...a.contents),t=a.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let r=t.split(`/`),i=r.pop()??``,a=r.join(`/`),o=await this.cache.getListing(a);if(o&&!this.cache.isStale(o.cachedAt)){let t=o.entries.find(e=>e.name===i);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??o.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??o.cachedAt};if(!t)throw new c(`ENOENT`,`no such file or directory`,e)}let s=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(t)});if(s.status===200){let e=Number(s.headers.get(`content-length`)??`0`),t=s.headers.get(`etag`)??``,n=s.headers.get(`last-modified`);return{kind:`file`,size:e,mtime:n?Date.parse(n):0,etag:t}}if(s.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new c(`ENOENT`,`no such file or directory`,e)}throw new c(`EIO`,`s3 stat failed: ${s.status}`,e)}async refresh(e){this.assertOpen(`/`);let t=await this.listObjectsV2(),n=new Set(t.map(e=>this.toMountRelativeKey(e.key))),r=new Map(t.map(e=>[this.toMountRelativeKey(e.key),e.etag])),i={added:[],removed:[],changed:[],unchanged:0,errors:[]};for(let e of n){let t=await this.cache.getBody(e),n=r.get(e);t?t.etag===n?i.unchanged++:(await this.cache.invalidateBody(e),i.changed.push(e)):i.added.push(e)}let a=this.groupByDir(t);for(let[e,t]of a)await this.cache.putListing(e,t);if(e?.bodies)for(let e of i.changed)try{await this.readFile(e)}catch(t){i.errors.push({path:e,message:t instanceof Error?t.message:String(t)})}return i}async mkdir(e){}async remove(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t?.recursive)throw new c(`EINVAL`,`recursive remove not yet supported on S3`,e);let r=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(r.status===404)throw new c(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new c(`EACCES`,`s3 delete denied`,e);if(r.status>=400)throw new c(`EIO`,`s3 delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}},v=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function y(){let{getAccounts:t}=await e(async()=>{let{getAccounts:e}=await import(`./account-store-dvAfa3y8.js`).then(e=>e.r);return{getAccounts:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21])),n=t().find(e=>e.providerId===`adobe`);if(!n?.accessToken)throw new v(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>n.accessToken}}var b=`slicc-mount-cache`,x=`listings`,S=`bodies`,C=class{mountId;ttlMs;dbName;dbPromise=null;constructor(e){this.mountId=e.mountId,this.ttlMs=e.ttlMs,this.dbName=e.dbName??b}isStale(e,t){return Date.now()-e>=(t??this.ttlMs)}async openDb(){return this.dbPromise||=new Promise((e,t)=>{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(x)||e.createObjectStore(x),e.objectStoreNames.contains(S)||e.createObjectStore(S)},n.onsuccess=()=>{let t=n.result;t.onversionchange=()=>{t.close(),this.dbPromise=null},t.onclose=()=>{this.dbPromise=null},e(t)},n.onerror=()=>t(n.error)}),this.dbPromise}key(e){return`${this.mountId}::${e}`}async getListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readonly`).objectStore(x).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putListing(e,t){let n=await this.openDb();return new Promise((r,i)=>{let a=n.transaction(x,`readwrite`),o={entries:t,cachedAt:Date.now()};a.objectStore(x).put(o,this.key(e)),a.oncomplete=()=>r(),a.onerror=()=>i(a.error)})}async invalidateListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(x,`readwrite`);i.objectStore(x).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async getBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(S,`readonly`).objectStore(S).get(this.key(e));i.onsuccess=()=>n(i.result??null),i.onerror=()=>r(i.error)})}async putBody(e,t,n){let r=await this.openDb(),i={body:t,etag:n,size:t.byteLength,cachedAt:Date.now()};try{await this.txPut(r,S,this.key(e),i)}catch(t){if(t instanceof DOMException&&t.name===`QuotaExceededError`){await this.evictLru(.25);try{await this.txPut(r,S,this.key(e),i)}catch{}return}throw t}}async invalidateBody(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(S,`readwrite`);i.objectStore(S).delete(this.key(e)),i.oncomplete=()=>n(),i.onerror=()=>r(i.error)})}async clearMount(){let e=await this.openDb(),t=`${this.mountId}::`,n=n=>new Promise((r,i)=>{let a=e.transaction(n,`readwrite`),o=a.objectStore(n),s=o.getAllKeys();s.onsuccess=()=>{for(let e of s.result)typeof e==`string`&&e.startsWith(t)&&o.delete(e)},a.oncomplete=()=>r(),a.onerror=()=>i(a.error)});await Promise.all([n(x),n(S)])}txPut(e,t,n,r){return new Promise((i,a)=>{let o=e.transaction(t,`readwrite`);o.objectStore(t).put(r,n),o.oncomplete=()=>i(),o.onerror=()=>a(o.error)})}async evictLru(e){let t=await this.openDb(),n=`${this.mountId}::`,r=await new Promise((e,r)=>{let i=t.transaction(S,`readonly`).objectStore(S),a=[],o=i.openCursor();o.onsuccess=()=>{let t=o.result;if(!t){e(a);return}if(typeof t.key==`string`&&t.key.startsWith(n)){let e=t.value;a.push({key:t.key,cachedAt:e.cachedAt})}t.continue()},o.onerror=()=>r(o.error)});r.sort((e,t)=>e.cachedAt-t.cachedAt);let i=Math.max(1,Math.ceil(r.length*e)),a=r.slice(0,i);await new Promise((e,n)=>{let r=t.transaction(S,`readwrite`),i=r.objectStore(S);for(let{key:e}of a)i.delete(e);r.oncomplete=()=>e(),r.onerror=()=>n(r.error)})}},w=r,T=n,E=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),D=new Set([101,103,204,205,304]);function O(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new c(`EACCES`,e.error):e.errorCode===`invalid_request`?new c(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||E.has(String(e.errorCode))?new c(`EIO`,e.error):new c(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=w(e.bodyBase64)}catch(e){throw new c(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=D.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function k(e,t){let n;try{n=await fetch(i(e),{method:`POST`,headers:o({"content-type":`application/json`}),body:JSON.stringify(t)})}catch(e){throw new c(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await n.json()}catch(e){throw new c(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function A(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new c(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}async function j(e,t,n){return s()?A(e,n):a()?l(e,n):k(t,n)}function M(e){return async t=>O(await j(`mount.s3-sign-and-forward`,`/api/s3-sign-and-forward`,{profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?T(t.body):void 0}))}function N(e){let t=e?.getImsToken??(async()=>(await y()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new c(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}return O(await j(`mount.da-sign-and-forward`,`/api/da-sign-and-forward`,{imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?T(e.body):void 0}))}}export{m as DaMountBackend,C as RemoteMountCache,_ as S3MountBackend,N as makeSignedFetchDa,M as makeSignedFetchS3};
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./port-bridge-client-Btb0CfZS.js";import{t as n}from"./types-idfTVsM8.js";var r=e({callMountBridge:()=>a}),i=t({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new n(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function a(e,t){return i({type:e,envelope:t})}export{r as n,a as t};
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./port-bridge-client-CdvMlimf.js";import{t as n}from"./types-idfTVsM8.js";var r=e({callMountBridge:()=>a}),i=t({portName:`mount.sign-and-forward`,panelRpcOp:`mount-sign-and-forward`,timeoutMs:12e4,onUnavailable:`reject`,makeError:e=>new n(`EIO`,`mount transport failed: ${e}`),logNamespace:`mount-bridge`,toPortMessage:({type:e,envelope:t})=>({type:e,envelope:t}),toPanelRpcPayload:({type:e,envelope:t})=>({type:e,envelope:t})});function a(e,t){return i({type:e,envelope:t})}export{r as n,a as t};
@@ -0,0 +1,2 @@
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./backend-local-J_dSen8g.js";import{a as n,i as r,n as i,r as a}from"./mount-C4XESP9i.js";import{n as o}from"./mount-table-store-CTrzlrNn.js";import{t as s}from"./remote-cache-D59F5FOx.js";var c=e({formatMountRecoveryPrompt:()=>f,mdInlineCode:()=>d,recoverMounts:()=>l,shellQuote:()=>u});async function l(e,c,l){let u=[],d=[];for(let f of e){let{targetPath:e,descriptor:p}=f;if(p.kind===`local`){let n=await o(p.idbHandleKey),r=typeof n?.name==`string`?n.name:``;if(!n||!(`queryPermission`in n)){d.push({kind:`local`,path:e,dirName:r});continue}let i;try{i=await n.queryPermission({mode:`readwrite`})}catch(t){l?.warn?.(`queryPermission threw on persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),d.push({kind:`local`,path:e,dirName:r});continue}if(i!==`granted`){d.push({kind:`local`,path:e,dirName:r});continue}try{let i=t.fromHandle(n,{mountId:p.mountId});await c.mount(e,i),l?.info?.(`Restored mount from previous session`,{path:e,name:r}),u.push({kind:`local`,path:e,dirName:r})}catch(t){l?.warn?.(`Failed to re-mount persisted handle`,{path:e,error:t instanceof Error?t.message:String(t)}),d.push({kind:`local`,path:e,dirName:r})}continue}if(p.kind===`s3`){try{let t=new s({mountId:p.mountId,ttlMs:3e4}),n=new r({source:p.source,profile:p.profile,cache:t,mountId:p.mountId,signedFetch:a(p.profile)});await c.mount(e,n),l?.info?.(`Restored S3 mount from previous session`,{path:e,source:p.source}),u.push({kind:`s3`,path:e,source:p.source,profile:p.profile,reason:``})}catch(t){let n=t instanceof Error?t.message:String(t);l?.warn?.(`Failed to restore S3 mount`,{path:e,error:n}),d.push({kind:`s3`,path:e,source:p.source,profile:p.profile,reason:n})}continue}if(p.kind===`da`)try{let t=new s({mountId:p.mountId,ttlMs:3e4}),r=new n({source:p.source,profile:p.profile,cache:t,mountId:p.mountId,signedFetch:i()});await c.mount(e,r),l?.info?.(`Restored DA mount from previous session`,{path:e,source:p.source}),u.push({kind:`da`,path:e,source:p.source,profile:p.profile,reason:``})}catch(t){let n=t instanceof Error?t.message:String(t);l?.warn?.(`Failed to restore DA mount`,{path:e,error:n}),d.push({kind:`da`,path:e,source:p.source,profile:p.profile,reason:n})}}return{restored:u,needsRecovery:d}}function u(e){return`'${e.replace(/'/g,`'\\''`)}'`}function d(e){let t=e.replace(/\r\n|[\r\n]/g,` `),n=t.match(/`+/g),r=n?Math.max(...n.map(e=>e.length))+1:1,i="`".repeat(r);return`${i}${t.startsWith("`")||t.endsWith("`")?` ${t} `:t}${i}`}function f(e){if(!Array.isArray(e)||e.length===0)return null;let t=e.length===1?`mount point`:`mount points`,n=e.length===1?`it`:`them`,r=e.filter(e=>e.kind===`local`),i=e.filter(e=>e.kind===`s3`||e.kind===`da`),a=[`[Session Reload] Mount recovery required for ${e.length} ${t}.`,``];if(r.length>0){let e=r.map(({path:e,dirName:t})=>{let n=t?` (previously mounted from ${d(t)})`:``;return`- ${d(e)}${n}`}),i=r.map(({path:e})=>` mount ${u(e)}`);a.push(`The page was reloaded and the following local ${t} lost filesystem permission. The browser cannot restore access without a fresh user gesture, so ${n} cannot be used until the user re-authorizes:`,``,...e,``,`Please tell the user what happened and ask whether they want to re-mount. If yes, run the corresponding command(s) so the folder picker opens and they can re-select the same directory:`,``,...i,``)}if(i.length>0){let e=i.map(({path:e,source:t,profile:n,reason:r})=>{let i=n==="default"?``:` --profile ${u(n)}`,a=`mount --source ${u(t)}${i} ${u(e)}`;return`- ${d(e)} (${d(t)}, profile ${d(n)}) — ${r}\n Retry: ${d(a)}`});a.push(`The following remote ${t} could not be auto-restored:`,``,...e,``)}return a.push("If the user no longer needs a mount, run `mount unmount <path>` (with the path shell-quoted the same way) to clear the stale entry instead."),a.join(`
2
+ `)}export{c as n,u as r,f as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";function t(){return crypto.randomUUID()}var n=e({clearMountEntries:()=>u,getAllMountEntries:()=>c,loadMountHandle:()=>l,removeMountEntry:()=>s,saveMountEntry:()=>o});const r=`mounts`,i=`mount-entries`;function a(){return new Promise((e,n)=>{let a=indexedDB.open(`slicc-mount-table`,2);a.onupgradeneeded=e=>{let n=a.result,o=e.oldVersion;if(n.objectStoreNames.contains(r)||n.createObjectStore(r),n.objectStoreNames.contains(i)||n.createObjectStore(i),o<2){let e=a.transaction,n=e.objectStore(r),o=e.objectStore(i),s=n.getAllKeys();s.onsuccess=()=>{for(let e of s.result){if(typeof e!=`string`)continue;let n={targetPath:e,descriptor:{kind:`local`,mountId:t(),idbHandleKey:e},createdAt:Date.now()};o.put(n,e)}}}},a.onsuccess=()=>e(a.result),a.onerror=()=>n(a.error)})}async function o(e,t){let n=await a();try{let a=e.descriptor.kind===`local`&&t?[r,i]:[i],o=n.transaction(a,`readwrite`);o.objectStore(i).put(e,e.targetPath),e.descriptor.kind===`local`&&t&&o.objectStore(r).put(t,e.descriptor.idbHandleKey),await new Promise((e,t)=>{o.oncomplete=()=>e(),o.onerror=()=>t(o.error),o.onabort=()=>t(o.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{n.close()}}async function s(e){let t=await a();try{let n=t.transaction([r,i],`readwrite`);n.objectStore(i).delete(e),n.objectStore(r).delete(e),await new Promise((e,t)=>{n.oncomplete=()=>e(),n.onerror=()=>t(n.error),n.onabort=()=>t(n.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{t.close()}}async function c(){let e=await a();try{return await new Promise((t,n)=>{let r=e.transaction(i,`readonly`),a=r.objectStore(i).getAll();a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error),r.onabort=()=>n(r.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{e.close()}}async function l(e){let t=await a();try{return await new Promise((n,i)=>{let a=t.transaction(r,`readonly`).objectStore(r).get(e);a.onsuccess=()=>n(a.result??null),a.onerror=()=>i(a.error)})}finally{t.close()}}async function u(){let e=await a();try{let t=e.transaction([r,i],`readwrite`);t.objectStore(r).clear(),t.objectStore(i).clear(),await new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error),t.onabort=()=>n(t.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{e.close()}}export{o as a,s as i,l as n,t as o,n as r,u as t};
@@ -0,0 +1 @@
1
+ import{t as e}from"./logger-DDBAeTLF.js";import{t}from"./handoff-link-CfgH86mb.js";function n(e){for(let t of e)if(t.rel.includes(`ai-catalog`))return{kind:`ai-catalog`,url:t.href};return null}var r=[{kind:`ai-catalog`,path:`/.well-known/ai-catalog.json`},{kind:`llms-txt`,path:`/llms.txt`}],i=3e3;async function a(e,t,n={}){let a=n.timeoutMs??i,s;try{s=new URL(e).origin}catch{return[]}return(await Promise.all(r.map(e=>o(s,e,t,a)))).filter(e=>e!==null)}async function o(e,t,n,r){let i=e+t.path,a=new AbortController,o=setTimeout(()=>a.abort(Error(`timeout`)),r);try{let e=await n(i,{method:`GET`,signal:a.signal});return e.status!==200||!s(e.headers.get(`content-type`),t.kind)?null:{kind:t.kind,url:i}}catch{return null}finally{clearTimeout(o)}}function s(e,t){if(e==null)return!0;let n=e.toLowerCase();return n.length===0?!0:n.includes(`text/html`)||n.includes(`application/xhtml`)?!1:t===`ai-catalog`?n.includes(`json`)||n.includes(`text/plain`)||n.includes(`octet-stream`):n.includes(`text/plain`)||n.includes(`markdown`)||n.includes(`octet-stream`)}var c=e(`navigation-watcher`);function l(e,n){return t(e,n)}var u=class{transport;onEvent;sessions=new Map;started=!1;onDiscovery;probeFetch;isDiscoveryEnabled;probeTimeoutMs;probedOrigins=new Set;onAttachedToTarget=e=>{this.handleAttachedToTarget(e)};onDetachedFromTarget=e=>{let t=e.sessionId;t&&this.sessions.delete(t)};onTargetInfoChanged=e=>{let t=e.targetInfo;if(t?.targetId)for(let e of this.sessions.values())e.targetId===t.targetId&&(typeof t.title==`string`&&(e.title=t.title),typeof t.url==`string`&&(e.url=t.url))};onTargetCreated=e=>{this.handleTargetCreated(e)};onFrameNavigated=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n)return;let r=e.frame;r?.id&&(r.parentId||(n.rootFrameId=r.id,typeof r.url==`string`&&(n.url=r.url)))};onResponseReceived=e=>{let t=e.sessionId;if(!t)return;let n=this.sessions.get(t);if(!n||e.type!==`Document`)return;let r=e.frameId;if(!r||r!==n.rootFrameId)return;let i=e.response;if(!i)return;let a=typeof i.url==`string`&&i.url.length>0?i.url:n.url;if(!a)return;let{match:o,links:s}=l(i.headers,a);if(o){let e={url:a,verb:o.verb,target:o.target,links:s,targetId:n.targetId};o.instruction!=null&&(e.instruction=o.instruction),o.branch!=null&&(e.branch=o.branch),o.path!=null&&(e.path=o.path),n.title!=null&&(e.title=n.title),this.onEvent(e)}this.maybeRunDiscovery(a,s,n.targetId)};constructor(e,t,n={}){this.transport=e,this.onEvent=t,this.onDiscovery=n.onDiscovery,this.probeFetch=n.probeFetch,this.isDiscoveryEnabled=n.isDiscoveryEnabled??(()=>!0),this.probeTimeoutMs=n.probeTimeoutMs}maybeRunDiscovery(e,t,r){if(!this.onDiscovery||!this.isDiscoveryEnabled())return;let i;try{i=new URL(e).origin}catch{return}let a=n(t);a&&this.onDiscovery({origin:i,kind:a.kind,url:a.url,targetId:r}),this.probeFetch&&!this.probedOrigins.has(i)&&(this.probedOrigins.add(i),this.runWellKnownProbe(i,r))}async runWellKnownProbe(e,t){if(!(!this.probeFetch||!this.onDiscovery))try{let n=await a(e,this.probeFetch,{timeoutMs:this.probeTimeoutMs});for(let r of n)this.onDiscovery({origin:e,kind:r.kind,url:r.url,targetId:t})}catch(t){c.debug(`Well-known discovery probe failed`,{origin:e,error:t instanceof Error?t.message:String(t)})}}async start(){if(!this.started){this.transport.on(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.on(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.on(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.on(`Target.targetCreated`,this.onTargetCreated),this.transport.on(`Page.frameNavigated`,this.onFrameNavigated),this.transport.on(`Network.responseReceived`,this.onResponseReceived);try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!0})}catch(e){c.error(`Failed to enable target discovery`,{error:e instanceof Error?e.message:String(e)}),this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived);return}this.started=!0;try{let e=(await this.transport.send(`Target.getTargets`)).targetInfos??[];for(let t of e){if(t.type!==`page`)continue;let e=t.attached===!0,n=t.targetId;if(!(e||typeof n!=`string`))try{await this.transport.send(`Target.attachToTarget`,{targetId:n,flatten:!0})}catch(e){c.debug(`Failed to attach to preexisting target`,{targetId:n,error:e instanceof Error?e.message:String(e)})}}}catch(e){c.debug(`Failed to enumerate preexisting targets`,{error:e instanceof Error?e.message:String(e)})}}}async stop(){if(this.started){this.started=!1,this.transport.off(`Target.attachedToTarget`,this.onAttachedToTarget),this.transport.off(`Target.detachedFromTarget`,this.onDetachedFromTarget),this.transport.off(`Target.targetInfoChanged`,this.onTargetInfoChanged),this.transport.off(`Target.targetCreated`,this.onTargetCreated),this.transport.off(`Page.frameNavigated`,this.onFrameNavigated),this.transport.off(`Network.responseReceived`,this.onResponseReceived),this.sessions.clear();try{await this.transport.send(`Target.setDiscoverTargets`,{discover:!1})}catch(e){c.debug(`Failed to disable target discovery on stop`,{error:e instanceof Error?e.message:String(e)})}}}async handleTargetCreated(e){let t=e.targetInfo;if(!(t?.type!==`page`||typeof t.targetId!=`string`)&&!t.attached)try{await this.transport.send(`Target.attachToTarget`,{targetId:t.targetId,flatten:!0})}catch(e){c.debug(`Failed to attach to discovered target`,{targetId:t.targetId,error:e instanceof Error?e.message:String(e)})}}async handleAttachedToTarget(e){let t=e.sessionId,n=e.targetInfo;if(!(!t||!n||n.type!==`page`||typeof n.targetId!=`string`)){this.sessions.set(t,{targetId:n.targetId,rootFrameId:null,title:n.title,url:n.url});try{await this.transport.send(`Page.enable`,{},t),await this.transport.send(`Network.enable`,{},t);let e=(await this.transport.send(`Page.getFrameTree`,{},t)).frameTree?.frame;if(e?.id&&typeof e.id==`string`){let n=this.sessions.get(t);n&&(n.rootFrameId=e.id)}}catch(e){c.debug(`Failed to enable Page/Network on attached target`,{sessionId:t,error:e instanceof Error?e.message:String(e)})}}}};export{l as n,u as t};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/quick-llm-DzhE1JW0.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/preload-helper-Czpn1I53.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/account-store-dvAfa3y8.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-CvODsjGm.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js","assets/llm-session-id-bZQs6gBN.js","assets/icons-C5g936Qd.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{F as t,m as n}from"./account-store-dvAfa3y8.js";import{t as r}from"./logger-DDBAeTLF.js";import"./provider-settings-BraIAAA7.js";import{t as i}from"./llm-session-id-bZQs6gBN.js";import{n as a,r as o}from"./session-freezer-CUzeQ9yz.js";import{SessionStore as s}from"./session-store-DAM8GRJ0.js";var c=r(`new-session`),l=`ui-new-session`,u=2e4,d=250;async function f(e,t,n,r){for(let i of n){let n=`${t}/${i.name}`;r.has(n)||i.type===`directory`&&(await f(e,n,await e.readDir(n),r),[...r].some(e=>e.startsWith(`${n}/`)))||await e.rm(n)}}async function p(e){let t=new Set((await e.listMountPoints()).map(({path:e})=>e).filter(e=>e===`/tmp`||e.startsWith(`/tmp/`)));if(t.has(`/tmp`))return;let n;try{n=await e.readDir(`/tmp`)}catch(t){if(t?.code!==`ENOENT`)throw t;await e.mkdir(`/tmp`,{recursive:!0});return}await f(e,`/tmp`,n,t),await e.mkdir(`/tmp`,{recursive:!0})}async function m(r){let d=r.enrichmentRaceMs??u,f=n()??void 0,p;try{p=t()}catch(e){c.info(`No active model — freezing without LLM enrichment`,{error:e instanceof Error?e.message:String(e)})}let m=p?.provider===`adobe`?{"X-Session-Id":i(l)}:void 0,g=new s;try{await g.init()}catch(e){return c.warn(`SessionStore init failed — cannot freeze`,{error:e instanceof Error?e.message:String(e)}),null}let _=await o({sessionStore:g,vfs:r.vfs,mode:`quick`});if(!_)return null;if(!f||!p)return c.info(`Frozen without enrichment (no LLM credentials) — left pending`,{filename:_.filename}),_;let v=p,y=a(r.vfs,_,{model:v,apiKey:f,headers:m,pickIcon:t=>e(async()=>{let{pickLucideIcon:e}=await import(`./quick-llm-DzhE1JW0.js`).then(e=>e.n);return{pickLucideIcon:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24])).then(({pickLucideIcon:e})=>e(t))}).catch(e=>(c.warn(`Single-click enrichment threw (entry stays pending)`,{filename:_.filename,error:e instanceof Error?e.message:String(e)}),null)),b=await h(y,d,r.onProgress);return b.kind===`llm`?b.updated?{...b.updated,archive:_.archive}:_:(y.then(e=>{c.info(`Background enrichment resolved after race window`,{filename:_.filename,enriched:e?.filename??null}),r.onBackgroundEnriched?.(e)}),_)}async function h(e,t,n){let r=Date.now(),i,a;n?.(0),n&&(i=setInterval(()=>{n(Math.min(1,(Date.now()-r)/t))},d));let o=new Promise(e=>{a=setTimeout(()=>e({kind:`timer`}),t)}),s=e.then(e=>({kind:`llm`,updated:e}));try{return await Promise.race([s,o])}finally{i&&clearInterval(i),a&&clearTimeout(a),n?.(null)}}async function g(e){let t=new s;try{await t.init()}catch(e){return c.warn(`SessionStore init failed — cannot quick-freeze`,{error:e instanceof Error?e.message:String(e)}),null}return o({sessionStore:t,vfs:e.vfs,mode:`quick`})}export{p as resetNewSessionTmp,m as runNewSessionFreeze,g as runNewSessionFreezeQuick};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-DeZ3vGbS.js","assets/preload-helper-Czpn1I53.js","assets/account-store-dvAfa3y8.js","assets/rolldown-runtime-aKtaBQYM.js","assets/compat-DyT25qXb.js","assets/models-CzSI8IsT.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/context-compaction-dcYYajWb.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-DETjVL-j.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-D2k1IxFk.js","assets/secrets-bridge-client-CONYX8PU.js","assets/port-bridge-client-CdvMlimf.js","assets/tool-ui-DfXu6quJ.js","assets/providers-CvODsjGm.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-BEi8MYUS.js","assets/transform-messages-fFaW-DLG.js","assets/provider-store-access-B_pR-9Xx.js","assets/global-db-CbuLl-zx.js","assets/types-idfTVsM8.js"])))=>i.map(i=>d[i]);
2
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{R as t,d as n}from"./account-store-dvAfa3y8.js";import{t as r}from"./logger-DDBAeTLF.js";import{t as i}from"./providers-CvODsjGm.js";import"./provider-settings-BraIAAA7.js";var a=r(`oauth-bootstrap`),o=6e4;async function s(){try{let{ensureAllMcpProvidersRegistered:t}=await e(async()=>{let{ensureAllMcpProvidersRegistered:e}=await import(`./provider-DeZ3vGbS.js`);return{ensureAllMcpProvidersRegistered:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])),n=await t();n.length>0&&a.debug(`Pre-registered MCP providers for OAuth bootstrap`,{count:n.length})}catch(e){a.warn(`Failed to pre-register MCP providers for OAuth bootstrap`,{error:e instanceof Error?e.message:String(e)})}let r=n();a.info(`Bootstrap OAuth replicas`,{count:r.length});for(let e of r){if(!e.accessToken){a.debug(`Skipping account without token`,{providerId:e.providerId});continue}if((e.tokenExpiresAt??1/0)-Date.now()<=o){let t=i(e.providerId);if(t?.onSilentRenew)try{if(await t.onSilentRenew()){a.info(`Silently renewed OAuth token`,{providerId:e.providerId});continue}a.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:e.providerId});continue}catch(t){a.warn(`Silent renewal failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)});continue}a.debug(`Skipping expired account (no silent-renew hook)`,{providerId:e.providerId});continue}try{await t({providerId:e.providerId,accessToken:e.accessToken,refreshToken:e.refreshToken,tokenExpiresAt:e.tokenExpiresAt,userName:e.userName,userAvatar:e.userAvatar}),a.debug(`Bootstrapped OAuth replica`,{providerId:e.providerId})}catch(t){a.error(`OAuth bootstrap failed`,{providerId:e.providerId,error:t instanceof Error?t.message:String(t)})}}}export{s as bootstrapOAuthReplicas};
@@ -1 +1 @@
1
- import{t as e}from"./preload-helper-CZgWQFsJ.js";import{o as t,t as n}from"./proxied-fetch-D3wsof0i.js";import{n as r}from"./runtime-env-DH4NDw4t.js";import{t as i}from"./panel-rpc-DmJSNs0I.js";import{t as a}from"./wc-permissions-registry-Blyunq37.js";var o=12e4;function s(e,t){return t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t||e.startsWith(`${t}?`)||e.startsWith(`${t}#`)}function c(e){return e.endsWith(`*`)?e:`${e}*`}function l(e,t){if(!t||t.length===0)return e;let n=e;for(let e of t)if(n.includes(e.match)){if(e.replaceUrl){n=e.replaceUrl;continue}if(e.appendParams)try{let t=new URL(n);for(let[n,r]of Object.entries(e.appendParams))t.searchParams.set(n,r);n=t.toString()}catch{}}return n}function u(e){return async t=>{let n=t.timeoutMs??o,r=t.rewrite??[],i=t.onCapture??`close`,a,u,d=!1,f=null,p=async()=>{if(u){try{await e.send(`Fetch.disable`,{},u)}catch{}try{await e.send(`Target.detachFromTarget`,{sessionId:u})}catch{}}if(a&&i===`close`)try{await e.send(`Target.closeTarget`,{targetId:a})}catch{}};return await new Promise(i=>{let o=async t=>{d||(d=!0,clearTimeout(h),e.off(`Fetch.requestPaused`,m),await p(),i(t))},m=n=>{let i=n;if(!i?.request?.url||!u||(typeof n.sessionId==`string`?n.sessionId:void 0)!==u)return;if(s(i.request.url,t.redirectUriPattern)){f=i.request.url,e.send(`Fetch.failRequest`,{requestId:i.requestId,errorReason:`Aborted`},u).catch(()=>{}),o(f);return}let a=l(i.request.url,r);if(a!==i.request.url){e.send(`Fetch.continueRequest`,{requestId:i.requestId,url:a},u).catch(e=>{console.warn(`[intercepted-oauth] continueRequest (rewrite) failed:`,e instanceof Error?e.message:String(e))});return}e.send(`Fetch.continueRequest`,{requestId:i.requestId},u).catch(()=>{})},h=setTimeout(()=>{o(null)},n);(async()=>{try{a=(await e.send(`Target.createTarget`,{url:`about:blank`})).targetId,u=(await e.send(`Target.attachToTarget`,{targetId:a,flatten:!0})).sessionId,e.on(`Fetch.requestPaused`,m),await e.send(`Fetch.enable`,{patterns:[{urlPattern:c(t.redirectUriPattern),requestStage:`Request`},...r.map(e=>({urlPattern:`*${e.match}*`,requestStage:`Request`}))]},u),await e.send(`Page.navigate`,{url:t.authorizeUrl},u)}catch(e){console.error(`[intercepted-oauth] setup failed:`,e instanceof Error?e.message:String(e)),o(null)}})()})}}var d=r();function f(){return d?S:typeof window>`u`?g:_}async function p(){let e=await m();return e?u(e):null}async function m(){try{let{getActiveCdpTransport:t}=await e(async()=>{let{getActiveCdpTransport:e}=await import(`./active-transport-BIjzxdwv.js`);return{getActiveCdpTransport:e}},[]);return await t()}catch(e){return console.warn(`[oauth-service] could not resolve active CDP transport:`,e instanceof Error?e.message:String(e)),null}}async function h(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let e=i();if(!e)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let t=await e.call(`page-info`,void 0);return{origin:t.origin,href:t.href}}async function g(e){let t=i();if(!t)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await t.call(`oauth-popup`,{url:e},{timeoutMs:13e4})).redirectUrl}catch(e){return console.error(`[oauth-service] oauth-popup RPC failed:`,e instanceof Error?e.message:String(e)),null}}async function _(e){if(v())return y(window.open(e,`_blank`,`width=500,height=700,popup=yes`));let t=a();if(t){let n=await b(t,e);return n===void 0?null:y(n)}return y(window.open(e,`_blank`,`width=500,height=700,popup=yes`))}function v(){return(typeof navigator<`u`?navigator.userActivation:void 0)?.isActive===!0}function y(e){return new Promise(r=>{let i=!1,a=null,o=null,s=()=>{i||(i=!0,window.removeEventListener(`message`,c),clearTimeout(l),a&&clearInterval(a),o&&clearInterval(o))},c=t=>{if(t.data?.type!==`oauth-callback`||t.origin!==window.location.origin||e&&t.source!==e)return;if(s(),t.data.error){console.error(`[oauth-service] CLI OAuth error:`,t.data.error),r(null);return}let n=t.data.redirectUrl;typeof n!=`string`&&n!=null||r(n??null)};window.addEventListener(`message`,c),a=setInterval(async()=>{if(!i)try{let e=await fetch(t(`/api/oauth-result`),{headers:n()});if(e.status===204||!e.ok)return;let a=await e.json();if(i)return;if(s(),a.error){console.error(`[oauth-service] Server relay OAuth error:`,a.error),r(null);return}r(a.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3),e&&(o=setInterval(()=>{e.closed&&(clearInterval(o),o=null,setTimeout(()=>{i||(s(),r(null))},1500))},500));let l=setTimeout(()=>{s();try{e?.close()}catch{}r(null)},12e4)})}async function b(e,t){let n=await e.prompt({kinds:[`popup`],description:`Continue to sign in. A new window will open to the provider.`,grantLabel:`Continue`,requestOptions:{popup:{url:t}}});if(n.status!==`granted`)return;let r=n.grants.find(e=>e.kind===`popup`);return r&&r.kind===`popup`?r.window:null}async function x(e,t=180*1e3){if(typeof window>`u`||d)return;let n=window.open(e,`_blank`,`width=500,height=600,popup=yes`);if(!n){console.warn(`[oauth-service] Could not open IdP logout popup — popups may be blocked`);return}await new Promise(e=>{let r=setTimeout(()=>{clearInterval(i);try{n.close()}catch{}e()},t),i=setInterval(()=>{n.closed&&(clearTimeout(r),clearInterval(i),e())},500)})}async function S(e,t){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,chrome.runtime.onMessage.removeListener(a),clearTimeout(o))},a=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(i(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),n(null);return}n(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(a),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e,interactive:t?.interactive??!0}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let o=setTimeout(()=>{i(),n(null)},12e4)})}export{p as createInterceptingOAuthLauncherForCurrentRuntime,f as createOAuthLauncher,h as getOAuthPageOrigin,x as openIdpLogoutUrl};
1
+ import{t as e}from"./preload-helper-Czpn1I53.js";import{o as t,t as n}from"./proxied-fetch-DETjVL-j.js";import{n as r}from"./runtime-env-DH4NDw4t.js";import{t as i}from"./panel-rpc-DmJSNs0I.js";import{t as a}from"./wc-permissions-registry-Blyunq37.js";var o=12e4;function s(e,t){return t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t||e.startsWith(`${t}?`)||e.startsWith(`${t}#`)}function c(e){return e.endsWith(`*`)?e:`${e}*`}function l(e,t){if(!t||t.length===0)return e;let n=e;for(let e of t)if(n.includes(e.match)){if(e.replaceUrl){n=e.replaceUrl;continue}if(e.appendParams)try{let t=new URL(n);for(let[n,r]of Object.entries(e.appendParams))t.searchParams.set(n,r);n=t.toString()}catch{}}return n}function u(e){return async t=>{let n=t.timeoutMs??o,r=t.rewrite??[],i=t.onCapture??`close`,a,u,d=!1,f=null,p=async()=>{if(u){try{await e.send(`Fetch.disable`,{},u)}catch{}try{await e.send(`Target.detachFromTarget`,{sessionId:u})}catch{}}if(a&&i===`close`)try{await e.send(`Target.closeTarget`,{targetId:a})}catch{}};return await new Promise(i=>{let o=async t=>{d||(d=!0,clearTimeout(h),e.off(`Fetch.requestPaused`,m),await p(),i(t))},m=n=>{let i=n;if(!i?.request?.url||!u||(typeof n.sessionId==`string`?n.sessionId:void 0)!==u)return;if(s(i.request.url,t.redirectUriPattern)){f=i.request.url,e.send(`Fetch.failRequest`,{requestId:i.requestId,errorReason:`Aborted`},u).catch(()=>{}),o(f);return}let a=l(i.request.url,r);if(a!==i.request.url){e.send(`Fetch.continueRequest`,{requestId:i.requestId,url:a},u).catch(e=>{console.warn(`[intercepted-oauth] continueRequest (rewrite) failed:`,e instanceof Error?e.message:String(e))});return}e.send(`Fetch.continueRequest`,{requestId:i.requestId},u).catch(()=>{})},h=setTimeout(()=>{o(null)},n);(async()=>{try{a=(await e.send(`Target.createTarget`,{url:`about:blank`})).targetId,u=(await e.send(`Target.attachToTarget`,{targetId:a,flatten:!0})).sessionId,e.on(`Fetch.requestPaused`,m),await e.send(`Fetch.enable`,{patterns:[{urlPattern:c(t.redirectUriPattern),requestStage:`Request`},...r.map(e=>({urlPattern:`*${e.match}*`,requestStage:`Request`}))]},u),await e.send(`Page.navigate`,{url:t.authorizeUrl},u)}catch(e){console.error(`[intercepted-oauth] setup failed:`,e instanceof Error?e.message:String(e)),o(null)}})()})}}var d=r();function f(){return d?S:typeof window>`u`?g:_}async function p(){let e=await m();return e?u(e):null}async function m(){try{let{getActiveCdpTransport:t}=await e(async()=>{let{getActiveCdpTransport:e}=await import(`./active-transport-BIjzxdwv.js`);return{getActiveCdpTransport:e}},[]);return await t()}catch(e){return console.warn(`[oauth-service] could not resolve active CDP transport:`,e instanceof Error?e.message:String(e)),null}}async function h(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let e=i();if(!e)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let t=await e.call(`page-info`,void 0);return{origin:t.origin,href:t.href}}async function g(e){let t=i();if(!t)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await t.call(`oauth-popup`,{url:e},{timeoutMs:13e4})).redirectUrl}catch(e){return console.error(`[oauth-service] oauth-popup RPC failed:`,e instanceof Error?e.message:String(e)),null}}async function _(e){if(v())return y(window.open(e,`_blank`,`width=500,height=700,popup=yes`));let t=a();if(t){let n=await b(t,e);return n===void 0?null:y(n)}return y(window.open(e,`_blank`,`width=500,height=700,popup=yes`))}function v(){return(typeof navigator<`u`?navigator.userActivation:void 0)?.isActive===!0}function y(e){return new Promise(r=>{let i=!1,a=null,o=null,s=()=>{i||(i=!0,window.removeEventListener(`message`,c),clearTimeout(l),a&&clearInterval(a),o&&clearInterval(o))},c=t=>{if(t.data?.type!==`oauth-callback`||t.origin!==window.location.origin||e&&t.source!==e)return;if(s(),t.data.error){console.error(`[oauth-service] CLI OAuth error:`,t.data.error),r(null);return}let n=t.data.redirectUrl;typeof n!=`string`&&n!=null||r(n??null)};window.addEventListener(`message`,c),a=setInterval(async()=>{if(!i)try{let e=await fetch(t(`/api/oauth-result`),{headers:n()});if(e.status===204||!e.ok)return;let a=await e.json();if(i)return;if(s(),a.error){console.error(`[oauth-service] Server relay OAuth error:`,a.error),r(null);return}r(a.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3),e&&(o=setInterval(()=>{e.closed&&(clearInterval(o),o=null,setTimeout(()=>{i||(s(),r(null))},1500))},500));let l=setTimeout(()=>{s();try{e?.close()}catch{}r(null)},12e4)})}async function b(e,t){let n=await e.prompt({kinds:[`popup`],description:`Continue to sign in. A new window will open to the provider.`,grantLabel:`Continue`,requestOptions:{popup:{url:t}}});if(n.status!==`granted`)return;let r=n.grants.find(e=>e.kind===`popup`);return r&&r.kind===`popup`?r.window:null}async function x(e,t=180*1e3){if(typeof window>`u`||d)return;let n=window.open(e,`_blank`,`width=500,height=600,popup=yes`);if(!n){console.warn(`[oauth-service] Could not open IdP logout popup — popups may be blocked`);return}await new Promise(e=>{let r=setTimeout(()=>{clearInterval(i);try{n.close()}catch{}e()},t),i=setInterval(()=>{n.closed&&(clearTimeout(r),clearInterval(i),e())},500)})}async function S(e,t){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,chrome.runtime.onMessage.removeListener(a),clearTimeout(o))},a=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(i(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),n(null);return}n(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(a),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e,interactive:t?.interactive??!0}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let o=setTimeout(()=>{i(),n(null)},12e4)})}export{p as createInterceptingOAuthLauncherForCurrentRuntime,f as createOAuthLauncher,h as getOAuthPageOrigin,x as openIdpLogoutUrl};
@@ -0,0 +1 @@
1
+ import{o as e,t}from"./proxied-fetch-sbHa3Tte.js";import{t as n}from"./runtime-env-byAg9ij-.js";import{n as r}from"./panel-rpc-CjFVE0nK.js";import{t as i}from"./wc-permissions-registry-C7PhTX3c.js";import{t as a}from"./intercepted-oauth-CaCw-rJ5.js";const o=n();function s(){return o?_:typeof window>`u`?d:f}async function c(){let e=await l();return e?a(e):null}async function l(){try{let{getActiveCdpTransport:e}=await import(`./active-transport-BIjzxdwv.js`);return await e()}catch(e){return console.warn(`[oauth-service] could not resolve active CDP transport:`,e instanceof Error?e.message:String(e)),null}}async function u(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let e=r();if(!e)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let t=await e.call(`page-info`,void 0);return{origin:t.origin,href:t.href}}async function d(e){let t=r();if(!t)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await t.call(`oauth-popup`,{url:e},{timeoutMs:13e4})).redirectUrl}catch(e){return console.error(`[oauth-service] oauth-popup RPC failed:`,e instanceof Error?e.message:String(e)),null}}async function f(e){if(p())return m(window.open(e,`_blank`,`width=500,height=700,popup=yes`));let t=i();if(t){let n=await h(t,e);return n===void 0?null:m(n)}return m(window.open(e,`_blank`,`width=500,height=700,popup=yes`))}function p(){return(typeof navigator<`u`?navigator.userActivation:void 0)?.isActive===!0}function m(n){return new Promise(r=>{let i=!1,a=null,o=null,s=()=>{i||(i=!0,window.removeEventListener(`message`,c),clearTimeout(l),a&&clearInterval(a),o&&clearInterval(o))},c=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(s(),e.data.error){console.error(`[oauth-service] CLI OAuth error:`,e.data.error),r(null);return}let t=e.data.redirectUrl;typeof t!=`string`&&t!=null||r(t??null)};window.addEventListener(`message`,c),a=setInterval(async()=>{if(!i)try{let n=await fetch(e(`/api/oauth-result`),{headers:t()});if(n.status===204||!n.ok)return;let a=await n.json();if(i)return;if(s(),a.error){console.error(`[oauth-service] Server relay OAuth error:`,a.error),r(null);return}r(a.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3),n&&(o=setInterval(()=>{n.closed&&(clearInterval(o),o=null,setTimeout(()=>{i||(s(),r(null))},1500))},500));let l=setTimeout(()=>{s();try{n?.close()}catch{}r(null)},12e4)})}async function h(e,t){let n=await e.prompt({kinds:[`popup`],description:`Continue to sign in. A new window will open to the provider.`,grantLabel:`Continue`,requestOptions:{popup:{url:t}}});if(n.status!==`granted`)return;let r=n.grants.find(e=>e.kind===`popup`);return r&&r.kind===`popup`?r.window:null}async function g(e,t=180*1e3){if(typeof window>`u`||o)return;let n=window.open(e,`_blank`,`width=500,height=600,popup=yes`);if(!n){console.warn(`[oauth-service] Could not open IdP logout popup — popups may be blocked`);return}await new Promise(e=>{let r=setTimeout(()=>{clearInterval(i);try{n.close()}catch{}e()},t),i=setInterval(()=>{n.closed&&(clearTimeout(r),clearInterval(i),e())},500)})}async function _(e,t){return new Promise(n=>{let r=!1,i=()=>{r||(r=!0,chrome.runtime.onMessage.removeListener(a),clearTimeout(o))},a=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(i(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),n(null);return}n(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(a),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e,interactive:t?.interactive??!0}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let o=setTimeout(()=>{i(),n(null)},12e4)})}export{c as createInterceptingOAuthLauncherForCurrentRuntime,s as createOAuthLauncher,u as getOAuthPageOrigin,g as openIdpLogoutUrl};
@@ -2,8 +2,8 @@ function e(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable
2
2
  `):[]}};D=new WeakMap,O=new WeakMap,We.NEWLINE_CHARS=new Set([`
3
3
  `,`\r`]),We.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ge(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ke(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var qe={off:0,error:200,warn:300,info:400,debug:500},Je=(e,t,n)=>{if(e){if(re(qe,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(qe))}`)}};function Ye(){}function Xe(e,t,n){return!t||qe[e]>qe[n]?Ye:t[e].bind(t)}var Ze={error:Ye,warn:Ye,info:Ye,debug:Ye},Qe=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ze;let r=Qe.get(t);if(r&&r[0]===n)return r[1];let i={error:Xe(`error`,t,n),warn:Xe(`warn`,t,n),info:Xe(`info`,t,n),debug:Xe(`debug`,t,n)};return Qe.set(t,[n,i]),i}var A=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),$e,et=class n{constructor(t,n,r){this.iterator=t,$e.set(this,void 0),this.controller=n,e(this,$e,r,`f`)}static fromSSEResponse(e,t,i,s){let c=!1,l=i?k(i):console;async function*u(){if(c)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let n=!1;try{for await(let r of tt(e,t))if(!n){if(r.data.startsWith(`[DONE]`)){n=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let t;try{t=JSON.parse(r.data)}catch(e){throw l.error(`Could not parse message into JSON:`,r.data),l.error(`From chunk:`,r.raw),e}if(t&&t.error)throw new o(void 0,t.error,void 0,e.headers);yield s?{event:r.event,data:t}:t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new o(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}n=!0}catch(e){if(r(e))return;throw e}finally{n||t.abort()}}return new n(u,t,i)}static fromReadableStream(e,t,i){let o=!1;async function*s(){let t=new We,n=ye(e);for await(let e of n)for(let n of t.decode(e))yield n;for(let e of t.flush())yield e}async function*c(){if(o)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let e=!1;try{for await(let t of s())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(r(e))return;throw e}finally{e||t.abort()}}return new n(c,t,i)}[($e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],i=this.iterator(),a=t=>({next:()=>{if(t.length===0){let t=i.next();e.push(t),r.push(t)}return t.shift()}});return[new n(()=>a(e),this.controller,t(this,$e,`f`)),new n(()=>a(r),this.controller,t(this,$e,`f`))]}toReadableStream(){let e=this,t;return _e({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Ve(JSON.stringify(n)+`
4
4
  `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*tt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);let n=new rt,r=new We,i=ye(e.body);for await(let e of nt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*nt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ve(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ke(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=it(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function it(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function at(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):et.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:ot(await n.json(),n):await n.text()})();return k(e).debug(`[${r}] response parsed`,A({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function ot(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var st,ct=class n extends Promise{constructor(t,n,r=at){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,st.set(this,void 0),e(this,st,t,`f`)}_thenUnwrap(e){return new n(t(this,st,`f`),this.responsePromise,async(t,n)=>ot(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(t(this,st,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};st=new WeakMap;var lt,ut=class{constructor(t,n,r,i){lt.set(this,void 0),e(this,lt,t,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,lt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(lt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},dt=class extends ct{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await at(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ft=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},j=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...C(this.options.query),after:t}}:null}},pt=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...C(this.options.query),after:e}}:null}},mt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function ht(e,t,n){return mt(),new File(e,t??`unknown_file`,n)}function gt(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var _t=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,vt=async(e,t)=>wt(e.body)?{...e,body:await xt(e.body,t)}:e,M=async(e,t)=>({...e,body:await xt(e.body,t)}),yt=new WeakMap;function bt(e){let t=typeof e==`function`?e:e.fetch,n=yt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return yt.set(t,r),r}var xt=async(e,t)=>{if(!await bt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Tt(n,e,t))),n},St=e=>e instanceof Blob&&`name`in e,Ct=e=>typeof e==`object`&&!!e&&(e instanceof Response||_t(e)||St(e)),wt=e=>{if(Ct(e))return!0;if(Array.isArray(e))return e.some(wt);if(e&&typeof e==`object`){for(let t in e)if(wt(e[t]))return!0}return!1},Tt=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,ht([await n.blob()],gt(n)));else if(_t(n))e.append(t,ht([await new Response(ve(n)).blob()],gt(n)));else if(St(n))e.append(t,n,gt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Tt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Tt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Et=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Dt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Et(e),Ot=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function kt(e,t,n){if(mt(),e=await e,Dt(e))return e instanceof File?e:ht([await e.arrayBuffer()],e.name);if(Ot(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),ht(await At(r),t,n)}let r=await At(e);if(t||=gt(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return ht(r,t,n)}async function At(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Et(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(_t(e))for await(let n of e)t.push(...await At(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${jt(e)}`)}return t}function jt(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var N=class{constructor(e){this._client=e}};function Mt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Nt=Object.freeze(Object.create(null)),P=((e=Mt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Nt)??Nt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
- `)}\n${o}\n${t}`)}return o})(Mt),Pt=class extends N{list(e,t={},n){return this._client.getAPIList(P`/chat/completions/${e}/messages`,j,{query:t,...n})}};function Ft(e){return e!==void 0&&`function`in e&&e.function!==void 0}function It(e){return e?.$brand===`auto-parseable-response-format`}function Lt(e){return e?.$brand===`auto-parseable-tool`}function Rt(e,t){return!t||!Ut(t)?{...e,choices:e.choices.map(e=>(Wt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:zt(e,t)}function zt(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new v;if(e.finish_reason===`content_filter`)throw new y;return Wt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Vt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Bt(t,e.message.content):null}}});return{...e,choices:n}}function Bt(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Vt(e,t){let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Lt(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Ht(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return Ft(n)&&(Lt(n)||n?.function.strict||!1)}function Ut(e){return It(e.response_format)?!0:e.tools?.some(e=>Lt(e)||e.type===`function`&&e.function.strict===!0)??!1}function Wt(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Gt(e){for(let t of e??[]){if(t.type!==`function`)throw new a(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new a(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Kt=e=>e?.role===`assistant`,qt=e=>e?.role===`tool`,Jt,Yt,Xt,Zt,Qt,$t,en,F,tn,nn,rn,an,on,sn=class{constructor(){Jt.add(this),this.controller=new AbortController,Yt.set(this,void 0),Xt.set(this,()=>{}),Zt.set(this,()=>{}),Qt.set(this,void 0),$t.set(this,()=>{}),en.set(this,()=>{}),F.set(this,{}),tn.set(this,!1),nn.set(this,!1),rn.set(this,!1),an.set(this,!1),e(this,Yt,new Promise((t,n)=>{e(this,Xt,t,`f`),e(this,Zt,n,`f`)}),`f`),e(this,Qt,new Promise((t,n)=>{e(this,$t,t,`f`),e(this,en,n,`f`)}),`f`),t(this,Yt,`f`).catch(()=>{}),t(this,Qt,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,Jt,`m`,on).bind(this))},0)}_connected(){this.ended||(t(this,Xt,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,tn,`f`)}get errored(){return t(this,nn,`f`)}get aborted(){return t(this,rn,`f`)}abort(){this.controller.abort()}on(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n}),this}off(e,n){let r=t(this,F,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{e(this,an,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,an,!0,`f`),await t(this,Qt,`f`)}_emit(n,...r){if(t(this,tn,`f`))return;n===`end`&&(e(this,tn,!0,`f`),t(this,$t,`f`).call(this));let i=t(this,F,`f`)[n];if(i&&(t(this,F,`f`)[n]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),n===`abort`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,en=new WeakMap,F=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,Jt=new WeakSet,on=function(t){if(e(this,nn,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,rn,!0,`f`),this._emit(`abort`,t);if(t instanceof a)return this._emit(`error`,t);if(t instanceof Error){let e=new a(t.message);return e.cause=t,this._emit(`error`,e)}return this._emit(`error`,new a(String(t)))};function cn(e){return typeof e.parse==`function`}var I,ln,un,dn,fn,pn,mn,hn,gn=10,_n=class extends sn{constructor(){super(...arguments),I.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),qt(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Kt(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),t(this,I,`m`,ln).call(this)}async finalMessage(){return await this.done(),t(this,I,`m`,un).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,I,`m`,dn).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,I,`m`,fn).call(this)}async totalUsage(){return await this.done(),t(this,I,`m`,pn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let n=t(this,I,`m`,un).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,I,`m`,ln).call(this);r&&this._emit(`finalContent`,r);let i=t(this,I,`m`,dn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,I,`m`,fn).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,I,`m`,pn).call(this))}async _createChatCompletion(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,I,`m`,mn).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(zt(a,n))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,n,r){let i=`tool`,{tool_choice:o=`auto`,stream:s,...c}=n,l=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:u=gn}=r||{},d=n.tools.map(e=>{if(Lt(e)){if(!e.$callback)throw new a("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in n?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of n.messages)this._addMessage(e,!1);for(let n=0;n<u;++n){let n=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!n)throw new a(`missing message in ChatCompletion response`);if(!n.tool_calls?.length)return;for(let e of n.tool_calls){if(e.type!==`function`)continue;let n=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}else if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}let s;try{s=cn(o)?await o.parse(a):a}catch(e){let t=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:n,content:t});continue}let c=await o.function(s,this),u=t(this,I,`m`,hn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};I=new WeakSet,ln=function(){return t(this,I,`m`,un).call(this).content??null},un=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Kt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},dn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Kt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},fn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(qt(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},pn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},mn=function(e){if(e.n!=null&&e.n>1)throw new a(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},hn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var vn=class e extends _n{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Kt(e)&&e.content&&this._emit(`content`,e.content)}},L={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},yn=class extends Error{},bn=class extends Error{};function xn(e,t=L.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Sn(e.trim(),t)}var Sn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new yn(`${e} at position ${r}`)},a=e=>{throw new bn(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||L.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||L.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||L.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||L.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||L.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||L.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(L.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&L.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(L.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(L.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(L.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(L.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(L.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=it(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function it(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function at(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):et.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:ot(await n.json(),n):await n.text()})();return k(e).debug(`[${r}] response parsed`,A({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function ot(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var st,ct=class n extends Promise{constructor(t,n,r=at){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,st.set(this,void 0),e(this,st,t,`f`)}_thenUnwrap(e){return new n(t(this,st,`f`),this.responsePromise,async(t,n)=>ot(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(t(this,st,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};st=new WeakMap;var lt,ut=class{constructor(t,n,r,i){lt.set(this,void 0),e(this,lt,t,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,lt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(lt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},dt=class extends ct{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await at(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ft=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},j=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...C(this.options.query),after:t}}:null}},pt=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...C(this.options.query),after:e}}:null}},mt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function ht(e,t,n){return mt(),new File(e,t??`unknown_file`,n)}function gt(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var _t=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,vt=async(e,t)=>wt(e.body)?{...e,body:await xt(e.body,t)}:e,M=async(e,t)=>({...e,body:await xt(e.body,t)}),yt=new WeakMap;function bt(e){let t=typeof e==`function`?e:e.fetch,n=yt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return yt.set(t,r),r}var xt=async(e,t)=>{if(!await bt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Tt(n,e,t))),n},St=e=>e instanceof Blob&&`name`in e,Ct=e=>typeof e==`object`&&!!e&&(e instanceof Response||_t(e)||St(e)),wt=e=>{if(Ct(e))return!0;if(Array.isArray(e))return e.some(wt);if(e&&typeof e==`object`){for(let t in e)if(wt(e[t]))return!0}return!1},Tt=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,ht([await n.blob()],gt(n)));else if(_t(n))e.append(t,ht([await new Response(ve(n)).blob()],gt(n)));else if(St(n))e.append(t,n,gt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Tt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Tt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Et=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Dt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Et(e),Ot=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function kt(e,t,n){if(mt(),e=await e,Dt(e))return e instanceof File?e:ht([await e.arrayBuffer()],e.name);if(Ot(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),ht(await At(r),t,n)}let r=await At(e);if(t||=gt(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return ht(r,t,n)}async function At(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Et(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(_t(e))for await(let n of e)t.push(...await At(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${jt(e)}`)}return t}function jt(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var N=class{constructor(e){this._client=e}};function Mt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Nt=Object.freeze(Object.create(null)),P=((e=Mt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Nt)??Nt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
+ `)}\n${o}\n${t}`)}return o})(Mt),Pt=class extends N{list(e,t={},n){return this._client.getAPIList(P`/chat/completions/${e}/messages`,j,{query:t,...n})}};function Ft(e){return e!==void 0&&`function`in e&&e.function!==void 0}function It(e){return e?.$brand===`auto-parseable-response-format`}function Lt(e){return e?.$brand===`auto-parseable-tool`}function Rt(e,t){return!t||!Ut(t)?{...e,choices:e.choices.map(e=>(Wt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:zt(e,t)}function zt(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new v;if(e.finish_reason===`content_filter`)throw new y;return Wt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Vt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Bt(t,e.message.content):null}}});return{...e,choices:n}}function Bt(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Vt(e,t){let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Lt(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Ht(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return Ft(n)&&(Lt(n)||n?.function.strict||!1)}function Ut(e){return It(e.response_format)?!0:e.tools?.some(e=>Lt(e)||e.type===`function`&&e.function.strict===!0)??!1}function Wt(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Gt(e){for(let t of e??[]){if(t.type!==`function`)throw new a(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new a(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Kt=e=>e?.role===`assistant`,qt=e=>e?.role===`tool`,Jt,Yt,Xt,Zt,Qt,$t,en,F,tn,nn,rn,an,on,sn=class{constructor(){Jt.add(this),this.controller=new AbortController,Yt.set(this,void 0),Xt.set(this,()=>{}),Zt.set(this,()=>{}),Qt.set(this,void 0),$t.set(this,()=>{}),en.set(this,()=>{}),F.set(this,{}),tn.set(this,!1),nn.set(this,!1),rn.set(this,!1),an.set(this,!1),e(this,Yt,new Promise((t,n)=>{e(this,Xt,t,`f`),e(this,Zt,n,`f`)}),`f`),e(this,Qt,new Promise((t,n)=>{e(this,$t,t,`f`),e(this,en,n,`f`)}),`f`),t(this,Yt,`f`).catch(()=>{}),t(this,Qt,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,Jt,`m`,on).bind(this))},0)}_connected(){this.ended||(t(this,Xt,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,tn,`f`)}get errored(){return t(this,nn,`f`)}get aborted(){return t(this,rn,`f`)}abort(){this.controller.abort()}on(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n}),this}off(e,n){let r=t(this,F,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{e(this,an,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,an,!0,`f`),await t(this,Qt,`f`)}_emit(n,...r){if(t(this,tn,`f`))return;n===`end`&&(e(this,tn,!0,`f`),t(this,$t,`f`).call(this));let i=t(this,F,`f`)[n];if(i&&(t(this,F,`f`)[n]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),n===`abort`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,en=new WeakMap,F=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,Jt=new WeakSet,on=function(t){if(e(this,nn,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,rn,!0,`f`),this._emit(`abort`,t);if(t instanceof a)return this._emit(`error`,t);if(t instanceof Error){let e=new a(t.message);return e.cause=t,this._emit(`error`,e)}return this._emit(`error`,new a(String(t)))};function cn(e){return typeof e.parse==`function`}var I,ln,un,dn,fn,pn,mn,hn,gn=10,_n=class extends sn{constructor(){super(...arguments),I.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),qt(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Kt(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),t(this,I,`m`,ln).call(this)}async finalMessage(){return await this.done(),t(this,I,`m`,un).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,I,`m`,dn).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,I,`m`,fn).call(this)}async totalUsage(){return await this.done(),t(this,I,`m`,pn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let n=t(this,I,`m`,un).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,I,`m`,ln).call(this);r&&this._emit(`finalContent`,r);let i=t(this,I,`m`,dn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,I,`m`,fn).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,I,`m`,pn).call(this))}async _createChatCompletion(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,I,`m`,mn).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(zt(a,n))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,n,r){let i=`tool`,{tool_choice:o=`auto`,stream:s,...c}=n,l=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:u=gn}=r||{},d=n.tools.map(e=>{if(Lt(e)){if(!e.$callback)throw new a("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in n?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of n.messages)this._addMessage(e,!1);for(let n=0;n<u;++n){let n=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!n)throw new a(`missing message in ChatCompletion response`);if(!n.tool_calls?.length)return;for(let e of n.tool_calls){if(e.type!==`function`)continue;let n=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}else if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}let s;try{s=cn(o)?await o.parse(a):a}catch(e){let t=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:n,content:t});continue}let c=await o.function(s,this),u=t(this,I,`m`,hn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};I=new WeakSet,ln=function(){return t(this,I,`m`,un).call(this).content??null},un=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Kt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},dn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Kt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},fn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(qt(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},pn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},mn=function(e){if(e.n!=null&&e.n>1)throw new a(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},hn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var vn=class e extends _n{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Kt(e)&&e.content&&this._emit(`content`,e.content)}},L={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},yn=class extends Error{},bn=class extends Error{};function xn(e,t=L.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Sn(e.trim(),t)}var Sn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new yn(`${e} at position ${r}`)},a=e=>{throw new bn(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||L.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||L.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||L.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||L.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||L.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||L.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(L.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&L.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(L.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(L.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(L.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(L.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(L.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
7
7
  \r `.includes(e[r]);)r++};return o()},Cn=e=>xn(e,L.ALL^L.NUM),R,z,B,V,wn,Tn,En,Dn,On,kn,An,jn,Mn=class n extends _n{constructor(t){super(),R.add(this),z.set(this,void 0),B.set(this,void 0),V.set(this,void 0),e(this,z,t,`f`),e(this,B,[],`f`)}get currentChatCompletionSnapshot(){return t(this,V,`f`)}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let i=new n(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,n,r){super._createChatCompletion;let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,wn).call(this);let a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of a)t(this,R,`m`,En).call(this,e);if(a.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,kn).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,wn).call(this),this._connected();let i=et.fromReadableStream(e,this.controller),a;for await(let e of i)a&&a!==e.id&&this._addChatCompletion(t(this,R,`m`,kn).call(this)),t(this,R,`m`,En).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,kn).call(this))}[(z=new WeakMap,B=new WeakMap,V=new WeakMap,R=new WeakSet,wn=function(){this.ended||e(this,V,void 0,`f`)},Tn=function(e){let n=t(this,B,`f`)[e.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},t(this,B,`f`)[e.index]=n,n)},En=function(e){if(this.ended)return;let n=t(this,R,`m`,jn).call(this,e);this._emit(`chunk`,e,n);for(let r of e.choices){let e=n.choices[r.index];r.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.delta.content,e.message.content),this._emit(`content.delta`,{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),r.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=t(this,R,`m`,Tn).call(this,e);e.finish_reason&&(t(this,R,`m`,On).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,Dn).call(this,e,i.current_tool_call_index));for(let n of r.delta.tool_calls??[])i.current_tool_call_index!==n.index&&(t(this,R,`m`,On).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,Dn).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=n.index;for(let t of r.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},Dn=function(e,n){if(t(this,R,`m`,Tn).call(this,e).done_tool_calls.has(n))return;let r=e.message.tool_calls?.[n];if(!r)throw Error(`no tool call snapshot`);if(!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let e=t(this,z,`f`)?.tools?.find(e=>Ft(e)&&e.function.name===r.function.name);this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:n,arguments:r.function.arguments,parsed_arguments:Lt(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},On=function(e){let n=t(this,R,`m`,Tn).call(this,e);if(e.message.content&&!n.content_done){n.content_done=!0;let r=t(this,R,`m`,An).call(this);this._emit(`content.done`,{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},kn=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,V,`f`);if(!n)throw new a(`request ended without sending any chunks`);return e(this,V,void 0,`f`),e(this,B,[],`f`),Nn(n,t(this,z,`f`))},An=function(){let e=t(this,z,`f`)?.response_format;return It(e)?e:null},jn=function(n){var r,i,a,o;let s=t(this,V,`f`),{choices:c,...l}=n;s?Object.assign(s,l):s=e(this,V,{...l,choices:[]},`f`);for(let{delta:e,finish_reason:c,index:l,logprobs:u=null,...d}of n.choices){let n=s.choices[l];if(n||=s.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d},u)if(!n.logprobs)n.logprobs=Object.assign({},u);else{let{content:e,refusal:t,...a}=u;Object.assign(n.logprobs,a),e&&((r=n.logprobs).content??(r.content=[]),n.logprobs.content.push(...e)),t&&((i=n.logprobs).refusal??(i.refusal=[]),n.logprobs.refusal.push(...t))}if(c&&(n.finish_reason=c,t(this,z,`f`)&&Ut(t(this,z,`f`)))){if(c===`length`)throw new v;if(c===`content_filter`)throw new y}if(Object.assign(n,d),!e)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,..._}=e;if(Object.assign(n.message,_),p&&(n.message.refusal=(n.message.refusal||``)+p),h&&(n.message.role=h),m&&(n.message.function_call?(m.name&&(n.message.function_call.name=m.name),m.arguments&&((a=n.message.function_call).arguments??(a.arguments=``),n.message.function_call.arguments+=m.arguments)):n.message.function_call=m),f&&(n.message.content=(n.message.content||``)+f,!n.message.refusal&&t(this,R,`m`,An).call(this)&&(n.message.parsed=Cn(n.message.content))),g){n.message.tool_calls||(n.message.tool_calls=[]);for(let{index:e,id:r,type:i,function:a,...s}of g){let c=(o=n.message.tool_calls)[e]??(o[e]={});Object.assign(c,s),r&&(c.id=r),i&&(c.type=i),a&&(c.function??={name:a.name??``,arguments:``}),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Ht(t(this,z,`f`),c)&&(c.function.parsed_arguments=Cn(c.function.arguments)))}}}return s},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Nn(e,t){let{id:n,choices:r,created:i,model:o,system_fingerprint:s,...c}=e;return Rt({...c,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...o})=>{if(!n)throw new a(`missing finish_reason for choice ${r}`);let{content:s=null,function_call:c,tool_calls:l,...u}=t,d=t.role;if(!d)throw new a(`missing role for choice ${r}`);if(c){let{arguments:e,name:l}=c;if(e==null)throw new a(`missing function_call.arguments for choice ${r}`);if(!l)throw new a(`missing function_call.name for choice ${r}`);return{...o,message:{content:s,function_call:{arguments:e,name:l},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return l?{...o,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:i,type:o,id:s,...c}=t,{arguments:l,name:u,...d}=i||{};if(s==null)throw new a(`missing choices[${r}].tool_calls[${n}].id\n${Pn(e)}`);if(o==null)throw new a(`missing choices[${r}].tool_calls[${n}].type\n${Pn(e)}`);if(u==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.name\n${Pn(e)}`);if(l==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Pn(e)}`);return{...c,id:s,type:o,function:{...d,name:u,arguments:l}}})}}:{...o,message:{...u,content:s,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Pn(e){return JSON.stringify(e)}var Fn=class e extends Mn{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},In=class extends N{constructor(){super(...arguments),this.messages=new Pt(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(P`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(P`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/chat/completions/${e}`,t)}parse(e,t){return Gt(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>zt(t,e))}runTools(e,t){return e.stream?Fn.runTools(this._client,e,t):vn.runTools(this._client,e,t)}stream(e,t){return Mn.createChatCompletion(this._client,e,t)}};In.Messages=Pt;var Ln=class extends N{constructor(){super(...arguments),this.completions=new In(this._client)}};Ln.Completions=In;var Rn=Symbol(`brand.privateNullableHeaders`);function*zn(e){if(!e)return;if(Rn in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():S(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=S(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var H=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of zn(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Rn]:!0,values:t,nulls:n}},Bn=class extends N{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:H([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},Vn=class extends N{create(e,t){return this._client.post(`/audio/transcriptions`,M({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},Hn=class extends N{create(e,t){return this._client.post(`/audio/translations`,M({body:e,...t,__metadata:{model:e.model}},this._client))}},Un=class extends N{constructor(){super(...arguments),this.transcriptions=new Vn(this._client),this.translations=new Hn(this._client),this.speech=new Bn(this._client)}};Un.Transcriptions=Vn,Un.Translations=Hn,Un.Speech=Bn;var Wn=class extends N{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/batches/${e}/cancel`,t)}},Gn=class extends N{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/assistants/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,j,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Kn=class extends N{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},qn=class extends N{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Jn=class extends N{constructor(){super(...arguments),this.sessions=new Kn(this._client),this.transcriptionSessions=new qn(this._client)}};Jn.Sessions=Kn,Jn.TranscriptionSessions=qn;var Yn=class extends N{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(P`/chatkit/sessions/${e}/cancel`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},Xn=class extends N{retrieve(e,t){return this._client.get(P`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,pt,{query:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(P`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(P`/chatkit/threads/${e}/items`,pt,{query:t,...n,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},Zn=class extends N{constructor(){super(...arguments),this.sessions=new Yn(this._client),this.threads=new Xn(this._client)}};Zn.Sessions=Yn,Zn.Threads=Xn;var Qn=class extends N{create(e,t,n){return this._client.post(P`/threads/${e}/messages`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/messages/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/messages`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(P`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},$n=class extends N{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(P`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(P`/threads/${r}/runs/${e}/steps`,j,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},er=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},U=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()},W,G,tr,K,nr,q,J,rr,Y,ir,X,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr,_r=class extends sn{constructor(){super(...arguments),W.add(this),tr.set(this,[]),K.set(this,{}),nr.set(this,{}),q.set(this,void 0),J.set(this,void 0),rr.set(this,void 0),Y.set(this,void 0),ir.set(this,void 0),X.set(this,void 0),ar.set(this,void 0),or.set(this,void 0),sr.set(this,void 0)}[(tr=new WeakMap,K=new WeakMap,nr=new WeakMap,q=new WeakMap,J=new WeakMap,rr=new WeakMap,Y=new WeakMap,ir=new WeakMap,X=new WeakMap,ar=new WeakMap,or=new WeakMap,sr=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new G;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let i=et.fromReadableStream(e,this.controller);for await(let e of i)t(this,W,`m`,cr).call(this,e);if(i.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,lr).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new G;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.submitToolOutputs(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,W,`m`,cr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,lr).call(this))}static createThreadAssistantStream(e,t,n){let r=new G;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new G;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return t(this,ar,`f`)}currentRun(){return t(this,or,`f`)}currentMessageSnapshot(){return t(this,q,`f`)}currentRunStepSnapshot(){return t(this,sr,`f`)}async finalRunSteps(){return await this.done(),Object.values(t(this,K,`f`))}async finalMessages(){return await this.done(),Object.values(t(this,nr,`f`))}async finalRun(){if(await this.done(),!t(this,J,`f`))throw Error(`Final run was not received.`);return t(this,J,`f`)}async _createThreadAssistantStream(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)t(this,W,`m`,cr).call(this,e);if(o.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,lr).call(this))}async _createAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.create(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,W,`m`,cr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,lr).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ie(t)&&ie(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ie(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};G=_r,cr=function(n){if(!this.ended)switch(e(this,ar,n,`f`),t(this,W,`m`,fr).call(this,n),n.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:t(this,W,`m`,gr).call(this,n);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:t(this,W,`m`,dr).call(this,n);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:t(this,W,`m`,ur).call(this,n);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},lr=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);if(!t(this,J,`f`))throw Error(`Final run has not been received`);return t(this,J,`f`)},ur=function(n){let[r,i]=t(this,W,`m`,mr).call(this,n,t(this,q,`f`));e(this,q,r,`f`),t(this,nr,`f`)[r.id]=r;for(let e of i){let t=r.content[e.index];t?.type==`text`&&this._emit(`textCreated`,t.text)}switch(n.event){case`thread.message.created`:this._emit(`messageCreated`,n.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,n.data.delta,r),n.data.delta.content)for(let i of n.data.delta.content){if(i.type==`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type==`text`)this._emit(`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!=t(this,rr,`f`)){if(t(this,Y,`f`))switch(t(this,Y,`f`).type){case`text`:this._emit(`textDone`,t(this,Y,`f`).text,t(this,q,`f`));break;case`image_file`:this._emit(`imageFileDone`,t(this,Y,`f`).image_file,t(this,q,`f`));break}e(this,rr,i.index,`f`)}e(this,Y,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(t(this,rr,`f`)!==void 0){let e=n.data.content[t(this,rr,`f`)];if(e)switch(e.type){case`image_file`:this._emit(`imageFileDone`,e.image_file,t(this,q,`f`));break;case`text`:this._emit(`textDone`,e.text,t(this,q,`f`));break}}t(this,q,`f`)&&this._emit(`messageDone`,n.data),e(this,q,void 0,`f`)}},dr=function(n){let r=t(this,W,`m`,pr).call(this,n);switch(e(this,sr,r,`f`),n.event){case`thread.run.step.created`:this._emit(`runStepCreated`,n.data);break;case`thread.run.step.delta`:let i=n.data.delta;if(i.step_details&&i.step_details.type==`tool_calls`&&i.step_details.tool_calls&&r.step_details.type==`tool_calls`)for(let n of i.step_details.tool_calls)n.index==t(this,ir,`f`)?this._emit(`toolCallDelta`,n,r.step_details.tool_calls[n.index]):(t(this,X,`f`)&&this._emit(`toolCallDone`,t(this,X,`f`)),e(this,ir,n.index,`f`),e(this,X,r.step_details.tool_calls[n.index],`f`),t(this,X,`f`)&&this._emit(`toolCallCreated`,t(this,X,`f`)));this._emit(`runStepDelta`,n.data.delta,r);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:e(this,sr,void 0,`f`),n.data.step_details.type==`tool_calls`&&t(this,X,`f`)&&(this._emit(`toolCallDone`,t(this,X,`f`)),e(this,X,void 0,`f`)),this._emit(`runStepDone`,n.data,r);break;case`thread.run.step.in_progress`:break}},fr=function(e){t(this,tr,`f`).push(e),this._emit(`event`,e)},pr=function(e){switch(e.event){case`thread.run.step.created`:return t(this,K,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let n=t(this,K,`f`)[e.data.id];if(!n)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data;if(r.delta){let i=G.accumulateDelta(n,r.delta);t(this,K,`f`)[e.data.id]=i}return t(this,K,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:t(this,K,`f`)[e.data.id]=e.data;break}if(t(this,K,`f`)[e.data.id])return t(this,K,`f`)[e.data.id];throw Error(`No snapshot available`)},mr=function(e,n){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:if(!n)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content)for(let e of i.delta.content)if(e.index in n.content){let r=n.content[e.index];n.content[e.index]=t(this,W,`m`,hr).call(this,e,r)}else n.content[e.index]=e,r.push(e);return[n,r];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(n)return[n,r];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},hr=function(e,t){return G.accumulateDelta(t,e)},gr=function(n){switch(e(this,or,n.data,`f`),n.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:e(this,J,n.data,`f`),t(this,X,`f`)&&(this._emit(`toolCallDone`,t(this,X,`f`)),e(this,X,void 0,`f`));break;case`thread.run.cancelling`:break}};var vr=class extends N{constructor(){super(...arguments),this.steps=new $n(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/runs/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/runs`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(P`/threads/${r}/runs/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return _r.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return _r.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return _r.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};vr.Steps=$n;var yr=class extends N{constructor(){super(...arguments),this.runs=new vr(this._client),this.messages=new Qn(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/threads/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(P`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return _r.createThreadAssistantStream(e,this._client.beta.threads,t)}};yr.Runs=vr,yr.Messages=Qn;var br=class extends N{constructor(){super(...arguments),this.realtime=new Jn(this._client),this.chatkit=new Zn(this._client),this.assistants=new Gn(this._client),this.threads=new yr(this._client)}};br.Realtime=Jn,br.ChatKit=Zn,br.Assistants=Gn,br.Threads=yr;var xr=class extends N{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},Sr=class extends N{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}/content`,{...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},Cr=class extends N{constructor(){super(...arguments),this.content=new Sr(this._client)}create(e,t,n){return this._client.post(P`/containers/${e}/files`,vt({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/containers/${e}/files`,j,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(P`/containers/${r}/files/${e}`,{...n,headers:H([{Accept:`*/*`},n?.headers])})}};Cr.Content=Sr;var wr=class extends N{constructor(){super(...arguments),this.files=new Cr(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/containers/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}};wr.Files=Cr;var Tr=class extends N{create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(P`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(P`/conversations/${e}/items`,pt,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(P`/conversations/${r}/items/${e}`,n)}},Er=class extends N{constructor(){super(...arguments),this.items=new Tr(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/conversations/${e}`,t)}update(e,t,n){return this._client.post(P`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(P`/conversations/${e}`,t)}};Er.Items=Tr;var Dr=class extends N{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(k(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=er(t)}),e)))}},Or=class extends N{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(P`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(P`/evals/${r}/runs/${e}/output_items`,j,{query:i,...n})}},kr=class extends N{constructor(){super(...arguments),this.outputItems=new Or(this._client)}create(e,t,n){return this._client.post(P`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(P`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/evals/${e}/runs`,j,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(P`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(P`/evals/${r}/runs/${e}`,n)}};kr.OutputItems=Or;var Ar=class extends N{constructor(){super(...arguments),this.runs=new kr(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/evals/${e}`,t)}update(e,t,n){return this._client.post(P`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/evals/${e}`,t)}};Ar.Runs=kr;var jr=class extends N{create(e,t){return this._client.post(`/files`,M({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/files/${e}`,t)}content(e,t){return this._client.get(P`/files/${e}/content`,{...t,headers:H([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await se(t),a=await this.retrieve(e),Date.now()-i>n)throw new l({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Mr=class extends N{},Nr=class extends N{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}},Pr=class extends N{constructor(){super(...arguments),this.graders=new Nr(this._client)}};Pr.Graders=Nr;var Fr=class extends N{create(e,t,n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,ft,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(P`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,pt,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(P`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},Ir=class extends N{constructor(){super(...arguments),this.permissions=new Fr(this._client)}};Ir.Permissions=Fr;var Lr=class extends N{list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/checkpoints`,j,{query:t,...n})}},Rr=class extends N{constructor(){super(...arguments),this.checkpoints=new Lr(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/events`,j,{query:t,...n})}pause(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/resume`,t)}};Rr.Checkpoints=Lr;var Z=class extends N{constructor(){super(...arguments),this.methods=new Mr(this._client),this.jobs=new Rr(this._client),this.checkpoints=new Ir(this._client),this.alpha=new Pr(this._client)}};Z.Methods=Mr,Z.Jobs=Rr,Z.Checkpoints=Ir,Z.Alpha=Pr;var zr=class extends N{},Br=class extends N{constructor(){super(...arguments),this.graderModels=new zr(this._client)}};Br.GraderModels=zr;var Vr=class extends N{createVariation(e,t){return this._client.post(`/images/variations`,M({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,M({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}},Hr=class extends N{retrieve(e,t){return this._client.get(P`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,ft,e)}delete(e,t){return this._client.delete(P`/models/${e}`,t)}},Ur=class extends N{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},Wr=class extends N{accept(e,t,n){return this._client.post(P`/realtime/calls/${e}/accept`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(P`/realtime/calls/${e}/hangup`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(P`/realtime/calls/${e}/refer`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(P`/realtime/calls/${e}/reject`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}},Gr=class extends N{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},Kr=class extends N{constructor(){super(...arguments),this.clientSecrets=new Gr(this._client),this.calls=new Wr(this._client)}};Kr.ClientSecrets=Gr,Kr.Calls=Wr;function qr(e,t){return!t||!Xr(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:Jr(e,t)}function Jr(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:$r(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:Yr(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||ei(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function Yr(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function Xr(e){return!!It(e.text?.format)}function Zr(e){return e?.$brand===`auto-parseable-tool`}function Qr(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function $r(e,t){let n=Qr(e.tools??[],t.name);return{...t,...t,parsed_arguments:Zr(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function ei(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var ti,ni,Q,ri,ii,ai,oi,si,ci=class n extends sn{constructor(t){super(),ti.add(this),ni.set(this,void 0),Q.set(this,void 0),ri.set(this,void 0),e(this,ni,t,`f`)}static createResponse(e,t,r){let i=new n(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,ti,`m`,ii).call(this);let a,o=null;`response_id`in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of a)t(this,ti,`m`,ai).call(this,e,o);if(a.controller.signal?.aborted)throw new s;return t(this,ti,`m`,oi).call(this)}[(ni=new WeakMap,Q=new WeakMap,ri=new WeakMap,ti=new WeakSet,ii=function(){this.ended||e(this,Q,void 0,`f`)},ai=function(e,n){if(this.ended)return;let r=(e,t)=>{(n==null||t.sequence_number>n)&&this._emit(e,t)},i=t(this,ti,`m`,si).call(this,e);switch(r(`event`,e),e.type){case`response.output_text.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);if(t.type===`message`){let n=t.content[e.content_index];if(!n)throw new a(`missing content at index ${e.content_index}`);if(n.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${n.type}`);r(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);t.type===`function_call`&&r(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:r(e.type,e);break}},oi=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,Q,`f`);if(!n)throw new a(`request ended without sending any events`);e(this,Q,void 0,`f`);let r=li(n,t(this,ni,`f`));return e(this,ri,r,`f`),r},si=function(n){let r=t(this,Q,`f`);if(!r){if(n.type!==`response.created`)throw new a(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=e(this,Q,n.response,`f`),r}switch(n.type){case`response.output_item.added`:r.output.push(n.item);break;case`response.content_part.added`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);let t=e.type,i=n.part;t===`message`&&i.type!==`reasoning_text`?e.content.push(i):t===`reasoning`&&i.type===`reasoning_text`&&(e.content||=[],e.content.push(i));break}case`response.output_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`message`){let t=e.content[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${t.type}`);t.text+=n.delta}break}case`response.function_call_arguments.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);e.type===`function_call`&&(e.arguments+=n.delta);break}case`response.reasoning_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`reasoning`){let t=e.content?.[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`reasoning_text`)throw new a(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=n.delta}break}case`response.completed`:e(this,Q,n.response,`f`);break}return r},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=t(this,ri,`f`);if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}};function li(e,t){return qr(e,t)}var ui=class extends N{list(e,t={},n){return this._client.getAPIList(P`/responses/${e}/input_items`,j,{query:t,...n})}},di=class extends N{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},fi=class extends N{constructor(){super(...arguments),this.inputItems=new ui(this._client),this.inputTokens=new di(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&ei(e),e))}retrieve(e,t={},n){return this._client.get(P`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&ei(e),e))}delete(e,t){return this._client.delete(P`/responses/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>Jr(t,e))}stream(e,t){return ci.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(P`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};fi.InputItems=ui,fi.InputTokens=di;var pi=class extends N{retrieve(e,t){return this._client.get(P`/skills/${e}/content`,{...t,headers:H([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}},mi=class extends N{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}/content`,{...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},hi=class extends N{constructor(){super(...arguments),this.content=new mi(this._client)}create(e,t={},n){return this._client.post(P`/skills/${e}/versions`,vt({body:t,...n},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/skills/${e}/versions`,j,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(P`/skills/${r}/versions/${e}`,n)}};hi.Content=mi;var gi=class extends N{constructor(){super(...arguments),this.content=new pi(this._client),this.versions=new hi(this._client)}create(e={},t){return this._client.post(`/skills`,vt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/skills/${e}`,t)}update(e,t,n){return this._client.post(P`/skills/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/skills`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/skills/${e}`,t)}};gi.Content=pi,gi.Versions=hi;var _i=class extends N{create(e,t,n){return this._client.post(P`/uploads/${e}/parts`,M({body:t,...n},this._client))}},vi=class extends N{constructor(){super(...arguments),this.parts=new _i(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(P`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(P`/uploads/${e}/complete`,{body:t,...n})}};vi.Parts=_i;var yi=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},bi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/file_batches`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/file_batches/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(P`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(P`/vector_stores/${r}/file_batches/${e}/files`,j,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await yi(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},xi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/files`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(P`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/vector_stores/${e}/files`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(P`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(P`/vector_stores/${r}/files/${e}/content`,ft,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},Si=class extends N{constructor(){super(...arguments),this.files=new xi(this._client),this.fileBatches=new bi(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/vector_stores/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,j,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(P`/vector_stores/${e}/search`,ft,{body:t,method:`post`,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};Si.Files=xi,Si.FileBatches=bi;var Ci=class extends N{create(e,t){return this._client.post(`/videos`,vt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,pt,{query:e,...t})}delete(e,t){return this._client.delete(P`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(P`/videos/${e}/content`,{query:t,...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(P`/videos/${e}/remix`,vt({body:t,...n},this._client))}},wi,Ti,Ei,Di=class extends N{constructor(){super(...arguments),wi.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,i=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");t(this,wi,`m`,Ti).call(this,r);let a=H([n]).values,o=t(this,wi,`m`,Ei).call(this,a,`webhook-signature`),s=t(this,wi,`m`,Ei).call(this,a,`webhook-timestamp`),c=t(this,wi,`m`,Ei).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new b(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new b(`Webhook timestamp is too old`);if(l>u+i)throw new b(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=r.startsWith(`whsec_`)?Buffer.from(r.replace(`whsec_`,``),`base64`):Buffer.from(r,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new b(`The given webhook signature does not match the expected signature`)}};wi=new WeakSet,Ti=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},Ei=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var Oi,ki,Ai,ji,$=class{constructor({baseURL:t=U(`OPENAI_BASE_URL`),apiKey:n=U(`OPENAI_API_KEY`),organization:r=U(`OPENAI_ORG_ID`)??null,project:i=U(`OPENAI_PROJECT_ID`)??null,webhookSecret:o=U(`OPENAI_WEBHOOK_SECRET`)??null,...s}={}){if(Oi.add(this),Ai.set(this,void 0),this.completions=new xr(this),this.chat=new Ln(this),this.embeddings=new Dr(this),this.files=new jr(this),this.images=new Vr(this),this.audio=new Un(this),this.moderations=new Ur(this),this.models=new Hr(this),this.fineTuning=new Z(this),this.graders=new Br(this),this.vectorStores=new Si(this),this.webhooks=new Di(this),this.beta=new br(this),this.batches=new Wn(this),this.uploads=new vi(this),this.responses=new fi(this),this.realtime=new Kr(this),this.conversations=new Er(this),this.evals=new Ar(this),this.containers=new wr(this),this.skills=new gi(this),this.videos=new Ci(this),n===void 0)throw new a("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let c={apiKey:n,organization:r,project:i,webhookSecret:o,...s,baseURL:t||`https://api.openai.com/v1`};if(!c.dangerouslyAllowBrowser&&ce())throw new a(`It looks like you're running in a browser-like environment.
8
8
 
9
9
  This is disabled by default, as it risks exposing your secret API credentials to attackers.