sliccy 5.73.3 → 5.74.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 (247) hide show
  1. package/README.md +1 -0
  2. package/dist/node-server/_shared/index.d.ts +2 -0
  3. package/dist/node-server/_shared/index.d.ts.map +1 -1
  4. package/dist/node-server/_shared/index.js +2 -0
  5. package/dist/node-server/_shared/index.js.map +1 -1
  6. package/dist/node-server/_shared/secrets-pipeline.d.ts +22 -0
  7. package/dist/node-server/_shared/secrets-pipeline.d.ts.map +1 -1
  8. package/dist/node-server/_shared/secrets-pipeline.js +50 -0
  9. package/dist/node-server/_shared/secrets-pipeline.js.map +1 -1
  10. package/dist/node-server/_shared/transcript-export.d.ts +161 -0
  11. package/dist/node-server/_shared/transcript-export.d.ts.map +1 -0
  12. package/dist/node-server/_shared/transcript-export.js +804 -0
  13. package/dist/node-server/_shared/transcript-export.js.map +1 -0
  14. package/dist/node-server/_shared/transcript-redaction.d.ts +25 -0
  15. package/dist/node-server/_shared/transcript-redaction.d.ts.map +1 -0
  16. package/dist/node-server/_shared/transcript-redaction.js +107 -0
  17. package/dist/node-server/_shared/transcript-redaction.js.map +1 -0
  18. package/dist/node-server/_shared/tray-sync-protocol.d.ts +56 -1
  19. package/dist/node-server/_shared/tray-sync-protocol.d.ts.map +1 -1
  20. package/dist/node-server/_shared/tray-sync-protocol.js +1 -1
  21. package/dist/node-server/_shared/tray-sync-protocol.js.map +1 -1
  22. package/dist/node-server/routes/secrets.js +52 -22
  23. package/dist/ui/assets/account-store-CJqBAm1f.js +43 -0
  24. package/dist/ui/assets/account-store-CxSwSaS8.js +101 -0
  25. package/dist/ui/assets/{adobe-lCsH7Lwq.js → adobe-j3AP8U12.js} +2 -2
  26. package/dist/ui/assets/{adobe-ufabHIuG.js → adobe-lvezht3s.js} +1 -1
  27. package/dist/ui/assets/anthropic-messages-BFic5zKY.js +39 -0
  28. package/dist/ui/assets/anthropic-messages-C8dDJE2X.js +39 -0
  29. package/dist/ui/assets/{apps-Cz0oexXD.js → apps-D8IGKFP6.js} +1 -1
  30. package/dist/ui/assets/{azure-openai-DjIwn0QF.js → azure-openai-BD60xdeq.js} +1 -1
  31. package/dist/ui/assets/{azure-openai-CMEdXGgc.js → azure-openai-DyqeeHYG.js} +1 -1
  32. package/dist/ui/assets/azure-openai-responses-B_twhN44.js +1 -0
  33. package/dist/ui/assets/azure-openai-responses-CzG7X9qb.js +1 -0
  34. package/dist/ui/assets/bedrock-camp-BO4bvAKs.js +1 -0
  35. package/dist/ui/assets/{bedrock-camp-PMQ4Iu6f.js → bedrock-camp-CVignIdH.js} +1 -1
  36. package/dist/ui/assets/{bridge-launch-params-jegYRGJ6.js → bridge-launch-params-QY3l_LbM.js} +1 -1
  37. package/dist/ui/assets/{cdp-7evcrxxP.js → cdp-D9eDDEuA.js} +1 -1
  38. package/dist/ui/assets/{cerebras-VrdMK4Tc.js → cerebras-B0L70LLb.js} +1 -1
  39. package/dist/ui/assets/{cerebras-BvFtCskg.js → cerebras-Di6jTcHx.js} +1 -1
  40. package/dist/ui/assets/{client-BliYDaDA.js → client-BxYB_ioq.js} +1 -1
  41. package/dist/ui/assets/compat-aVSWLlYQ.js +2 -0
  42. package/dist/ui/assets/{composer-speech-BSy_wbJC.js → composer-speech-FeteaFpi.js} +1 -1
  43. package/dist/ui/assets/{connect-surface-ETqeSANr.js → connect-surface-CAwJVqDK.js} +1 -1
  44. package/dist/ui/assets/constrained-sampling-DafcjXU6.js +1 -0
  45. package/dist/ui/assets/{context-compaction-CW5AQ9bv.js → context-compaction-_UkD06XB.js} +1 -1
  46. package/dist/ui/assets/{discovery-preference-CUhsI-AU.js → discovery-preference-C0L_79z7.js} +1 -1
  47. package/dist/ui/assets/{ensure-speech-assets-8cWrra0n.js → ensure-speech-assets-DGq5bX3t.js} +1 -1
  48. package/dist/ui/assets/export-provider-B6K_eHX_.js +1 -0
  49. package/dist/ui/assets/export-spool-DCxGPg43.js +1 -0
  50. package/dist/ui/assets/{follower-navigate-watcher-UN0jo7Ge.js → follower-navigate-watcher-DgusZOpY.js} +1 -1
  51. package/dist/ui/assets/{fs-CgX9Ebib.js → fs-BI3-y-dt.js} +2 -2
  52. package/dist/ui/assets/{fs-C5GhaBCZ.js → fs-DUi6CyVs.js} +1 -1
  53. package/dist/ui/assets/{github-DMFLbpJz.js → github-CsLyOpIY.js} +1 -1
  54. package/dist/ui/assets/{github-B85TuvhV.js → github-DdtaZi7X.js} +2 -2
  55. package/dist/ui/assets/{github-copilot-kOORCU_n.js → github-copilot-B3YCnypU.js} +1 -1
  56. package/dist/ui/assets/{github-copilot-CXnNPGCI.js → github-copilot-CLH7n3QY.js} +1 -1
  57. package/dist/ui/assets/google-generative-ai-4YtIu_sJ.js +1 -0
  58. package/dist/ui/assets/google-generative-ai-DzD1vsXe.js +1 -0
  59. package/dist/ui/assets/google-shared-BAKd3aSn.js +371 -0
  60. package/dist/ui/assets/google-shared-CCLlnqMF.js +11 -0
  61. package/dist/ui/assets/google-vertex-8lUayXF0.js +1 -0
  62. package/dist/ui/assets/google-vertex-oQOD3HKr.js +1 -0
  63. package/dist/ui/assets/{handoff-link-CfgH86mb.js → handoff-link-Dmaaww5x.js} +1 -1
  64. package/dist/ui/assets/{hear-B5lURJtR.js → hear-CRBq5mEX.js} +1 -1
  65. package/dist/ui/assets/{hear-DI5vlKdf.js → hear-v5qXSZw8.js} +1 -1
  66. package/dist/ui/assets/{kernel-worker-HuBcjkoV.js → kernel-worker-BL7ADt6y.js} +727 -599
  67. package/dist/ui/assets/{kokoro-engine-DX7VicqD.js → kokoro-engine-CogHLlSk.js} +1 -1
  68. package/dist/ui/assets/{legacy-api-aliases-CRTuRAqQ.js → legacy-api-aliases-IllWZ-uu.js} +1 -1
  69. package/dist/ui/assets/{legacy-api-aliases-CdGTJw-r.js → legacy-api-aliases-sqlB2uHc.js} +1 -1
  70. package/dist/ui/assets/{lick-manager-Ct3WOtut.js → lick-manager-wU1FKkH8.js} +1 -1
  71. package/dist/ui/assets/{lick-ws-bridge-D5zKuunw.js → lick-ws-bridge-CFKIh9aE.js} +1 -1
  72. package/dist/ui/assets/lick-ws-bridge-yMljNHwr.js +1 -0
  73. package/dist/ui/assets/{local-llm-DuNuGkgI.js → local-llm-BdGGSRtU.js} +2 -2
  74. package/dist/ui/assets/{local-llm-qHC_HYck.js → local-llm-Cys4QAHg.js} +1 -1
  75. package/dist/ui/assets/main-BZzNeGKC.js +22 -0
  76. package/dist/ui/assets/main-cherry-D_hgi0by.js +1 -0
  77. package/dist/ui/assets/mistral-conversations-C57IiFrP.js +8 -0
  78. package/dist/ui/assets/mistral-conversations-CzEm7KNl.js +7 -0
  79. package/dist/ui/assets/{mount-Dh0O4orp.js → mount-Dk-I5R7K.js} +1 -1
  80. package/dist/ui/assets/{mount-CpyDRxP6.js → mount-GBkZgZPI.js} +2 -2
  81. package/dist/ui/assets/{mount-bridge-client-DHGevTQu.js → mount-bridge-client-BWPRzAQ5.js} +1 -1
  82. package/dist/ui/assets/{mount-recovery-D687TLZv.js → mount-recovery-DO04oIYN.js} +1 -1
  83. package/dist/ui/assets/{navigation-watcher-BoJS9hdc.js → navigation-watcher-DkN9hU8i.js} +1 -1
  84. package/dist/ui/assets/new-session-DDu0IRGc.js +2 -0
  85. package/dist/ui/assets/oauth-bootstrap-DfSYlub_.js +2 -0
  86. package/dist/ui/assets/{oauth-service-foejPYvF.js → oauth-service-BuEH8BXq.js} +1 -1
  87. package/dist/ui/assets/{oauth-service-lE9AyywH.js → oauth-service-Dk3L2UWh.js} +1 -1
  88. package/dist/ui/assets/{openai-codex-jK5ybbFx.js → openai-codex-DuyyDpZA.js} +1 -1
  89. package/dist/ui/assets/openai-codex-responses-DRR6raXn.js +7 -0
  90. package/dist/ui/assets/openai-codex-responses-DU5CHdDQ.js +7 -0
  91. package/dist/ui/assets/openai-codex-rpYkFAL8.js +1 -0
  92. package/dist/ui/assets/openai-completions-B9S6450Q.js +5 -0
  93. package/dist/ui/assets/openai-completions-DhKgaAgM.js +5 -0
  94. package/dist/ui/assets/openai-responses-C4_jiYtu.js +1 -0
  95. package/dist/ui/assets/openai-responses-DmKhLxzV.js +1 -0
  96. package/dist/ui/assets/openai-responses-shared-CiIL52L-.js +10 -0
  97. package/dist/ui/assets/openai-responses-shared-IJFiSqdz.js +10 -0
  98. package/dist/ui/assets/{openrouter-C_pGnoz1.js → openrouter-BcPlZu_G.js} +1 -1
  99. package/dist/ui/assets/{openrouter-DVFBhELg.js → openrouter-DHTAGWtd.js} +1 -1
  100. package/dist/ui/assets/openrouter-images-6_MxZkJZ.js +1 -0
  101. package/dist/ui/assets/openrouter-images-BixC5B6a.js +1 -0
  102. package/dist/ui/assets/{openrouter-models-DM9v24kQ.js → openrouter-models-Bu1Cy5AD.js} +1 -1
  103. package/dist/ui/assets/{openrouter-models-B8MWxzTa.js → openrouter-models-CfnkMx5-.js} +1 -1
  104. package/dist/ui/assets/{openrouter-oauth-CukjxICV.js → openrouter-oauth-CTIG_xj5.js} +1 -1
  105. package/dist/ui/assets/{openrouter-oauth-DdKdfU0P.js → openrouter-oauth-iVwMGpbk.js} +1 -1
  106. package/dist/ui/assets/openrouter.models-DS1_VkCm.js +1 -0
  107. package/dist/ui/assets/openrouter.models-HnnH-abS.js +1 -0
  108. package/dist/ui/assets/page-follower-tray-M061L6UY.js +5 -0
  109. package/dist/ui/assets/{panel-rpc-handlers-UyWgyt3z.js → panel-rpc-handlers-CkC-CpDZ.js} +2 -2
  110. package/dist/ui/assets/{port-bridge-client-CoFZLSYm.js → port-bridge-client-DdolH4cw.js} +1 -1
  111. package/dist/ui/assets/{port-bridge-client-BC810skI.js → port-bridge-client-f_6YKEkm.js} +1 -1
  112. package/dist/ui/assets/{provider-B4WqwJf8.js → provider-Db5o_XYj.js} +2 -2
  113. package/dist/ui/assets/{provider-C-y-cI9Y.js → provider-DiWogq8f.js} +1 -1
  114. package/dist/ui/assets/provider-retry-C8PJzY_l.js +1 -0
  115. package/dist/ui/assets/{provider-settings-C5o54NBg.js → provider-settings-CSt8YEx4.js} +1 -1
  116. package/dist/ui/assets/provider-settings-DnRChWz9.js +2 -0
  117. package/dist/ui/assets/provider-store-access-Bo--BwLf.js +1 -0
  118. package/dist/ui/assets/{provider-store-access-B-0tnW1p.js → provider-store-access-DQypuwRG.js} +2 -2
  119. package/dist/ui/assets/{providers-BVNM94x0.js → providers-Bchg39l1.js} +1 -1
  120. package/dist/ui/assets/providers-DpzUvgPJ.js +2 -0
  121. package/dist/ui/assets/{proxied-fetch-D5h5REZy.js → proxied-fetch-CfcFb0B0.js} +1 -1
  122. package/dist/ui/assets/{proxied-fetch-ldIfAeIb.js → proxied-fetch-D8ebvbVd.js} +1 -1
  123. package/dist/ui/assets/quick-llm-CuKruUki.js +1 -0
  124. package/dist/ui/assets/{remote-cdp-transport-DOoXIxy3.js → remote-cdp-transport-Dmg2NdTA.js} +1 -1
  125. package/dist/ui/assets/{runtime-mode-BVHOImD_.js → runtime-mode-B8Tqab3Z.js} +1 -1
  126. package/dist/ui/assets/runtime-mode-BweZnYql.js +1 -0
  127. package/dist/ui/assets/{secret-env-dQA8rL_1.js → secret-env-Cn-GSA1R.js} +1 -1
  128. package/dist/ui/assets/{secret-topology-CptRwAX3.js → secret-topology-Baeul5rD.js} +1 -1
  129. package/dist/ui/assets/{secrets-bridge-client-D6nwnBvr.js → secrets-bridge-client-CLRo0NLf.js} +1 -1
  130. package/dist/ui/assets/session-freezer-DGs88nTW.js +21 -0
  131. package/dist/ui/assets/session-store-DQztDoVa.js +1 -0
  132. package/dist/ui/assets/setup-standalone-prelude-DJUR-Jx-.js +2 -0
  133. package/dist/ui/assets/setup-sudo-Cc-d6eO1.js +2 -0
  134. package/dist/ui/assets/sha256-DmK25X5D.js +1 -0
  135. package/dist/ui/assets/{silent-renew-backoff-DyzFsWYC.js → silent-renew-backoff-Chq7fPuc.js} +1 -1
  136. package/dist/ui/assets/{silent-renew-backoff-Dzkpjjro.js → silent-renew-backoff-CqD4WRin.js} +1 -1
  137. package/dist/ui/assets/{skills-XOQZdId1.js → skills-gGjRrQeq.js} +1 -1
  138. package/dist/ui/assets/{speak-aEIq7SEP.js → speak-DZhfxcQp.js} +1 -1
  139. package/dist/ui/assets/{speak-B4wyr-p6.js → speak-wEvzUJ_4.js} +1 -1
  140. package/dist/ui/assets/{sprinkle-manager-354rS3Fe.js → sprinkle-manager-BYlc7AHg.js} +1 -1
  141. package/dist/ui/assets/src-BcePBv4G.js +1 -0
  142. package/dist/ui/assets/src-C9oNvq2b2.js +2 -0
  143. package/dist/ui/assets/src-DoFhVmQT.js +1 -0
  144. package/dist/ui/assets/{store-BifrdU3S.js → store-ByY8CO32.js} +1 -1
  145. package/dist/ui/assets/{sudo-CdCTvp3_.js → sudo-DsN_KTcg.js} +1 -1
  146. package/dist/ui/assets/{telemetry-C8rZr13D.js → telemetry-Dxrv_mDE.js} +1 -1
  147. package/dist/ui/assets/{transformers-env-DZtq7i0I.js → transformers-env-Cr03eE3X.js} +1 -1
  148. package/dist/ui/assets/{transformers-env-CeJN6XlP.js → transformers-env-DKadceXA.js} +1 -1
  149. package/dist/ui/assets/{tray-leader-DicSB8Dn.js → tray-leader-BDMuV-1a.js} +1 -1
  150. package/dist/ui/assets/{tray-leave-runtime-BI5IM82V.js → tray-leave-runtime-DuZ41JQ-.js} +1 -1
  151. package/dist/ui/assets/{tray-runtime-config-DquE2Rx9.js → tray-runtime-config-9kTxza5l.js} +1 -1
  152. package/dist/ui/assets/{tray-runtime-config-8-BCHO27.js → tray-runtime-config-GgP0BHji.js} +1 -1
  153. package/dist/ui/assets/{tray-sync-protocol-CVdiCvfU.js → tray-sync-protocol-CxWJ329c.js} +1 -1
  154. package/dist/ui/assets/{upgrade-detection-B3uBpES8.js → upgrade-detection-BjD6M6tx.js} +1 -1
  155. package/dist/ui/assets/{voice-reply-6cMxpz9H.js → voice-reply-CkYr1oSF.js} +1 -1
  156. package/dist/ui/assets/{wc-attach-DU0svqb7.js → wc-attach-CYMk5mBA.js} +1 -1
  157. package/dist/ui/assets/wc-extension-WOxllVQv.js +2 -0
  158. package/dist/ui/assets/{wc-float-label-2tniyRvt.js → wc-float-label-yV3hzRXJ.js} +1 -1
  159. package/dist/ui/assets/wc-follower-CqNUhals.js +17 -0
  160. package/dist/ui/assets/wc-live-DN4iNS1F.js +8 -0
  161. package/dist/ui/assets/wc-nav-DdL1jc0a.js +2 -0
  162. package/dist/ui/assets/{wc-onboarding-DMsV9vuN.js → wc-onboarding-Bzxu5Ii4.js} +2 -2
  163. package/dist/ui/assets/{wc-placeholder-CNOsszW8.js → wc-placeholder-5zeCfEVA.js} +2 -2
  164. package/dist/ui/assets/{wc-settings-QlugO7SB.js → wc-settings-CrG7sAlG.js} +3 -3
  165. package/dist/ui/assets/{wc-shell-DZD-3K-u.js → wc-shell-DL44I68b.js} +3 -3
  166. package/dist/ui/assets/{wc-sprinkles-D38PuO87.js → wc-sprinkles-D52GEpi0.js} +2 -2
  167. package/dist/ui/assets/wc-transcript-export-5Pmfejur.js +2 -0
  168. package/dist/ui/assets/wc-tray-jp0YtxQG.js +2 -0
  169. package/dist/ui/assets/{whisper-engine-G1YfvaDM.js → whisper-engine-CHKYCaAu.js} +1 -1
  170. package/dist/ui/assets/{whisper-session-Ds5v74N9.js → whisper-session-W-6_Qa-h.js} +2 -2
  171. package/dist/ui/assets/{xai-grok-BujeRcN4.js → xai-grok-BuiKJ83J.js} +1 -1
  172. package/dist/ui/assets/xai-grok-BxZVhpe_.js +1 -0
  173. package/dist/ui/index.html +20 -18
  174. package/dist/ui/llm-proxy-sw.js +1 -1
  175. package/dist/ui/packages/webapp/index.html +20 -18
  176. package/package.json +1 -1
  177. package/dist/ui/assets/account-store-Dz-pna2J.js +0 -38
  178. package/dist/ui/assets/account-store-yyyfGfoQ.js +0 -94
  179. package/dist/ui/assets/amazon-bedrock-Cg62P8pR.json +0 -1
  180. package/dist/ui/assets/anthropic-4_qTN2Mu.json +0 -1
  181. package/dist/ui/assets/anthropic-messages-6XWFkWWy.js +0 -39
  182. package/dist/ui/assets/anthropic-messages-D42B1WVl.js +0 -39
  183. package/dist/ui/assets/azure-openai-responses-BvEv9lZE.js +0 -1
  184. package/dist/ui/assets/azure-openai-responses-DE9sINqp.json +0 -1
  185. package/dist/ui/assets/azure-openai-responses-DRSA640t.js +0 -1
  186. package/dist/ui/assets/bedrock-camp-D_7EbOFH.js +0 -1
  187. package/dist/ui/assets/cloudflare-ai-gateway-DDb7hKDm.json +0 -1
  188. package/dist/ui/assets/cloudflare-workers-ai-hYVOS3es.json +0 -1
  189. package/dist/ui/assets/compat-Spvv5tCW.js +0 -2
  190. package/dist/ui/assets/fireworks-B7kEGNCU.json +0 -1
  191. package/dist/ui/assets/github-copilot-K9C_HNHm.json +0 -1
  192. package/dist/ui/assets/google-F4XgvJ1y.json +0 -1
  193. package/dist/ui/assets/google-generative-ai-BqEHWDKc.js +0 -1
  194. package/dist/ui/assets/google-generative-ai-DOAY2Bef.js +0 -1
  195. package/dist/ui/assets/google-shared-2WQG4pNx.js +0 -11
  196. package/dist/ui/assets/google-shared-CGD-JGZx.js +0 -371
  197. package/dist/ui/assets/google-vertex-C-dQj0iH.js +0 -1
  198. package/dist/ui/assets/google-vertex-CiTExP0E.js +0 -1
  199. package/dist/ui/assets/huggingface-BjNadu0v.json +0 -1
  200. package/dist/ui/assets/lick-ws-bridge-BX-cBxCM.js +0 -1
  201. package/dist/ui/assets/main-BwSf9XOe.js +0 -22
  202. package/dist/ui/assets/main-cherry-9qp2ecC4.js +0 -1
  203. package/dist/ui/assets/mistral-CLEcIOtP.json +0 -1
  204. package/dist/ui/assets/mistral-conversations-BIHTMTfL.js +0 -7
  205. package/dist/ui/assets/mistral-conversations-CFKNSaPt.js +0 -8
  206. package/dist/ui/assets/moonshotai-8QShYhhE.json +0 -1
  207. package/dist/ui/assets/moonshotai-cn-7hHZff5z.json +0 -1
  208. package/dist/ui/assets/new-session-EfIhjpHZ.js +0 -2
  209. package/dist/ui/assets/nvidia-dA6GzUPm.json +0 -1
  210. package/dist/ui/assets/oauth-bootstrap-DFYztLmR.js +0 -2
  211. package/dist/ui/assets/openai-BehvdaXx.json +0 -1
  212. package/dist/ui/assets/openai-codex-XS4icMCX.js +0 -1
  213. package/dist/ui/assets/openai-codex-responses-B7cFMjWk.js +0 -7
  214. package/dist/ui/assets/openai-codex-responses-DqxoDEwc.js +0 -7
  215. package/dist/ui/assets/openai-completions-Z1aRkqWe.js +0 -5
  216. package/dist/ui/assets/openai-completions-o78dOizF.js +0 -5
  217. package/dist/ui/assets/openai-responses-SPfzkTJm.js +0 -1
  218. package/dist/ui/assets/openai-responses-shared-BHsJFKuB.js +0 -10
  219. package/dist/ui/assets/openai-responses-shared-Dg5Ojqlw.js +0 -10
  220. package/dist/ui/assets/openai-responses-xSdsW9lw.js +0 -1
  221. package/dist/ui/assets/opencode-4chvZrBR.json +0 -1
  222. package/dist/ui/assets/opencode-go-Chp1OOUx.json +0 -1
  223. package/dist/ui/assets/openrouter-ZLTwKIjA.json +0 -1
  224. package/dist/ui/assets/openrouter-images-BrQDTa3_.js +0 -1
  225. package/dist/ui/assets/openrouter-images-DtvjLeGK.js +0 -1
  226. package/dist/ui/assets/openrouter.models-Bi9GV7Zn.js +0 -1
  227. package/dist/ui/assets/openrouter.models-D41M1z_D.js +0 -1
  228. package/dist/ui/assets/page-follower-tray-Cm9cuA-m.js +0 -5
  229. package/dist/ui/assets/provider-settings-Bf4riFFt.js +0 -2
  230. package/dist/ui/assets/provider-store-access-DQ3Xz22u.js +0 -1
  231. package/dist/ui/assets/providers-BZHUuJkX.js +0 -2
  232. package/dist/ui/assets/quick-llm-CTddYx3-.js +0 -1
  233. package/dist/ui/assets/qwen-token-plan-BpxmzamU.json +0 -1
  234. package/dist/ui/assets/qwen-token-plan-cn-CPhDR0u_.json +0 -1
  235. package/dist/ui/assets/session-freezer-CVXiE5lj.js +0 -21
  236. package/dist/ui/assets/session-store-DAM8GRJ0.js +0 -1
  237. package/dist/ui/assets/setup-sudo-C8hl5UHa.js +0 -2
  238. package/dist/ui/assets/src-CS5gSDhT.js +0 -1
  239. package/dist/ui/assets/src-Dk1QVJRd.js +0 -1
  240. package/dist/ui/assets/together-CYZ-lBBF.json +0 -1
  241. package/dist/ui/assets/vercel-ai-gateway-ZtkcQH_C.json +0 -1
  242. package/dist/ui/assets/wc-extension-Dnbc6pqX.js +0 -2
  243. package/dist/ui/assets/wc-follower-DgOR4hQ4.js +0 -17
  244. package/dist/ui/assets/wc-live-DZ6Z4ggE.js +0 -8
  245. package/dist/ui/assets/wc-nav-CpXNlZRT.js +0 -2
  246. package/dist/ui/assets/wc-tray-MAH8ntv2.js +0 -2
  247. package/dist/ui/assets/xai-grok-CgCHECRn.js +0 -1
