sliccy 3.0.3 → 3.2.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 (192) hide show
  1. package/README.md +1 -1
  2. package/dist/ui/assets/__vite-browser-external-B0Aozsa-.js +1 -0
  3. package/dist/ui/assets/adobe-CQkUqrZB.js +1 -0
  4. package/dist/ui/assets/adobe-TpBzqWxv.js +2 -0
  5. package/dist/ui/assets/agent-bridge-CUrfnLhB.js +1 -0
  6. package/dist/ui/assets/{agent-message-to-chat-BCltq66T.js → agent-message-to-chat-7ySe6LOC.js} +1 -1
  7. package/dist/ui/assets/{anthropic-CW4Fql_O.js → anthropic-BazfeP88.js} +2 -2
  8. package/dist/ui/assets/anthropic-DrIv-Sj8.js +39 -0
  9. package/dist/ui/assets/azure-openai-D57g94Od.js +1 -0
  10. package/dist/ui/assets/azure-openai-responses-DGiPDuLb.js +1 -0
  11. package/dist/ui/assets/azure-openai-responses-DaFIsbip.js +1 -0
  12. package/dist/ui/assets/azure-openai-syGxMed8.js +1 -0
  13. package/dist/ui/assets/{bsh-watchdog-0KPLx0BS.js → bsh-watchdog-Cy1Phycv.js} +1 -1
  14. package/dist/ui/assets/{cdp-CDF6RoDF.js → cdp-C7-GqDX7.js} +4 -4
  15. package/dist/ui/assets/cost-command-D4966sTV.js +1 -0
  16. package/dist/ui/assets/{dist-N8xNrrAa.js → dist-BTGs16AV.js} +1 -1
  17. package/dist/ui/assets/{dist-C867mOPm.js → dist-BcBxL8nL.js} +1 -1
  18. package/dist/ui/assets/{dist-VRuvLOER.js → dist-Bgcuvc8h.js} +1 -1
  19. package/dist/ui/assets/{dist-Dv2Nk_Uq.js → dist-EkY3RL7q.js} +1 -1
  20. package/dist/ui/assets/{dist-BT9E_vUE.js → dist-cK1g1pHF.js} +1 -1
  21. package/dist/ui/assets/{es-CbCfYSmQ.js → es-BBFipyo7.js} +5 -5
  22. package/dist/ui/assets/follower-sprinkle-bridge-Bvk6d5Lt.js +1 -0
  23. package/dist/ui/assets/github-C7iB6IW8.js +1 -0
  24. package/dist/ui/assets/github-D9o07OM2.js +2 -0
  25. package/dist/ui/assets/google-BViJaPNs.js +1 -0
  26. package/dist/ui/assets/google-BqPFk_Hy.js +1 -0
  27. package/dist/ui/assets/{google-shared-D_qkojxq.js → google-shared-BSWPDQyC.js} +3 -3
  28. package/dist/ui/assets/google-shared-DB5TYWXI.js +11 -0
  29. package/dist/ui/assets/google-vertex-BxSo3Ndm.js +1 -0
  30. package/dist/ui/assets/google-vertex-CezozIAv.js +1 -0
  31. package/dist/ui/assets/index-A_yObWaU.js +1574 -0
  32. package/dist/ui/assets/index-BeHZmqLr.css +1 -0
  33. package/dist/ui/assets/intercepted-oauth-D-GrdXf5.js +1 -0
  34. package/dist/ui/assets/kernel-worker-Du6Tb6XA.js +7651 -0
  35. package/dist/ui/assets/{local-llm-BOxOEv5D.js → local-llm-KIzd2XHf.js} +2 -2
  36. package/dist/ui/assets/magick-wasm-DfEA4h23.js +1 -0
  37. package/dist/ui/assets/{mistral-BGhArSbR.js → mistral-B9W99mq4.js} +2 -2
  38. package/dist/ui/assets/{mistral-BjvHW1zm.js → mistral-DdhVmVmD.js} +2 -2
  39. package/dist/ui/assets/{nuke-command-D5unBYdb.js → nuke-command-Njj8xVqm.js} +1 -1
  40. package/dist/ui/assets/oauth-bootstrap-BIoZ-1iT.js +1 -0
  41. package/dist/ui/assets/oauth-service-DEV-lUfQ.js +1 -0
  42. package/dist/ui/assets/oauth-service-DvOjqu8g.js +1 -0
  43. package/dist/ui/assets/offscreen-client-BQT-86bJ.js +1 -0
  44. package/dist/ui/assets/onboarding-orchestrator-DG6gLseB.js +1 -0
  45. package/dist/ui/assets/openai-codex-responses-BEGQfxLc.js +7 -0
  46. package/dist/ui/assets/openai-codex-responses-DB3Vu7ed.js +7 -0
  47. package/dist/ui/assets/openai-completions-CGQBWCgH.js +5 -0
  48. package/dist/ui/assets/openai-responses-CtvH1M3o.js +1 -0
  49. package/dist/ui/assets/openai-responses-DN7LxPQE.js +1 -0
  50. package/dist/ui/assets/{openai-responses-shared-iv5WheAz.js → openai-responses-shared-CSGV3fZY.js} +3 -3
  51. package/dist/ui/assets/{openai-responses-shared-iYgA7Khl.js → openai-responses-shared-Dgs-mRZN.js} +4 -4
  52. package/dist/ui/assets/panel-rpc-handlers-CvD_7V3n.js +1 -0
  53. package/dist/ui/assets/{py-realm-worker-vbqFsiux.js → py-realm-worker-zrXeREDr.js} +1 -1
  54. package/dist/ui/assets/pyodide-Bv1KSh-_.js +3 -0
  55. package/dist/ui/assets/pyodide-DP-fllM-.js +3 -0
  56. package/dist/ui/assets/remote-terminal-view-DbubM0iY.js +6 -0
  57. package/dist/ui/assets/secret-env-YKWt497t.js +1 -0
  58. package/dist/ui/assets/slicc-editor-DYDRVURI.js +12 -0
  59. package/dist/ui/assets/{spawn-DfNLdcnW.js → spawn-9oH05Sa3.js} +1 -1
  60. package/dist/ui/assets/{sql-wasm-DZVUCGLK.js → sql-wasm-CpKN22NN.js} +2 -2
  61. package/dist/ui/assets/upgrade-detection-oR3blKyL.js +1 -0
  62. package/dist/ui/assets/xai-grok-CNhK84Kt.js +1 -0
  63. package/dist/ui/assets/xai-grok-qxlQfVDb.js +1 -0
  64. package/dist/ui/assets/{xai-grok-sanitize-DTcvIA0E.js → xai-grok-sanitize-BeI8rdV5.js} +1 -1
  65. package/dist/ui/assets/{xai-grok-sanitize-DsBfxZb8.js → xai-grok-sanitize-CiOn_xsO.js} +1 -1
  66. package/dist/ui/electron-overlay-entry.js +7 -7
  67. package/dist/ui/index.html +2 -21
  68. package/dist/ui/packages/webapp/index.html +2 -21
  69. package/package.json +3 -3
  70. package/dist/ui/assets/__vite-browser-external-CTFk2Lkt.js +0 -1
  71. package/dist/ui/assets/__vite-browser-external-CdaqDer8.js +0 -1
  72. package/dist/ui/assets/adobe-B80c3min.js +0 -2
  73. package/dist/ui/assets/adobe-CAH_NOLf.js +0 -1
  74. package/dist/ui/assets/agent-bridge-gA34hm1Z.js +0 -1
  75. package/dist/ui/assets/anthropic-4ASJTRhO.js +0 -39
  76. package/dist/ui/assets/azure-openai-B1aRebkL.js +0 -1
  77. package/dist/ui/assets/azure-openai-responses-C_KSa6jj.js +0 -1
  78. package/dist/ui/assets/azure-openai-responses-Ci2gkluO.js +0 -1
  79. package/dist/ui/assets/azure-openai-uOck_Bf9.js +0 -1
  80. package/dist/ui/assets/backend-local-BTd37iLF.js +0 -9
  81. package/dist/ui/assets/backend-local-CfhYopTE.js +0 -9
  82. package/dist/ui/assets/bedrock-camp-Bds6qFqf.js +0 -4
  83. package/dist/ui/assets/bedrock-camp-uPFt7YMZ.js +0 -5
  84. package/dist/ui/assets/chunk-Cn1BcAw8.js +0 -1
  85. package/dist/ui/assets/chunk-jRWAZmH_.js +0 -1
  86. package/dist/ui/assets/cost-command-Bc9LjZfl.js +0 -1
  87. package/dist/ui/assets/db-DPvmo9md.js +0 -1
  88. package/dist/ui/assets/diagnostics-Bab61WyO.js +0 -1
  89. package/dist/ui/assets/diagnostics-C5z6rwkV.js +0 -1
  90. package/dist/ui/assets/env-api-keys-BoL4zxcb.js +0 -1
  91. package/dist/ui/assets/env-api-keys-DEKGEdJy.js +0 -1
  92. package/dist/ui/assets/follower-sprinkle-bridge-D98CB4QW.js +0 -1
  93. package/dist/ui/assets/fs-Cf-IdW2x.js +0 -3
  94. package/dist/ui/assets/fs-bDRkGfEW.js +0 -4
  95. package/dist/ui/assets/git-config-CxvDN7N3.js +0 -7
  96. package/dist/ui/assets/github-CH73eM0a.js +0 -1
  97. package/dist/ui/assets/github-CXycVfPa.js +0 -2
  98. package/dist/ui/assets/github-copilot-headers-DPO4cOSI.js +0 -1
  99. package/dist/ui/assets/google-CBK_Mvyz.js +0 -1
  100. package/dist/ui/assets/google-gejI0Xd8.js +0 -1
  101. package/dist/ui/assets/google-shared-BB2MKu9Q.js +0 -11
  102. package/dist/ui/assets/google-vertex-tM5T-lH5.js +0 -1
  103. package/dist/ui/assets/google-vertex-wc4xtIz9.js +0 -1
  104. package/dist/ui/assets/headers-CGhBAvcc.js +0 -1
  105. package/dist/ui/assets/index-Bk_LVMna.js +0 -1422
  106. package/dist/ui/assets/index-eWuuouO-.css +0 -1
  107. package/dist/ui/assets/intercepted-oauth-CnYe4Pun.js +0 -1
  108. package/dist/ui/assets/json-parse-CKelIhmU.js +0 -3
  109. package/dist/ui/assets/json-parse-Cu2r6BfV.js +0 -3
  110. package/dist/ui/assets/kernel-worker-DgOE7S84.js +0 -7546
  111. package/dist/ui/assets/local-llm-xpXqSazD.js +0 -2
  112. package/dist/ui/assets/logger-B-No_qN_.js +0 -1
  113. package/dist/ui/assets/logger-BHrAkMIS.js +0 -1
  114. package/dist/ui/assets/magick-wasm-BMFWa7e1.js +0 -1
  115. package/dist/ui/assets/magick-wasm-D4Na_fL8.js +0 -1
  116. package/dist/ui/assets/mime-types-4JXpZe6p.js +0 -1
  117. package/dist/ui/assets/mime-types-DL940yDZ.js +0 -1
  118. package/dist/ui/assets/mount-B-d5niFK.js +0 -2
  119. package/dist/ui/assets/mount-BF7L2l0E.js +0 -1
  120. package/dist/ui/assets/mount-id-Ccy4_G8i.js +0 -1
  121. package/dist/ui/assets/mount-picker-popup-ys6_YNH0.js +0 -1
  122. package/dist/ui/assets/mount-table-store-BDnU4NqG.js +0 -1
  123. package/dist/ui/assets/oauth-bootstrap-Dwo48sgL.js +0 -1
  124. package/dist/ui/assets/oauth-service--O2P_cH3.js +0 -1
  125. package/dist/ui/assets/oauth-service-BXo87SGy.js +0 -1
  126. package/dist/ui/assets/offscreen-client-CogsU9xP.js +0 -1
  127. package/dist/ui/assets/onboarding-orchestrator-DkKjSNro.js +0 -1
  128. package/dist/ui/assets/openai-CQMTwQw3.js +0 -16
  129. package/dist/ui/assets/openai-codex-responses-BH7I3fcD.js +0 -7
  130. package/dist/ui/assets/openai-codex-responses-Box9MCzN.js +0 -7
  131. package/dist/ui/assets/openai-completions-BnShqSeR.js +0 -5
  132. package/dist/ui/assets/openai-completions-DmV2esrh.js +0 -5
  133. package/dist/ui/assets/openai-responses-Cp1E557G.js +0 -1
  134. package/dist/ui/assets/openai-responses-DOCxF9QM.js +0 -1
  135. package/dist/ui/assets/panel-rpc-DMFq2vU_.js +0 -1
  136. package/dist/ui/assets/panel-rpc-handlers-CKHTPsah.js +0 -1
  137. package/dist/ui/assets/panel-rpc-uLhnFoXD.js +0 -1
  138. package/dist/ui/assets/path-utils-C99GOg2c.js +0 -1
  139. package/dist/ui/assets/path-utils-CgbXfwyO.js +0 -1
  140. package/dist/ui/assets/preload-helper-ca-nBW7U.js +0 -1
  141. package/dist/ui/assets/provider-settings-BntkzQDt.js +0 -63
  142. package/dist/ui/assets/provider-settings-w0pFif0W.js +0 -28
  143. package/dist/ui/assets/providers-CTrcq-XG.js +0 -1
  144. package/dist/ui/assets/pyodide-DOGWuEal.js +0 -3
  145. package/dist/ui/assets/pyodide-DhfjhWo1.js +0 -3
  146. package/dist/ui/assets/remote-cache-Cd8CL8Mo.js +0 -1
  147. package/dist/ui/assets/remote-terminal-view-BD1tHNzj.js +0 -6
  148. package/dist/ui/assets/sanitize-unicode-DFrWoF2t.js +0 -1
  149. package/dist/ui/assets/secret-env-LcaaxgBy.js +0 -1
  150. package/dist/ui/assets/shared-AafAvJaI.js +0 -1
  151. package/dist/ui/assets/simple-options-CVJdKrCb.js +0 -1
  152. package/dist/ui/assets/simple-options-D8vGmEnp.js +0 -1
  153. package/dist/ui/assets/slicc-editor-CFqadznu.js +0 -12
  154. package/dist/ui/assets/sprinkle-renderer-sJJO5bqF.js +0 -112
  155. package/dist/ui/assets/telemetry-D728iVf5.js +0 -1
  156. package/dist/ui/assets/tool-ui-D9h6SJkp.js +0 -1
  157. package/dist/ui/assets/tool-ui-DaAXBPJY.js +0 -1
  158. package/dist/ui/assets/tray-follower-status-hrOEFANe.js +0 -1
  159. package/dist/ui/assets/upgrade-detection-B25rC3uA.js +0 -1
  160. package/dist/ui/assets/xai-grok-DTAnFIoT.js +0 -1
  161. package/dist/ui/assets/xai-grok-ZZg_1Erw.js +0 -1
  162. /package/dist/ui/assets/{active-transport-DjJ32qlA.js → active-transport-CfU1UxY6.js} +0 -0
  163. /package/dist/ui/assets/{active-transport-lYMG0Gv5.js → active-transport-DeSPCdTV.js} +0 -0
  164. /package/dist/ui/assets/{addon-fit-CBYO9uVb.js → addon-fit-BDUxDgg1.js} +0 -0
  165. /package/dist/ui/assets/{addon-fit-CTgRqR5i.js → addon-fit-Dkm5m5XK.js} +0 -0
  166. /package/dist/ui/assets/{azure-ai-foundry-DtrzZiwo.js → azure-ai-foundry-1pnZpxAJ.js} +0 -0
  167. /package/dist/ui/assets/{azure-ai-foundry--QIByvkN.js → azure-ai-foundry-k_w7vD5C.js} +0 -0
  168. /package/dist/ui/assets/{chat-fixture-t_1Cmb9j.js → chat-fixture-BNN19l1e.js} +0 -0
  169. /package/dist/ui/assets/{dist-B-Md2rjs.js → dist-BNe7ZIzA.js} +0 -0
  170. /package/dist/ui/assets/{dist-BXMOjFxx.js → dist-BYoCEWmq.js} +0 -0
  171. /package/dist/ui/assets/{dist-CZgcx_4U.js → dist-BrjVVq8c.js} +0 -0
  172. /package/dist/ui/assets/{git-config-DIdLP3yo.js → git-config-DFJqG7AS.js} +0 -0
  173. /package/dist/ui/assets/{github-copilot-headers-BKQV7zrp.js → github-copilot-headers-CTUP_cqn.js} +0 -0
  174. /package/dist/ui/assets/{hash-K0cSe8jy.js → hash-B9Dtr1VK.js} +0 -0
  175. /package/dist/ui/assets/{hash-ekRFATsu.js → hash-C3GX0Zuo.js} +0 -0
  176. /package/dist/ui/assets/{headers-C4jF_HTA.js → headers-AeYLn7L4.js} +0 -0
  177. /package/dist/ui/assets/{lick-manager-proxy-D4WRd8z3.js → lick-manager-proxy-DfectiMI.js} +0 -0
  178. /package/dist/ui/assets/{openai-DxnCgV1v.js → openai-Bf1npfRy.js} +0 -0
  179. /package/dist/ui/assets/{page-storage-sync-M2qhyuvc.js → page-storage-sync-BxtXNbwY.js} +0 -0
  180. /package/dist/ui/assets/{pdfjs-Cesr9Csk.js → pdfjs-DDDkZHZ4.js} +0 -0
  181. /package/dist/ui/assets/{rum-C0g6MAOC.js → rum-wVO4iYd-.js} +0 -0
  182. /package/dist/ui/assets/{sanitize-unicode-BA6bNBBh.js → sanitize-unicode-h0KEBmEw.js} +0 -0
  183. /package/dist/ui/assets/{sprinkle-bridge-channel-B_tegUwc.js → sprinkle-bridge-channel-BBxRgvga.js} +0 -0
  184. /package/dist/ui/assets/{sprinkle-bridge-channel-C2blpBXT.js → sprinkle-bridge-channel-no1Jz9ii.js} +0 -0
  185. /package/dist/ui/assets/{sprinkle-proxy-CgcbIA81.js → sprinkle-proxy-rF3NSOGq.js} +0 -0
  186. /package/dist/ui/assets/{src-lJxZtwWF.js → src-BQRb5emh.js} +0 -0
  187. /package/dist/ui/assets/{xai-grok-errors-DGVLpB4k.js → xai-grok-errors-CGcnoVae.js} +0 -0
  188. /package/dist/ui/assets/{xai-grok-errors-B7OqxH_0.js → xai-grok-errors-WbFsMZum.js} +0 -0
  189. /package/dist/ui/assets/{xai-grok-models-DGbQVjGO.js → xai-grok-models-0q2zveAT.js} +0 -0
  190. /package/dist/ui/assets/{xai-grok-models-0CbvNCeN.js → xai-grok-models-cvcIXmNM.js} +0 -0
  191. /package/dist/ui/assets/{xterm-CguO-Jtb.js → xterm-D8ldLLKi.js} +0 -0
  192. /package/dist/ui/assets/{xterm-BcRgm-P0.js → xterm-DhusGoAm.js} +0 -0