@@ -1 +1 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{h as t,m as n,r,s as i,t as a}from"./proxied-fetch-ldIfAeIb.js";import"./src-Dk1QVJRd.js";import{t as o}from"./runtime-env-byAg9ij-.js";import"./backend-local-D4WZgy4J.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-BC810skI.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-yyyfGfoQ.js`).then(e=>e.r),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=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 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 n;try{n=await fetch(i(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 n.json()}catch(e){throw new s(`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 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):r()?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};
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{h as t,m as n,r,s as i,t as a}from"./proxied-fetch-D8ebvbVd.js";import"./src-BcePBv4G.js";import{t as o}from"./runtime-env-byAg9ij-.js";import"./backend-local-D4WZgy4J.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-f_6YKEkm.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-CxSwSaS8.js`).then(e=>e.r),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=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 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 n;try{n=await fetch(i(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 n.json()}catch(e){throw new s(`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 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):r()?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};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/account-store-Dz-pna2J.js","assets/rolldown-runtime-aKtaBQYM.js","assets/preload-helper-Czpn1I53.js","assets/compat-Spvv5tCW.js","assets/models-Bnh9VDA1.js","assets/event-stream-qbAZIAKV.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/openrouter.models-D41M1z_D.js","assets/context-compaction-CW5AQ9bv.js","assets/logger-DDBAeTLF.js","assets/src-CS5gSDhT.js","assets/proxied-fetch-D5h5REZy.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-CptRwAX3.js","assets/secrets-bridge-client-D6nwnBvr.js","assets/port-bridge-client-CoFZLSYm.js","assets/tool-ui-DfXu6quJ.js","assets/providers-BZHUuJkX.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-PMQ4Iu6f.js","assets/transform-messages-wECJwtH0.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-D5h5REZy.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-DHGevTQu.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-Dz-pna2J.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,22,23])),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
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/account-store-CJqBAm1f.js","assets/rolldown-runtime-aKtaBQYM.js","assets/preload-helper-Czpn1I53.js","assets/compat-aVSWLlYQ.js","assets/models-Bnh9VDA1.js","assets/event-stream-qbAZIAKV.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/openrouter.models-DS1_VkCm.js","assets/context-compaction-_UkD06XB.js","assets/logger-DDBAeTLF.js","assets/src-DoFhVmQT.js","assets/proxied-fetch-CfcFb0B0.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-Baeul5rD.js","assets/secrets-bridge-client-CLRo0NLf.js","assets/port-bridge-client-DdolH4cw.js","assets/tool-ui-DfXu6quJ.js","assets/providers-DpzUvgPJ.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-CVignIdH.js","assets/transform-messages-wECJwtH0.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-DoFhVmQT.js";import{o as i,r as a,t as o}from"./proxied-fetch-CfcFb0B0.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-BWPRzAQ5.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-CJqBAm1f.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,22,23])),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-CoFZLSYm.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-DdolH4cw.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,2 +1,2 @@
1
- import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./backend-local-D4WZgy4J.js";import{a as n,i as r,n as i,r as a}from"./mount-Dh0O4orp.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(`
1
+ import{n as e}from"./rolldown-runtime-aKtaBQYM.js";import{t}from"./backend-local-D4WZgy4J.js";import{a as n,i as r,n as i,r as a}from"./mount-Dk-I5R7K.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
2
  `)}export{c as n,u as r,f as t};
@@ -1 +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};
1
+ import{t as e}from"./logger-DDBAeTLF.js";import{t}from"./handoff-link-Dmaaww5x.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-CuKruUki.js","assets/rolldown-runtime-aKtaBQYM.js","assets/account-store-CJqBAm1f.js","assets/preload-helper-Czpn1I53.js","assets/compat-aVSWLlYQ.js","assets/models-Bnh9VDA1.js","assets/event-stream-qbAZIAKV.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/openrouter.models-DS1_VkCm.js","assets/context-compaction-_UkD06XB.js","assets/logger-DDBAeTLF.js","assets/src-DoFhVmQT.js","assets/proxied-fetch-CfcFb0B0.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-Baeul5rD.js","assets/secrets-bridge-client-CLRo0NLf.js","assets/port-bridge-client-DdolH4cw.js","assets/tool-ui-DfXu6quJ.js","assets/providers-DpzUvgPJ.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-CVignIdH.js","assets/transform-messages-wECJwtH0.js","assets/llm-session-id-bZQs6gBN.js","assets/icons-C5g936Qd.js"])))=>i.map(i=>d[i]);
2
+ import{F as e,m as t}from"./account-store-CJqBAm1f.js";import{t as n}from"./preload-helper-Czpn1I53.js";import{t as r}from"./logger-DDBAeTLF.js";import"./provider-settings-DnRChWz9.js";import{t as i}from"./llm-session-id-bZQs6gBN.js";import{a,n as o,r as s}from"./session-freezer-DGs88nTW.js";import{t as c}from"./session-store-DQztDoVa.js";var l=r(`new-session`),u=`ui-new-session`,d=2e4,f=250;async function p(e,t,n,r){for(let i of n){let n=`${t}/${i.name}`;r.has(n)||i.type===`directory`&&(await p(e,n,await e.readDir(n),r),[...r].some(e=>e.startsWith(`${n}/`)))||await e.rm(n)}}async function m(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 p(e,`/tmp`,n,t),await e.mkdir(`/tmp`,{recursive:!0})}async function h(r){let f=r.enrichmentRaceMs??d,p=t()??void 0,m;try{m=e()}catch(e){l.info(`No active model — freezing without LLM enrichment`,{error:e instanceof Error?e.message:String(e)})}let h=m?.provider===`adobe`?{"X-Session-Id":i(u)}:void 0,_=new c;try{await _.init()}catch(e){return l.warn(`SessionStore init failed — cannot freeze`,{error:e instanceof Error?e.message:String(e)}),null}let v=await s({sessionStore:_,vfs:r.vfs,mode:`quick`});if(!v)return null;if(r.captureCompleteSnapshot)try{await r.captureCompleteSnapshot(v)}catch(e){let t=e?.code??`unknown`;l.warn(`captureCompleteSnapshot failed`,{code:t}),v.completeSnapshotUnavailable=!0;try{await a(r.vfs,v.filename)}catch{}}if(!p||!m)return l.info(`Frozen without enrichment (no LLM credentials) — left pending`,{filename:v.filename}),v;let y=m,b=o(r.vfs,v,{model:y,apiKey:p,headers:h,pickIcon:e=>n(async()=>{let{pickLucideIcon:e}=await import(`./quick-llm-CuKruUki.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,25,26])).then(({pickLucideIcon:t})=>t(e))}).catch(e=>(l.warn(`Single-click enrichment threw (entry stays pending)`,{filename:v.filename,error:e instanceof Error?e.message:String(e)}),null)),x=await g(b,f,r.onProgress);return x.kind===`llm`?x.updated?{...x.updated,archive:v.archive}:v:(b.then(e=>{l.info(`Background enrichment resolved after race window`,{filename:v.filename,enriched:e?.filename??null}),r.onBackgroundEnriched?.(e)}),v)}async function g(e,t,n){let r=Date.now(),i,a;n?.(0),n&&(i=setInterval(()=>{n(Math.min(1,(Date.now()-r)/t))},f));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 _(e){let t=new c;try{await t.init()}catch(e){return l.warn(`SessionStore init failed — cannot quick-freeze`,{error:e instanceof Error?e.message:String(e)}),null}let n=await s({sessionStore:t,vfs:e.vfs,mode:`quick`});if(n&&e.captureCompleteSnapshot)try{await e.captureCompleteSnapshot(n)}catch(t){let r=t?.code??`unknown`;l.warn(`captureCompleteSnapshot failed (quick-freeze)`,{code:r}),n.completeSnapshotUnavailable=!0;try{await a(e.vfs,n.filename)}catch{}}return n}export{m as resetNewSessionTmp,h as runNewSessionFreeze,_ as runNewSessionFreezeQuick};
@@ -0,0 +1,2 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-Db5o_XYj.js","assets/account-store-CJqBAm1f.js","assets/rolldown-runtime-aKtaBQYM.js","assets/preload-helper-Czpn1I53.js","assets/compat-aVSWLlYQ.js","assets/models-Bnh9VDA1.js","assets/event-stream-qbAZIAKV.js","assets/provider-env-D37PhSJu.js","assets/__vite-browser-external-SwrSgYTf.js","assets/openrouter.models-DS1_VkCm.js","assets/context-compaction-_UkD06XB.js","assets/logger-DDBAeTLF.js","assets/src-DoFhVmQT.js","assets/proxied-fetch-CfcFb0B0.js","assets/base64-DpPqYZJF.js","assets/runtime-env-DH4NDw4t.js","assets/fetch-body-D2PwksUW.js","assets/secret-topology-Baeul5rD.js","assets/secrets-bridge-client-CLRo0NLf.js","assets/port-bridge-client-DdolH4cw.js","assets/tool-ui-DfXu6quJ.js","assets/providers-DpzUvgPJ.js","assets/panel-rpc-DmJSNs0I.js","assets/bedrock-camp-CVignIdH.js","assets/transform-messages-wECJwtH0.js","assets/provider-store-access-DQypuwRG.js","assets/global-db-CbuLl-zx.js","assets/types-idfTVsM8.js"])))=>i.map(i=>d[i]);
2
+ import{R as e,d as t}from"./account-store-CJqBAm1f.js";import{t as n}from"./preload-helper-Czpn1I53.js";import{t as r}from"./logger-DDBAeTLF.js";import{t as i}from"./providers-DpzUvgPJ.js";import"./provider-settings-DnRChWz9.js";var a=r(`oauth-bootstrap`),o=6e4;async function s(){try{let{ensureAllMcpProvidersRegistered:e}=await n(async()=>{let{ensureAllMcpProvidersRegistered:e}=await import(`./provider-Db5o_XYj.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,26,27])),t=await e();t.length>0&&a.debug(`Pre-registered MCP providers for OAuth bootstrap`,{count:t.length})}catch(e){a.warn(`Failed to pre-register MCP providers for OAuth bootstrap`,{error:e instanceof Error?e.message:String(e)})}let r=t();a.info(`Bootstrap OAuth replicas`,{count:r.length});for(let t of r){if(!t.accessToken){a.debug(`Skipping account without token`,{providerId:t.providerId});continue}if((t.tokenExpiresAt??1/0)-Date.now()<=o){let e=i(t.providerId);if(e?.onSilentRenew)try{if(await e.onSilentRenew()){a.info(`Silently renewed OAuth token`,{providerId:t.providerId});continue}a.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:t.providerId});continue}catch(e){a.warn(`Silent renewal failed`,{providerId:t.providerId,error:e instanceof Error?e.message:String(e)});continue}a.debug(`Skipping expired account (no silent-renew hook)`,{providerId:t.providerId});continue}try{await e({providerId:t.providerId,accessToken:t.accessToken,refreshToken:t.refreshToken,tokenExpiresAt:t.tokenExpiresAt,userName:t.userName,userAvatar:t.userAvatar}),a.debug(`Bootstrapped OAuth replica`,{providerId:t.providerId})}catch(e){a.error(`OAuth bootstrap failed`,{providerId:t.providerId,error:e instanceof Error?e.message:String(e)})}}}export{s as bootstrapOAuthReplicas};
@@ -1 +1 @@
1
- import{n as e}from"./panel-rpc-CjFVE0nK.js";import{s as t,t as n}from"./proxied-fetch-ldIfAeIb.js";import{t as r}from"./runtime-env-byAg9ij-.js";import{t as i}from"./wc-permissions-registry-C7PhTX3c.js";import{t as a}from"./intercepted-oauth-CaCw-rJ5.js";const o=r();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 t=e();if(!t)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let n=await t.call(`page-info`,void 0);return{origin:n.origin,href:n.href}}async function d(t){let n=e();if(!n)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await n.call(`oauth-popup`,{url:t},{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(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 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){let n=chrome.runtime;return new Promise(r=>{let i=!1,a=()=>{i||(i=!0,n.onMessage.removeListener(o),clearTimeout(s))},o=e=>{if(typeof e!=`object`||!e)return;let t=e;if(t.source===`service-worker`&&t.payload?.type===`oauth-result`){if(a(),t.payload.error){console.error(`[oauth-service] Extension OAuth error:`,t.payload.error),r(null);return}r(t.payload.redirectUrl??null)}};n.onMessage.addListener(o),n.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 s=setTimeout(()=>{a(),r(null)},12e4)})}export{c as createInterceptingOAuthLauncherForCurrentRuntime,s as createOAuthLauncher,u as getOAuthPageOrigin,g as openIdpLogoutUrl};
1
+ import{n as e}from"./panel-rpc-CjFVE0nK.js";import{s as t,t as n}from"./proxied-fetch-D8ebvbVd.js";import{t as r}from"./runtime-env-byAg9ij-.js";import{t as i}from"./wc-permissions-registry-C7PhTX3c.js";import{t as a}from"./intercepted-oauth-CaCw-rJ5.js";const o=r();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 t=e();if(!t)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let n=await t.call(`page-info`,void 0);return{origin:n.origin,href:n.href}}async function d(t){let n=e();if(!n)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await n.call(`oauth-popup`,{url:t},{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(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 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){let n=chrome.runtime;return new Promise(r=>{let i=!1,a=()=>{i||(i=!0,n.onMessage.removeListener(o),clearTimeout(s))},o=e=>{if(typeof e!=`object`||!e)return;let t=e;if(t.source===`service-worker`&&t.payload?.type===`oauth-result`){if(a(),t.payload.error){console.error(`[oauth-service] Extension OAuth error:`,t.payload.error),r(null);return}r(t.payload.redirectUrl??null)}};n.onMessage.addListener(o),n.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 s=setTimeout(()=>{a(),r(null)},12e4)})}export{c as createInterceptingOAuthLauncherForCurrentRuntime,s as createOAuthLauncher,u as getOAuthPageOrigin,g as openIdpLogoutUrl};
@@ -1 +1 @@
1
- import{t as e}from"./preload-helper-Czpn1I53.js";import{o as t,t as n}from"./proxied-fetch-D5h5REZy.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){let n=chrome.runtime;return new Promise(r=>{let i=!1,a=()=>{i||(i=!0,n.onMessage.removeListener(o),clearTimeout(s))},o=e=>{if(typeof e!=`object`||!e)return;let t=e;if(t.source===`service-worker`&&t.payload?.type===`oauth-result`){if(a(),t.payload.error){console.error(`[oauth-service] Extension OAuth error:`,t.payload.error),r(null);return}r(t.payload.redirectUrl??null)}};n.onMessage.addListener(o),n.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 s=setTimeout(()=>{a(),r(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-CfcFb0B0.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){let n=chrome.runtime;return new Promise(r=>{let i=!1,a=()=>{i||(i=!0,n.onMessage.removeListener(o),clearTimeout(s))},o=e=>{if(typeof e!=`object`||!e)return;let t=e;if(t.source===`service-worker`&&t.payload?.type===`oauth-result`){if(a(),t.payload.error){console.error(`[oauth-service] Extension OAuth error:`,t.payload.error),r(null);return}r(t.payload.redirectUrl??null)}};n.onMessage.addListener(o),n.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 s=setTimeout(()=>{a(),r(null)},12e4)})}export{p as createInterceptingOAuthLauncherForCurrentRuntime,f as createOAuthLauncher,h as getOAuthPageOrigin,x as openIdpLogoutUrl};
@@ -1 +1 @@
1
- import{R as e,d as t}from"./account-store-yyyfGfoQ.js";import{n}from"./event-stream-qbAZIAKV.js";import{p as r}from"./bedrock-camp-D_7EbOFH.js";import{n as i,o as a}from"./legacy-api-aliases-CdGTJw-r.js";import"./provider-settings-C5o54NBg.js";const o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/token`,l=`http://localhost:1455/auth/callback`,u=`https://chatgpt.com/backend-api`,d=`openai-codex-responses`,f=`${o}-openai`,p={xhigh:`xhigh`,minimal:`low`},m=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:p}));function h(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function g(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function _(){return h(g(32))}async function v(e){let t=new TextEncoder().encode(e);return h(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function y(){return h(g(16))}async function b(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:l}),r=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function x(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function S(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function C(e){let t=S(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function w(e){let t=S(e)?.[`https://api.openai.com/auth`],n=C(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function T(e){let t=C(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function E(){return t().find(e=>e.providerId===o)}async function D(){let t=E();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await x(t.refreshToken);if(n?.access_token)return await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token}return t.accessToken}function O(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:f,provider:o,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()}}}const k=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await D(),o=i({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(O(e,t)),a.end()}})(),a},A=(e,t,r)=>{let i=n();return(async()=>{try{let n=await D(),o=a({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(O(e,t)),i.end()}})(),i},j={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>m,onOAuthLoginIntercepted:async(t,n,r)=>{let i=_(),a=await v(i),c=y(),d=new URL(`https://auth.openai.com/oauth/authorize`);d.searchParams.set(`response_type`,`code`),d.searchParams.set(`client_id`,s),d.searchParams.set(`redirect_uri`,l),d.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access`),d.searchParams.set(`code_challenge`,a),d.searchParams.set(`code_challenge_method`,`S256`),d.searchParams.set(`state`,c),d.searchParams.set(`id_token_add_organizations`,`true`),d.searchParams.set(`codex_cli_simplified_flow`,`true`),d.searchParams.set(`originator`,`pi`);let f=await t({authorizeUrl:d.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!f)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let p=new URL(f),m=p.searchParams.get(`code`),h=p.searchParams.get(`state`);if(!m)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(h!==c)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let g=await b(m,i);await e({providerId:o,accessToken:g.access_token,refreshToken:g.refresh_token,tokenExpiresAt:Date.now()+(g.expires_in??3600)*1e3,baseUrl:u,userName:w(g.access_token),userAvatar:await T(g.access_token)}),n()},onOAuthLogout:async()=>{await e({providerId:o,accessToken:``})},onSilentRenew:async()=>{let t=E();if(!t?.refreshToken)return null;let n=await x(t.refreshToken);return n?.access_token?(await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token):null}};function M(){r({api:f,stream:k,streamSimple:A})}export{j as config,M as register};
1
+ import{R as e,d as t}from"./account-store-CxSwSaS8.js";import{n}from"./event-stream-qbAZIAKV.js";import{p as r}from"./bedrock-camp-BO4bvAKs.js";import{n as i,o as a}from"./legacy-api-aliases-sqlB2uHc.js";import"./provider-settings-CSt8YEx4.js";const o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/token`,l=`http://localhost:1455/auth/callback`,u=`https://chatgpt.com/backend-api`,d=`openai-codex-responses`,f=`${o}-openai`,p={xhigh:`xhigh`,minimal:`low`},m=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:p}));function h(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function g(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function _(){return h(g(32))}async function v(e){let t=new TextEncoder().encode(e);return h(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function y(){return h(g(16))}async function b(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:l}),r=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function x(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(c,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function S(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function C(e){let t=S(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function w(e){let t=S(e)?.[`https://api.openai.com/auth`],n=C(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function T(e){let t=C(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function E(){return t().find(e=>e.providerId===o)}async function D(){let t=E();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await x(t.refreshToken);if(n?.access_token)return await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token}return t.accessToken}function O(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:f,provider:o,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()}}}const k=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await D(),o=i({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(O(e,t)),a.end()}})(),a},A=(e,t,r)=>{let i=n();return(async()=>{try{let n=await D(),o=a({...e,baseUrl:u,api:d},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(O(e,t)),i.end()}})(),i},j={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>m,onOAuthLoginIntercepted:async(t,n,r)=>{let i=_(),a=await v(i),c=y(),d=new URL(`https://auth.openai.com/oauth/authorize`);d.searchParams.set(`response_type`,`code`),d.searchParams.set(`client_id`,s),d.searchParams.set(`redirect_uri`,l),d.searchParams.set(`scope`,r?.scopes??`openid profile email offline_access`),d.searchParams.set(`code_challenge`,a),d.searchParams.set(`code_challenge_method`,`S256`),d.searchParams.set(`state`,c),d.searchParams.set(`id_token_add_organizations`,`true`),d.searchParams.set(`codex_cli_simplified_flow`,`true`),d.searchParams.set(`originator`,`pi`);let f=await t({authorizeUrl:d.toString(),redirectUriPattern:`http://localhost:1455/auth/callback*`,onCapture:`close`});if(!f)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let p=new URL(f),m=p.searchParams.get(`code`),h=p.searchParams.get(`state`);if(!m)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(h!==c)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let g=await b(m,i);await e({providerId:o,accessToken:g.access_token,refreshToken:g.refresh_token,tokenExpiresAt:Date.now()+(g.expires_in??3600)*1e3,baseUrl:u,userName:w(g.access_token),userAvatar:await T(g.access_token)}),n()},onOAuthLogout:async()=>{await e({providerId:o,accessToken:``})},onSilentRenew:async()=>{let t=E();if(!t?.refreshToken)return null;let n=await x(t.refreshToken);return n?.access_token?(await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:u,userName:w(n.access_token),userAvatar:await T(n.access_token)}),n.access_token):null}};function M(){r({api:f,stream:k,streamSimple:A})}export{j as config,M as register};
@@ -0,0 +1,7 @@
1
+ import{t as e}from"./event-stream-qbAZIAKV.js";import{n as t}from"./models-Bnh9VDA1.js";import{n,r,t as i}from"./diagnostics-BsVbaNHR.js";import{t as a}from"./provider-env-D37PhSJu.js";import{r as o}from"./transform-messages-wECJwtH0.js";import{t as s}from"./deferred-tools-C1IEsG5C.js";import{t as c}from"./headers-CbDaTl3c.js";import{n as l}from"./constrained-sampling-DafcjXU6.js";import{n as u,t as d}from"./error-body-C0EnfbdK.js";import{t as f}from"./openai-prompt-cache-DXo9f3w5.js";import{n as p,r as m,t as h}from"./openai-responses-shared-IJFiSqdz.js";var g=new Set;function _(e){return g.add(e),()=>{g.delete(e)}}var v=-1/0,y=0;function b(e){if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}function x(){let e=new Uint8Array(16);b(e);let t=Date.now();t>v?(y=e[6]*16777216+e[7]*65536+e[8]*256+e[9],v=t):(y=y+1>>>0,y===0&&v++);let n=new Uint8Array(16);n[0]=v/1099511627776&255,n[1]=v/4294967296&255,n[2]=v/16777216&255,n[3]=v/65536&255,n[4]=v/256&255,n[5]=v&255,n[6]=112|y>>>28&15,n[7]=y>>>20&255,n[8]=128|y>>>14&63,n[9]=y>>>6&255,n[10]=(y&63)<<2|e[10]&3,n[11]=e[11],n[12]=e[12],n[13]=e[13],n[14]=e[14],n[15]=e[15];let r=Array.from(n,e=>e.toString(16).padStart(2,`0`));return`${r.slice(0,4).join(``)}-${r.slice(4,6).join(``)}-${r.slice(6,8).join(``)}-${r.slice(8,10).join(``)}-${r.slice(10,16).join(``)}`}function S(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let n=new AbortController,r=[],i=e=>{n.signal.aborted||n.abort(e.reason)};for(let e of t){if(e.aborted){i(e);break}let t=()=>i(e);e.addEventListener(`abort`,t,{once:!0}),r.push({signal:e,listener:t})}return{signal:n.signal,cleanup:()=>{for(let{signal:e,listener:t}of r)e.removeEventListener(`abort`,t)}}}var C={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function w(e,t){let n=e.toLowerCase(),r=e.toUpperCase();return t?.[n]||t?.[r]||a(n)||a(r)||``}function T(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function E(e,t,n){let r=w(`no_proxy`,n).toLowerCase();return!r||r!==`*`&&r.split(/[,\s]/).every(n=>{if(!n)return!0;let r=n.match(/^(.+):(\d+)$/),i=r?r[1]:n,a=r?Number.parseInt(r[2],10):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.startsWith(`*`)&&(i=i.slice(1)),!e.endsWith(i)):e!==i})}function D(e,t){let n=T(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!E(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||C[r]||0,t))return``;let i=w(`${r}_proxy`,t)||w(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}var O=`Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.`;function k(e,t){let n=D(e,t);if(!n)return;let r;try{r=new URL(n)}catch(e){throw Error(`Invalid proxy URL ${JSON.stringify(n)}: ${e instanceof Error?e.message:String(e)}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`${O} Got ${r.protocol}`);return r}function A(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}var j=A(),M=`https://chatgpt.com/backend-api`,ee=`https://api.openai.com/auth`,te=0,N=1e3,ne=6e4,re=15e3,ie=3,ae=new Set([`openai`,`openai-codex`,`opencode`]),oe=1009,se=`websocket_connection_limit_reached`,ce=`previous_response_not_found`,le=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function ue(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function de(e,t){return e===429&&ue(t)?!1:e===429||e===500||e===502||e===503||e===504||/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function fe(e){let t=e.get(`retry-after-ms`);if(t!==null){let e=Number(t);if(Number.isFinite(e))return Math.max(0,e)}let n=e.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r*1e3);let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var pe=class extends Error{};function me(e,t){let n=t?.maxRetryDelayMs??ne;if(n>0&&e>n)throw new pe(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s)`);return e}function P(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}function F(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function he(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:zlib`)??null}function ge(e){let t=he();if(!t||typeof t.zstdCompressSync!=`function`)return null;try{let n=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:ie}});return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}catch{return null}}var I=(t,r,a)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:`openai-codex-responses`,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=a?.apiKey;if(!s)throw Error(`No API key for provider: ${t.provider}`);let u=$e(s),d=l(r.tools,t.compat?.supportsOpenAIGrammarTools??!1),p=a?.cacheRetention===`none`?void 0:a?.sessionId,m=f(p),h=ve(t,r,a,m,d),g=await a?.onPayload?.(h,t);g!==void 0&&(h=g);let _=m||x(),v=et(t.headers,a?.headers,u,s,m),y=tt(t.headers,a?.headers,u,s,_),b=JSON.stringify(h),C=F(a?.timeoutMs),w=F(a?.websocketConnectTimeoutMs),T=a?.transport||`auto`,E=!1,D=T!==`sse`&&Ne(p);if(D&&Pe(p),T!==`sse`&&!D){let r=!1,s=!1,c=!1;for(;;){r=!1;try{if(await Ze(be(t.baseUrl),h,y,e,o,t,()=>{r=!0,E||(E=!0,o.push({type:`start`,partial:e}))},C,w,p,d,a),a?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end();return}catch(t){let o=a?.signal?.aborted,l=!r&&Ce(t),u=we(t);if(!o&&u&&!c){c=!0;continue}if(!o&&l&&!s){s=!0;continue}if(o||Se(t)&&!l||(i(e,n(`provider_transport_failure`,t,{configuredTransport:T,fallbackTransport:r?void 0:`sse`,eventsEmitted:r,phase:r?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(b).byteLength})),Fe(p,t),r))throw t;Pe(p);break}}}let O=ge(b);O&&v.set(`content-encoding`,`zstd`);let k=O??b,A,j,M=a?.maxRetries??te;for(let e=0;e<=M;e++){if(a?.signal?.aborted)throw Error(`Request was aborted`);try{let n=C!==void 0&&C>0?AbortSignal.timeout(C):void 0,r=S([a?.signal,n]);try{A=await fetch(z(t.baseUrl),{method:`POST`,headers:v,body:k,signal:r.signal})}catch(e){throw n?.aborted&&!a?.signal?.aborted?Error(`Codex SSE response headers timed out after ${C}ms`):e}finally{r.cleanup()}if(await a?.onResponse?.({status:A.status,headers:c(A.headers)},t),A.ok)break;let i=await A.text();if(e<M&&de(A.status,i)){let t=fe(A.headers);await P(t===void 0?N*2**e:me(t,a),a?.signal);continue}let o=await Qe(new Response(i,{status:A.status,statusText:A.statusText}));throw Error(o.friendlyMessage||o.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(j=t instanceof Error?t:Error(String(t)),e<M&&!(j instanceof pe)&&!j.message.includes(`usage limit`)){await P(N*2**e,a?.signal);continue}throw j}}if(!A?.ok)throw j??Error(`Failed after retries`);if(!A.body)throw Error(`No response body`);if(E||(E=!0,o.push({type:`start`,partial:e})),await xe(A,e,o,t,d,a),a?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.partialJson,delete t.customInput;e.stopReason=a?.signal?.aborted?`aborted`:`error`,e.errorMessage=d(u(t)),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o},_e=(e,n,r)=>{let i=r?.apiKey;if(!i)throw Error(`No API key for provider: ${e.provider}`);let a=o(e,n,r,i),s=r?.reasoning?t(e,r.reasoning):void 0,c=s===`off`?void 0:s;return I(e,n,{...a,reasoningEffort:c})};function ve(e,t,n,r,i=l(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let a=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,c=s(t,e.compat?.supportsToolSearch??!1),u=h(e,t,ae,{includeSystemPrompt:!1,grammarToolInputProperties:i,deferredTools:c.deferred,toolOptions:{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o}}),d={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:u,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:r,tool_choice:n?.toolChoice??`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(d.temperature=n.temperature),n?.serviceTier!==void 0&&(d.service_tier=n.serviceTier),c.immediate.length>0&&(d.tools=p(c.immediate,{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(d.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return d}function ye(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function L(e,t,n){let r=ye(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function R(e,t){return e==="default"&&(t===`flex`||t===`priority`)?t:e??t}function z(e){let t=(e&&e.trim().length>0?e:M).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function be(e){let t=new URL(z(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function xe(e,t,n,r,i,a){await m(H(De(e,a?.signal)),t,n,r,{serviceTier:a?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,r)})}var B=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},V=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function Se(e){return e instanceof B||e instanceof V}function Ce(e){return e instanceof B&&e.code===se}function we(e){return e instanceof B&&e.code===ce}function Te(e){let t=e.error&&typeof e.error==`object`?e.error:void 0;return{code:typeof e.code==`string`?e.code:typeof t?.code==`string`?t.code:void 0,message:typeof e.message==`string`?e.message:typeof t?.message==`string`?t.message:void 0}}async function*H(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let{code:e,message:n}=Te(t);throw new B(`Codex error: ${n||e||JSON.stringify(t)}`,{code:e,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new B(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:Ee(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function Ee(e){if(typeof e==`string`)return le.has(e)?e:void 0}async function*De(e,t){if(!e.body)return;let n=e.body.getReader(),i=new TextDecoder,a=``,o=()=>{n.cancel().catch(()=>{})};t?.addEventListener(`abort`,o,{once:!0});try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{done:e,value:o}=await n.read();if(t?.aborted)throw Error(`Request was aborted`);if(e)break;a+=i.decode(o,{stream:!0});let s=a.indexOf(`
2
+
3
+ `);for(;s!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let t=e.split(`
4
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
5
+ `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new V(`Invalid Codex SSE JSON: ${r(t)}`,{cause:t,payload:e})}}s=a.indexOf(`
6
+
7
+ `)}}}finally{t?.removeEventListener(`abort`,o);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}var Oe=`responses_websockets=2026-02-06`,ke=300*1e3,Ae=3300*1e3,U=new Map,W=new Map,G=new Set;function K(e){let t=W.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},W.set(e,t)),t}function je(e){let t=W.get(e);return t?{...t}:void 0}function Me(e){if(e){W.delete(e),G.delete(e);return}W.clear(),G.clear()}function q(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),X(e.socket,1e3,`debug_close`)};if(e){let n=U.get(e);n&&t(n),U.delete(e);return}for(let e of U.values())t(e);U.clear()}_(q);function Ne(e){return e?G.has(e):!1}function Pe(e){if(!e)return;let t=K(e);t.sseFallbacks++,t.websocketFallbackActive=Ne(e)}function Fe(e,t){if(!e)return;G.add(e);let n=K(e);n.websocketFailures++,n.lastWebSocketError=r(t),n.websocketFallbackActive=!0}var J=null;async function Ie(e){if(!e&&J)return J;if(typeof process<`u`&&process.versions?.bun){let t=class extends WebSocket{constructor(t,n){let r={};r=Array.isArray(n)||typeof n==`string`?{protocols:n}:{...n};let i=k(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(J=t),t}let t=globalThis.WebSocket;return typeof t==`function`?t:null}var Le=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function Re(e){let t=e.readyState;return typeof t==`number`?t:void 0}function Y(e){let t=Re(e);return t===void 0||t===1}function ze(e){return Date.now()-e.createdAt>=Ae}function X(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function Be(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(X(t.socket,1e3,`idle_timeout`),U.delete(e))},ke)}async function Z(e,t,n,r=re,i){let a=await Ie(i);if(!a)throw Error(`WebSocket transport is not available in this runtime`);let o=c(t);return delete o[`OpenAI-Beta`],new Promise((t,i)=>{let s=!1,c,l;try{l=new a(e,{headers:o})}catch(e){i(e instanceof Error?e:Error(String(e)));return}let u=()=>{c&&=(clearTimeout(c),void 0),l.removeEventListener(`open`,f),l.removeEventListener(`error`,p),l.removeEventListener(`close`,m),n?.removeEventListener(`abort`,h)},d=(e,t)=>{s||(s=!0,u(),t&&X(l,1e3,t),i(e))},f=()=>{s||(s=!0,u(),t(l))},p=e=>{d(He(e))},m=e=>{d(Q(e))},h=()=>{d(Error(`Request was aborted`),`aborted`)};l.addEventListener(`open`,f),l.addEventListener(`error`,p),l.addEventListener(`close`,m),n?.addEventListener(`abort`,h),r>0&&(c=setTimeout(()=>{d(Error(`WebSocket connect timeout after ${r}ms`),`connect_timeout`)},r)),n?.aborted&&h()})}async function Ve(e,t,n,r,i,a){if(!n){let n=await Z(e,t,r,i,a);return{socket:n,reused:!1,release:()=>X(n)}}let o=U.get(n);if(o){if(o.idleTimer&&=(clearTimeout(o.idleTimer),void 0),!o.busy&&ze(o))X(o.socket,1e3,`connection_age_limit`),U.delete(n);else if(!o.busy&&Y(o.socket))return o.busy=!0,{socket:o.socket,entry:o,reused:!0,release:({keep:e}={})=>{if(!e||!Y(o.socket)){X(o.socket),U.delete(n);return}o.busy=!1,Be(n,o)}};if(o.busy){let n=await Z(e,t,r,i,a);return{socket:n,reused:!1,release:()=>{X(n)}}}Y(o.socket)||(X(o.socket),U.delete(n))}let s=await Z(e,t,r,i,a),c={socket:s,busy:!0,createdAt:Date.now()};return U.set(n,c),{socket:s,entry:c,reused:!1,release:({keep:e}={})=>{if(!e||!Y(c.socket)){X(c.socket),c.idleTimer&&clearTimeout(c.idleTimer),U.get(n)===c&&U.delete(n);return}c.busy=!1,Be(n,c)}}}function He(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function Q(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===oe&&(a=` message too big`),new Le(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function Ue(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*We(e,t,n){let i=[],a=null,o=!1,s=null,c=!1,l=()=>{if(!a)return;let e=a;a=null,e()},u=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await Ue(e.data),!t))return;let n=JSON.parse(t),r=typeof n.type==`string`?n.type:``;(r===`response.completed`||r===`response.done`||r===`response.incomplete`)&&(c=!0,o=!0),i.push(n),l()}catch(e){s=new V(`Invalid Codex WebSocket JSON: ${r(e)}`,{cause:e,payload:t}),o=!0,l()}})()},d=e=>{s=He(e),o=!0,l()},f=e=>{if(c){o=!0,l();return}s||=Q(e),o=!0,l()},p=()=>{s=Error(`Request was aborted`),o=!0,l()};e.addEventListener(`message`,u),e.addEventListener(`error`,d),e.addEventListener(`close`,f),t?.addEventListener(`abort`,p);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(i.length>0){yield i.shift();continue}if(o)break;let r;await new Promise((t,i)=>{a=t,n!==void 0&&n>0&&(r=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${n}ms`);s=t,o=!0,a=null,X(e,1e3,`idle_timeout`),i(t)},n))}).finally(()=>{r&&clearTimeout(r)})}if(s)throw s;if(!c)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,u),e.removeEventListener(`error`,d),e.removeEventListener(`close`,f),t?.removeEventListener(`abort`,p)}}function Ge(e){let{input:t,previous_response_id:n,...r}=e;return r}function Ke(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function qe(e,t){return JSON.stringify(Ge(e))===JSON.stringify(Ge(t))}function Je(e,t){if(!qe(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Ke(n.slice(0,r.length),r))return n.slice(r.length)}function Ye(e,t){let n=e.continuation;if(!n)return t;let r=Je(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Xe(e,t){let n=!1;for await(let r of e)n||(n=!0,t()),yield r}async function Ze(e,t,n,r,i,a,o,s,c,l,u,d){let{socket:f,entry:p,reused:g,release:_}=await Ve(e,n,l,d?.signal,c,d?.env),v=!0,y=d?.transport===`websocket-cached`||d?.transport===`auto`,b=t,x=y&&p?Ye(p,b):b,S=l?K(l):void 0;S&&(S.requests++,g?S.connectionsReused++:S.connectionsCreated++,y&&S.cachedContextRequests++,x.store===!0&&S.storeTrueRequests++,S.lastInputItems=x.input?.length??0,x.previous_response_id?(S.deltaRequests++,S.lastDeltaInputItems=x.input?.length??0,S.lastPreviousResponseId=x.previous_response_id):(S.fullContextRequests++,S.lastDeltaInputItems=void 0,S.lastPreviousResponseId=void 0));try{if(f.send(JSON.stringify({type:`response.create`,...x})),await m(Xe(H(We(f,d?.signal,s)),o),r,i,a,{serviceTier:d?.serviceTier,grammarToolInputProperties:u,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,a)}),d?.signal?.aborted)v=!1;else if(y&&p&&r.responseId){let e=h(a,{messages:[r]},ae,{includeSystemPrompt:!1,grammarToolInputProperties:u}).filter(e=>e.type!==`function_call_output`&&e.type!==`custom_tool_call_output`);p.continuation={lastRequestBody:b,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw p&&(p.continuation=void 0),v=!1,e}finally{_({keep:v})}}async function Qe(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function $e(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[ee]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function $(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))n===null?i.delete(e):i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=j?`pi (${j.platform()} ${j.release()}; ${j.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function et(e,t,n,r,i){let a=$(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session-id`,i),a.set(`x-client-request-id`,i)),a}function tt(e,t,n,r,i){let a=$(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,Oe),a.set(`x-client-request-id`,i),a.set(`session-id`,i),a}export{q as closeOpenAICodexWebSocketSessions,je as getOpenAICodexWebSocketDebugStats,Me as resetOpenAICodexWebSocketDebugStats,I as stream,_e as streamSimple};
@@ -0,0 +1,7 @@
1
+ import{t as e}from"./event-stream-qbAZIAKV.js";import{r as t,s as n}from"./transform-messages-Bp94o3FD.js";import{n as r,r as i,t as a}from"./diagnostics-BsVbaNHR.js";import{t as o}from"./provider-env-DwY8YuMk.js";import{t as s}from"./deferred-tools-DNuoafg8.js";import{t as c}from"./headers-CbDaTl3c.js";import{n as l}from"./constrained-sampling-DafcjXU6.js";import{n as u,t as d}from"./error-body-C0EnfbdK.js";import{t as f}from"./openai-prompt-cache-DXo9f3w5.js";import{n as p,r as m,t as h}from"./openai-responses-shared-CiIL52L-.js";const g=new Set;function _(e){return g.add(e),()=>{g.delete(e)}}let v=-1/0,y=0;function b(e){if(globalThis.crypto?.getRandomValues){globalThis.crypto.getRandomValues(e);return}for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256)}function x(){let e=new Uint8Array(16);b(e);let t=Date.now();t>v?(y=e[6]*16777216+e[7]*65536+e[8]*256+e[9],v=t):(y=y+1>>>0,y===0&&v++);let n=new Uint8Array(16);n[0]=v/1099511627776&255,n[1]=v/4294967296&255,n[2]=v/16777216&255,n[3]=v/65536&255,n[4]=v/256&255,n[5]=v&255,n[6]=112|y>>>28&15,n[7]=y>>>20&255,n[8]=128|y>>>14&63,n[9]=y>>>6&255,n[10]=(y&63)<<2|e[10]&3,n[11]=e[11],n[12]=e[12],n[13]=e[13],n[14]=e[14],n[15]=e[15];let r=Array.from(n,e=>e.toString(16).padStart(2,`0`));return`${r.slice(0,4).join(``)}-${r.slice(4,6).join(``)}-${r.slice(6,8).join(``)}-${r.slice(8,10).join(``)}-${r.slice(10,16).join(``)}`}function S(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let n=new AbortController,r=[],i=e=>{n.signal.aborted||n.abort(e.reason)};for(let e of t){if(e.aborted){i(e);break}let t=()=>i(e);e.addEventListener(`abort`,t,{once:!0}),r.push({signal:e,listener:t})}return{signal:n.signal,cleanup:()=>{for(let{signal:e,listener:t}of r)e.removeEventListener(`abort`,t)}}}const C={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function w(e,t){let n=e.toLowerCase(),r=e.toUpperCase();return t?.[n]||t?.[r]||o(n)||o(r)||``}function T(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function E(e,t,n){let r=w(`no_proxy`,n).toLowerCase();return!r||r!==`*`&&r.split(/[,\s]/).every(n=>{if(!n)return!0;let r=n.match(/^(.+):(\d+)$/),i=r?r[1]:n,a=r?Number.parseInt(r[2],10):0;return a&&a!==t?!0:/^[.*]/.test(i)?(i.startsWith(`*`)&&(i=i.slice(1)),!e.endsWith(i)):e!==i})}function D(e,t){let n=T(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!E(n.host.replace(/:\d*$/,``),Number.parseInt(n.port,10)||C[r]||0,t))return``;let i=w(`${r}_proxy`,t)||w(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}function O(e,t){let n=D(e,t);if(!n)return;let r;try{r=new URL(n)}catch(e){throw Error(`Invalid proxy URL ${JSON.stringify(n)}: ${e instanceof Error?e.message:String(e)}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL. Got ${r.protocol}`);return r}function k(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}const A=k(),j=1e3,M=new Set([`openai`,`openai-codex`,`opencode`]),N=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function ee(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function te(e,t){return e===429&&ee(t)?!1:e===429||e===500||e===502||e===503||e===504||/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function ne(e){let t=e.get(`retry-after-ms`);if(t!==null){let e=Number(t);if(Number.isFinite(e))return Math.max(0,e)}let n=e.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r*1e3);let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var P=class extends Error{};function re(e,t){let n=t?.maxRetryDelayMs??6e4;if(n>0&&e>n)throw new P(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s)`);return e}function F(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}function ie(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function ae(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:zlib`)??null}function oe(e){let t=ae();if(!t||typeof t.zstdCompressSync!=`function`)return null;try{let n=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:3}});return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}catch{return null}}const I=(t,n,i)=>{let o=new e;return(async()=>{let e={role:`assistant`,content:[],api:`openai-codex-responses`,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let s=i?.apiKey;if(!s)throw Error(`No API key for provider: ${t.provider}`);let u=Be(s),d=l(n.tools,t.compat?.supportsOpenAIGrammarTools??!1),p=i?.cacheRetention===`none`?void 0:i?.sessionId,m=f(p),h=ce(t,n,i,m,d),g=await i?.onPayload?.(h,t);g!==void 0&&(h=g);let _=m||x(),v=Ve(t.headers,i?.headers,u,s,m),y=He(t.headers,i?.headers,u,s,_),b=JSON.stringify(h),C=ie(i?.timeoutMs),w=ie(i?.websocketConnectTimeoutMs),T=i?.transport||`auto`,E=!1,D=T!==`sse`&&q(p);if(D&&J(p),T!==`sse`&&!D){let n=!1,s=!1,c=!1;for(;;){n=!1;try{if(await Re(ue(t.baseUrl),h,y,e,o,t,()=>{n=!0,E||(E=!0,o.push({type:`start`,partial:e}))},C,w,p,d,i),i?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end();return}catch(t){let o=i?.signal?.aborted,l=!n&&pe(t),u=me(t);if(!o&&u&&!c){c=!0;continue}if(!o&&l&&!s){s=!0;continue}if(o||fe(t)&&!l||(a(e,r(`provider_transport_failure`,t,{configuredTransport:T,fallbackTransport:n?void 0:`sse`,eventsEmitted:n,phase:n?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(b).byteLength})),xe(p,t),n))throw t;J(p);break}}}let O=oe(b);O&&v.set(`content-encoding`,`zstd`);let k=O??b,A,M,N=i?.maxRetries??0;for(let e=0;e<=N;e++){if(i?.signal?.aborted)throw Error(`Request was aborted`);try{let n=C!==void 0&&C>0?AbortSignal.timeout(C):void 0,r=S([i?.signal,n]);try{A=await fetch(z(t.baseUrl),{method:`POST`,headers:v,body:k,signal:r.signal})}catch(e){throw n?.aborted&&!i?.signal?.aborted?Error(`Codex SSE response headers timed out after ${C}ms`):e}finally{r.cleanup()}if(await i?.onResponse?.({status:A.status,headers:c(A.headers)},t),A.ok)break;let a=await A.text();if(e<N&&te(A.status,a)){let t=ne(A.headers);await F(t===void 0?j*2**e:re(t,i),i?.signal);continue}let o=await ze(new Response(a,{status:A.status,statusText:A.statusText}));throw Error(o.friendlyMessage||o.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(M=t instanceof Error?t:Error(String(t)),e<N&&!(M instanceof P)&&!M.message.includes(`usage limit`)){await F(j*2**e,i?.signal);continue}throw M}}if(!A?.ok)throw M??Error(`Failed after retries`);if(!A.body)throw Error(`No response body`);if(E||(E=!0,o.push({type:`start`,partial:e})),await de(A,e,o,t,d,i),i?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:e.stopReason,message:e}),o.end()}catch(t){for(let t of e.content)delete t.partialJson,delete t.customInput;e.stopReason=i?.signal?.aborted?`aborted`:`error`,e.errorMessage=d(u(t)),o.push({type:`error`,reason:e.stopReason,error:e}),o.end()}})(),o},se=(e,r,i)=>{let a=i?.apiKey;if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=t(e,r,i,a),s=i?.reasoning?n(e,i.reasoning):void 0,c=s===`off`?void 0:s;return I(e,r,{...o,reasoningEffort:c})};function ce(e,t,n,r,i=l(t.tools,e.compat?.supportsOpenAIGrammarTools??!1)){let a=e.compat?.supportsStrictMode??!0,o=e.compat?.supportsOpenAIGrammarTools??!1,c=s(t,e.compat?.supportsToolSearch??!1),u=h(e,t,M,{includeSystemPrompt:!1,grammarToolInputProperties:i,deferredTools:c.deferred,toolOptions:{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o}}),d={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:u,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:r,tool_choice:n?.toolChoice??`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(d.temperature=n.temperature),n?.serviceTier!==void 0&&(d.service_tier=n.serviceTier),c.immediate.length>0&&(d.tools=p(c.immediate,{strict:null,supportsStrictMode:a,supportsOpenAIGrammarTools:o})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(d.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return d}function le(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function L(e,t,n){let r=le(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function R(e,t){return e==="default"&&(t===`flex`||t===`priority`)?t:e??t}function z(e){let t=(e&&e.trim().length>0?e:`https://chatgpt.com/backend-api`).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function ue(e){let t=new URL(z(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function de(e,t,n,r,i,a){await m(H(_e(e,a?.signal)),t,n,r,{serviceTier:a?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,r)})}var B=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},V=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function fe(e){return e instanceof B||e instanceof V}function pe(e){return e instanceof B&&e.code===`websocket_connection_limit_reached`}function me(e){return e instanceof B&&e.code===`previous_response_not_found`}function he(e){let t=e.error&&typeof e.error==`object`?e.error:void 0;return{code:typeof e.code==`string`?e.code:typeof t?.code==`string`?t.code:void 0,message:typeof e.message==`string`?e.message:typeof t?.message==`string`?t.message:void 0}}async function*H(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let{code:e,message:n}=he(t);throw new B(`Codex error: ${n||e||JSON.stringify(t)}`,{code:e,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new B(r||`Codex response failed`,{code:n,payload:t})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=t.response,n=e&&{...e,status:ge(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function ge(e){if(typeof e==`string`)return N.has(e)?e:void 0}async function*_e(e,t){if(!e.body)return;let n=e.body.getReader(),r=new TextDecoder,a=``,o=()=>{n.cancel().catch(()=>{})};t?.addEventListener(`abort`,o,{once:!0});try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{done:e,value:o}=await n.read();if(t?.aborted)throw Error(`Request was aborted`);if(e)break;a+=r.decode(o,{stream:!0});let s=a.indexOf(`
2
+
3
+ `);for(;s!==-1;){let e=a.slice(0,s);a=a.slice(s+2);let t=e.split(`
4
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
5
+ `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new V(`Invalid Codex SSE JSON: ${i(t)}`,{cause:t,payload:e})}}s=a.indexOf(`
6
+
7
+ `)}}}finally{t?.removeEventListener(`abort`,o);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}const U=new Map,W=new Map,G=new Set;function K(e){let t=W.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},W.set(e,t)),t}function ve(e){let t=W.get(e);return t?{...t}:void 0}function ye(e){if(e){W.delete(e),G.delete(e);return}W.clear(),G.clear()}function be(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),Z(e.socket,1e3,`debug_close`)};if(e){let n=U.get(e);n&&t(n),U.delete(e);return}for(let e of U.values())t(e);U.clear()}_(be);function q(e){return e?G.has(e):!1}function J(e){if(!e)return;let t=K(e);t.sseFallbacks++,t.websocketFallbackActive=q(e)}function xe(e,t){if(!e)return;G.add(e);let n=K(e);n.websocketFailures++,n.lastWebSocketError=i(t),n.websocketFallbackActive=!0}let Y=null;async function Se(e){if(!e&&Y)return Y;if(typeof process<`u`&&process.versions?.bun){let t=class extends WebSocket{constructor(t,n){let r={};r=Array.isArray(n)||typeof n==`string`?{protocols:n}:{...n};let i=O(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(Y=t),t}let t=globalThis.WebSocket;return typeof t==`function`?t:null}var Ce=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function we(e){let t=e.readyState;return typeof t==`number`?t:void 0}function X(e){let t=we(e);return t===void 0||t===1}function Te(e){return Date.now()-e.createdAt>=33e5}function Z(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function Ee(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(Z(t.socket,1e3,`idle_timeout`),U.delete(e))},3e5)}async function Q(e,t,n,r=15e3,i){let a=await Se(i);if(!a)throw Error(`WebSocket transport is not available in this runtime`);let o=c(t);return delete o[`OpenAI-Beta`],new Promise((t,i)=>{let s=!1,c,l;try{l=new a(e,{headers:o})}catch(e){i(e instanceof Error?e:Error(String(e)));return}let u=()=>{c&&=(clearTimeout(c),void 0),l.removeEventListener(`open`,f),l.removeEventListener(`error`,p),l.removeEventListener(`close`,m),n?.removeEventListener(`abort`,h)},d=(e,t)=>{s||(s=!0,u(),t&&Z(l,1e3,t),i(e))},f=()=>{s||(s=!0,u(),t(l))},p=e=>{d(Oe(e))},m=e=>{d(ke(e))},h=()=>{d(Error(`Request was aborted`),`aborted`)};l.addEventListener(`open`,f),l.addEventListener(`error`,p),l.addEventListener(`close`,m),n?.addEventListener(`abort`,h),r>0&&(c=setTimeout(()=>{d(Error(`WebSocket connect timeout after ${r}ms`),`connect_timeout`)},r)),n?.aborted&&h()})}async function De(e,t,n,r,i,a){if(!n){let n=await Q(e,t,r,i,a);return{socket:n,reused:!1,release:()=>Z(n)}}let o=U.get(n);if(o){if(o.idleTimer&&=(clearTimeout(o.idleTimer),void 0),!o.busy&&Te(o))Z(o.socket,1e3,`connection_age_limit`),U.delete(n);else if(!o.busy&&X(o.socket))return o.busy=!0,{socket:o.socket,entry:o,reused:!0,release:({keep:e}={})=>{if(!e||!X(o.socket)){Z(o.socket),U.delete(n);return}o.busy=!1,Ee(n,o)}};if(o.busy){let n=await Q(e,t,r,i,a);return{socket:n,reused:!1,release:()=>{Z(n)}}}X(o.socket)||(Z(o.socket),U.delete(n))}let s=await Q(e,t,r,i,a),c={socket:s,busy:!0,createdAt:Date.now()};return U.set(n,c),{socket:s,entry:c,reused:!1,release:({keep:e}={})=>{if(!e||!X(c.socket)){Z(c.socket),c.idleTimer&&clearTimeout(c.idleTimer),U.get(n)===c&&U.delete(n);return}c.busy=!1,Ee(n,c)}}}function Oe(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function ke(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===1009&&(a=` message too big`),new Ce(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function Ae(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*je(e,t,n){let r=[],a=null,o=!1,s=null,c=!1,l=()=>{if(!a)return;let e=a;a=null,e()},u=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await Ae(e.data),!t))return;let n=JSON.parse(t),i=typeof n.type==`string`?n.type:``;(i===`response.completed`||i===`response.done`||i===`response.incomplete`)&&(c=!0,o=!0),r.push(n),l()}catch(e){s=new V(`Invalid Codex WebSocket JSON: ${i(e)}`,{cause:e,payload:t}),o=!0,l()}})()},d=e=>{s=Oe(e),o=!0,l()},f=e=>{if(c){o=!0,l();return}s||=ke(e),o=!0,l()},p=()=>{s=Error(`Request was aborted`),o=!0,l()};e.addEventListener(`message`,u),e.addEventListener(`error`,d),e.addEventListener(`close`,f),t?.addEventListener(`abort`,p);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(r.length>0){yield r.shift();continue}if(o)break;let i;await new Promise((t,r)=>{a=t,n!==void 0&&n>0&&(i=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${n}ms`);s=t,o=!0,a=null,Z(e,1e3,`idle_timeout`),r(t)},n))}).finally(()=>{i&&clearTimeout(i)})}if(s)throw s;if(!c)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,u),e.removeEventListener(`error`,d),e.removeEventListener(`close`,f),t?.removeEventListener(`abort`,p)}}function Me(e){let{input:t,previous_response_id:n,...r}=e;return r}function Ne(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function Pe(e,t){return JSON.stringify(Me(e))===JSON.stringify(Me(t))}function Fe(e,t){if(!Pe(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Ne(n.slice(0,r.length),r))return n.slice(r.length)}function Ie(e,t){let n=e.continuation;if(!n)return t;let r=Fe(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*Le(e,t){let n=!1;for await(let r of e)n||(n=!0,t()),yield r}async function Re(e,t,n,r,i,a,o,s,c,l,u,d){let{socket:f,entry:p,reused:g,release:_}=await De(e,n,l,d?.signal,c,d?.env),v=!0,y=d?.transport===`websocket-cached`||d?.transport===`auto`,b=t,x=y&&p?Ie(p,b):b,S=l?K(l):void 0;S&&(S.requests++,g?S.connectionsReused++:S.connectionsCreated++,y&&S.cachedContextRequests++,x.store===!0&&S.storeTrueRequests++,S.lastInputItems=x.input?.length??0,x.previous_response_id?(S.deltaRequests++,S.lastDeltaInputItems=x.input?.length??0,S.lastPreviousResponseId=x.previous_response_id):(S.fullContextRequests++,S.lastDeltaInputItems=void 0,S.lastPreviousResponseId=void 0));try{if(f.send(JSON.stringify({type:`response.create`,...x})),await m(Le(H(je(f,d?.signal,s)),o),r,i,a,{serviceTier:d?.serviceTier,grammarToolInputProperties:u,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,a)}),d?.signal?.aborted)v=!1;else if(y&&p&&r.responseId){let e=h(a,{messages:[r]},M,{includeSystemPrompt:!1,grammarToolInputProperties:u}).filter(e=>e.type!==`function_call_output`&&e.type!==`custom_tool_call_output`);p.continuation={lastRequestBody:b,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw p&&(p.continuation=void 0),v=!1,e}finally{_({keep:v})}}async function ze(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function Be(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[`https://api.openai.com/auth`]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function $(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))n===null?i.delete(e):i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=A?`pi (${A.platform()} ${A.release()}; ${A.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function Ve(e,t,n,r,i){let a=$(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session-id`,i),a.set(`x-client-request-id`,i)),a}function He(e,t,n,r,i){let a=$(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,`responses_websockets=2026-02-06`),a.set(`x-client-request-id`,i),a.set(`session-id`,i),a}export{be as closeOpenAICodexWebSocketSessions,ve as getOpenAICodexWebSocketDebugStats,ye as resetOpenAICodexWebSocketDebugStats,I as stream,se as streamSimple};
@@ -0,0 +1 @@
1
+ import{R as e,d as t}from"./account-store-CJqBAm1f.js";import{n}from"./event-stream-qbAZIAKV.js";import{a as r}from"./compat-aVSWLlYQ.js";import{n as i,o as a}from"./legacy-api-aliases-IllWZ-uu.js";import"./provider-settings-DnRChWz9.js";var o=`openai-codex`,s=`app_EMoamEEZ73f0CkXaXp7hrann`,c=`https://auth.openai.com/oauth/authorize`,l=`https://auth.openai.com/oauth/token`,u=`openid profile email offline_access`,d=`http://localhost:1455/auth/callback`,f=`http://localhost:1455/auth/callback*`,p=`https://chatgpt.com/backend-api`,m=`openai-codex-responses`,h=`${o}-openai`,g={xhigh:`xhigh`,minimal:`low`},_=[{id:`gpt-5.5`,name:`GPT-5.5`,input:[`text`,`image`]},{id:`gpt-5.4`,name:`GPT-5.4`,input:[`text`,`image`]},{id:`gpt-5.4-mini`,name:`GPT-5.4 mini`,input:[`text`,`image`]},{id:`gpt-5.3-codex`,name:`GPT-5.3 Codex`,input:[`text`,`image`]},{id:`gpt-5.3-codex-spark`,name:`GPT-5.3 Codex Spark`,input:[`text`]},{id:`gpt-5.2`,name:`GPT-5.2`,input:[`text`,`image`]}].map(e=>({...e,api:`openai`,reasoning:!0,context_window:272e3,max_tokens:128e3,thinkingLevelMap:g}));function v(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function y(e){let t=new Uint8Array(e);return crypto.getRandomValues(t),t}function b(){return v(y(32))}async function x(e){let t=new TextEncoder().encode(e);return v(new Uint8Array(await crypto.subtle.digest(`SHA-256`,t)))}function S(){return v(y(16))}async function C(e,t){let n=new URLSearchParams({grant_type:`authorization_code`,client_id:s,code:e,code_verifier:t,redirect_uri:d}),r=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:n});if(!r.ok)throw Error(`OpenAI Codex token exchange failed: ${r.status} ${await r.text()}`);let i=await r.json();if(!i.access_token)throw Error(`OpenAI Codex token exchange did not return access_token.`);return i}async function w(e){try{let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e,client_id:s}),n=await fetch(l,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:t});return n.ok?await n.json():(console.error(`[openai-codex] refresh failed:`,n.status,await n.text()),null)}catch(e){return console.error(`[openai-codex] refresh error:`,e instanceof Error?e.message:String(e)),null}}function T(e){try{let t=e.split(`.`);if(t.length!==3)return;let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`);return n.length%4&&(n+=`=`.repeat(4-n.length%4)),JSON.parse(atob(n))}catch{return}}function E(e){let t=T(e)?.[`https://api.openai.com/profile`];return typeof t?.email==`string`?t.email:void 0}function D(e){let t=T(e)?.[`https://api.openai.com/auth`],n=E(e),r=typeof t?.chatgpt_plan_type==`string`?t.chatgpt_plan_type:void 0,i=r?r.charAt(0).toUpperCase()+r.slice(1):void 0;if(n&&i)return`${n} (${i})`;if(n)return n;if(i)return`ChatGPT ${i}`}async function O(e){let t=E(e);if(t)try{let e=t.trim().toLowerCase(),n=new Uint8Array(await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e)));return`https://www.gravatar.com/avatar/${Array.from(n).map(e=>e.toString(16).padStart(2,`0`)).join(``)}?s=128&d=404`}catch{return}}function k(){return t().find(e=>e.providerId===o)}async function A(){let t=k();if(!t?.accessToken)throw Error("Not signed in to OpenAI Codex — run `oauth-token openai-codex` or /login");let n=t.tokenExpiresAt??0;if(n&&Date.now()+6e4<n)return t.accessToken;if(t.refreshToken){let n=await w(t.refreshToken);if(n?.access_token)return await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:p,userName:D(n.access_token),userAvatar:await O(n.access_token)}),n.access_token}return t.accessToken}function j(e,t){return{type:`error`,reason:`error`,error:{role:`assistant`,content:[],api:h,provider:o,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()}}}var M=(e,t,r={})=>{let a=n();return(async()=>{try{let n=await A(),o=i({...e,baseUrl:p,api:m},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)a.push(e);a.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),a.push(j(e,t)),a.end()}})(),a},N=(e,t,r)=>{let i=n();return(async()=>{try{let n=await A(),o=a({...e,baseUrl:p,api:m},t,{...r,apiKey:n,transport:`sse`});for await(let e of o)i.push(e);i.end()}catch(t){console.error(`[openai-codex] Stream error:`,t instanceof Error?t.message:String(t)),i.push(j(e,t)),i.end()}})(),i},P={id:o,name:`OpenAI Codex (ChatGPT Subscription)`,description:`GPT-5 Codex via your ChatGPT Plus/Pro/Business subscription — OAuth login, no API key needed. Default model is GPT-5.5.`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,defaultModelId:`gpt-5.5`,oauthTokenDomains:[`chatgpt.com`,`*.chatgpt.com`,`auth.openai.com`,`api.openai.com`],getModelIds:()=>_,onOAuthLoginIntercepted:async(t,n,r)=>{let i=b(),a=await x(i),l=S(),m=new URL(c);m.searchParams.set(`response_type`,`code`),m.searchParams.set(`client_id`,s),m.searchParams.set(`redirect_uri`,d),m.searchParams.set(`scope`,r?.scopes??u),m.searchParams.set(`code_challenge`,a),m.searchParams.set(`code_challenge_method`,`S256`),m.searchParams.set(`state`,l),m.searchParams.set(`id_token_add_organizations`,`true`),m.searchParams.set(`codex_cli_simplified_flow`,`true`),m.searchParams.set(`originator`,`pi`);let h=await t({authorizeUrl:m.toString(),redirectUriPattern:f,onCapture:`close`});if(!h)throw Error(`OpenAI Codex OAuth login was cancelled or timed out`);let g=new URL(h),_=g.searchParams.get(`code`),v=g.searchParams.get(`state`);if(!_)throw Error(`OpenAI Codex OAuth redirect did not include a code`);if(v!==l)throw Error(`OpenAI Codex OAuth state mismatch — possible CSRF, aborting`);let y=await C(_,i);await e({providerId:o,accessToken:y.access_token,refreshToken:y.refresh_token,tokenExpiresAt:Date.now()+(y.expires_in??3600)*1e3,baseUrl:p,userName:D(y.access_token),userAvatar:await O(y.access_token)}),n()},onOAuthLogout:async()=>{await e({providerId:o,accessToken:``})},onSilentRenew:async()=>{let t=k();if(!t?.refreshToken)return null;let n=await w(t.refreshToken);return n?.access_token?(await e({providerId:o,accessToken:n.access_token,refreshToken:n.refresh_token??t.refreshToken,tokenExpiresAt:Date.now()+(n.expires_in??3600)*1e3,baseUrl:p,userName:D(n.access_token),userAvatar:await O(n.access_token)}),n.access_token):null}};function F(){r({api:h,stream:M,streamSimple:N})}export{P as config,F as register};
@@ -0,0 +1,5 @@
1
+ import{t as e}from"./event-stream-qbAZIAKV.js";import{n as t,t as n}from"./models-Bnh9VDA1.js";import{n as r}from"./json-parse-rb7sUwcH.js";import{t as i}from"./provider-env-D37PhSJu.js";import{r as a,t as o}from"./transform-messages-wECJwtH0.js";import{t as s}from"./headers-CbDaTl3c.js";import{t as c}from"./provider-retry-C8PJzY_l.js";import{t as l}from"./sanitize-unicode-DmIE6hZJ.js";import{a as u,i as d,n as f,r as p,t as m}from"./constrained-sampling-DafcjXU6.js";import{n as h,t as g}from"./github-copilot-headers-DRgtIyTm.js";import{n as _}from"./openai-BxFF4GUL.js";import{n as v,t as y}from"./error-body-C0EnfbdK.js";import{t as b}from"./openai-prompt-cache-DXo9f3w5.js";import{t as x}from"./hash-yQufAZII.js";function S(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function C(e,t,n){if(t)return t;if(S(n,`authorization`)||S(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function w(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function T(e){let t=new Set;for(let n of e)if(n.role===`toolResult`)for(let e of n.addedToolNames??[])t.add(e);return t}function E(e,t){if(!e)return[];let n=new Map(e.map(e=>[e.name,e]));return Array.from(t).map(e=>n.get(e)).filter(e=>e!==void 0)}function D(e){return e.type===`text`}function O(e){return e.type===`thinking`}function k(e){return e.type===`toolCall`}function A(e){return e.type===`image`}function j(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.type===`reasoning.encrypted`&&typeof t.id==`string`&&t.id.length>0&&typeof t.data==`string`&&t.data.length>0}function M(e,t){return e||(i(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}var N=(t,n,i)=>{let a=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let o=C(t.provider,i?.apiKey,i?.headers),l=Q(t),u=f(n.tools,l.supportsOpenAIGrammarTools),d=M(i?.cacheRetention,i?.env),p=d===`none`?void 0:i?.sessionId,h=F(t,n,o,i?.headers,p,l),g=I(t,n,i,l,d,u),_=await i?.onPayload?.(g,t);_!==void 0&&(g=_);let v={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:0},{data:y,response:b}=await c(()=>h.chat.completions.create(g,v).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await i?.onResponse?.({status:b.status,headers:s(b.headers)},t),a.push({type:`start`,partial:e});let x=null,S=null,w=!1,T=new Map,E=new Map,D=new Map,O=e.content,k=e=>O.indexOf(e),A=e=>{let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``},N=(e,t,n)=>{let r=e.customInput;if(!r)return;let i=m(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i},P=t=>{let n=k(t);if(n!==-1){if(t.type===`text`)a.push({type:`text_end`,contentIndex:n,content:t.text,partial:e});else if(t.type===`thinking`)a.push({type:`thinking_end`,contentIndex:n,content:t.thinking,partial:e});else if(t.type===`toolCall`){if(t.customInput){let r=N(t,A(t),!0);r!==void 0&&a.push({type:`toolcall_delta`,contentIndex:n,delta:r,partial:e})}else t.arguments=r(t.partialArgs);delete t.partialArgs,delete t.customInput,delete t.streamIndex,a.push({type:`toolcall_end`,contentIndex:n,toolCall:t,partial:e})}}},L=()=>(x||(x={type:`text`,text:``},O.push(x),a.push({type:`text_start`,contentIndex:k(x),partial:e})),x),R=t=>(S||(S={type:`thinking`,thinking:``,thinkingSignature:t},O.push(S),a.push({type:`thinking_start`,contentIndex:k(S),partial:e})),S),z=e=>{if(!e.id)return;let t=D.get(e.id);t&&(e.thoughtSignature=t,D.delete(e.id))},B=t=>{let n=typeof t.index==`number`?t.index:void 0,r=t.function?.name??t.custom?.name??``,i=n===void 0?void 0:T.get(n);if(!i&&t.id&&(i=E.get(t.id)),!i){let o=t.custom?u.get(r)??`input`:void 0,s=o!==void 0;i={type:`toolCall`,id:t.id||``,name:r,arguments:s?{[o]:``}:{},partialArgs:s?void 0:``,customInput:s?{property:o,jsonBuffer:{input:``,started:!1,closed:!1}}:void 0,streamIndex:n},n!==void 0&&T.set(n,i),t.id&&E.set(t.id,i),O.push(i),a.push({type:`toolcall_start`,contentIndex:k(i),partial:e})}if(n!==void 0&&i.streamIndex===void 0&&(i.streamIndex=n,T.set(n,i)),t.id&&E.set(t.id,i),!i.name&&r&&(i.name=r),t.custom&&!i.customInput){let e=u.get(i.name)??`input`;i.arguments={[e]:``},i.customInput={property:e,jsonBuffer:{input:``,started:!1,closed:!1}},delete i.partialArgs}return z(i),i};for await(let n of y){if(!n||typeof n!=`object`)continue;e.responseId||=n.id,typeof n.model==`string`&&n.model.length>0&&n.model!==t.id&&(e.responseModel||=n.model),n.usage&&(e.usage=Y(n.usage,t));let i=Array.isArray(n.choices)?n.choices[0]:void 0;if(i){if(!n.usage&&i.usage&&(e.usage=Y(i.usage,t)),i.finish_reason){let t=X(i.finish_reason);e.stopReason=t.stopReason,t.errorMessage&&(e.errorMessage=t.errorMessage),w=!0}if(i.delta){if(i.delta.content!==null&&i.delta.content!==void 0&&i.delta.content.length>0){let t=L();t.text+=i.delta.content,a.push({type:`text_delta`,contentIndex:k(t),delta:i.delta.content,partial:e})}let n=[`reasoning_content`,`reasoning`,`reasoning_text`],o=i.delta,s=null;for(let e of n){let t=o[e];if(typeof t==`string`&&t.length>0){s=e;break}}if(s){let n=o[s];if(typeof n==`string`&&n.length>0){let r=R(t.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);r.thinking+=n,a.push({type:`thinking_delta`,contentIndex:k(r),delta:n,partial:e})}}if(i?.delta?.tool_calls)for(let t of i.delta.tool_calls){let n=B(t);!n.id&&t.id&&(n.id=t.id,E.set(t.id,n));let i=t.function?.name??t.custom?.name;!n.name&&i&&(n.name=i);let o=``;t.function?.arguments?(o=t.function.arguments,n.partialArgs=(n.partialArgs??``)+t.function.arguments,n.arguments=r(n.partialArgs)):t.custom?.input&&(o=N(n,A(n)+t.custom.input,!1)??``),a.push({type:`toolcall_delta`,contentIndex:k(n),delta:o,partial:e})}let c=i.delta.reasoning_details;if(Array.isArray(c)){for(let e of c)if(j(e)){let t=JSON.stringify(e),n=E.get(e.id);n?n.thoughtSignature=t:D.set(e.id,t)}}}}}for(let e of O)P(e);if(i?.signal?.aborted||e.stopReason===`aborted`)throw Error(`Request was aborted`);if(e.stopReason===`error`)throw Error(e.errorMessage||`Provider returned an error stop reason`);if(!w)throw Error(`Stream ended without finish_reason`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialArgs,delete t.customInput,delete t.streamIndex;e.stopReason=i?.signal?.aborted?`aborted`:`error`,e.errorMessage=y(v(t));let n=t?.error?.metadata?.raw;n&&!e.errorMessage.includes(String(n))&&(e.errorMessage+=`\n${n}`),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a},P=(e,n,r)=>{C(e.provider,r?.apiKey,r?.headers);let i=a(e,n,r,r?.apiKey),o=r?.reasoning?t(e,r.reasoning):void 0,s=o===`off`?void 0:o,c=r?.toolChoice;return N(e,n,{...i,reasoningEffort:s,toolChoice:c})};function F(e,t,n,r,i,a=Q(e)){let o={...e.headers};if(e.provider===`github-copilot`){let e=h(t.messages),n=g({messages:t.messages,hasImages:e});Object.assign(o,n)}return i&&a.sendSessionAffinityHeaders&&(a.sessionAffinityFormat===`openrouter`?o[`x-session-id`]=i:(a.sessionAffinityFormat===`openai`&&(o.session_id=i),o[`x-client-request-id`]=i,o[`x-session-affinity`]=i)),r&&Object.assign(o,r),new _({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:o})}function I(e,t,n,r=Q(e),i=M(n?.cacheRetention,n?.env),a=f(t.tools,r.supportsOpenAIGrammarTools)){let o=q(e,t,r,{grammarToolInputProperties:a}),s=z(r,i),c={model:e.id,messages:o,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&i!==`none`||i===`long`&&r.supportsLongCacheRetention?b(n?.sessionId):void 0,prompt_cache_retention:i===`long`&&r.supportsLongCacheRetention?`24h`:void 0};r.supportsUsageInStreaming!==!1&&(c.stream_options={include_usage:!0}),r.supportsStore&&(c.store=!1),n?.maxTokens&&(r.maxTokensField===`max_tokens`?c.max_tokens=n.maxTokens:c.max_completion_tokens=n.maxTokens),n?.temperature!==void 0&&(c.temperature=n.temperature);let l=r.deferredToolsMode===`kimi`?T(t.messages):new Set,u=t.tools?.filter(e=>!l.has(e.name));if(u&&u.length>0?(c.tools=J(u,r),r.zaiToolStream&&(c.tool_stream=!0)):w(t.messages)&&(c.tools=[]),s&&B(o,c.tools,s),n?.toolChoice&&(c.tool_choice=n.toolChoice),r.thinkingFormat===`zai`&&e.reasoning){let t=c;if(t.thinking=n?.reasoningEffort?{type:`enabled`,clear_thinking:!1}:{type:`disabled`},n?.reasoningEffort&&r.supportsReasoningEffort){let r=e.thinkingLevelMap?.[n.reasoningEffort],i=r===void 0?n.reasoningEffort:r;typeof i==`string`&&(t.reasoning_effort=i)}}else if(r.thinkingFormat===`qwen`&&e.reasoning)c.enable_thinking=!!n?.reasoningEffort;else if(r.thinkingFormat===`qwen-chat-template`&&e.reasoning)c.chat_template_kwargs={enable_thinking:!!n?.reasoningEffort,preserve_thinking:!0};else if(r.thinkingFormat===`chat-template`&&e.reasoning){let t=L(e,n,r);t&&(c.chat_template_kwargs=t)}else if(r.thinkingFormat===`deepseek`&&e.reasoning)n?.reasoningEffort?c.thinking={type:`enabled`}:e.thinkingLevelMap?.off!==null&&(c.thinking={type:`disabled`}),n?.reasoningEffort&&r.supportsReasoningEffort&&(c.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort);else if(r.thinkingFormat===`openrouter`&&e.reasoning){let t=c;n?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(t.reasoning={effort:e.thinkingLevelMap?.off??`none`})}else if(r.thinkingFormat===`ant-ling`&&e.reasoning&&n?.reasoningEffort){let t=e.thinkingLevelMap?.[n.reasoningEffort];typeof t==`string`&&(c.reasoning={effort:t})}else if(r.thinkingFormat===`together`&&e.reasoning){let t=c;t.reasoning={enabled:!!n?.reasoningEffort},n?.reasoningEffort&&r.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort)}else if(r.thinkingFormat===`string-thinking`&&e.reasoning){let t=c;n?.reasoningEffort?t.thinking=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:e.thinkingLevelMap?.off!==null&&(t.thinking=e.thinkingLevelMap?.off??`none`)}else if(n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort)c.reasoning_effort=e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;else if(!n?.reasoningEffort&&e.reasoning&&r.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(c.reasoning_effort=t)}if(e.compat?.openRouterRouting&&(c.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),c.providerOptions={gateway:e}}}return c}function L(e,t,n){let r={};for(let[i,a]of Object.entries(n.chatTemplateKwargs)){let n=R(e,t,a);n!==void 0&&(r[i]=n)}return Object.keys(r).length>0?r:void 0}function R(e,t,n){if(typeof n!=`object`||!n)return n;let r=t?.reasoningEffort;if(!r&&n.omitWhenOff)return;if(n.$var===`thinking.enabled`)return!!r;let i=r?e.thinkingLevelMap?.[r]:e.thinkingLevelMap?.off;return i===void 0?r:typeof i==`string`?i:void 0}function z(e,t){if(e.cacheControlFormat!==`anthropic`||t===`none`)return;let n=t===`long`&&e.supportsLongCacheRetention?`1h`:void 0;return{type:`ephemeral`,...n?{ttl:n}:{}}}function B(e,t,n){V(e,n),U(t,n),H(e,n)}function V(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){W(n,t);return}}function H(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`||r.role===`tool`)&&G(r,t))return}}function U(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function W(e,t){return K(e,t)}function G(e,t){return e.role===`user`||e.role===`assistant`||e.role===`tool`?K(e,t):!1}function K(e,t){let n=e.content;if(typeof n==`string`)return n.length===0?!1:(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function q(e,t,n,r){let i=[],a=t=>{if(t.includes(`|`)){let e=t.indexOf(`|`),n=t.slice(0,e).replace(/[^a-zA-Z0-9_-]/g,`_`),r=t.slice(e+1).replace(/[^a-zA-Z0-9_-]/g,`_`),i=r.length>0?`${n}_${r}`:n;if(i.length<=40)return i;let a=x(t).slice(0,8);return`${n.slice(0,Math.max(1,40-a.length-1))}_${a}`}return e.provider===`openai`&&t.length>40?t.slice(0,40):t},s=o(t.messages,e,e=>a(e));if(t.systemPrompt){let r=e.reasoning&&n.supportsDeveloperRole?`developer`:`system`;i.push({role:r,content:l(t.systemPrompt)})}let c=null;for(let a=0;a<s.length;a++){let o=s[a];if(n.requiresAssistantAfterToolResult&&c===`toolResult`&&o.role===`user`&&i.push({role:`assistant`,content:`I have processed the tool results.`}),o.role===`user`)if(typeof o.content==`string`)i.push({role:`user`,content:l(o.content)});else{let e=o.content.map(e=>e.type===`text`?{type:`text`,text:l(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;i.push({role:`user`,content:e})}else if(o.role===`assistant`){let t={role:`assistant`,content:n.requiresAssistantAfterToolResult?``:null},a=o.content.filter(D).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:l(e.text)})),s=a.map(e=>e.text).join(``),c=o.content.filter(O).filter(e=>e.thinking.trim().length>0);if(c.length>0)if(n.requiresThinkingAsText)t.content=[{type:`text`,text:c.map(e=>l(e.thinking)).join(`
2
+
3
+ `)},...a];else{s.length>0&&(t.content=s);let n=c[0].thinkingSignature;e.provider===`opencode-go`&&n===`reasoning`&&(n=`reasoning_content`),n&&n.length>0&&(t[n]=c.map(e=>e.thinking).join(`
4
+ `))}else s.length>0&&(t.content=s);let u=o.content.filter(k);if(u.length>0){t.tool_calls=u.map(e=>{let t=r?.grammarToolInputProperties?.get(e.name);return t===void 0?{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}:{id:e.id,type:`custom`,custom:{name:e.name,input:l(p(e.name,e.arguments,t))}}});let e=u.filter(e=>e.thoughtSignature).map(e=>{try{return JSON.parse(e.thoughtSignature)}catch{return null}}).filter(Boolean);e.length>0&&(t.reasoning_details=e)}n.requiresReasoningContentOnAssistantMessages&&e.reasoning&&t.reasoning_content===void 0&&(t.reasoning_content=``);let d=t.content;if(!(d!=null&&d.length>0)&&!t.tool_calls)continue;i.push(t)}else if(o.role===`toolResult`){let r=[],o=new Set,u=a;for(;u<s.length&&s[u].role===`toolResult`;u++){let t=s[u],a=t.content.filter(D).map(e=>e.text).join(`
5
+ `),c=t.content.some(e=>e.type===`image`),d={role:`tool`,content:l(a.length>0?a:c?`(see attached image)`:`(no tool output)`),tool_call_id:t.toolCallId};if(n.requiresToolResultName&&t.toolName&&(d.name=t.toolName),i.push(d),n.deferredToolsMode===`kimi`)for(let e of t.addedToolNames??[])o.add(e);if(c&&e.input.includes(`image`))for(let e of t.content)A(e)&&r.push({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})}if(a=u-1,r.length>0?(n.requiresAssistantAfterToolResult&&i.push({role:`assistant`,content:`I have processed the tool results.`}),i.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...r]}),c=`user`):c=`toolResult`,o.size>0){let e=E(t.tools,o);if(e.length>0){let t={role:`system`,tools:J(e,n)};i.push(t)}}continue}c=o.role}return i}function J(e,t){return e.map(e=>{let n=d(e,t.supportsOpenAIGrammarTools);if(n)return{type:`custom`,custom:{name:e.name,description:e.description,format:{type:`grammar`,grammar:{syntax:n.format,definition:n.definition}}}};let r=u(e,t.supportsStrictMode!==!1);return{type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters,...t.supportsStrictMode!==!1&&{strict:r??!1}}}})}function Y(e,t){let r=e.prompt_tokens||0,i=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??0,a=e.prompt_tokens_details?.cache_write_tokens||0,o=Math.max(0,r-i-a),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:i,cacheWrite:a,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:o+s+i+a,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return n(t,c),c}function X(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function Z(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||t===`zai-coding-cn`||n.includes(`api.z.ai`)||n.includes(`open.bigmodel.cn`),i=t===`together`||n.includes(`api.together.ai`)||n.includes(`api.together.xyz`),a=t===`moonshotai`||t===`moonshotai-cn`||n.includes(`api.moonshot.`),o=t===`openrouter`||n.includes(`openrouter.ai`),s=t===`cloudflare-workers-ai`||n.includes(`api.cloudflare.com`),c=t===`cloudflare-ai-gateway`||n.includes(`gateway.ai.cloudflare.com`),l=t===`nvidia`||n.includes(`integrate.api.nvidia.com`),u=t===`ant-ling`||n.includes(`api.ant-ling.com`),d=l||t===`cerebras`||n.includes(`cerebras.ai`)||t===`xai`||n.includes(`api.x.ai`)||i||n.includes(`chutes.ai`)||n.includes(`deepseek.com`)||r||a||t===`opencode`||n.includes(`opencode.ai`)||s||c||u,f=n.includes(`chutes.ai`)||a||c||i||l||u,p=t===`xai`||n.includes(`api.x.ai`),m=t===`deepseek`||n.includes(`deepseek.com`),h=o&&(e.id.startsWith(`anthropic/`)||e.id.startsWith(`openai/`)),g=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!d,supportsDeveloperRole:h||!d&&!o,supportsReasoningEffort:!p&&!r&&!a&&!i&&!c&&!l&&!u,supportsUsageInStreaming:!0,maxTokensField:f?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:m,thinkingFormat:m?`deepseek`:r?`zai`:i?`together`:u?`ant-ling`:o?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},zaiToolStream:!1,supportsStrictMode:!a&&!i&&!c&&!l,supportsOpenAIGrammarTools:!1,cacheControlFormat:g,sendSessionAffinityHeaders:!1,deferredToolsMode:void 0,sessionAffinityFormat:o?`openrouter`:`openai`,supportsLongCacheRetention:!(i||s||c||l||u)}}function Q(e){let t=Z(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??t.chatTemplateKwargs,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??t.supportsOpenAIGrammarTools,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,deferredToolsMode:e.compat.deferredToolsMode??t.deferredToolsMode,sessionAffinityFormat:e.compat.sessionAffinityFormat??t.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention}:t}export{q as convertMessages,N as stream,P as streamSimple};