@@ -1,2 +0,0 @@
1
- import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./logger-BHrAkMIS.js";import{o as n}from"./provider-settings-BntkzQDt.js";import{m as r}from"./bedrock-camp-uPFt7YMZ.js";import{o as i}from"./simple-options-CVJdKrCb.js";import{n as a,r as o}from"./openai-completions-BnShqSeR.js";var s=e({config:()=>d,detectRuntime:()=>C,discoverModels:()=>S,originOf:()=>b,register:()=>y,verifyConnection:()=>E});const c=t(`local-llm`),l=`local-llm`,u=`${l}-unconfigured`,d={id:l,name:`Local LLM (OpenAI-compatible)`,description:[`Connect to any OpenAI-compatible local model server.`,``,`Common base URLs:`,` • Ollama http://localhost:11434/v1`,` • LM Studio http://localhost:1234/v1`,` • llama.cpp http://localhost:8080/v1`,` • vLLM http://localhost:8000/v1`,` • mlx_lm http://localhost:8080/v1`,` • Jan http://localhost:1337/v1`,``,`Ollama needs OLLAMA_ORIGINS=* (or chrome-extension://*) so the`,`browser can reach it. macOS: launchctl setenv OLLAMA_ORIGINS "*".`].join(`
2
- `),requiresApiKey:!1,optionalApiKey:!0,apiKeyPlaceholder:`Leave empty for local servers, or paste a key for hosted endpoints`,apiKeyEnvVar:`LOCAL_LLM_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`http://localhost:11434/v1`,baseUrlDescription:`Ollama: 11434 • LM Studio: 1234 • llama.cpp/mlx: 8080 • vLLM: 8000 • Jan: 1337. Trailing /v1 required.`,requiresDeployment:!0,deploymentPlaceholder:`llama3.1:8b, qwen2.5-coder:14b`,deploymentDescription:`Comma-separated model IDs from your server. List them with: curl <baseUrl>/models | jq -r .data[].id`,getModelIds:()=>{let e=f(n(l));return e.length===0?[{id:u,name:`Local LLM (set base URL + model IDs in Settings)`,api:`openai`}]:e.map(e=>({id:e,name:e,api:`openai`,input:[`text`],context_window:32e3,max_tokens:4096}))}};function f(e){return e?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]}const p=`${l}-openai`;function m(e){return{...e,api:`openai-completions`}}function h(e){let t=e??{};return!t.apiKey||t.apiKey.length===0?{...t,apiKey:`local`}:t}const g=(e,t,n={})=>e.id===u?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?a(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`),_=(e,t,n)=>e.id===u?v(e,`Local LLM is not configured. Set base URL and model IDs in Settings.`):e.baseUrl?o(m(e),t,h(n)):v(e,`Local LLM base URL is required (e.g. http://localhost:11434/v1).`);function v(e,t){let n=i(),r={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t,timestamp:Date.now()};return queueMicrotask(()=>{n.push({type:`error`,reason:`error`,error:r}),n.end()}),n}function y(){r({api:p,stream:g,streamSimple:_})}function b(e){try{let t=new URL(e);return`${t.protocol}//${t.host}`}catch{return e.replace(/\/v1\/?$/,``).replace(/\/+$/,``)}}function x(e){let t=e.replace(/\/+$/,``);try{let e=new URL(t);if(e.pathname===``||e.pathname===`/`)return`${t}/v1`}catch{}return t}async function S(e,t,n){let r=`${x(e)}/models`,i={Accept:`application/json`};t&&t.length>0&&(i.Authorization=`Bearer ${t}`);let a=await fetch(r,{method:`GET`,headers:i,signal:n});if(!a.ok)throw Error(`GET ${r} -> ${a.status} ${a.statusText}`);let o=await a.json();return Array.isArray(o.data)?o.data.map(e=>e.id??``).filter(e=>e.length>0):[]}async function C(e,t){let n=b(e),r=await T(`${n}/api/version`,t);if(r&&typeof r.version==`string`)return{kind:`ollama`,version:r.version};let i=await T(`${n}/api/v0/models`,t);if(i&&i.object===`list`)return{kind:`lmstudio`};let a=await T(`${n}/props`,t);if(a&&`build_info`in a)return{kind:`llamacpp`,version:a.build_info?.version};let o=w(e);return o===`11434`?{kind:`ollama`}:o===`1234`?{kind:`lmstudio`}:o===`8000`?{kind:`vllm`}:o===`1337`?{kind:`jan`}:{kind:`unknown`}}function w(e){try{return new URL(e).port||null}catch{return null}}async function T(e,t){try{let n=await fetch(e,{method:`GET`,signal:t});return n.ok?await n.json():null}catch{return null}}async function E(e,t,n){let r={kind:`unknown`};try{r=await C(e,n)}catch{}try{let i=await S(e,t,n);return{ok:!0,runtime:r,models:i}}catch(t){let n=t instanceof Error?t.message:String(t),i=D(n,r.kind);return c.warn(`verifyConnection failed`,{baseUrl:e,runtime:r.kind,message:n}),{ok:!1,runtime:r,models:[],error:i}}}function D(e,t){let n=e.toLowerCase();return n.includes(`failed to fetch`)||n.includes(`networkerror`)?t===`ollama`?{kind:`cors`,message:e,hint:'Ollama rejects requests from non-localhost origins by default. Set OLLAMA_ORIGINS=* (or chrome-extension://*) and restart Ollama. macOS: `launchctl setenv OLLAMA_ORIGINS "*"` then quit and relaunch the Ollama app.'}:{kind:`connection`,message:e,hint:`Server unreachable. Check the URL and that the server is running.`}:n.includes(` 401`)||n.includes(` 403`)?{kind:`auth`,message:e,hint:`Server returned an auth error. If your endpoint requires a key, set it in Settings.`}:/-> \d{3} /.test(e)?{kind:`http`,message:e}:{kind:`unknown`,message:e}}export{s as n,d as t};
@@ -1 +0,0 @@
1
- var e={DEBUG:0,INFO:1,WARN:2,ERROR:3},t=e.ERROR,n=10,r=6e4;function i(e,t){let n=e;if(t.length>0)try{n+=` `+JSON.stringify(t)}catch{n+=` [unserializable]`}return n.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,`<id>`).replace(/\b[0-9a-f]{8,}\b/gi,`<hex>`).replace(/\b\d{10,}\b/g,`<ts>`).replace(/\b\d+(\.\d+)?\b/g,`<n>`)}var a=class{entries=[];log(e,t,r,a,o){let s=i(a,o),c=Date.now();this.evict(c);let l=this.entries.find(e=>e.fingerprint===s&&e.level===r);if(l)return l.count++,!1;if(this.entries.length>=n){let e=this.entries.shift();this.flushEntry(e)}return this.entries.push({fingerprint:s,count:0,firstSeen:c,level:r,consoleFn:e,prefix:t,message:a}),!0}flush(){for(let e of this.entries)this.flushEntry(e);this.entries=[]}evict(e){for(;this.entries.length>0&&e-this.entries[0].firstSeen>r;){let e=this.entries.shift();this.flushEntry(e)}}flushEntry(e){e.count>0&&t<=e.level&&e.consoleFn(e.prefix,`(suppressed ${e.count} similar: "${e.message}")`)}};function o(n){let r=`[${n}]`,i=new a;function o(n){return(a,...o)=>{if(t>n)return;let s=n===e.DEBUG?console.debug:n===e.INFO?console.info:n===e.WARN?console.warn:console.error;i.log(s,r,n,a,o)&&s(r,a,...o)}}return{debug:o(e.DEBUG),info:o(e.INFO),warn:o(e.WARN),error:o(e.ERROR)}}export{o as t};
@@ -1 +0,0 @@
1
- const e={DEBUG:0,INFO:1,WARN:2,ERROR:3};let t=e.ERROR;function n(e,t){let n=e;if(t.length>0)try{n+=` `+JSON.stringify(t)}catch{n+=` [unserializable]`}return n.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,`<id>`).replace(/\b[0-9a-f]{8,}\b/gi,`<hex>`).replace(/\b\d{10,}\b/g,`<ts>`).replace(/\b\d+(\.\d+)?\b/g,`<n>`)}var r=class{entries=[];log(e,t,r,i,a){let o=n(i,a),s=Date.now();this.evict(s);let c=this.entries.find(e=>e.fingerprint===o&&e.level===r);if(c)return c.count++,!1;if(this.entries.length>=10){let e=this.entries.shift();this.flushEntry(e)}return this.entries.push({fingerprint:o,count:0,firstSeen:s,level:r,consoleFn:e,prefix:t,message:i}),!0}flush(){for(let e of this.entries)this.flushEntry(e);this.entries=[]}evict(e){for(;this.entries.length>0&&e-this.entries[0].firstSeen>6e4;){let e=this.entries.shift();this.flushEntry(e)}}flushEntry(e){e.count>0&&t<=e.level&&e.consoleFn(e.prefix,`(suppressed ${e.count} similar: "${e.message}")`)}};function i(n){let i=`[${n}]`,a=new r;function o(n){return(r,...o)=>{if(t>n)return;let s=n===e.DEBUG?console.debug:n===e.INFO?console.info:n===e.WARN?console.warn:console.error;a.log(s,i,n,r,o)&&s(i,r,...o)}}return{debug:o(e.DEBUG),info:o(e.INFO),warn:o(e.WARN),error:o(e.ERROR)}}export{i as t};
@@ -1 +0,0 @@
1
- import{o as e,r as t}from"./chunk-jRWAZmH_.js";import{n}from"./path-utils-CgbXfwyO.js";import{t as r}from"./mime-types-4JXpZe6p.js";function i(e,t){if(typeof t!=`string`||!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(t))throw Error(`${e} must use an exact semver version in package.json`);return t}const a=`v20.0.0-js-shim`;let o=null;function s(e){let t=e.length>1&&e.endsWith(`/`)?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function c(e){let t=e.lastIndexOf(`/`);return t<=0?`/`:e.slice(0,t)}function l(e,t){return e===`/`?`/${t}`:`${e}/${t}`}function u(e){if(/^(https?:\/\/|about:|file:|chrome:)/i.test(e))return!0;try{return new URL(e).protocol.length>0}catch{return!1}}function d(e,t){return e===`/`?t.startsWith(`/`):t===e||t.startsWith(`${e}/`)}function f(e){return Array.from(e).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function p(e){return e==null?``:e instanceof Uint8Array?`x'${f(e)}'`:String(e)}function m(e){return r(e)}function h(e){let t=typeof chrome<`u`&&!!chrome?.runtime?.id,n=`/preview${e}`;return t?chrome.runtime.getURL(n):`${typeof window<`u`&&window.location?.origin?window.location.origin:`http://localhost:5710`}${n}`}function g(e){return e.length===0||e.startsWith(`/`)?!1:!e.split(`/`).some(e=>e===`..`)}function _(e,t){return n(`${e}/${t}`)}function v(e,t){let n=import.meta.resolve;if(typeof n==`function`)try{return new URL(`./`,n(e))}catch{}return new URL(t,import.meta.url)}function y(){return typeof process<`u`&&!!process.versions?.node}function b(){return typeof chrome<`u`&&!!chrome?.runtime?.id}async function x(){return o||=(async()=>{let t=(await import(`./sql-wasm-DZVUCGLK.js`).then(t=>e(t.default,1))).default,n=y()?v(`sql.js/dist/sql-wasm.js`,`../../../../../node_modules/sql.js/dist/`).toString():`https://sql.js.org/dist/`;return t({locateFile:e=>`${n}${e}`})})(),o}var S=t({MAGICK_WASM_CDN:()=>T,MIME_TO_MAGICK_FORMAT:()=>C,getMagick:()=>D,isExtension:()=>E});const C={"image/jpeg":`JPEG`,"image/png":`PNG`,"image/gif":`GIF`,"image/webp":`WEBP`,"image/bmp":`BMP`,"image/tiff":`TIFF`,"image/avif":`AVIF`};let w=null;const T=`https://cdn.jsdelivr.net/npm/@imagemagick/magick-wasm@0.0.38/dist/`,E=typeof chrome<`u`&&!!chrome?.runtime?.id;async function D(){return w||=(async()=>{try{let e=await import(`./dist-BXMOjFxx.js`);if(E){let t=chrome.runtime.getURL(`magick.wasm`),n=await fetch(t);if(!n.ok)throw Error(`Failed to fetch magick.wasm: ${n.status} ${n.statusText}`);let r=new Uint8Array(await n.arrayBuffer());await e.initializeImageMagick(r)}else{let t=y()?new URL(`/assets/index-BeMnZBAU.js`,``+import.meta.url).toString():T,n=new URL(`magick.wasm`,t);await e.initializeImageMagick(n)}return e}catch(e){throw w=null,e}})(),w}export{_,m as a,p as c,u as d,y as f,i as g,v as h,s as i,x as l,l as m,S as n,c as o,g as p,a as r,d as s,D as t,b as u,h as v};
@@ -1 +0,0 @@
1
- import{t as e}from"./preload-helper-ca-nBW7U.js";import{t}from"./shared-AafAvJaI.js";var n={"image/jpeg":`JPEG`,"image/png":`PNG`,"image/gif":`GIF`,"image/webp":`WEBP`,"image/bmp":`BMP`,"image/tiff":`TIFF`,"image/avif":`AVIF`},r=null,i=`https://cdn.jsdelivr.net/npm/@imagemagick/magick-wasm@0.0.38/dist/`,a=typeof chrome<`u`&&!!chrome?.runtime?.id;async function o(){return r||=(async()=>{try{let n=await e(()=>import(`./dist-CZgcx_4U.js`),[]);if(a){let e=chrome.runtime.getURL(`magick.wasm`),t=await fetch(e);if(!t.ok)throw Error(`Failed to fetch magick.wasm: ${t.status} ${t.statusText}`);let r=new Uint8Array(await t.arrayBuffer());await n.initializeImageMagick(r)}else{let e=t()?new URL(`/assets/index-BeMnZBAU.js`,``+import.meta.url).toString():i,r=new URL(`magick.wasm`,e);await n.initializeImageMagick(r)}return n}catch(e){throw r=null,e}})(),r}export{i as MAGICK_WASM_CDN,n as MIME_TO_MAGICK_FORMAT,o as getMagick,a as isExtension};
@@ -1 +0,0 @@
1
- const e={html:`text/html`,htm:`text/html`,css:`text/css`,js:`application/javascript`,mjs:`application/javascript`,json:`application/json`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,apng:`image/apng`,bmp:`image/bmp`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,mp3:`audio/mpeg`,mp4:`video/mp4`,webm:`video/webm`,mov:`video/quicktime`,m4v:`video/x-m4v`,ogv:`video/ogg`,pdf:`application/pdf`,txt:`text/plain`,xml:`application/xml`,wasm:`application/wasm`};function t(t){return e[t.split(`.`).pop()?.toLowerCase()??``]??`application/octet-stream`}function n(e){return e.startsWith(`image/`)}function r(e){return e.startsWith(`video/`)}function i(e){return n(e)||r(e)}export{i as n,t};
@@ -1 +0,0 @@
1
- var e={html:`text/html`,htm:`text/html`,css:`text/css`,js:`application/javascript`,mjs:`application/javascript`,json:`application/json`,svg:`image/svg+xml`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,avif:`image/avif`,apng:`image/apng`,bmp:`image/bmp`,ico:`image/x-icon`,woff:`font/woff`,woff2:`font/woff2`,ttf:`font/ttf`,mp3:`audio/mpeg`,mp4:`video/mp4`,webm:`video/webm`,mov:`video/quicktime`,m4v:`video/x-m4v`,ogv:`video/ogg`,pdf:`application/pdf`,txt:`text/plain`,xml:`application/xml`,wasm:`application/wasm`};function t(t){return e[t.split(`.`).pop()?.toLowerCase()??``]??`application/octet-stream`}function n(e){return e.startsWith(`image/`)}function r(e){return e.startsWith(`video/`)}function i(e){return n(e)||r(e)}function a(e){return i(t(e))}export{a as n,t};
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/provider-settings-w0pFif0W.js","assets/chunk-jRWAZmH_.js","assets/preload-helper-ca-nBW7U.js","assets/bedrock-camp-Bds6qFqf.js","assets/env-api-keys-BoL4zxcb.js","assets/simple-options-D8vGmEnp.js","assets/json-parse-Cu2r6BfV.js","assets/tray-follower-status-hrOEFANe.js","assets/logger-B-No_qN_.js","assets/tool-ui-DaAXBPJY.js","assets/telemetry-D728iVf5.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./mime-types-DL940yDZ.js";import{t as n}from"./preload-helper-ca-nBW7U.js";import{r}from"./backend-local-CfhYopTE.js";var i=`slicc-mount-cache`,a=`listings`,o=`bodies`,s=class{mountId;ttlMs;dbName;dbPromise=null;constructor(e){this.mountId=e.mountId,this.ttlMs=e.ttlMs,this.dbName=e.dbName??i}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(a)||e.createObjectStore(a),e.objectStoreNames.contains(o)||e.createObjectStore(o)},n.onsuccess=()=>e(n.result),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(a,`readonly`).objectStore(a).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 o=n.transaction(a,`readwrite`),s={entries:t,cachedAt:Date.now()};o.objectStore(a).put(s,this.key(e)),o.oncomplete=()=>r(),o.onerror=()=>i(o.error)})}async invalidateListing(e){let t=await this.openDb();return new Promise((n,r)=>{let i=t.transaction(a,`readwrite`);i.objectStore(a).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(o,`readonly`).objectStore(o).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,o,this.key(e),i)}catch(t){if(t instanceof DOMException&&t.name===`QuotaExceededError`){await this.evictLru(.25);try{await this.txPut(r,o,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(o,`readwrite`);i.objectStore(o).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(a),n(o)])}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(o,`readonly`).objectStore(o),a=[],s=i.openCursor();s.onsuccess=()=>{let t=s.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()},s.onerror=()=>r(s.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(o,`readwrite`),i=r.objectStore(o);for(let{key:e}of a)i.delete(e);r.oncomplete=()=>e(),r.onerror=()=>n(r.error)})}},c=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function l(){let{getAccounts:e}=await n(async()=>{let{getAccounts:e}=await import(`./provider-settings-w0pFif0W.js`).then(e=>e.h);return{getAccounts:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10])),t=e().find(e=>e.providerId===`adobe`);if(!t||!t.accessToken)throw new c(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}function u(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 d=25*1024*1024,f=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=u(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??d,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new r(`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 i={};n&&(i[`if-none-match`]=n.etag);let a=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(t),headers:i});if(a.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(a.status===404)throw await this.cache.invalidateBody(t),new r(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new r(`EACCES`,`s3 access denied`,e);if(a.status>=400)throw new r(`EIO`,`s3 readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,t){this.assertOpen(e);let n=this.toMountRelative(e);if(t.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=await this.cache.getBody(n),a={"content-type":`application/octet-stream`,"content-length":String(t.byteLength)};i?a[`if-match`]=i.etag:a[`if-none-match`]=`*`;let o=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:a,body:t}),s,c=1;try{s=await o()}catch{c=2,s=await o()}if(s.status===412){if(c===2){let i=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(i.status>=400)throw new r(`EIO`,`s3 reconcile HEAD failed: ${i.status}`,e);let a=i.headers.get(`etag`)??``;await this.cache.putBody(n,t,a);let o=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(n);try{await this.readFile(e)}catch{}throw new r(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new r(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new r(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(n,t,l);let u=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],t;do{let n={"list-type":`2`};this.parsed.prefix&&(n.prefix=`${this.parsed.prefix}/`),t&&(n[`continuation-token`]=t);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:n});if(i.status>=400)throw new r(`EIO`,`s3 list failed: ${i.status}`,`/`);let a=await i.text(),o=this.parseListingXml(a);e.push(...o.contents),t=o.nextContinuationToken}while(t);return e}parseListingXml(e){let t=[];for(let n of e.matchAll(/<Contents>([\s\S]*?)<\/Contents>/g)){let e=n[1],r=e.match(/<Key>([^<]+)<\/Key>/)?.[1]??``,i=e.match(/<ETag>([^<]+)<\/ETag>/)?.[1]??``,a=e.match(/<Size>([^<]+)<\/Size>/)?.[1]??`0`,o=e.match(/<LastModified>([^<]+)<\/LastModified>/)?.[1]??``;t.push({key:r,etag:i,size:Number(a),lastModified:o?Date.parse(o):0})}return{contents:t,nextContinuationToken:e.match(/<IsTruncated>([^<]+)<\/IsTruncated>/)?.[1]===`true`?e.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/)?.[1]:void 0}}async readDir(e){this.assertOpen(e);let t=this.toMountRelative(e).replace(/\/+$/,``),n=await this.cache.getListing(t);if(n&&!this.cache.isStale(n.cachedAt))return n.entries;let r=await this.listObjectsV2(),i=this.groupByDir(r);for(let[e,t]of i)await this.cache.putListing(e,t);return i.get(t)??[]}groupByDir(e){let t=new Map,n=e=>(t.has(e)||t.set(e,[]),t.get(e));n(``);for(let t of e){let e=this.toMountRelativeKey(t.key).split(`/`),r=e.pop();n(e.join(`/`)).push({name:r,kind:`file`,size:t.size,etag:t.etag,lastModified:t.lastModified});let i=``;for(let t of e){let e=i;i=i?`${i}/${t}`:t;let r=n(e);r.find(e=>e.name===t&&e.kind===`directory`)||r.push({name:t,kind:`directory`}),n(i)}}return t}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.body.byteLength,mtime:n.cachedAt,etag:n.etag};let i=t.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===a);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new r(`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 r(`ENOENT`,`no such file or directory`,e)}throw new r(`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 r(`EINVAL`,`recursive remove not yet supported on S3`,e);let i=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(n)});if(i.status===404)throw new r(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new r(`EACCES`,`s3 delete denied`,e);if(i.status>=400)throw new r(`EIO`,`s3 delete failed: ${i.status}`,e);await this.cache.invalidateBody(n);let a=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function p(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 m(e){return e.split(`/`).pop()||`data`}function h(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 g=5*1024*1024,_=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=h(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??g,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new r(`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 i={};n&&(i[`if-none-match`]=n.etag);let a=await this.transport({method:`GET`,path:this.toSourcePath(t),headers:i});if(a.status===304&&n)return await this.cache.putBody(t,n.body,n.etag),n.body;if(a.status===404)throw await this.cache.invalidateBody(t),new r(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new r(`EACCES`,`da access denied`,e);if(a.status>=400)throw new r(`EIO`,`da readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(t,c,l),c}async writeFile(e,n){if(this.assertOpen(e),n.byteLength>this.maxBodyBytes)throw new r(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=this.toMountRelative(e),a=await this.cache.getBody(i),o=p(m(e),t(e),n),s={"content-type":o.contentType,"content-length":String(o.body.byteLength)};a&&a.etag?s[`if-match`]=a.etag:a||(s[`if-none-match`]=`*`);let c=()=>this.transport({method:`POST`,path:this.toSourcePath(i),headers:s,body:o.body}),l,u=1;try{l=await c()}catch{u=2,l=await c()}if(l.status===412){if(u===2){let t=await this.transport({method:`HEAD`,path:this.toSourcePath(i)});if(t.status>=400)throw new r(`EIO`,`da reconcile HEAD failed: ${t.status}`,e);let a=t.headers.get(`etag`)??``;await this.cache.putBody(i,n,a);let o=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(i);try{await this.readFile(e)}catch{}throw new r(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(l.status===401||l.status===403)throw new r(`EACCES`,`da write denied`,e);if(l.status>=400)throw new r(`EIO`,`da writeFile failed: ${l.status}`,e);let d=l.headers.get(`etag`)??``;await this.cache.putBody(i,n,d);let f=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(f)}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 i=await this.transport({method:`GET`,path:this.toListPath(t)});if(i.status===404)throw new r(`ENOENT`,`no such directory`,e);if(i.status>=400)throw new r(`EIO`,`da list failed: ${i.status}`,e);let a=(await i.json()).map(e=>e.ext?{name:`${e.name}.${e.ext}`,kind:`file`,etag:e.etag,lastModified:e.lastModified}:{name:e.name,kind:`directory`,lastModified:e.lastModified});return await this.cache.putListing(t,a),a}async stat(e){this.assertOpen(e);let t=this.toMountRelative(e),n=await this.cache.getBody(t);if(n)return{kind:`file`,size:n.size,mtime:n.cachedAt,etag:n.etag};let i=t.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let t=s.entries.find(e=>e.name===a);if(t?.kind===`file`&&t.size!==void 0)return{kind:`file`,size:t.size,mtime:t.lastModified??s.cachedAt,etag:t.etag??``};if(t?.kind===`directory`)return{kind:`directory`,size:0,mtime:t.lastModified??s.cachedAt};if(!t)throw new r(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(t)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===a&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(o,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let n=await this.cache.getListing(t);if(n)return{kind:`directory`,size:0,mtime:n.cachedAt};throw new r(`ENOENT`,`no such file or directory`,e)}throw new r(`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 r(`ENOENT`,`no such file`,e);if(n.status===401||n.status===403)throw new r(`EACCES`,`da delete denied`,e);if(n.status>=400)throw new r(`EIO`,`da delete failed: ${n.status}`,e);await this.cache.invalidateBody(t);let i=t.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{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}`});continue}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});let i=await this.cache.getBody(n);i?r.etag&&i.etag!==r.etag?(await this.cache.invalidateBody(n),t.changed.push(n)):t.unchanged++:t.added.push(n)}else{a.push({name:r.name,kind:`directory`});let t=e?`${e}/${r.name}`:r.name;n.push(t)}await this.cache.putListing(e,a)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}if(e?.bodies)for(let e of t.changed)try{await this.readFile(e)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}return t}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 v(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function y(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function b(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}var x=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),S=new Set([101,103,204,205,304]);function C(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new r(`EACCES`,e.error):e.errorCode===`invalid_request`?new r(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||x.has(String(e.errorCode))?new r(`EIO`,e.error):new r(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let t;try{t=y(e.bodyBase64)}catch(e){throw new r(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let n=S.has(e.status)?null:t;return new Response(n,{status:e.status,headers:new Headers(e.headers)})}async function w(e,t){let n;try{n=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t)})}catch(e){throw new r(`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 r(`EIO`,`mount transport: response is not a JSON envelope (status ${n.status}): ${e instanceof Error?e.message:String(e)}`)}}async function T(e,t){try{return await chrome.runtime.sendMessage({type:e,envelope:t})}catch(e){throw new r(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}function E(e){return async t=>{let n={profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?b(t.body):void 0};return C(v()?await T(`mount.s3-sign-and-forward`,n):await w(`/api/s3-sign-and-forward`,n))}}function D(e){let t=e?.getImsToken??(async()=>(await l()).getBearerToken());return async e=>{let n;try{n=await t()}catch(e){throw new r(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}let i={imsToken:n,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?b(e.body):void 0};return C(v()?await T(`mount.da-sign-and-forward`,i):await w(`/api/da-sign-and-forward`,i))}}var O=e({DaMountBackend:()=>_,RemoteMountCache:()=>s,S3MountBackend:()=>f,makeSignedFetchDa:()=>D,makeSignedFetchS3:()=>E});export{f as a,_ as i,D as n,s as o,E as r,O as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./chunk-jRWAZmH_.js";import{i as t}from"./backend-local-BTd37iLF.js";import{t as n}from"./mime-types-4JXpZe6p.js";import{t as r}from"./remote-cache-Cd8CL8Mo.js";function i(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 a=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=i(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??26214400,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`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 n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:this.toS3Key(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`s3 access denied`,e);if(a.status>=400)throw new t(`EIO`,`s3 readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes (${s} > ${this.maxBodyBytes})`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=await this.cache.getBody(r),a={"content-type":`application/octet-stream`,"content-length":String(n.byteLength)};i?a[`if-match`]=i.etag:a[`if-none-match`]=`*`;let o=()=>this.transport({method:`PUT`,bucket:this.parsed.bucket,key:this.toS3Key(r),headers:a,body:n}),s,c=1;try{s=await o()}catch{c=2,s=await o()}if(s.status===412){if(c===2){let i=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status>=400)throw new t(`EIO`,`s3 reconcile HEAD failed: ${i.status}`,e);let a=i.headers.get(`etag`)??``;await this.cache.putBody(r,n,a);let o=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(r);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(s.status===401||s.status===403)throw new t(`EACCES`,`s3 write denied`,e);if(s.status>=400)throw new t(`EIO`,`s3 writeFile failed: ${s.status}`,e);let l=s.headers.get(`etag`)??``;await this.cache.putBody(r,n,l);let u=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(u)}async listObjectsV2(){let e=[],n;do{let r={"list-type":`2`};this.parsed.prefix&&(r.prefix=`${this.parsed.prefix}/`),n&&(r[`continuation-token`]=n);let i=await this.transport({method:`GET`,bucket:this.parsed.bucket,key:``,query:r});if(i.status>=400)throw new t(`EIO`,`s3 list failed: ${i.status}`,`/`);let a=await i.text(),o=this.parseListingXml(a);e.push(...o.contents),n=o.nextContinuationToken}while(n);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 n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.body.byteLength,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,bucket:this.parsed.bucket,key:this.toS3Key(n)});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 r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`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,n){this.assertOpen(e);let r=this.toMountRelative(e);if(n?.recursive)throw new t(`EINVAL`,`recursive remove not yet supported on S3`,e);let i=await this.transport({method:`DELETE`,bucket:this.parsed.bucket,key:this.toS3Key(r)});if(i.status===404)throw new t(`ENOENT`,`no such file`,e);if(i.status===401||i.status===403)throw new t(`EACCES`,`s3 delete denied`,e);if(i.status>=400)throw new t(`EIO`,`s3 delete failed: ${i.status}`,e);await this.cache.invalidateBody(r);let a=r.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(a)}describe(){return{displayName:this.parsed.prefix?`${this.parsed.bucket}/${this.parsed.prefix}`:this.parsed.bucket,source:this.source,profile:this.profile}}async close(){this.closed||=!0}};function o(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 s(e){return e.split(`/`).pop()||`data`}function c(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 l=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=c(e.source),this.cache=e.cache,this.maxBodyBytes=e.maxBodyBytes??5242880,this.transport=e.signedFetch}assertOpen(e){if(this.closed)throw new t(`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 n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r&&!this.cache.isStale(r.cachedAt))return r.body;let i={};r&&(i[`if-none-match`]=r.etag);let a=await this.transport({method:`GET`,path:this.toSourcePath(n),headers:i});if(a.status===304&&r)return await this.cache.putBody(n,r.body,r.etag),r.body;if(a.status===404)throw await this.cache.invalidateBody(n),new t(`ENOENT`,`no such file`,e);if(a.status===401||a.status===403)throw new t(`EACCES`,`da access denied`,e);if(a.status>=400)throw new t(`EIO`,`da readFile failed: ${a.status}`,e);let o=a.headers.get(`content-length`),s=o?Number(o):void 0;if(s!==void 0&&s>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let c=new Uint8Array(await a.arrayBuffer());if(c.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let l=a.headers.get(`etag`)??``;return await this.cache.putBody(n,c,l),c}async writeFile(e,r){if(this.assertOpen(e),r.byteLength>this.maxBodyBytes)throw new t(`EFBIG`,`body exceeds maxBodyBytes`,e);let i=this.toMountRelative(e),a=await this.cache.getBody(i),c=o(s(e),n(e),r),l={"content-type":c.contentType,"content-length":String(c.body.byteLength)};a&&a.etag?l[`if-match`]=a.etag:a||(l[`if-none-match`]=`*`);let u=()=>this.transport({method:`POST`,path:this.toSourcePath(i),headers:l,body:c.body}),d,f=1;try{d=await u()}catch{f=2,d=await u()}if(d.status===412){if(f===2){let n=await this.transport({method:`HEAD`,path:this.toSourcePath(i)});if(n.status>=400)throw new t(`EIO`,`da reconcile HEAD failed: ${n.status}`,e);let a=n.headers.get(`etag`)??``;await this.cache.putBody(i,r,a);let o=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(o);return}await this.cache.invalidateBody(i);try{await this.readFile(e)}catch{}throw new t(`EBUSY`,`remote modified since last read — re-read and retry`,e)}if(d.status===401||d.status===403)throw new t(`EACCES`,`da write denied`,e);if(d.status>=400)throw new t(`EIO`,`da writeFile failed: ${d.status}`,e);let p=d.headers.get(`etag`)??``;await this.cache.putBody(i,r,p);let m=i.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(m)}async readDir(e){this.assertOpen(e);let n=this.toMountRelative(e).replace(/\/+$/,``),r=await this.cache.getListing(n);if(r&&!this.cache.isStale(r.cachedAt))return r.entries;let i=await this.transport({method:`GET`,path:this.toListPath(n)});if(i.status===404)throw new t(`ENOENT`,`no such directory`,e);if(i.status>=400)throw new t(`EIO`,`da list failed: ${i.status}`,e);let a=(await i.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(n,a),a}async stat(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.cache.getBody(n);if(r)return{kind:`file`,size:r.size,mtime:r.cachedAt,etag:r.etag};let i=n.split(`/`),a=i.pop()??``,o=i.join(`/`),s=await this.cache.getListing(o);if(s&&!this.cache.isStale(s.cachedAt)){let n=s.entries.find(e=>e.name===a);if(n?.kind===`file`&&n.size!==void 0)return{kind:`file`,size:n.size,mtime:n.lastModified??s.cachedAt,etag:n.etag??``};if(n?.kind===`directory`)return{kind:`directory`,size:0,mtime:n.lastModified??s.cachedAt};if(!n)throw new t(`ENOENT`,`no such file or directory`,e)}let c=await this.transport({method:`HEAD`,path:this.toSourcePath(n)});if(c.status===200){let e=Number(c.headers.get(`content-length`)??`0`),t=c.headers.get(`etag`)??``,n=c.headers.get(`last-modified`),r=n?Date.parse(n):0;if(s){let n=s.entries.map(n=>n.name===a&&n.kind===`file`?{...n,size:e,etag:t,lastModified:r}:n);await this.cache.putListing(o,n)}return{kind:`file`,size:e,mtime:r,etag:t}}if(c.status===404){let r=await this.cache.getListing(n);if(r)return{kind:`directory`,size:0,mtime:r.cachedAt};throw new t(`ENOENT`,`no such file or directory`,e)}throw new t(`EIO`,`da stat failed: ${c.status}`,e)}async mkdir(e){}async remove(e){this.assertOpen(e);let n=this.toMountRelative(e),r=await this.transport({method:`DELETE`,path:this.toSourcePath(n)});if(r.status===404)throw new t(`ENOENT`,`no such file`,e);if(r.status===401||r.status===403)throw new t(`EACCES`,`da delete denied`,e);if(r.status>=400)throw new t(`EIO`,`da delete failed: ${r.status}`,e);await this.cache.invalidateBody(n);let i=n.split(`/`).slice(0,-1).join(`/`);await this.cache.invalidateListing(i)}async refresh(e){this.assertOpen(`/`);let t={added:[],removed:[],changed:[],unchanged:0,errors:[]},n=[``];for(;n.length>0;){let e=n.pop();try{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}`});continue}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});let i=await this.cache.getBody(n);i?r.etag&&i.etag!==r.etag?(await this.cache.invalidateBody(n),t.changed.push(n)):t.unchanged++:t.added.push(n)}else{a.push({name:r.name,kind:`directory`});let t=e?`${e}/${r.name}`:r.name;n.push(t)}await this.cache.putListing(e,a)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}}if(e?.bodies)for(let e of t.changed)try{await this.readFile(e)}catch(n){t.errors.push({path:e,message:n instanceof Error?n.message:String(n)})}return t}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}},u=class extends Error{constructor(e){super(e),this.name=`ProfileNotConfiguredError`}};async function d(){let{getAccounts:e}=await import(`./provider-settings-BntkzQDt.js`).then(e=>e.l),t=e().find(e=>e.providerId===`adobe`);if(!t||!t.accessToken)throw new u(`No Adobe IMS account found. Log in via Settings → Providers → Adobe first.`);return{identity:`adobe-ims`,getBearerToken:async()=>t.accessToken}}function f(){return typeof chrome<`u`&&!!chrome?.runtime?.id}function p(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function m(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}const h=new Set([`invalid_profile`,`invalid_request`,`profile_not_configured`,`fetch_failed`,`internal`]),g=new Set([101,103,204,205,304]);function _(e){if(!e.ok)throw e.errorCode===`profile_not_configured`||e.errorCode===`invalid_profile`?new t(`EACCES`,e.error):e.errorCode===`invalid_request`?new t(`EINVAL`,e.error):e.errorCode===`fetch_failed`||e.errorCode===`internal`||h.has(String(e.errorCode))?new t(`EIO`,e.error):new t(`EINVAL`,`mount transport returned unrecognized errorCode '${e.errorCode}': ${e.error}`);let n;try{n=p(e.bodyBase64)}catch(e){throw new t(`EIO`,`mount transport: response body decode failed: ${e instanceof Error?e.message:String(e)}`)}let r=g.has(e.status)?null:n;return new Response(r,{status:e.status,headers:new Headers(e.headers)})}async function v(e,n){let r;try{r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (SLICC backend at localhost may not be running)`)}try{return await r.json()}catch(e){throw new t(`EIO`,`mount transport: response is not a JSON envelope (status ${r.status}): ${e instanceof Error?e.message:String(e)}`)}}async function y(e,n){try{return await chrome.runtime.sendMessage({type:e,envelope:n})}catch(e){throw new t(`EIO`,`mount transport failed: ${e instanceof Error?e.message:String(e)} (extension service worker not responding)`)}}function b(e){return async t=>{let n={profile:e,method:t.method,bucket:t.bucket,key:t.key,query:t.query,headers:t.headers,bodyBase64:t.body?m(t.body):void 0};return _(f()?await y(`mount.s3-sign-and-forward`,n):await v(`/api/s3-sign-and-forward`,n))}}function x(e){let n=e?.getImsToken??(async()=>(await d()).getBearerToken());return async e=>{let r;try{r=await n()}catch(e){throw new t(`EACCES`,`DA mount: ${e instanceof Error?e.message:String(e)}`)}let i={imsToken:r,method:e.method,path:e.path,query:e.query,headers:e.headers,bodyBase64:e.body?m(e.body):void 0};return _(f()?await y(`mount.da-sign-and-forward`,i):await v(`/api/da-sign-and-forward`,i))}}var S=e({DaMountBackend:()=>l,RemoteMountCache:()=>r,S3MountBackend:()=>a,makeSignedFetchDa:()=>x,makeSignedFetchS3:()=>b});export{a,l as i,x as n,b as r,S as t};
@@ -1 +0,0 @@
1
- function e(){return crypto.randomUUID()}export{e as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./logger-B-No_qN_.js";var n=e({loadAndClearPendingHandle:()=>c,openMountPickerPopup:()=>o,reactivateHandle:()=>l,storePendingHandle:()=>s}),r=t(`mount-picker-popup`),i=`slicc-pending-mount`,a=6e4;function o(e){let t=e??`mount-${Date.now().toString(36)}`;return new Promise(e=>{let n=chrome.runtime.getURL(`mount-popup.html?requestId=${encodeURIComponent(t)}`),i=()=>{clearTimeout(o),chrome.runtime.onMessage.removeListener(s)},o=setTimeout(()=>{i(),e({cancelled:!0})},a),s=n=>{let r=n;!r||r.source!==`mount-popup`||r.requestId!==t||(i(),e(r))};chrome.runtime.onMessage.addListener(s),chrome.windows.create({url:n,type:`popup`,width:300,height:80,focused:!0}).catch(n=>{i(),r.error(`chrome.windows.create failed for mount picker popup`,{requestId:t,error:n instanceof Error?n.message:String(n),name:n instanceof Error?n.name:void 0}),e({error:`Failed to open directory picker window`})})})}async function s(e,t){let n=await new Promise((e,t)=>{let n=indexedDB.open(i,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(`handles`)||n.result.createObjectStore(`handles`)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),r=n.transaction(`handles`,`readwrite`);r.objectStore(`handles`).put(t,e),await new Promise((e,t)=>{r.oncomplete=()=>e(),r.onerror=()=>t(r.error??Error(`IDB transaction failed`)),r.onabort=()=>t(r.error??Error(`IDB transaction aborted`))}),n.close()}async function c(e){let t=await new Promise((e,t)=>{let n=indexedDB.open(i,1);n.onupgradeneeded=()=>{n.result.objectStoreNames.contains(`handles`)||n.result.createObjectStore(`handles`)},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),n=t.transaction(`handles`,`readwrite`),a=n.objectStore(`handles`),o=a.get(e),s=a.delete(e);s.onerror=()=>{r.warn(`Failed to delete pending handle from IDB`,{idbKey:e,error:s.error})};let c=await new Promise((e,t)=>{n.oncomplete=()=>e(o.result??null),o.onerror=()=>t(o.error??Error(`IDB get failed`)),n.onerror=()=>t(n.error??Error(`IDB transaction failed`)),n.onabort=()=>t(n.error??Error(`IDB transaction aborted`))});return t.close(),c}async function l(e){let t=e;if(t.requestPermission){let n=await t.requestPermission({mode:`readwrite`});if(n!==`granted`)throw Error(`Permission denied for "${e.name}" (${n})`)}}export{l as i,n,o as r,c as t};
@@ -1 +0,0 @@
1
- import{r as e}from"./chunk-jRWAZmH_.js";import{t}from"./mount-id-Ccy4_G8i.js";var n=e({clearMountEntries:()=>u,getAllMountEntries:()=>c,loadMountHandle:()=>l,removeMountEntry:()=>s,saveMountEntry:()=>o});const r=`mounts`,i=`mount-entries`;function a(){return new Promise((e,n)=>{let a=indexedDB.open(`slicc-mount-table`,2);a.onupgradeneeded=e=>{let n=a.result,o=e.oldVersion;if(n.objectStoreNames.contains(r)||n.createObjectStore(r),n.objectStoreNames.contains(i)||n.createObjectStore(i),o<2){let e=a.transaction,n=e.objectStore(r),o=e.objectStore(i),s=n.getAllKeys();s.onsuccess=()=>{for(let e of s.result){if(typeof e!=`string`)continue;let n={targetPath:e,descriptor:{kind:`local`,mountId:t(),idbHandleKey:e},createdAt:Date.now()};o.put(n,e)}}}},a.onsuccess=()=>e(a.result),a.onerror=()=>n(a.error)})}async function o(e,t){let n=await a();try{let a=e.descriptor.kind===`local`&&t?[r,i]:[i],o=n.transaction(a,`readwrite`);o.objectStore(i).put(e,e.targetPath),e.descriptor.kind===`local`&&t&&o.objectStore(r).put(t,e.descriptor.idbHandleKey),await new Promise((e,t)=>{o.oncomplete=()=>e(),o.onerror=()=>t(o.error),o.onabort=()=>t(o.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{n.close()}}async function s(e){let t=await a();try{let n=t.transaction([r,i],`readwrite`);n.objectStore(i).delete(e),n.objectStore(r).delete(e),await new Promise((e,t)=>{n.oncomplete=()=>e(),n.onerror=()=>t(n.error),n.onabort=()=>t(n.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{t.close()}}async function c(){let e=await a();try{return await new Promise((t,n)=>{let r=e.transaction(i,`readonly`),a=r.objectStore(i).getAll();a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error),r.onabort=()=>n(r.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{e.close()}}async function l(e){let t=await a();try{return await new Promise((n,i)=>{let a=t.transaction(r,`readonly`).objectStore(r).get(e);a.onsuccess=()=>n(a.result??null),a.onerror=()=>i(a.error)})}finally{t.close()}}async function u(){let e=await a();try{let t=e.transaction([r,i],`readwrite`);t.objectStore(r).clear(),t.objectStore(i).clear(),await new Promise((e,n)=>{t.oncomplete=()=>e(),t.onerror=()=>n(t.error),t.onabort=()=>n(t.error??new DOMException(`IndexedDB transaction aborted`,`AbortError`))})}finally{e.close()}}export{o as a,s as i,l as n,n as r,u as t};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-B-No_qN_.js";import{C as t,r as n,y as r}from"./provider-settings-w0pFif0W.js";var i=e(`oauth-bootstrap`),a=6e4;async function o(){let e=n();i.info(`Bootstrap OAuth replicas`,{count:e.length});for(let n of e){if(!n.accessToken){i.debug(`Skipping account without token`,{providerId:n.providerId});continue}if((n.tokenExpiresAt??1/0)-Date.now()<=a){let e=t(n.providerId);if(e?.onSilentRenew)try{if(await e.onSilentRenew()){i.info(`Silently renewed OAuth token`,{providerId:n.providerId});continue}i.warn(`Silent renewal yielded no token; user must re-authenticate`,{providerId:n.providerId});continue}catch(e){i.warn(`Silent renewal failed`,{providerId:n.providerId,error:e instanceof Error?e.message:String(e)});continue}i.debug(`Skipping expired account (no silent-renew hook)`,{providerId:n.providerId});continue}try{await r({providerId:n.providerId,accessToken:n.accessToken,refreshToken:n.refreshToken,tokenExpiresAt:n.tokenExpiresAt,userName:n.userName,userAvatar:n.userAvatar}),i.debug(`Bootstrapped OAuth replica`,{providerId:n.providerId})}catch(e){i.error(`OAuth bootstrap failed`,{providerId:n.providerId,error:e instanceof Error?e.message:String(e)})}}}export{o as bootstrapOAuthReplicas};
@@ -1 +0,0 @@
1
- import{t as e}from"./preload-helper-ca-nBW7U.js";import{t}from"./panel-rpc-DMFq2vU_.js";var n=12e4;function r(e,t){return t.endsWith(`*`)?e.startsWith(t.slice(0,-1)):e===t||e.startsWith(`${t}?`)||e.startsWith(`${t}#`)}function i(e){return e.endsWith(`*`)?e:`${e}*`}function a(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 o(e){return async t=>{let o=t.timeoutMs??n,s=t.rewrite??[],c=t.onCapture??`close`,l,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(l&&c===`close`)try{await e.send(`Target.closeTarget`,{targetId:l})}catch{}};return await new Promise(n=>{let c=async t=>{d||(d=!0,clearTimeout(h),e.off(`Fetch.requestPaused`,m),await p(),n(t))},m=n=>{let i=n;if(!i?.request?.url||!u||(typeof n.sessionId==`string`?n.sessionId:void 0)!==u)return;if(r(i.request.url,t.redirectUriPattern)){f=i.request.url,e.send(`Fetch.failRequest`,{requestId:i.requestId,errorReason:`Aborted`},u).catch(()=>{}),c(f);return}let o=a(i.request.url,s);if(o!==i.request.url){e.send(`Fetch.continueRequest`,{requestId:i.requestId,url:o},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(()=>{c(null)},o);(async()=>{try{l=(await e.send(`Target.createTarget`,{url:`about:blank`})).targetId,u=(await e.send(`Target.attachToTarget`,{targetId:l,flatten:!0})).sessionId,e.on(`Fetch.requestPaused`,m),await e.send(`Fetch.enable`,{patterns:[{urlPattern:i(t.redirectUriPattern),requestStage:`Request`},...s.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)),c(null)}})()})}}var s=typeof chrome<`u`&&!!chrome?.runtime?.id;function c(){return s?m:typeof window>`u`?f:p}async function l(){let e=await u();return e?o(e):null}async function u(){try{let{getActiveCdpTransport:t}=await e(async()=>{let{getActiveCdpTransport:e}=await import(`./active-transport-lYMG0Gv5.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 d(){if(typeof window<`u`)return{origin:window.location.origin,href:window.location.href};let e=t();if(!e)throw Error(`OAuth from worker context requires the panel-RPC bridge (no page-info available)`);let n=await e.call(`page-info`,void 0);return{origin:n.origin,href:n.href}}async function f(e){let n=t();if(!n)return console.error(`[oauth-service] panel-RPC client unavailable in worker`),null;try{return(await n.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 p(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=()=>{r||(r=!0,window.removeEventListener(`message`,o),clearTimeout(s),i&&clearInterval(i))},o=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(a(),e.data.error){console.error(`[oauth-service] CLI OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,o),(location.pathname.startsWith(`/electron`)||new URLSearchParams(location.search).get(`runtime`)===`electron-overlay`)&&(i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204)return;let n=await e.json();if(r)return;if(a(),n.error){console.error(`[oauth-service] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3));let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}async function m(e){return new Promise(t=>{let n=!1,r=()=>{n||(n=!0,chrome.runtime.onMessage.removeListener(i),clearTimeout(a))},i=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(r(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),t(null);return}t(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(i),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let a=setTimeout(()=>{r(),t(null)},12e4)})}export{l as createInterceptingOAuthLauncherForCurrentRuntime,c as createOAuthLauncher,d as getOAuthPageOrigin};
@@ -1 +0,0 @@
1
- import{t as e}from"./panel-rpc-uLhnFoXD.js";import{t}from"./intercepted-oauth-CnYe4Pun.js";const n=typeof chrome<`u`&&!!chrome?.runtime?.id;function r(){return n?l:typeof window>`u`?s:c}async function i(){let e=await a();return e?t(e):null}async function a(){try{let{getActiveCdpTransport:e}=await import(`./active-transport-DjJ32qlA.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 o(){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 s(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 c(e){return new Promise(t=>{let n=window.open(e,`_blank`,`width=500,height=700,popup=yes`),r=!1,i=null,a=()=>{r||(r=!0,window.removeEventListener(`message`,o),clearTimeout(s),i&&clearInterval(i))},o=e=>{if(e.data?.type!==`oauth-callback`||e.origin!==window.location.origin||n&&e.source!==n)return;if(a(),e.data.error){console.error(`[oauth-service] CLI OAuth error:`,e.data.error),t(null);return}let r=e.data.redirectUrl;typeof r!=`string`&&r!=null||t(r??null)};window.addEventListener(`message`,o),(location.pathname.startsWith(`/electron`)||new URLSearchParams(location.search).get(`runtime`)===`electron-overlay`)&&(i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204)return;let n=await e.json();if(r)return;if(a(),n.error){console.error(`[oauth-service] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[oauth-service] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3));let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}async function l(e){return new Promise(t=>{let n=!1,r=()=>{n||(n=!0,chrome.runtime.onMessage.removeListener(i),clearTimeout(a))},i=e=>{if(e?.source===`service-worker`&&e?.payload?.type===`oauth-result`){if(r(),e.payload.error){console.error(`[oauth-service] Extension OAuth error:`,e.payload.error),t(null);return}t(e.payload.redirectUrl??null)}};chrome.runtime.onMessage.addListener(i),chrome.runtime.sendMessage({source:`panel`,payload:{type:`oauth-request`,providerId:`oauth`,authorizeUrl:e}}).catch(e=>{console.error(`[oauth-service] Failed to send OAuth request to service worker:`,e)});let a=setTimeout(()=>{r(),t(null)},12e4)})}export{i as createInterceptingOAuthLauncherForCurrentRuntime,r as createOAuthLauncher,o as getOAuthPageOrigin};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-B-No_qN_.js";import{r as t}from"./tray-follower-status-hrOEFANe.js";import{r as n}from"./index-Bk_LVMna.js";var r=e(`panel-transport`);function i(e){return typeof e==`object`&&!!e&&`source`in e&&`payload`in e}function a(){return{onMessage:e=>{let t=(t,n,r)=>(i(t)&&e(t),!1);return chrome.runtime.onMessage.addListener(t),()=>chrome.runtime.onMessage.removeListener(t)},send:e=>{chrome.runtime.sendMessage({source:`panel`,payload:e}).catch(e=>{r.error(`failed to send to offscreen`,{error:e instanceof Error?e.message:String(e)})})}}}var o=e(`offscreen-client`),s=class{eventListeners=new Set;callbacks;scoops=[];scoopStatuses=new Map;currentMessageId=new Map;ready=!1;stateRetryTimer=null;localFs=null;pendingClearAcks=new Map;transport;selectedScoopJid=null;locked=!1;constructor(e,t){this.callbacks=e,this.transport=t??a(),this.setupMessageListener()}setLocalFS(e){this.localFs=e}createAgentHandle(){return{sendMessage:(e,t,n)=>{if(!this.selectedScoopJid){this.emitToUI({type:`error`,error:`No scoop selected`});return}this.send({type:`user-message`,scoopJid:this.selectedScoopJid,text:e,attachments:n,messageId:t??`msg-${Date.now()}-${Math.random().toString(36).slice(2,8)}`})},onEvent:e=>(this.eventListeners.add(e),()=>this.eventListeners.delete(e)),stop:()=>{this.selectedScoopJid&&this.send({type:`abort`,scoopJid:this.selectedScoopJid})}}}getScoops(){return this.scoops}getScoop(e){return this.scoops.find(t=>t.jid===e)}isProcessing(e){return this.scoopStatuses.get(e)===`processing`}async registerScoop(e){if(!e.isCone)throw Error(`OffscreenClient.registerScoop is cone-only; use scoop_scoop for non-cone scoops`);this.scoops.find(t=>t.name===e.name)||(this.scoops.push(e),this.scoopStatuses.set(e.jid,`initializing`)),this.send({type:`cone-create`,name:e.name})}async unregisterScoop(e){this.send({type:`scoop-drop`,scoopJid:e}),this.scoops=this.scoops.filter(t=>t.jid!==e),this.scoopStatuses.delete(e)}createScoopTab(e){}async getGlobalMemory(){if(!this.localFs)return``;try{let e=await this.localFs.readFile(`/shared/CLAUDE.md`,{encoding:`utf-8`});return typeof e==`string`?e:new TextDecoder().decode(e)}catch{return``}}getScoopContext(e){if(this.localFs)return{getFS:()=>this.localFs}}getSharedFS(){return this.localFs}stopScoop(e){this.send({type:`abort`,scoopJid:e})}async clearQueuedMessages(e){}async deleteQueuedMessage(e,t){}updateModel(){this.send({type:`refresh-model`})}setLocked(e){this.locked=e}setScoopThinkingLevel(e,t){this.send({type:`set-thinking-level`,scoopJid:e,level:t})}async clearAllMessages(){let e=`clear-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,t=new Promise(t=>{this.pendingClearAcks.set(e,t)});this.send({type:`clear-chat`,requestId:e}),await Promise.race([t,new Promise(e=>setTimeout(e,5e3))]),this.pendingClearAcks.delete(e)}clearFilesystem(){this.send({type:`clear-filesystem`})}requestScoopMessages(e){this.send({type:`request-scoop-messages`,scoopJid:e})}requestState(){this.send({type:`request-state`});let e=0;this.stateRetryTimer=setInterval(()=>{if(e++,this.ready||e>20){this.stateRetryTimer&&=(clearInterval(this.stateRetryTimer),null);return}o.debug(`Retrying request-state`,{attempt:e}),this.send({type:`request-state`})},500)}isReady(){return this.ready}sprinkleOpHandler=null;sendSprinkleLick(e,t,n){this.send({type:`sprinkle-lick`,sprinkleName:e,body:t,targetScoop:n})}sendWebhookEvent(e,t,n){this.send({type:`lick-webhook-event`,webhookId:e,headers:t,body:n})}setSprinkleOpHandler(e){this.sprinkleOpHandler=e}sendRaw(e){this.send(e)}setupMessageListener(){this.transport.onMessage(e=>{if(e.source!==`offscreen`)return;let t=e.payload;t?.type===`sprinkle-op`&&this.sprinkleOpHandler?this.sprinkleOpHandler(t):this.handleOffscreenMessage(e.payload)})}handleOffscreenMessage(e){switch(e.type){case`offscreen-ready`:this.ready?(o.warn(`Offscreen restarted — re-requesting state`),this.ready=!1):o.info(`Offscreen engine ready`),this.send({type:`request-state`});break;case`agent-event`:this.handleAgentEvent(e);break;case`scoop-status`:this.handleScoopStatus(e);break;case`compaction-state`:this.callbacks.onCompactionStateChange?.(e.scoopJid,e.state);break;case`clear-chat-ack`:{let t=this.pendingClearAcks.get(e.requestId);t&&(this.pendingClearAcks.delete(e.requestId),t());break}case`scoop-created`:this.handleScoopCreated(e);break;case`scoop-list`:this.handleScoopList(e);break;case`state-snapshot`:this.handleStateSnapshot(e);break;case`error`:this.handleError(e);break;case`incoming-message`:this.handleIncomingMessage(e);break;case`scoop-messages-replaced`:{let t=e;this.callbacks.onScoopMessagesReplaced?.(t.scoopJid,t.messages);break}case`tray-runtime-status`:{let t=e;l(t.leader,t.follower);break}case`terminal-status`:case`terminal-output`:case`terminal-media-preview`:case`terminal-exit`:case`terminal-cleared`:for(let t of this.terminalEventListeners)try{t(e)}catch(e){o.error(`terminal event listener error`,{error:e instanceof Error?e.message:String(e)})}break}}terminalEventListeners=new Set;onTerminalEvent(e){return this.terminalEventListeners.add(e),()=>this.terminalEventListeners.delete(e)}handleAgentEvent(e){if(e.scoopJid===this.selectedScoopJid)switch(e.eventType){case`text_delta`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`content_delta`,messageId:t,text:e.text??``});break}case`tool_start`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`tool_use_start`,messageId:t,toolName:e.toolName??``,toolInput:e.toolInput});break}case`tool_end`:{let t=this.currentMessageId.get(e.scoopJid);t&&this.emitToUI({type:`tool_result`,messageId:t,toolName:e.toolName??``,result:e.toolResult??``,isError:e.isError});break}case`tool_ui`:{let t=this.currentMessageId.get(e.scoopJid);t||(t=`scoop-${e.scoopJid}-${c()}`,this.currentMessageId.set(e.scoopJid,t),this.emitToUI({type:`message_start`,messageId:t})),this.emitToUI({type:`tool_ui`,messageId:t,toolName:e.toolName??``,requestId:e.requestId??``,html:e.html??``});break}case`tool_ui_done`:{let t=this.currentMessageId.get(e.scoopJid);t&&this.emitToUI({type:`tool_ui_done`,messageId:t,requestId:e.requestId??``});break}case`response_done`:{let t=this.currentMessageId.get(e.scoopJid);t&&(this.emitToUI({type:`content_done`,messageId:t}),this.currentMessageId.delete(e.scoopJid));break}case`turn_end`:{let t=this.currentMessageId.get(e.scoopJid)??`done-${e.scoopJid}-${c()}`;this.currentMessageId.delete(e.scoopJid),this.emitToUI({type:`turn_end`,messageId:t});break}}}handleScoopStatus(e){this.scoopStatuses.set(e.scoopJid,e.status),this.callbacks.onStatusChange(e.scoopJid,e.status)}handleScoopCreated(e){let t=this.msgScoopToRegistered(e.scoop);this.scoops=this.scoops.filter(e=>e.name!==t.name||e.jid===t.jid),this.scoops.find(e=>e.jid===t.jid)||this.scoops.push(t),this.scoopStatuses.set(t.jid,e.scoop.status),this.callbacks.onScoopCreated(t)}handleScoopList(e){this.scoops=e.scoops.map(e=>this.msgScoopToRegistered(e));for(let t of e.scoops)this.scoopStatuses.set(t.jid,t.status);this.callbacks.onScoopListUpdate(e.scoops)}handleStateSnapshot(e){o.info(`Received state snapshot`,{scoopCount:e.scoops.length}),this.scoops=e.scoops.map(e=>this.msgScoopToRegistered(e));for(let t of e.scoops)this.scoopStatuses.set(t.jid,t.status);e.trayRuntimeStatus&&l(e.trayRuntimeStatus.leader,e.trayRuntimeStatus.follower);let t=!this.ready;t&&(this.ready=!0,this.stateRetryTimer&&=(clearInterval(this.stateRetryTimer),null)),this.callbacks.onScoopListUpdate(e.scoops),t&&this.callbacks.onReady?.()}handleError(e){e.scoopJid===this.selectedScoopJid&&this.emitToUI({type:`error`,error:e.error})}handleIncomingMessage(e){this.callbacks.onIncomingMessage(e.scoopJid,e.message)}msgScoopToRegistered(e){return{jid:e.jid,name:e.name,folder:e.folder,isCone:e.isCone,type:e.isCone?`cone`:`scoop`,requiresTrigger:!e.isCone,assistantLabel:e.assistantLabel,addedAt:new Date().toISOString(),...e.config?{config:{...e.config}}:{}}}emitToUI(e){for(let t of this.eventListeners)try{t(e)}catch(e){o.error(`Listener error`,{error:e instanceof Error?e.message:String(e)})}}send(e){if(this.locked){this.emitToUI({type:`error`,error:`This window is detached. Close it and use the detached tab.`});return}this.transport.send(e)}};function c(){return Date.now().toString(36)+Math.random().toString(36).slice(2,8)}function l(e,r){n({state:e.state,error:e.error,reconnectAttempts:e.reconnectAttempts,session:e.session?{...e.session}:null}),t({state:r.state,joinUrl:r.joinUrl,trayId:r.trayId,error:r.error,lastError:r.lastError,reconnectAttempts:r.reconnectAttempts,attachAttempts:r.attachAttempts,lastAttachCode:r.lastAttachCode,connectingSince:r.connectingSince,lastPingTime:r.lastPingTime})}export{s as OffscreenClient};
@@ -1 +0,0 @@
1
- import{t as e}from"./logger-B-No_qN_.js";import{t}from"./index-Bk_LVMna.js";var n=[e=>`Nice to meet you, ${e}.`,e=>`Hello ${e} — glad you stopped by.`,e=>`Hey ${e}, welcome aboard.`,e=>`${e}! Pleasure to make your acquaintance.`],r=[`Nice to meet you, mysterious stranger — I'll respect the incognito.`,`Hello, anonymous traveler. You can always tell me your name later if you change your mind.`,`An unnamed visitor — intriguing. Whenever you'd like to introduce yourself, just say the word.`,`Hey there, ghost — happy to keep things first-name-optional. The door's always open if you decide to drop the cloak.`],i={work:[`Work mode — let's make today productive.`,`On the clock? Same. Let's chip away at it.`],school:[`School business — I love a good study session.`,`Hitting the books? Glad to ride along.`],personal:[`Personal project energy is the best kind.`,`Tinkering for yourself is how the good stuff happens.`],"side-project":[`Side projects keep the lights on creatively.`,`Two-job life — respect.`],exploring:[`Just poking around? Excellent. The best discoveries start there.`,`Exploration mode — no agenda, no pressure.`]},a={developer:[`I can write code, run shell commands, drive a real browser, and ship pages.`,`Code, terminals, browsers, repos — I live in all of them.`],designer:[`I can prototype layouts, generate assets, and walk page editors with you.`,`Pixels, components, screenshots — design ops are my jam.`],"content-creator":[`I can draft copy, edit, scrape references, and stitch publish-ready pages.`,`Words, structure, SEO, polish — say the topic and I'll get moving.`],marketer:[`I can audit funnels, scrape competitors, and stand up landing pages quickly.`,`Campaigns, analytics, creatives — plug me in and I'll go.`],"product-pm":[`I can summarise research, draft specs, and crunch competitive intel.`,`Briefs, roadmaps, comparisons — I take the boring half off your plate.`],founder:[`I can prototype landing pages, automate ops, and prep investor decks.`,`Idea → MVP → repeat. I'll do the legwork between coffee refills.`],student:[`I can read papers with you, draft notes, and turn lectures into outlines.`,`Studying together makes it bearable — let me handle the busywork.`],researcher:[`I can scrape sources, summarise findings, and keep a running bibliography.`,`Lit reviews, datasets, write-ups — I'm all in.`],other:[`I'm flexible — give me a task and I'll figure out the right tools.`,`Whatever the role, I can probably help. Tell me what's on the docket.`]},o=[`I can browse the web, run commands, write code, and automate the boring parts.`,`I'm comfortable with terminals, browsers, files, and a long backlog of skills.`],s=[`But to be honest, I'm not really an AI yet — I'm an empty shell. You'll need to help me become intelligent. Pick a model and I'll wake up:`,`Confession time: I can't actually think yet. Wire me up to an LLM and I'll start earning my keep:`,`Plot twist — there's no brain in here. Choose a provider so I can do more than read this script:`,`Truthfully? I'm a very polite placeholder until you give me a model. Help me out:`];function c(e,t){return e[Math.floor(t()*e.length)%e.length]}function l(e){return e.replace(/-/g,` `)}function u(e){if(e.length===0)return``;if(e.length===1)return e[0];if(e.length===2)return`${e[0]} and ${e[1]}`;let t=e[e.length-1];return`${e.slice(0,-1).join(`, `)}, and ${t}`}function d(e,t=Math.random){let a=(e.name||``).trim(),o=e.purpose?i[e.purpose]:void 0;return a?`${c(n,t)(a)}${o?` ${c(o,t)}`:``}`:`${c(r,t)}${o?` ${c(o,t)}`:``}`}function f(e,t=Math.random){let n=e.role&&a[e.role]?e.role:``,r=c(n?a[n]:o,t),i=(e.tasks??[]).slice(0,3).map(l);return`I'm sliccy. ${r}${i.length>0?` Especially handy for ${u(i)}.`:``} I'm an AI agent.`}function p(e,t=Math.random){return c(s,t)}function m(e,t=Math.random){return[d(e,t),f(e,t),p(e,t)]}var h={openai:{url:e=>`${(e??`https://api.openai.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},anthropic:{url:e=>`${(e??`https://api.anthropic.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({"x-api-key":e,"anthropic-version":`2023-06-01`})},groq:{url:e=>`${(e??`https://api.groq.com/openai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},cerebras:{url:e=>`${(e??`https://api.cerebras.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},mistral:{url:e=>`${(e??`https://api.mistral.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},"x-ai":{url:e=>`${(e??`https://api.x.ai`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},deepseek:{url:e=>`${(e??`https://api.deepseek.com`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},openrouter:{url:e=>`${(e??`https://openrouter.ai/api`).replace(/\/$/,``)}/v1/models`,headers:e=>({Authorization:`Bearer ${e}`})},google:{url:e=>`${(e??`https://generativelanguage.googleapis.com`).replace(/\/$/,``)}/v1beta/models`,headers:()=>({})}};function g(e,t){if(e===401||e===403)return`Authentication failed — the key was rejected by the provider.`;if(e===404)return`Endpoint not found — check the base URL.`;if(e===429)return`Rate-limited — try again in a moment.`;if(e>=500)return`Provider returned a server error.`;let n=t.trim();return n?`${e}: ${n.slice(0,160)}`:`Provider responded with HTTP ${e}.`}async function _(e){let{provider:t,apiKey:n,baseUrl:r,signal:i}=e,a=e.fetchImpl??fetch,o=n.trim();if(!o)return{kind:`failed`,status:null,message:`API key is empty.`};let s=h[t];if(!s)return{kind:`skipped`,reason:`No live validation available for "${t}" — saving without testing.`};let c=s.url(r);if(t===`google`){let e=c.includes(`?`)?`&`:`?`;c=`${c}${e}key=${encodeURIComponent(o)}`}try{let e=await a(c,{method:`GET`,headers:s.headers(o),signal:i});if(e.ok)return{kind:`ok`};let t=``;try{t=await e.text()}catch{}return e.status===401||e.status,{kind:`failed`,status:e.status,message:g(e.status,t)}}catch(e){if(e?.name===`AbortError`)throw e;return{kind:`skipped`,reason:`Couldn't reach the provider (${e instanceof Error?e.message:String(e)}). Saving without live test — you can retry from Settings.`}}}var v=e(`onboarding-orchestrator`),y=class{deps;stage=`idle`;profile={};constructor(e){this.deps=e}getStage(){return this.stage}getProfile(){return{...this.profile}}handleFirstRun(){this.stage===`idle`&&(this.deps.postDipReference(`Welcome to SLICC — let's get you set up.`),this.deps.postDipReference(`![Welcome](/shared/sprinkles/welcome/welcome.shtml)`))}async handleOnboardingComplete(e){if(this.stage!==`idle`)return v.debug(`Ignoring duplicate onboarding-complete`,{stage:this.stage}),!0;this.profile=e??{},this.stage=`awaiting-connect`,t(this.deps.fs).catch(e=>v.warn(`recordWelcomed failed`,e)),this.persistProfile(this.profile).catch(e=>v.warn(`persistProfile failed`,e));let n=m(this.profile,this.deps.rand);for(let e of n)this.deps.postSystemMessage(e);return this.deps.postDipReference(`![Connect a model](/shared/sprinkles/welcome/connect-llm.shtml)`),!0}handleConnectReady(){if(this.stage===`complete`)return;let e=this.deps.getProviderCatalogue();this.deps.broadcastToDip({type:`slicc-providers`,providers:e.providers,models:e.models})}async handleConnectAttempt(e){if(this.stage===`complete`)return;this.stage=`connecting`;let{provider:t,apiKey:n,baseUrl:r,deployment:i,apiVersion:a,model:o}=e;if(!t||typeof n!=`string`||!n.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Provider and API key are required.`}),this.stage=`awaiting-connect`;return}let s=(()=>{try{return this.deps.getProviderCatalogue().providers.find(e=>e.id===t)}catch{return}})();if(s?.requiresDeployment&&!i?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${s.name} requires a deployment name.`}),this.stage=`awaiting-connect`;return}if(s?.requiresBaseUrl&&!r?.trim()){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`${s.name} requires a base URL.`}),this.stage=`awaiting-connect`;return}let c;try{c=await _({provider:t,apiKey:n.trim(),baseUrl:r??void 0,fetchImpl:this.deps.fetchImpl})}catch(e){v.warn(`validateApiKey threw`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Validation request was aborted.`}),this.stage=`awaiting-connect`;return}if(c.kind===`failed`){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:c.message}),this.stage=`awaiting-connect`;return}let l=o||null;if(!l)try{let e=this.deps.getProviderCatalogue().models?.[t]?.[0]?.id;e&&(l=e)}catch(e){v.warn(`Failed to resolve fallback model for provider`,{provider:t,err:e})}try{this.deps.saveAccount(t,n.trim(),r?.trim()||void 0,i?.trim()||void 0,a?.trim()||void 0),l&&this.deps.setSelectedModel(l)}catch(e){v.warn(`saveAccount failed`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`Failed to save credentials locally.`}),this.stage=`awaiting-connect`;return}let u=c.kind===`skipped`?`Saved — ${c.reason}`:`Validated against the provider. Ready when you are.`;this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:c.kind,note:u});let d=l&&this.deps.resolveModelLabel?.(t,l)?this.deps.resolveModelLabel?.(t,l):l||null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:t,model:l??null,modelLabel:d,validation:c.kind}})}async handleOAuthAttempt(e){if(this.stage===`complete`)return;if(!this.deps.launchOAuth){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:`OAuth login is not available in this runtime.`});return}this.stage=`connecting`;let t;try{t=await this.deps.launchOAuth(e.provider,e.baseUrl??null)}catch(e){v.warn(`launchOAuth threw`,e),this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:e instanceof Error?e.message:`Login was cancelled.`}),this.stage=`awaiting-connect`;return}if(!t.ok){this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!1,kind:`failed`,message:t.message||`Login was cancelled.`}),this.stage=`awaiting-connect`;return}if(t.model)try{this.deps.setSelectedModel(t.model)}catch(e){v.warn(`setSelectedModel after OAuth failed`,e)}this.deps.broadcastToDip({type:`slicc-connect-result`,ok:!0,kind:`ok`,note:t.message||`Logged in.`});let n=t.model&&this.deps.resolveModelLabel?.(e.provider,t.model)?this.deps.resolveModelLabel?.(e.provider,t.model):t.model??null;this.stage=`complete`,this.deps.fireFinalLick({action:`onboarding-complete-with-provider`,data:{profile:this.profile,provider:e.provider,model:t.model??null,modelLabel:n,validation:`oauth`}})}async persistProfile(e){let t=(e.name||`user`).toLowerCase().trim().replace(/[^a-z0-9]+/g,`-`).replace(/(^-+|-+$)/g,``)||`user`;await this.deps.fs.writeFile(`/home/${t}/.welcome.json`,JSON.stringify(e,null,2))}};export{y as OnboardingOrchestrator};
@@ -1,16 +0,0 @@
1
- function e(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function t(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let n=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return n=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function r(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const i=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var a=class extends Error{},o=class e extends a{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,a){if(!t||!a)return new c({message:r,cause:i(n)});let o=n?.error;return t===400?new u(t,o,r,a):t===401?new d(t,o,r,a):t===403?new f(t,o,r,a):t===404?new p(t,o,r,a):t===409?new m(t,o,r,a):t===422?new h(t,o,r,a):t===429?new g(t,o,r,a):t>=500?new _(t,o,r,a):new e(t,o,r,a)}},s=class extends o{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},c=class extends o{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},l=class extends c{constructor({message:e}={}){super({message:e??`Request timed out.`})}},u=class extends o{},d=class extends o{},f=class extends o{},p=class extends o{},m=class extends o{},h=class extends o{},g=class extends o{},_=class extends o{},v=class extends a{constructor(){super(`Could not parse response content as the length limit was reached`)}},y=class extends a{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},b=class extends Error{constructor(e){super(e)}};const ee=/^[a-z][a-z0-9+.-]*:/i,te=e=>ee.test(e);let x=e=>(x=Array.isArray,x(e)),S=x;function C(e){return typeof e==`object`?e??{}:{}}function ne(e){if(!e)return!0;for(let t in e)return!1;return!0}function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const ae=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new a(`${e} must be an integer`);if(t<0)throw new a(`${e} must be a positive integer`);return t},oe=e=>{try{return JSON.parse(e)}catch{return}},se=e=>new Promise(t=>setTimeout(t,e)),w=`6.26.0`,ce=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function le(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const ue=()=>{let e=le();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":pe(Deno.build.os),"X-Stainless-Arch":fe(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":pe(globalThis.process.platform??`unknown`),"X-Stainless-Arch":fe(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=de();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":w,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function de(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const fe=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,pe=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let me;const he=()=>me??=ue();function ge(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function _e(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function ve(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return _e({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ye(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function be(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const xe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),Se=`RFC3986`,Ce=e=>String(e),we={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Ce};let Te=(e,t)=>(Te=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Te(e,t));const T=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Ee=1024,De=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Ee){let t=a.length>=Ee?a.slice(e,e+Ee):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=T[r];continue}if(r<2048){n[n.length]=T[192|r>>6]+T[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=T[224|r>>12]+T[128|r>>6&63]+T[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=T[240|r>>18]+T[128|r>>12&63]+T[128|r>>6&63]+T[128|r&63]}o+=n.join(``)}return o};function Oe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ke(e,t){if(x(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ae={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},je=function(e,t){Array.prototype.push.apply(e,x(t)?t:[t])};let Me;const E={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:De,encodeValuesOnly:!1,format:Se,formatter:Ce,indices:!1,serializeDate(e){return(Me??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Ne(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const Pe={};function Fe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,ee=!1;for(;(y=y.get(Pe))!==void 0&&!ee;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);ee=!0}y.get(Pe)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&x(v)&&(v=ke(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,E.encoder,g,`key`,p):t;v=``}if(Ne(v)||Oe(v)){if(c){let e=h?t:c(t,E.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,E.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let te=[];if(v===void 0)return te;let S;if(n===`comma`&&x(v))h&&c&&(v=ke(v,c)),S=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(x(l))S=l;else{let e=Object.keys(v);S=u?e.sort(u):e}let C=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&x(v)&&v.length===1?C+`[]`:C;if(i&&x(v)&&v.length===0)return ne+`[]`;for(let t=0;t<S.length;++t){let y=S[t],ee=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&ee===null)continue;let C=d&&s?y.replace(/\./g,`%2E`):y,re=x(v)?typeof n==`function`?n(ne,C):ne:ne+(d?`.`+C:`[`+C+`]`);_.set(e,b);let ie=new WeakMap;ie.set(Pe,_),je(te,Fe(ee,re,n,r,i,a,o,s,n===`comma`&&h&&x(v)?null:c,l,u,d,f,p,m,h,g,ie))}return te}function Ie(e=E){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||E.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=Se;if(e.format!==void 0){if(!Te(we,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=we[n],i=E.filter;(typeof e.filter==`function`||x(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ae?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:E.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:E.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:E.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:E.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:E.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?E.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:E.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:E.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:E.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:E.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:E.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:E.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:E.strictNullHandling}}function Le(e,t={}){let n=e,r=Ie(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):x(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ae[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||je(o,Fe(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Re(e){return Le(e,{arrayFormat:`brackets`})}function ze(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let Be;function Ve(e){let t;return(Be??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let He;function Ue(e){let t;return(He??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var D,O,We=class{constructor(){D.set(this,void 0),O.set(this,void 0),e(this,D,new Uint8Array,`f`),e(this,O,null,`f`)}decode(n){if(n==null)return[];let r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ve(n):n;e(this,D,ze([t(this,D,`f`),r]),`f`);let i=[],a;for(;(a=Ge(t(this,D,`f`),t(this,O,`f`)))!=null;){if(a.carriage&&t(this,O,`f`)==null){e(this,O,a.index,`f`);continue}if(t(this,O,`f`)!=null&&(a.index!==t(this,O,`f`)+1||a.carriage)){i.push(Ue(t(this,D,`f`).subarray(0,t(this,O,`f`)-1))),e(this,D,t(this,D,`f`).subarray(t(this,O,`f`)),`f`),e(this,O,null,`f`);continue}let n=t(this,O,`f`)===null?a.preceding:a.preceding-1,r=Ue(t(this,D,`f`).subarray(0,n));i.push(r),e(this,D,t(this,D,`f`).subarray(a.index),`f`),e(this,O,null,`f`)}return i}flush(){return t(this,D,`f`).length?this.decode(`
2
- `):[]}};D=new WeakMap,O=new WeakMap,We.NEWLINE_CHARS=new Set([`
3
- `,`\r`]),We.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ge(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ke(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const qe={off:0,error:200,warn:300,info:400,debug:500},Je=(e,t,n)=>{if(e){if(re(qe,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(qe))}`)}};function Ye(){}function Xe(e,t,n){return!t||qe[e]>qe[n]?Ye:t[e].bind(t)}const Ze={error:Ye,warn:Ye,info:Ye,debug:Ye};let Qe=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Ze;let r=Qe.get(t);if(r&&r[0]===n)return r[1];let i={error:Xe(`error`,t,n),warn:Xe(`warn`,t,n),info:Xe(`info`,t,n),debug:Xe(`debug`,t,n)};return Qe.set(t,[n,i]),i}const A=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var $e,et=class n{constructor(t,n,r){this.iterator=t,$e.set(this,void 0),this.controller=n,e(this,$e,r,`f`)}static fromSSEResponse(e,t,i,s){let c=!1,l=i?k(i):console;async function*u(){if(c)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let n=!1;try{for await(let r of tt(e,t))if(!n){if(r.data.startsWith(`[DONE]`)){n=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let t;try{t=JSON.parse(r.data)}catch(e){throw l.error(`Could not parse message into JSON:`,r.data),l.error(`From chunk:`,r.raw),e}if(t&&t.error)throw new o(void 0,t.error,void 0,e.headers);yield s?{event:r.event,data:t}:t}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new o(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}n=!0}catch(e){if(r(e))return;throw e}finally{n||t.abort()}}return new n(u,t,i)}static fromReadableStream(e,t,i){let o=!1;async function*s(){let t=new We,n=ye(e);for await(let e of n)for(let n of t.decode(e))yield n;for(let e of t.flush())yield e}async function*c(){if(o)throw new a("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let e=!1;try{for await(let t of s())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(r(e))return;throw e}finally{e||t.abort()}}return new n(c,t,i)}[($e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],i=this.iterator(),a=t=>({next:()=>{if(t.length===0){let t=i.next();e.push(t),r.push(t)}return t.shift()}});return[new n(()=>a(e),this.controller,t(this,$e,`f`)),new n(()=>a(r),this.controller,t(this,$e,`f`))]}toReadableStream(){let e=this,t;return _e({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=Ve(JSON.stringify(n)+`
4
- `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*tt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new a(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new a(`Attempted to iterate over a response with no body`);let n=new rt,r=new We,i=ye(e.body);for await(let e of nt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*nt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?Ve(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Ke(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var rt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=it(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function it(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function at(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):et.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:ot(await n.json(),n):await n.text()})();return k(e).debug(`[${r}] response parsed`,A({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function ot(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`x-request-id`),enumerable:!1})}var st,ct=class n extends Promise{constructor(t,n,r=at){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,st.set(this,void 0),e(this,st,t,`f`)}_thenUnwrap(e){return new n(t(this,st,`f`),this.responsePromise,async(t,n)=>ot(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(t(this,st,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};st=new WeakMap;var lt,ut=class{constructor(t,n,r,i){lt.set(this,void 0),e(this,lt,t,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new a("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t(this,lt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(lt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},dt=class extends ct{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await at(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ft=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},j=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...C(this.options.query),after:t}}:null}},pt=class extends ut{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...C(this.options.query),after:e}}:null}};const mt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function ht(e,t,n){return mt(),new File(e,t??`unknown_file`,n)}function gt(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const _t=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,vt=async(e,t)=>wt(e.body)?{...e,body:await xt(e.body,t)}:e,M=async(e,t)=>({...e,body:await xt(e.body,t)}),yt=new WeakMap;function bt(e){let t=typeof e==`function`?e:e.fetch,n=yt.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return yt.set(t,r),r}const xt=async(e,t)=>{if(!await bt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Tt(n,e,t))),n},St=e=>e instanceof Blob&&`name`in e,Ct=e=>typeof e==`object`&&!!e&&(e instanceof Response||_t(e)||St(e)),wt=e=>{if(Ct(e))return!0;if(Array.isArray(e))return e.some(wt);if(e&&typeof e==`object`){for(let t in e)if(wt(e[t]))return!0}return!1},Tt=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,ht([await n.blob()],gt(n)));else if(_t(n))e.append(t,ht([await new Response(ve(n)).blob()],gt(n)));else if(St(n))e.append(t,n,gt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Tt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Tt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Et=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Dt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Et(e),Ot=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function kt(e,t,n){if(mt(),e=await e,Dt(e))return e instanceof File?e:ht([await e.arrayBuffer()],e.name);if(Ot(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),ht(await At(r),t,n)}let r=await At(e);if(t||=gt(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return ht(r,t,n)}async function At(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Et(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(_t(e))for await(let n of e)t.push(...await At(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${jt(e)}`)}return t}function jt(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var N=class{constructor(e){this._client=e}};function Mt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Nt=Object.freeze(Object.create(null)),P=((e=Mt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],o=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??Nt)??Nt)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),s=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new a(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
- `)}\n${o}\n${t}`)}return o})(Mt);var Pt=class extends N{list(e,t={},n){return this._client.getAPIList(P`/chat/completions/${e}/messages`,j,{query:t,...n})}};function Ft(e){return e!==void 0&&`function`in e&&e.function!==void 0}function It(e){return e?.$brand===`auto-parseable-response-format`}function Lt(e){return e?.$brand===`auto-parseable-tool`}function Rt(e,t){return!t||!Ut(t)?{...e,choices:e.choices.map(e=>(Wt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:zt(e,t)}function zt(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new v;if(e.finish_reason===`content_filter`)throw new y;return Wt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Vt(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Bt(t,e.message.content):null}}});return{...e,choices:n}}function Bt(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Vt(e,t){let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Lt(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function Ht(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>Ft(e)&&e.function?.name===t.function.name);return Ft(n)&&(Lt(n)||n?.function.strict||!1)}function Ut(e){return It(e.response_format)?!0:e.tools?.some(e=>Lt(e)||e.type===`function`&&e.function.strict===!0)??!1}function Wt(e){for(let t of e||[])if(t.type!==`function`)throw new a(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function Gt(e){for(let t of e??[]){if(t.type!==`function`)throw new a(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new a(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Kt=e=>e?.role===`assistant`,qt=e=>e?.role===`tool`;var Jt,Yt,Xt,Zt,Qt,$t,en,F,tn,nn,rn,an,on,sn=class{constructor(){Jt.add(this),this.controller=new AbortController,Yt.set(this,void 0),Xt.set(this,()=>{}),Zt.set(this,()=>{}),Qt.set(this,void 0),$t.set(this,()=>{}),en.set(this,()=>{}),F.set(this,{}),tn.set(this,!1),nn.set(this,!1),rn.set(this,!1),an.set(this,!1),e(this,Yt,new Promise((t,n)=>{e(this,Xt,t,`f`),e(this,Zt,n,`f`)}),`f`),e(this,Qt,new Promise((t,n)=>{e(this,$t,t,`f`),e(this,en,n,`f`)}),`f`),t(this,Yt,`f`).catch(()=>{}),t(this,Qt,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},t(this,Jt,`m`,on).bind(this))},0)}_connected(){this.ended||(t(this,Xt,`f`).call(this),this._emit(`connect`))}get ended(){return t(this,tn,`f`)}get errored(){return t(this,nn,`f`)}get aborted(){return t(this,rn,`f`)}abort(){this.controller.abort()}on(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n}),this}off(e,n){let r=t(this,F,`f`)[e];if(!r)return this;let i=r.findIndex(e=>e.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(t(this,F,`f`)[e]||(t(this,F,`f`)[e]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{e(this,an,!0,`f`),t!==`error`&&this.once(`error`,r),this.once(t,n)})}async done(){e(this,an,!0,`f`),await t(this,Qt,`f`)}_emit(n,...r){if(t(this,tn,`f`))return;n===`end`&&(e(this,tn,!0,`f`),t(this,$t,`f`).call(this));let i=t(this,F,`f`)[n];if(i&&(t(this,F,`f`)[n]=i.filter(e=>!e.once),i.forEach(({listener:e})=>e(...r))),n===`abort`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`);return}if(n===`error`){let e=r[0];!t(this,an,`f`)&&!i?.length&&Promise.reject(e),t(this,Zt,`f`).call(this,e),t(this,en,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Yt=new WeakMap,Xt=new WeakMap,Zt=new WeakMap,Qt=new WeakMap,$t=new WeakMap,en=new WeakMap,F=new WeakMap,tn=new WeakMap,nn=new WeakMap,rn=new WeakMap,an=new WeakMap,Jt=new WeakSet,on=function(t){if(e(this,nn,!0,`f`),t instanceof Error&&t.name===`AbortError`&&(t=new s),t instanceof s)return e(this,rn,!0,`f`),this._emit(`abort`,t);if(t instanceof a)return this._emit(`error`,t);if(t instanceof Error){let e=new a(t.message);return e.cause=t,this._emit(`error`,e)}return this._emit(`error`,new a(String(t)))};function cn(e){return typeof e.parse==`function`}var I,ln,un,dn,fn,pn,mn,hn,gn=class extends sn{constructor(){super(...arguments),I.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),qt(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Kt(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),t(this,I,`m`,ln).call(this)}async finalMessage(){return await this.done(),t(this,I,`m`,un).call(this)}async finalFunctionToolCall(){return await this.done(),t(this,I,`m`,dn).call(this)}async finalFunctionToolCallResult(){return await this.done(),t(this,I,`m`,fn).call(this)}async totalUsage(){return await this.done(),t(this,I,`m`,pn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let n=t(this,I,`m`,un).call(this);n&&this._emit(`finalMessage`,n);let r=t(this,I,`m`,ln).call(this);r&&this._emit(`finalContent`,r);let i=t(this,I,`m`,dn).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=t(this,I,`m`,fn).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,t(this,I,`m`,pn).call(this))}async _createChatCompletion(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,I,`m`,mn).call(this,n);let a=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(zt(a,n))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,n,r){let i=`tool`,{tool_choice:o=`auto`,stream:s,...c}=n,l=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:u=10}=r||{},d=n.tools.map(e=>{if(Lt(e)){if(!e.$callback)throw new a("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),f={};for(let e of d)e.type===`function`&&(f[e.function.name||e.function.function.name]=e.function);let p=`tools`in n?d.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of n.messages)this._addMessage(e,!1);for(let n=0;n<u;++n){let n=(await this._createChatCompletion(e,{...c,tool_choice:o,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!n)throw new a(`missing message in ChatCompletion response`);if(!n.tool_calls?.length)return;for(let e of n.tool_calls){if(e.type!==`function`)continue;let n=e.id,{name:r,arguments:a}=e.function,o=f[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(f).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}else if(l&&l!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:i,tool_call_id:n,content:e});continue}let s;try{s=cn(o)?await o.parse(a):a}catch(e){let t=e instanceof Error?e.message:String(e);this._addMessage({role:i,tool_call_id:n,content:t});continue}let c=await o.function(s,this),u=t(this,I,`m`,hn).call(this,c);if(this._addMessage({role:i,tool_call_id:n,content:u}),l)return}}}};I=new WeakSet,ln=function(){return t(this,I,`m`,un).call(this).content??null},un=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Kt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new a(`stream ended without producing a ChatCompletionMessage with role=assistant`)},dn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Kt(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},fn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(qt(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},pn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},mn=function(e){if(e.n!=null&&e.n>1)throw new a(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},hn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var _n=class e extends gn{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Kt(e)&&e.content&&this._emit(`content`,e.content)}};const L={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};var vn=class extends Error{},yn=class extends Error{};function bn(e,t=L.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return xn(e.trim(),t)}const xn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new vn(`${e} at position ${r}`)},a=e=>{throw new yn(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||L.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||L.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||L.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||L.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||L.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||L.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(L.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&L.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(L.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(L.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(L.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(L.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(L.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&L.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
7
- \r `.includes(e[r]);)r++};return o()},Sn=e=>bn(e,L.ALL^L.NUM);var R,z,B,V,Cn,wn,Tn,En,Dn,On,kn,An,jn=class n extends gn{constructor(t){super(),R.add(this),z.set(this,void 0),B.set(this,void 0),V.set(this,void 0),e(this,z,t,`f`),e(this,B,[],`f`)}get currentChatCompletionSnapshot(){return t(this,V,`f`)}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let i=new n(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,n,r){super._createChatCompletion;let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,Cn).call(this);let a=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let e of a)t(this,R,`m`,Tn).call(this,e);if(a.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,On).call(this))}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),t(this,R,`m`,Cn).call(this),this._connected();let i=et.fromReadableStream(e,this.controller),a;for await(let e of i)a&&a!==e.id&&this._addChatCompletion(t(this,R,`m`,On).call(this)),t(this,R,`m`,Tn).call(this,e),a=e.id;if(i.controller.signal?.aborted)throw new s;return this._addChatCompletion(t(this,R,`m`,On).call(this))}[(z=new WeakMap,B=new WeakMap,V=new WeakMap,R=new WeakSet,Cn=function(){this.ended||e(this,V,void 0,`f`)},wn=function(e){let n=t(this,B,`f`)[e.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},t(this,B,`f`)[e.index]=n,n)},Tn=function(e){if(this.ended)return;let n=t(this,R,`m`,An).call(this,e);this._emit(`chunk`,e,n);for(let r of e.choices){let e=n.choices[r.index];r.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.delta.content,e.message.content),this._emit(`content.delta`,{delta:r.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),r.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.delta.refusal,snapshot:e.message.refusal}),r.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:e.logprobs?.content??[]}),r.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=t(this,R,`m`,wn).call(this,e);e.finish_reason&&(t(this,R,`m`,Dn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,En).call(this,e,i.current_tool_call_index));for(let n of r.delta.tool_calls??[])i.current_tool_call_index!==n.index&&(t(this,R,`m`,Dn).call(this,e),i.current_tool_call_index!=null&&t(this,R,`m`,En).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=n.index;for(let t of r.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},En=function(e,n){if(t(this,R,`m`,wn).call(this,e).done_tool_calls.has(n))return;let r=e.message.tool_calls?.[n];if(!r)throw Error(`no tool call snapshot`);if(!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let e=t(this,z,`f`)?.tools?.find(e=>Ft(e)&&e.function.name===r.function.name);this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:n,arguments:r.function.arguments,parsed_arguments:Lt(e)?e.$parseRaw(r.function.arguments):e?.function.strict?JSON.parse(r.function.arguments):null})}else r.type},Dn=function(e){let n=t(this,R,`m`,wn).call(this,e);if(e.message.content&&!n.content_done){n.content_done=!0;let r=t(this,R,`m`,kn).call(this);this._emit(`content.done`,{content:e.message.content,parsed:r?r.$parseRaw(e.message.content):null})}e.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},On=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,V,`f`);if(!n)throw new a(`request ended without sending any chunks`);return e(this,V,void 0,`f`),e(this,B,[],`f`),Mn(n,t(this,z,`f`))},kn=function(){let e=t(this,z,`f`)?.response_format;return It(e)?e:null},An=function(n){var r,i,a,o;let s=t(this,V,`f`),{choices:c,...l}=n;s?Object.assign(s,l):s=e(this,V,{...l,choices:[]},`f`);for(let{delta:e,finish_reason:c,index:l,logprobs:u=null,...d}of n.choices){let n=s.choices[l];if(n||=s.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d},u)if(!n.logprobs)n.logprobs=Object.assign({},u);else{let{content:e,refusal:t,...a}=u;Object.assign(n.logprobs,a),e&&((r=n.logprobs).content??(r.content=[]),n.logprobs.content.push(...e)),t&&((i=n.logprobs).refusal??(i.refusal=[]),n.logprobs.refusal.push(...t))}if(c&&(n.finish_reason=c,t(this,z,`f`)&&Ut(t(this,z,`f`)))){if(c===`length`)throw new v;if(c===`content_filter`)throw new y}if(Object.assign(n,d),!e)continue;let{content:f,refusal:p,function_call:m,role:h,tool_calls:g,..._}=e;if(Object.assign(n.message,_),p&&(n.message.refusal=(n.message.refusal||``)+p),h&&(n.message.role=h),m&&(n.message.function_call?(m.name&&(n.message.function_call.name=m.name),m.arguments&&((a=n.message.function_call).arguments??(a.arguments=``),n.message.function_call.arguments+=m.arguments)):n.message.function_call=m),f&&(n.message.content=(n.message.content||``)+f,!n.message.refusal&&t(this,R,`m`,kn).call(this)&&(n.message.parsed=Sn(n.message.content))),g){n.message.tool_calls||(n.message.tool_calls=[]);for(let{index:e,id:r,type:i,function:a,...s}of g){let c=(o=n.message.tool_calls)[e]??(o[e]={});Object.assign(c,s),r&&(c.id=r),i&&(c.type=i),a&&(c.function??={name:a.name??``,arguments:``}),a?.name&&(c.function.name=a.name),a?.arguments&&(c.function.arguments+=a.arguments,Ht(t(this,z,`f`),c)&&(c.function.parsed_arguments=Sn(c.function.arguments)))}}}return s},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Mn(e,t){let{id:n,choices:r,created:i,model:o,system_fingerprint:s,...c}=e;return Rt({...c,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...o})=>{if(!n)throw new a(`missing finish_reason for choice ${r}`);let{content:s=null,function_call:c,tool_calls:l,...u}=t,d=t.role;if(!d)throw new a(`missing role for choice ${r}`);if(c){let{arguments:e,name:l}=c;if(e==null)throw new a(`missing function_call.arguments for choice ${r}`);if(!l)throw new a(`missing function_call.name for choice ${r}`);return{...o,message:{content:s,function_call:{arguments:e,name:l},role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return l?{...o,index:r,finish_reason:n,logprobs:i,message:{...u,role:d,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:i,type:o,id:s,...c}=t,{arguments:l,name:u,...d}=i||{};if(s==null)throw new a(`missing choices[${r}].tool_calls[${n}].id\n${Nn(e)}`);if(o==null)throw new a(`missing choices[${r}].tool_calls[${n}].type\n${Nn(e)}`);if(u==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.name\n${Nn(e)}`);if(l==null)throw new a(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Nn(e)}`);return{...c,id:s,type:o,function:{...d,name:u,arguments:l}}})}}:{...o,message:{...u,content:s,role:d,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Nn(e){return JSON.stringify(e)}var Pn=class e extends jn{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},Fn=class extends N{constructor(){super(...arguments),this.messages=new Pt(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(P`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(P`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/chat/completions/${e}`,t)}parse(e,t){return Gt(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>zt(t,e))}runTools(e,t){return e.stream?Pn.runTools(this._client,e,t):_n.runTools(this._client,e,t)}stream(e,t){return jn.createChatCompletion(this._client,e,t)}};Fn.Messages=Pt;var In=class extends N{constructor(){super(...arguments),this.completions=new Fn(this._client)}};In.Completions=Fn;const Ln=Symbol(`brand.privateNullableHeaders`);function*Rn(e){if(!e)return;if(Ln in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():S(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=S(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const H=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Rn(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Ln]:!0,values:t,nulls:n}};var zn=class extends N{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:H([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},Bn=class extends N{create(e,t){return this._client.post(`/audio/transcriptions`,M({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},Vn=class extends N{create(e,t){return this._client.post(`/audio/translations`,M({body:e,...t,__metadata:{model:e.model}},this._client))}},Hn=class extends N{constructor(){super(...arguments),this.transcriptions=new Bn(this._client),this.translations=new Vn(this._client),this.speech=new zn(this._client)}};Hn.Transcriptions=Bn,Hn.Translations=Vn,Hn.Speech=zn;var Un=class extends N{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/batches/${e}/cancel`,t)}},Wn=class extends N{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/assistants/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,j,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Gn=class extends N{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},Kn=class extends N{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},qn=class extends N{constructor(){super(...arguments),this.sessions=new Gn(this._client),this.transcriptionSessions=new Kn(this._client)}};qn.Sessions=Gn,qn.TranscriptionSessions=Kn;var Jn=class extends N{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(P`/chatkit/sessions/${e}/cancel`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},Yn=class extends N{retrieve(e,t){return this._client.get(P`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,pt,{query:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(P`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(P`/chatkit/threads/${e}/items`,pt,{query:t,...n,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},Xn=class extends N{constructor(){super(...arguments),this.sessions=new Jn(this._client),this.threads=new Yn(this._client)}};Xn.Sessions=Jn,Xn.Threads=Yn;var Zn=class extends N{create(e,t,n){return this._client.post(P`/threads/${e}/messages`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/messages/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/messages`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(P`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},Qn=class extends N{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(P`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(P`/threads/${r}/runs/${e}/steps`,j,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};const $n=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},U=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()};var W,G,er,K,tr,q,J,nr,Y,rr,X,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,mr,hr,gr=class extends sn{constructor(){super(...arguments),W.add(this),er.set(this,[]),K.set(this,{}),tr.set(this,{}),q.set(this,void 0),J.set(this,void 0),nr.set(this,void 0),Y.set(this,void 0),rr.set(this,void 0),X.set(this,void 0),ir.set(this,void 0),ar.set(this,void 0),or.set(this,void 0)}[(er=new WeakMap,K=new WeakMap,tr=new WeakMap,q=new WeakMap,J=new WeakMap,nr=new WeakMap,Y=new WeakMap,rr=new WeakMap,X=new WeakMap,ir=new WeakMap,ar=new WeakMap,or=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new G;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let i=et.fromReadableStream(e,this.controller);for await(let e of i)t(this,W,`m`,sr).call(this,e);if(i.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new G;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.submitToolOutputs(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,W,`m`,sr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}static createThreadAssistantStream(e,t,n){let r=new G;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new G;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return t(this,ir,`f`)}currentRun(){return t(this,ar,`f`)}currentMessageSnapshot(){return t(this,q,`f`)}currentRunStepSnapshot(){return t(this,or,`f`)}async finalRunSteps(){return await this.done(),Object.values(t(this,K,`f`))}async finalMessages(){return await this.done(),Object.values(t(this,tr,`f`))}async finalRun(){if(await this.done(),!t(this,J,`f`))throw Error(`Final run was not received.`);return t(this,J,`f`)}async _createThreadAssistantStream(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)t(this,W,`m`,sr).call(this,e);if(o.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}async _createAssistantStream(e,n,r,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener(`abort`,()=>this.controller.abort()));let o={...r,stream:!0},c=await e.create(n,o,{...i,signal:this.controller.signal});this._connected();for await(let e of c)t(this,W,`m`,sr).call(this,e);if(c.controller.signal?.aborted)throw new s;return this._addRun(t(this,W,`m`,cr).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ie(t)&&ie(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ie(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};G=gr,sr=function(n){if(!this.ended)switch(e(this,ir,n,`f`),t(this,W,`m`,dr).call(this,n),n.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:t(this,W,`m`,hr).call(this,n);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:t(this,W,`m`,ur).call(this,n);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:t(this,W,`m`,lr).call(this,n);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},cr=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);if(!t(this,J,`f`))throw Error(`Final run has not been received`);return t(this,J,`f`)},lr=function(n){let[r,i]=t(this,W,`m`,pr).call(this,n,t(this,q,`f`));e(this,q,r,`f`),t(this,tr,`f`)[r.id]=r;for(let e of i){let t=r.content[e.index];t?.type==`text`&&this._emit(`textCreated`,t.text)}switch(n.event){case`thread.message.created`:this._emit(`messageCreated`,n.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,n.data.delta,r),n.data.delta.content)for(let i of n.data.delta.content){if(i.type==`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type==`text`)this._emit(`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!=t(this,nr,`f`)){if(t(this,Y,`f`))switch(t(this,Y,`f`).type){case`text`:this._emit(`textDone`,t(this,Y,`f`).text,t(this,q,`f`));break;case`image_file`:this._emit(`imageFileDone`,t(this,Y,`f`).image_file,t(this,q,`f`));break}e(this,nr,i.index,`f`)}e(this,Y,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(t(this,nr,`f`)!==void 0){let e=n.data.content[t(this,nr,`f`)];if(e)switch(e.type){case`image_file`:this._emit(`imageFileDone`,e.image_file,t(this,q,`f`));break;case`text`:this._emit(`textDone`,e.text,t(this,q,`f`));break}}t(this,q,`f`)&&this._emit(`messageDone`,n.data),e(this,q,void 0,`f`)}},ur=function(n){let r=t(this,W,`m`,fr).call(this,n);switch(e(this,or,r,`f`),n.event){case`thread.run.step.created`:this._emit(`runStepCreated`,n.data);break;case`thread.run.step.delta`:let i=n.data.delta;if(i.step_details&&i.step_details.type==`tool_calls`&&i.step_details.tool_calls&&r.step_details.type==`tool_calls`)for(let n of i.step_details.tool_calls)n.index==t(this,rr,`f`)?this._emit(`toolCallDelta`,n,r.step_details.tool_calls[n.index]):(t(this,X,`f`)&&this._emit(`toolCallDone`,t(this,X,`f`)),e(this,rr,n.index,`f`),e(this,X,r.step_details.tool_calls[n.index],`f`),t(this,X,`f`)&&this._emit(`toolCallCreated`,t(this,X,`f`)));this._emit(`runStepDelta`,n.data.delta,r);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:e(this,or,void 0,`f`),n.data.step_details.type==`tool_calls`&&t(this,X,`f`)&&(this._emit(`toolCallDone`,t(this,X,`f`)),e(this,X,void 0,`f`)),this._emit(`runStepDone`,n.data,r);break;case`thread.run.step.in_progress`:break}},dr=function(e){t(this,er,`f`).push(e),this._emit(`event`,e)},fr=function(e){switch(e.event){case`thread.run.step.created`:return t(this,K,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let n=t(this,K,`f`)[e.data.id];if(!n)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data;if(r.delta){let i=G.accumulateDelta(n,r.delta);t(this,K,`f`)[e.data.id]=i}return t(this,K,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:t(this,K,`f`)[e.data.id]=e.data;break}if(t(this,K,`f`)[e.data.id])return t(this,K,`f`)[e.data.id];throw Error(`No snapshot available`)},pr=function(e,n){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:if(!n)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content)for(let e of i.delta.content)if(e.index in n.content){let r=n.content[e.index];n.content[e.index]=t(this,W,`m`,mr).call(this,e,r)}else n.content[e.index]=e,r.push(e);return[n,r];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(n)return[n,r];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},mr=function(e,t){return G.accumulateDelta(t,e)},hr=function(n){switch(e(this,ar,n.data,`f`),n.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:e(this,J,n.data,`f`),t(this,X,`f`)&&(this._emit(`toolCallDone`,t(this,X,`f`)),e(this,X,void 0,`f`));break;case`thread.run.cancelling`:break}};var _r=class extends N{constructor(){super(...arguments),this.steps=new Qn(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(P`/threads/${r}/runs/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/threads/${e}/runs`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(P`/threads/${r}/runs/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return gr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return gr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(P`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return gr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};_r.Steps=Qn;var vr=class extends N{constructor(){super(...arguments),this.runs=new _r(this._client),this.messages=new Zn(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/threads/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(P`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return gr.createThreadAssistantStream(e,this._client.beta.threads,t)}};vr.Runs=_r,vr.Messages=Zn;var yr=class extends N{constructor(){super(...arguments),this.realtime=new qn(this._client),this.chatkit=new Xn(this._client),this.assistants=new Wn(this._client),this.threads=new vr(this._client)}};yr.Realtime=qn,yr.ChatKit=Xn,yr.Assistants=Wn,yr.Threads=vr;var br=class extends N{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},xr=class extends N{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}/content`,{...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},Sr=class extends N{constructor(){super(...arguments),this.content=new xr(this._client)}create(e,t,n){return this._client.post(P`/containers/${e}/files`,vt({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(P`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/containers/${e}/files`,j,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(P`/containers/${r}/files/${e}`,{...n,headers:H([{Accept:`*/*`},n?.headers])})}};Sr.Content=xr;var Cr=class extends N{constructor(){super(...arguments),this.files=new Sr(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/containers/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}};Cr.Files=Sr;var wr=class extends N{create(e,t,n){let{include:r,...i}=t;return this._client.post(P`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(P`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(P`/conversations/${e}/items`,pt,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(P`/conversations/${r}/items/${e}`,n)}},Tr=class extends N{constructor(){super(...arguments),this.items=new wr(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/conversations/${e}`,t)}update(e,t,n){return this._client.post(P`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(P`/conversations/${e}`,t)}};Tr.Items=wr;var Er=class extends N{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(k(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=$n(t)}),e)))}},Dr=class extends N{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(P`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(P`/evals/${r}/runs/${e}/output_items`,j,{query:i,...n})}},Or=class extends N{constructor(){super(...arguments),this.outputItems=new Dr(this._client)}create(e,t,n){return this._client.post(P`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(P`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/evals/${e}/runs`,j,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(P`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(P`/evals/${r}/runs/${e}`,n)}};Or.OutputItems=Dr;var kr=class extends N{constructor(){super(...arguments),this.runs=new Or(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/evals/${e}`,t)}update(e,t,n){return this._client.post(P`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/evals/${e}`,t)}};kr.Runs=Or;var Ar=class extends N{create(e,t){return this._client.post(`/files`,M({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/files/${e}`,t)}content(e,t){return this._client.get(P`/files/${e}/content`,{...t,headers:H([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await se(t),a=await this.retrieve(e),Date.now()-i>n)throw new l({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},jr=class extends N{},Mr=class extends N{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}},Nr=class extends N{constructor(){super(...arguments),this.graders=new Mr(this._client)}};Nr.Graders=Mr;var Pr=class extends N{create(e,t,n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,ft,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(P`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/checkpoints/${e}/permissions`,pt,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(P`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},Fr=class extends N{constructor(){super(...arguments),this.permissions=new Pr(this._client)}};Fr.Permissions=Pr;var Ir=class extends N{list(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/checkpoints`,j,{query:t,...n})}},Lr=class extends N{constructor(){super(...arguments),this.checkpoints=new Ir(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(P`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,j,{query:e,...t})}cancel(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(P`/fine_tuning/jobs/${e}/events`,j,{query:t,...n})}pause(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(P`/fine_tuning/jobs/${e}/resume`,t)}};Lr.Checkpoints=Ir;var Z=class extends N{constructor(){super(...arguments),this.methods=new jr(this._client),this.jobs=new Lr(this._client),this.checkpoints=new Fr(this._client),this.alpha=new Nr(this._client)}};Z.Methods=jr,Z.Jobs=Lr,Z.Checkpoints=Fr,Z.Alpha=Nr;var Rr=class extends N{},zr=class extends N{constructor(){super(...arguments),this.graderModels=new Rr(this._client)}};zr.GraderModels=Rr;var Br=class extends N{createVariation(e,t){return this._client.post(`/images/variations`,M({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,M({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}},Vr=class extends N{retrieve(e,t){return this._client.get(P`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,ft,e)}delete(e,t){return this._client.delete(P`/models/${e}`,t)}},Hr=class extends N{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},Ur=class extends N{accept(e,t,n){return this._client.post(P`/realtime/calls/${e}/accept`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(P`/realtime/calls/${e}/hangup`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(P`/realtime/calls/${e}/refer`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(P`/realtime/calls/${e}/reject`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}},Wr=class extends N{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},Gr=class extends N{constructor(){super(...arguments),this.clientSecrets=new Wr(this._client),this.calls=new Ur(this._client)}};Gr.ClientSecrets=Wr,Gr.Calls=Ur;function Kr(e,t){return!t||!Yr(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:qr(e,t)}function qr(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:Qr(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:Jr(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||$r(r),Object.defineProperty(r,`output_parsed`,{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function Jr(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function Yr(e){return!!It(e.text?.format)}function Xr(e){return e?.$brand===`auto-parseable-tool`}function Zr(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function Qr(e,t){let n=Zr(e.tools??[],t.name);return{...t,...t,parsed_arguments:Xr(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function $r(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var ei,ti,Q,ni,ri,ii,ai,oi,si=class n extends sn{constructor(t){super(),ei.add(this),ti.set(this,void 0),Q.set(this,void 0),ni.set(this,void 0),e(this,ti,t,`f`)}static createResponse(e,t,r){let i=new n(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort())),t(this,ei,`m`,ri).call(this);let a,o=null;`response_id`in n?(a=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=n.starting_after??null):a=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of a)t(this,ei,`m`,ii).call(this,e,o);if(a.controller.signal?.aborted)throw new s;return t(this,ei,`m`,ai).call(this)}[(ti=new WeakMap,Q=new WeakMap,ni=new WeakMap,ei=new WeakSet,ri=function(){this.ended||e(this,Q,void 0,`f`)},ii=function(e,n){if(this.ended)return;let r=(e,t)=>{(n==null||t.sequence_number>n)&&this._emit(e,t)},i=t(this,ei,`m`,oi).call(this,e);switch(r(`event`,e),e.type){case`response.output_text.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);if(t.type===`message`){let n=t.content[e.content_index];if(!n)throw new a(`missing content at index ${e.content_index}`);if(n.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${n.type}`);r(`response.output_text.delta`,{...e,snapshot:n.text})}break}case`response.function_call_arguments.delta`:{let t=i.output[e.output_index];if(!t)throw new a(`missing output at index ${e.output_index}`);t.type===`function_call`&&r(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:r(e.type,e);break}},ai=function(){if(this.ended)throw new a(`stream has ended, this shouldn't happen`);let n=t(this,Q,`f`);if(!n)throw new a(`request ended without sending any events`);e(this,Q,void 0,`f`);let r=ci(n,t(this,ti,`f`));return e(this,ni,r,`f`),r},oi=function(n){let r=t(this,Q,`f`);if(!r){if(n.type!==`response.created`)throw new a(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=e(this,Q,n.response,`f`),r}switch(n.type){case`response.output_item.added`:r.output.push(n.item);break;case`response.content_part.added`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);let t=e.type,i=n.part;t===`message`&&i.type!==`reasoning_text`?e.content.push(i):t===`reasoning`&&i.type===`reasoning_text`&&(e.content||=[],e.content.push(i));break}case`response.output_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`message`){let t=e.content[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`output_text`)throw new a(`expected content to be 'output_text', got ${t.type}`);t.text+=n.delta}break}case`response.function_call_arguments.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);e.type===`function_call`&&(e.arguments+=n.delta);break}case`response.reasoning_text.delta`:{let e=r.output[n.output_index];if(!e)throw new a(`missing output at index ${n.output_index}`);if(e.type===`reasoning`){let t=e.content?.[n.content_index];if(!t)throw new a(`missing content at index ${n.content_index}`);if(t.type!==`reasoning_text`)throw new a(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=n.delta}break}case`response.completed`:e(this,Q,n.response,`f`);break}return r},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=t(this,ni,`f`);if(!e)throw new a(`stream ended without producing a ChatCompletion`);return e}};function ci(e,t){return Kr(e,t)}var li=class extends N{list(e,t={},n){return this._client.getAPIList(P`/responses/${e}/input_items`,j,{query:t,...n})}},ui=class extends N{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},di=class extends N{constructor(){super(...arguments),this.inputItems=new li(this._client),this.inputTokens=new ui(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&$r(e),e))}retrieve(e,t={},n){return this._client.get(P`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&$r(e),e))}delete(e,t){return this._client.delete(P`/responses/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>qr(t,e))}stream(e,t){return si.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(P`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};di.InputItems=li,di.InputTokens=ui;var fi=class extends N{retrieve(e,t){return this._client.get(P`/skills/${e}/content`,{...t,headers:H([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}},pi=class extends N{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}/content`,{...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},mi=class extends N{constructor(){super(...arguments),this.content=new pi(this._client)}create(e,t={},n){return this._client.post(P`/skills/${e}/versions`,vt({body:t,...n},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(P`/skills/${r}/versions/${e}`,n)}list(e,t={},n){return this._client.getAPIList(P`/skills/${e}/versions`,j,{query:t,...n})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(P`/skills/${r}/versions/${e}`,n)}};mi.Content=pi;var hi=class extends N{constructor(){super(...arguments),this.content=new fi(this._client),this.versions=new mi(this._client)}create(e={},t){return this._client.post(`/skills`,vt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/skills/${e}`,t)}update(e,t,n){return this._client.post(P`/skills/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/skills`,j,{query:e,...t})}delete(e,t){return this._client.delete(P`/skills/${e}`,t)}};hi.Content=fi,hi.Versions=mi;var gi=class extends N{create(e,t,n){return this._client.post(P`/uploads/${e}/parts`,M({body:t,...n},this._client))}},_i=class extends N{constructor(){super(...arguments),this.parts=new gi(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(P`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(P`/uploads/${e}/complete`,{body:t,...n})}};_i.Parts=gi;const vi=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r};var yi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/file_batches`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/file_batches/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(P`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(P`/vector_stores/${r}/file_batches/${e}/files`,j,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await vi(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},bi=class extends N{create(e,t,n){return this._client.post(P`/vector_stores/${e}/files`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(P`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(P`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(P`/vector_stores/${e}/files`,j,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(P`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await se(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(P`/vector_stores/${r}/files/${e}/content`,ft,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},xi=class extends N{constructor(){super(...arguments),this.files=new bi(this._client),this.fileBatches=new yi(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(P`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(P`/vector_stores/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,j,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(P`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(P`/vector_stores/${e}/search`,ft,{body:t,method:`post`,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};xi.Files=bi,xi.FileBatches=yi;var Si=class extends N{create(e,t){return this._client.post(`/videos`,vt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(P`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,pt,{query:e,...t})}delete(e,t){return this._client.delete(P`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(P`/videos/${e}/content`,{query:t,...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(P`/videos/${e}/remix`,vt({body:t,...n},this._client))}},Ci,wi,Ti,Ei=class extends N{constructor(){super(...arguments),Ci.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,i=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");t(this,Ci,`m`,wi).call(this,r);let a=H([n]).values,o=t(this,Ci,`m`,Ti).call(this,a,`webhook-signature`),s=t(this,Ci,`m`,Ti).call(this,a,`webhook-timestamp`),c=t(this,Ci,`m`,Ti).call(this,a,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new b(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>i)throw new b(`Webhook timestamp is too old`);if(l>u+i)throw new b(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=r.startsWith(`whsec_`)?Buffer.from(r.replace(`whsec_`,``),`base64`):Buffer.from(r,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new b(`The given webhook signature does not match the expected signature`)}};Ci=new WeakSet,wi=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},Ti=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var Di,Oi,ki,Ai,$=class{constructor({baseURL:t=U(`OPENAI_BASE_URL`),apiKey:n=U(`OPENAI_API_KEY`),organization:r=U(`OPENAI_ORG_ID`)??null,project:i=U(`OPENAI_PROJECT_ID`)??null,webhookSecret:o=U(`OPENAI_WEBHOOK_SECRET`)??null,...s}={}){if(Di.add(this),ki.set(this,void 0),this.completions=new br(this),this.chat=new In(this),this.embeddings=new Er(this),this.files=new Ar(this),this.images=new Br(this),this.audio=new Hn(this),this.moderations=new Hr(this),this.models=new Vr(this),this.fineTuning=new Z(this),this.graders=new zr(this),this.vectorStores=new xi(this),this.webhooks=new Ei(this),this.beta=new yr(this),this.batches=new Un(this),this.uploads=new _i(this),this.responses=new di(this),this.realtime=new Gr(this),this.conversations=new Tr(this),this.evals=new kr(this),this.containers=new Cr(this),this.skills=new hi(this),this.videos=new Si(this),n===void 0)throw new a("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let c={apiKey:n,organization:r,project:i,webhookSecret:o,...s,baseURL:t||`https://api.openai.com/v1`};if(!c.dangerouslyAllowBrowser&&ce())throw new a(`It looks like you're running in a browser-like environment.
8
-
9
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
- If you understand the risks and have appropriate mitigations in place,
11
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
-
13
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
14
-
15
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
16
- `);this.baseURL=c.baseURL,this.timeout=c.timeout??Oi.DEFAULT_TIMEOUT,this.logger=c.logger??console;let l=`warn`;this.logLevel=l,this.logLevel=Je(c.logLevel,`ClientOptions.logLevel`,this)??Je(U(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??l,this.fetchOptions=c.fetchOptions,this.maxRetries=c.maxRetries??2,this.fetch=c.fetch??ge(),e(this,ki,xe,`f`),this._options=c,this.apiKey=typeof n==`string`?n:`Missing Key`,this.organization=r,this.project=i,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return H([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Re(e)}getUserAgent(){return`${this.constructor.name}/JS ${w}`}defaultIdempotencyKey(){return`stainless-node-retry-${n()}`}makeStatusError(e,t,n,r){return o.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof a?e:new a(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new a(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,n,r){let i=!t(this,Di,`m`,Ai).call(this)&&r||this.baseURL,a=te(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery();return ne(o)||(n={...o,...n}),typeof n==`object`&&n&&!Array.isArray(n)&&(a.search=this.stringifyQuery(n)),a.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ct(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let a=await e,o=a.maxRetries??this.maxRetries;t??=o,await this.prepareOptions(a);let{req:u,url:d,timeout:f}=await this.buildRequest(a,{retryCount:o-t});await this.prepareRequest(u,{url:d,options:a});let p=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),m=n===void 0?``:`, retryOf: ${n}`,h=Date.now();if(k(this).debug(`[${p}] sending request`,A({retryOfRequestLogID:n,method:a.method,url:d,options:a,headers:u.headers})),a.signal?.aborted)throw new s;let g=new AbortController,_=await this.fetchWithTimeout(d,u,f,g).catch(i),v=Date.now();if(_ instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(a.signal?.aborted)throw new s;let i=r(_)||/timed? ?out/i.test(String(_)+(`cause`in _?String(_.cause):``));if(t)return k(this).info(`[${p}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (${e})`,A({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),this.retryRequest(a,t,n??p);throw k(this).info(`[${p}] connection ${i?`timed out`:`failed`} - error; no more retries left`),k(this).debug(`[${p}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,A({retryOfRequestLogID:n,url:d,durationMs:v-h,message:_.message})),i?new l:new c({cause:_})}let y=`[${p}${m}${[..._.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${u.method} ${d} ${_.ok?`succeeded`:`failed`} with status ${_.status} in ${v-h}ms`;if(!_.ok){let e=await this.shouldRetry(_);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await be(_.body),k(this).info(`${y} - ${e}`),k(this).debug(`[${p}] response error (${e})`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),this.retryRequest(a,t,n??p,_.headers)}let r=e?`error; no more retries left`:`error; not retryable`;k(this).info(`${y} - ${r}`);let o=await _.text().catch(e=>i(e).message),s=oe(o),c=s?void 0:o;throw k(this).debug(`[${p}] response error (${r})`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,message:c,durationMs:Date.now()-h})),this.makeStatusError(_.status,s,c,_.headers)}return k(this).info(y),k(this).debug(`[${p}] response start`,A({retryOfRequestLogID:n,url:_.url,status:_.status,headers:_.headers,durationMs:v-h})),{response:_,options:a,controller:g,requestLogID:p,retryOfRequestLogID:n,startTime:h}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new dt(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await se(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ae(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=H([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...he(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=H([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&r.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:ve(e)}:typeof e==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(e)}:t(this,ki,`f`).call(this,{body:e,headers:r})}};Oi=$,ki=new WeakMap,Di=new WeakSet,Ai=function(){return this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=Oi,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=a,$.APIError=o,$.APIConnectionError=c,$.APIConnectionTimeoutError=l,$.APIUserAbortError=s,$.NotFoundError=p,$.ConflictError=m,$.RateLimitError=g,$.BadRequestError=u,$.AuthenticationError=d,$.InternalServerError=_,$.PermissionDeniedError=f,$.UnprocessableEntityError=h,$.InvalidWebhookSignatureError=b,$.toFile=kt,$.Completions=br,$.Chat=In,$.Embeddings=Er,$.Files=Ar,$.Images=Br,$.Audio=Hn,$.Moderations=Hr,$.Models=Vr,$.FineTuning=Z,$.Graders=zr,$.VectorStores=xi,$.Webhooks=Ei,$.Beta=yr,$.Batches=Un,$.Uploads=_i,$.Responses=di,$.Realtime=Gr,$.Conversations=Tr,$.Evals=kr,$.Containers=Cr,$.Skills=hi,$.Videos=Si;var ji=class extends ${constructor({baseURL:e=U(`OPENAI_BASE_URL`),apiKey:t=U(`AZURE_OPENAI_API_KEY`),apiVersion:n=U(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:o,dangerouslyAllowBrowser:s,...c}={}){if(!n)throw new a(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof o==`function`&&(s=!0),!o&&!t)throw new a("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new a("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(c.defaultQuery={...c.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new a("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${r}/openai`}else if(r)throw new a(`baseURL and endpoint are mutually exclusive`);super({apiKey:o??t,baseURL:e,...c,...s===void 0?{}:{dangerouslyAllowBrowser:s}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(Mi.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!ie(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e){return typeof this._options.apiKey==`string`?H([{"api-key":this.apiKey}]):super.authHeaders(e)}};const Mi=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);export{$ as n,ji as t};
@@ -1,7 +0,0 @@
1
- import{t as e}from"./env-api-keys-DEKGEdJy.js";import{a as t,c as n,n as r}from"./simple-options-CVJdKrCb.js";import{i,n as a,r as o,t as s}from"./diagnostics-C5z6rwkV.js";import{t as c}from"./headers-CGhBAvcc.js";import{n as l,r as u,t as d}from"./openai-responses-shared-iv5WheAz.js";let f=null;typeof process<`u`&&(process.versions?.node||process.versions?.bun)&&(e=>import(e))(`node:os`).then(e=>{f=e});const p=1e3,m=new Set([`openai`,`openai-codex`,`opencode`]),h=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function g(e,t){return e===429||e===500||e===502||e===503||e===504?!0:/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function _(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`))})})}const v=(n,r,i)=>{let o=new t;return(async()=>{let t={role:`assistant`,content:[],api:`openai-codex-responses`,provider:n.provider,model:n.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 l=i?.apiKey||e(n.provider)||``;if(!l)throw Error(`No API key for provider: ${n.provider}`);let u=ue(l),d=b(n,r,i),f=await i?.onPayload?.(d,n);f!==void 0&&(d=f);let m=i?.sessionId||de(),h=fe(n.headers,i?.headers,u,l,i?.sessionId),v=pe(n.headers,i?.headers,u,l,m),y=JSON.stringify(d),x=i?.transport||`auto`,S=x!==`sse`&&B(i?.sessionId);if(S&&V(i?.sessionId),x!==`sse`&&!S){let e=!1;try{if(await ce(T(n.baseUrl),d,v,t,o,n,()=>{e=!0},i),i?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:t.stopReason,message:t}),o.end();return}catch(n){if(i?.signal?.aborted||k(n)||(s(t,a(`provider_transport_failure`,n,{configuredTransport:x,fallbackTransport:e?void 0:`sse`,eventsEmitted:e,phase:e?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(y).byteLength})),ee(i?.sessionId,n),e))throw n;V(i?.sessionId)}}let C,D;for(let e=0;e<=3;e++){if(i?.signal?.aborted)throw Error(`Request was aborted`);try{if(C=await fetch(w(n.baseUrl),{method:`POST`,headers:h,body:y,signal:i?.signal}),await i?.onResponse?.({status:C.status,headers:c(C.headers)},n),C.ok)break;let t=await C.text();if(e<3&&g(C.status,t)){await _(p*2**e,i?.signal);continue}let r=await le(new Response(t,{status:C.status,statusText:C.statusText}));throw Error(r.friendlyMessage||r.message)}catch(t){if(t instanceof Error&&(t.name===`AbortError`||t.message===`Request was aborted`))throw Error(`Request was aborted`);if(D=t instanceof Error?t:Error(String(t)),e<3&&!D.message.includes(`usage limit`)){await _(p*2**e,i?.signal);continue}throw D}}if(!C?.ok)throw D??Error(`Failed after retries`);if(!C.body)throw Error(`No response body`);if(o.push({type:`start`,partial:t}),await E(C,t,o,n,i),i?.signal?.aborted)throw Error(`Request was aborted`);o.push({type:`done`,reason:t.stopReason,message:t}),o.end()}catch(e){for(let e of t.content)delete e.partialJson;t.stopReason=i?.signal?.aborted?`aborted`:`error`,t.errorMessage=e instanceof Error?e.message:String(e),o.push({type:`error`,reason:t.stopReason,error:t}),o.end()}})(),o},y=(t,i,a)=>{let o=a?.apiKey||e(t.provider);if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=r(t,a,o),c=a?.reasoning?n(t,a.reasoning):void 0,l=c===`off`?void 0:c;return v(t,i,{...s,reasoningEffort:l})};function b(e,t,n){let r=d(e,t,m,{includeSystemPrompt:!1}),i={model:e.id,store:!1,stream:!0,instructions:t.systemPrompt||`You are a helpful assistant.`,input:r,text:{verbosity:n?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:n?.sessionId,tool_choice:`auto`,parallel_tool_calls:!0};if(n?.temperature!==void 0&&(i.temperature=n.temperature),n?.serviceTier!==void 0&&(i.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(i.tools=l(t.tools,{strict:null})),n?.reasoningEffort!==void 0){let t=n.reasoningEffort===`none`?e.thinkingLevelMap?.off??`none`:e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort;t!==null&&(i.reasoning={effort:t,summary:n.reasoningSummary??`auto`})}return i}function x(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function S(e,t,n){let r=x(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 C(e,t){return e===`default`&&(t===`flex`||t===`priority`)?t:e??t}function w(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 T(e){let t=new URL(w(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function E(e,t,n,r,i){await u(A(M(e)),t,n,r,{serviceTier:i?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,r)})}var D=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}},O=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}};function k(e){return e instanceof D||e instanceof O}async function*A(e){for await(let t of e){let e=typeof t.type==`string`?t.type:void 0;if(e){if(e===`error`){let e=t.code||``;throw new D(`Codex error: ${t.message||e||JSON.stringify(t)}`,{code:e||void 0,payload:t})}if(e===`response.failed`){let e=t.response,n=e?.error?.code,r=e?.error?.message;throw new D(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:j(e.status)};yield{...t,type:`response.completed`,response:n};return}yield t}}}function j(e){if(typeof e==`string`)return h.has(e)?e:void 0}async function*M(e){if(!e.body)return;let t=e.body.getReader(),n=new TextDecoder,r=``;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;r+=n.decode(i,{stream:!0});let a=r.indexOf(`
2
-
3
- `);for(;a!==-1;){let e=r.slice(0,a);r=r.slice(a+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 O(`Invalid Codex SSE JSON: ${o(t)}`,{cause:t,payload:e})}}a=r.indexOf(`
6
-
7
- `)}}}finally{try{await t.cancel()}catch{}try{t.releaseLock()}catch{}}}const N=new Map,P=new Map,F=new Set;function I(e){let t=P.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},P.set(e,t)),t}function L(e){let t=P.get(e);return t?{...t}:void 0}function R(e){if(e){P.delete(e),F.delete(e);return}P.clear(),F.clear()}function z(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),G(e.socket,1e3,`debug_close`)};if(e){let n=N.get(e);n&&t(n),N.delete(e);return}for(let e of N.values())t(e);N.clear()}i(z);function B(e){return e?F.has(e):!1}function V(e){if(!e)return;let t=I(e);t.sseFallbacks++,t.websocketFallbackActive=B(e)}function ee(e,t){if(!e)return;F.add(e);let n=I(e);n.websocketFailures++,n.lastWebSocketError=o(t),n.websocketFallbackActive=!0}function te(){let e=globalThis.WebSocket;return typeof e==`function`?e:null}var H=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 U(e){let t=e.readyState;return typeof t==`number`?t:void 0}function W(e){let t=U(e);return t===void 0||t===1}function G(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function K(e,t){t.idleTimer&&clearTimeout(t.idleTimer),t.idleTimer=setTimeout(()=>{t.busy||(G(t.socket,1e3,`idle_timeout`),N.delete(e))},3e5)}async function q(e,t,n){let r=te();if(!r)throw Error(`WebSocket transport is not available in this runtime`);let i=c(t);return delete i[`OpenAI-Beta`],new Promise((t,a)=>{let o=!1,s;try{s=new r(e,{headers:i})}catch(e){a(e instanceof Error?e:Error(String(e)));return}let c=()=>{o||(o=!0,f(),t(s))},l=e=>{let t=Y(e);o||(o=!0,f(),a(t))},u=e=>{let t=X(e);o||(o=!0,f(),a(t))},d=()=>{o||(o=!0,f(),s.close(1e3,`aborted`),a(Error(`Request was aborted`)))},f=()=>{s.removeEventListener(`open`,c),s.removeEventListener(`error`,l),s.removeEventListener(`close`,u),n?.removeEventListener(`abort`,d)};s.addEventListener(`open`,c),s.addEventListener(`error`,l),s.addEventListener(`close`,u),n?.addEventListener(`abort`,d)})}async function J(e,t,n,r){if(!n){let n=await q(e,t,r);return{socket:n,reused:!1,release:({keep:e}={})=>{if(e===!1){G(n);return}G(n)}}}let i=N.get(n);if(i){if(i.idleTimer&&=(clearTimeout(i.idleTimer),void 0),!i.busy&&W(i.socket))return i.busy=!0,{socket:i.socket,entry:i,reused:!0,release:({keep:e}={})=>{if(!e||!W(i.socket)){G(i.socket),N.delete(n);return}i.busy=!1,K(n,i)}};if(i.busy){let n=await q(e,t,r);return{socket:n,reused:!1,release:()=>{G(n)}}}W(i.socket)||(G(i.socket),N.delete(n))}let a=await q(e,t,r),o={socket:a,busy:!0};return N.set(n,o),{socket:a,entry:o,reused:!1,release:({keep:e}={})=>{if(!e||!W(o.socket)){G(o.socket),o.idleTimer&&clearTimeout(o.idleTimer),N.get(n)===o&&N.delete(n);return}o.busy=!1,K(n,o)}}}function Y(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 X(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 H(`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 Z(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*ne(e,t){let n=[],r=null,i=!1,a=null,s=!1,c=()=>{if(!r)return;let e=r;r=null,e()},l=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await Z(e.data),!t))return;let r=JSON.parse(t),a=typeof r.type==`string`?r.type:``;(a===`response.completed`||a===`response.done`||a===`response.incomplete`)&&(s=!0,i=!0),n.push(r),c()}catch(e){a=new O(`Invalid Codex WebSocket JSON: ${o(e)}`,{cause:e,payload:t}),i=!0,c()}})()},u=e=>{a=Y(e),i=!0,c()},d=e=>{if(s){i=!0,c();return}a||=X(e),i=!0,c()},f=()=>{a=Error(`Request was aborted`),i=!0,c()};e.addEventListener(`message`,l),e.addEventListener(`error`,u),e.addEventListener(`close`,d),t?.addEventListener(`abort`,f);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(n.length>0){yield n.shift();continue}if(i)break;await new Promise(e=>{r=e})}if(a)throw a;if(!s)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,l),e.removeEventListener(`error`,u),e.removeEventListener(`close`,d),t?.removeEventListener(`abort`,f)}}function Q(e){let{input:t,previous_response_id:n,...r}=e;return r}function re(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function ie(e,t){return JSON.stringify(Q(e))===JSON.stringify(Q(t))}function ae(e,t){if(!ie(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&re(n.slice(0,r.length),r))return n.slice(r.length)}function oe(e,t){let n=e.continuation;if(!n)return t;let r=ae(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*se(e,t,n,r){let i=!1;for await(let a of e)i||(i=!0,r(),n.push({type:`start`,partial:t})),yield a}async function ce(e,t,n,r,i,a,o,s){let{socket:c,entry:l,reused:f,release:p}=await J(e,n,s?.sessionId,s?.signal),h=!0,g=s?.transport===`websocket-cached`||s?.transport===`auto`,_=t,v=g&&l?oe(l,_):_,y=s?.sessionId?I(s.sessionId):void 0;y&&(y.requests++,f?y.connectionsReused++:y.connectionsCreated++,g&&y.cachedContextRequests++,v.store===!0&&y.storeTrueRequests++,y.lastInputItems=v.input?.length??0,v.previous_response_id?(y.deltaRequests++,y.lastDeltaInputItems=v.input?.length??0,y.lastPreviousResponseId=v.previous_response_id):(y.fullContextRequests++,y.lastDeltaInputItems=void 0,y.lastPreviousResponseId=void 0));try{if(c.send(JSON.stringify({type:`response.create`,...v})),await u(se(A(ne(c,s?.signal)),r,i,o),r,i,a,{serviceTier:s?.serviceTier,resolveServiceTier:C,applyServiceTierPricing:(e,t)=>S(e,t,a)}),s?.signal?.aborted)h=!1;else if(g&&l&&r.responseId){let e=d(a,{messages:[r]},m,{includeSystemPrompt:!1}).filter(e=>e.type!==`function_call_output`);l.continuation={lastRequestBody:_,lastResponseId:r.responseId,lastResponseItems:e}}}catch(e){throw l&&(l.continuation=void 0),h=!1,e}finally{p({keep:h})}}async function le(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 ue(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 de(){return typeof globalThis.crypto?.randomUUID==`function`?globalThis.crypto.randomUUID():`codex_${Date.now()}_${Math.random().toString(36).slice(2,10)}`}function $(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))i.set(e,n);i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`);let a=f?`pi (${f.platform()} ${f.release()}; ${f.arch()})`:`pi (browser)`;return i.set(`User-Agent`,a),i}function fe(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 pe(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{z as closeOpenAICodexWebSocketSessions,L as getOpenAICodexWebSocketDebugStats,R as resetOpenAICodexWebSocketDebugStats,v as streamOpenAICodexResponses,y as streamSimpleOpenAICodexResponses};