sliccy 3.40.1 → 3.40.3
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.
- package/README.md +1 -1
- package/dist/node-server/_shared/index.d.ts +2 -0
- package/dist/node-server/_shared/index.d.ts.map +1 -1
- package/dist/node-server/_shared/index.js +2 -0
- package/dist/node-server/_shared/index.js.map +1 -1
- package/dist/node-server/_shared/sign-and-forward.d.ts +75 -0
- package/dist/node-server/_shared/sign-and-forward.d.ts.map +1 -0
- package/dist/node-server/_shared/sign-and-forward.js +278 -0
- package/dist/node-server/_shared/sign-and-forward.js.map +1 -0
- package/dist/node-server/_shared/sigv4.d.ts +26 -0
- package/dist/node-server/_shared/sigv4.d.ts.map +1 -0
- package/dist/node-server/{secrets/signing-s3.js → _shared/sigv4.js} +8 -16
- package/dist/node-server/_shared/sigv4.js.map +1 -0
- package/dist/node-server/secrets/sign-and-forward.d.ts +6 -26
- package/dist/node-server/secrets/sign-and-forward.js +40 -247
- package/dist/ui/assets/__vite-browser-external-CM3Eme-n.js +1 -0
- package/dist/ui/assets/adobe-9MnG5h7i.js +2 -0
- package/dist/ui/assets/{adobe-BuddmT1_.js → adobe-BCOGa4JO.js} +1 -1
- package/dist/ui/assets/agent-bridge-DrtqeACp.js +1 -0
- package/dist/ui/assets/agent-message-to-chat-BadHh_U6.js +7 -0
- package/dist/ui/assets/{anthropic-BgHKqajT.js → anthropic-DOdK4eXe.js} +4 -4
- package/dist/ui/assets/{anthropic-CtzKOYSY.js → anthropic-DVQtRZtV.js} +2 -2
- package/dist/ui/assets/{apps-DUrh4PEK.js → apps-D6zYxCJj.js} +2 -2
- package/dist/ui/assets/azure-openai-Cr3DISar.js +1 -0
- package/dist/ui/assets/azure-openai-DX23xqSp.js +1 -0
- package/dist/ui/assets/azure-openai-responses-DXY_e5sT.js +1 -0
- package/dist/ui/assets/azure-openai-responses-KQPM7_wG.js +1 -0
- package/dist/ui/assets/backend-local-CMfz45hs.js +9 -0
- package/dist/ui/assets/bedrock-camp-CWvhREqw.js +4 -0
- package/dist/ui/assets/bedrock-camp-Cg_vY0Xg.js +5 -0
- package/dist/ui/assets/biome_wasm-DEjrJMqV.js +1 -0
- package/dist/ui/assets/{bsh-watchdog-x1NhC21S.js → bsh-watchdog-DVEMoD1Q.js} +1 -1
- package/dist/ui/assets/{cdp-CIf67Kji.js → cdp-lOc6_BAx.js} +4 -4
- package/dist/ui/assets/cdp-ws-page-bridge-D_PY6ku1.js +1 -0
- package/dist/ui/assets/chunk-CMxvf4Kt.js +1 -0
- package/dist/ui/assets/chunk-aKtaBQYM.js +1 -0
- package/dist/ui/assets/clipboard-C2cR8flR.js +1 -0
- package/dist/ui/assets/clipboard-DgFtRQbq.js +1 -0
- package/dist/ui/assets/common-ewBM5he1.js +1 -0
- package/dist/ui/assets/{connect-surface-D4wcacvR.js → connect-surface-DoTyR_ZG.js} +1 -1
- package/dist/ui/assets/cost-command-CThcmGZA.js +1 -0
- package/dist/ui/assets/diagnostics-DRDFDs4d.js +1 -0
- package/dist/ui/assets/diagnostics-mI-AnKx_.js +1 -0
- package/dist/ui/assets/{dist-CUdWMJvw.js → dist-BrPNw_vU.js} +4 -4
- package/dist/ui/assets/{dist-CU640e2s.js → dist-C9EWpOKG.js} +1 -1
- package/dist/ui/assets/{dist-CrZ60vIK.js → dist-Cu5Yqq5d2.js} +1 -1
- package/dist/ui/assets/{dist-CXh0a315.js → dist-DbTbRU9p2.js} +4 -4
- package/dist/ui/assets/{es-BCqpNDbf.js → es-Do-6wb2C.js} +5 -5
- package/dist/ui/assets/{esp32-z35G3TbR.js → esp32-BTVUAltJ.js} +1 -1
- package/dist/ui/assets/esp32-CatgC_Vd.js +1 -0
- package/dist/ui/assets/{esp32c2-gLxOsZif.js → esp32c2-CpROmlB0.js} +1 -1
- package/dist/ui/assets/{esp32c2-pl5qy6El.js → esp32c2-Cvhq9547.js} +1 -1
- package/dist/ui/assets/{esp32c3-P3fd2u0V.js → esp32c3-D9lOBWYZ.js} +1 -1
- package/dist/ui/assets/esp32c3-heViyR1Q.js +1 -0
- package/dist/ui/assets/{esp32c5-B1WV7eXo.js → esp32c5-D2poFXyG.js} +1 -1
- package/dist/ui/assets/{esp32c5-VtJmrubf.js → esp32c5-KJSqwo2Q.js} +1 -1
- package/dist/ui/assets/{esp32c6-B-u1dpSJ.js → esp32c6-BMEnOhZ6.js} +1 -1
- package/dist/ui/assets/{esp32c6-roW5XaV9.js → esp32c6-Ct3LxBMw.js} +1 -1
- package/dist/ui/assets/{esp32c61-BEqxfS6j.js → esp32c61-BsudQf3e.js} +1 -1
- package/dist/ui/assets/{esp32c61-e_DudgN9.js → esp32c61-sRp43nbI.js} +1 -1
- package/dist/ui/assets/{esp32h2-BNSoMBaR.js → esp32h2-BKv-WORi.js} +1 -1
- package/dist/ui/assets/{esp32h2-DfHWoI2F.js → esp32h2-CPO25efF.js} +1 -1
- package/dist/ui/assets/{esp32p4-B28QO5xI.js → esp32p4-GHiT8voO.js} +1 -1
- package/dist/ui/assets/{esp32p4-oT03skoL.js → esp32p4-g1tFG0sh.js} +1 -1
- package/dist/ui/assets/{esp32s2-PvYKf6wY.js → esp32s2-BE2gO68i.js} +1 -1
- package/dist/ui/assets/{esp32s2-B4ccaXVM.js → esp32s2-DrH4e7iJ.js} +1 -1
- package/dist/ui/assets/{esp32s3-BEGROUfT.js → esp32s3-BHbeScNz.js} +1 -1
- package/dist/ui/assets/{esp32s3-BR5mq9LB.js → esp32s3-CjMu3q4c.js} +1 -1
- package/dist/ui/assets/esp8266-BPLrOmN4.js +1 -0
- package/dist/ui/assets/esp8266-DNz2CP4r.js +1 -0
- package/dist/ui/assets/esptool-operations-CiX8mbpu.js +12 -0
- package/dist/ui/assets/{esptool-operations-BmdDP4Te.js → esptool-operations-SV6FPHJC.js} +2 -2
- package/dist/ui/assets/{follower-sprinkle-bridge-DhhhEoEw.js → follower-sprinkle-bridge-DTufY-0i.js} +1 -1
- package/dist/ui/assets/fs-DqDo5o60.js +1 -0
- package/dist/ui/assets/github-CNn2NQAt.js +1 -0
- package/dist/ui/assets/github-DBywtHRG.js +2 -0
- package/dist/ui/assets/github-copilot-8wjbN6nq.js +1 -0
- package/dist/ui/assets/github-copilot-Dy9dkbr7.js +2 -0
- package/dist/ui/assets/google-BbVPHS50.js +1 -0
- package/dist/ui/assets/google-Dl6In6_I.js +1 -0
- package/dist/ui/assets/google-shared-BgawM9oG.js +11 -0
- package/dist/ui/assets/{google-shared-BqepQLFX.js → google-shared-BmpiIO3m.js} +3 -3
- package/dist/ui/assets/google-vertex-DGjVDVSA.js +1 -0
- package/dist/ui/assets/google-vertex-uZ8N77ah.js +1 -0
- package/dist/ui/assets/hid-device-registry-D2LsJCRr.js +1 -0
- package/dist/ui/assets/hosted-config-apply-uAym2aS5.js +1 -0
- package/dist/ui/assets/intercepted-oauth-tLpKagkf.js +1 -0
- package/dist/ui/assets/json-parse-BIGBjpLL.js +3 -0
- package/dist/ui/assets/json-parse-BUunmmNl.js +3 -0
- package/dist/ui/assets/kernel-worker-Cb8hTQlK.js +9547 -0
- package/dist/ui/assets/lick-ws-bridge-BiG3e_g1.js +1 -0
- package/dist/ui/assets/{local-llm-BSBAbQIB.js → local-llm-BazZFDj_.js} +2 -2
- package/dist/ui/assets/logger-DDBAeTLF.js +1 -0
- package/dist/ui/assets/logger-LESFN7Hj.js +1 -0
- package/dist/ui/assets/magick-wasm-DKLq0X9v.js +1 -0
- package/dist/ui/assets/main-cherry-_7zmLxgg.js +1 -0
- package/dist/ui/assets/main-yZCsVpFH.js +1813 -0
- package/dist/ui/assets/migration-run-CXbSDDok.js +1 -0
- package/dist/ui/assets/mime-types-B9LIwKG5.js +1 -0
- package/dist/ui/assets/mime-types-BG9Gw1bq.js +1 -0
- package/dist/ui/assets/{mistral-BgklU_Dp.js → mistral-CMJILYv2.js} +4 -4
- package/dist/ui/assets/{mistral-DzTfCccO.js → mistral-DGtcP1BQ.js} +4 -4
- package/dist/ui/assets/mount-C3YOm4Wn.js +1 -0
- package/dist/ui/assets/mount-id-nJcx05eu.js +1 -0
- package/dist/ui/assets/mount-picker-popup-DncaR5N8.js +1 -0
- package/dist/ui/assets/mount-table-store-CQJEV6Ij.js +1 -0
- package/dist/ui/assets/nodejs-BQ9Oov1A.js +1 -0
- package/dist/ui/assets/{nuke-command-B02fs5G-.js → nuke-command-Dmc-Sve3.js} +1 -1
- package/dist/ui/assets/oauth-Czw-MuuR.js +1 -0
- package/dist/ui/assets/oauth-bootstrap-C_DI66X8.js +2 -0
- package/dist/ui/assets/oauth-service-CFSmb2Xq.js +1 -0
- package/dist/ui/assets/oauth-service-CSJo71ct.js +1 -0
- package/dist/ui/assets/offscreen-client-Bn2ErFJg.js +1 -0
- package/dist/ui/assets/onboarding-orchestrator-DbSXIbPW.js +1 -0
- package/dist/ui/assets/openai-codex-BehcTqf4.js +1 -0
- package/dist/ui/assets/openai-codex-Df_T8mMz.js +1 -0
- package/dist/ui/assets/openai-codex-responses-Dpn8XW3b.js +7 -0
- package/dist/ui/assets/openai-codex-responses-bUy20doI.js +7 -0
- package/dist/ui/assets/openai-completions-B_5Ph3h0.js +5 -0
- package/dist/ui/assets/openai-completions-CoYClIFl.js +5 -0
- package/dist/ui/assets/openai-i4HWKCeW.js +16 -0
- package/dist/ui/assets/openai-responses-BQOBB5px.js +1 -0
- package/dist/ui/assets/openai-responses-DqkDb9a5.js +1 -0
- package/dist/ui/assets/{openai-responses-shared-CsK-8CQH.js → openai-responses-shared-CZOJCHE4.js} +4 -4
- package/dist/ui/assets/{openai-responses-shared-DYSAljRs.js → openai-responses-shared-D4pZ3bEY.js} +4 -4
- package/dist/ui/assets/openrouter-QETwrep8.js +1 -0
- package/dist/ui/assets/panel-rpc-Bcvr75SR.js +1 -0
- package/dist/ui/assets/panel-rpc-handlers-Bb_hIEUP.js +2 -0
- package/dist/ui/assets/path-utils-DU6QhF_k.js +1 -0
- package/dist/ui/assets/picker-approval-tzbkMw-e.js +9 -0
- package/dist/ui/assets/preload-helper-zJ_50EbN.js +1 -0
- package/dist/ui/assets/provider-Ba-IW-kd.js +2 -0
- package/dist/ui/assets/provider-CZ54o1eC.js +1 -0
- package/dist/ui/assets/provider-settings-CY5NYsC9.js +99 -0
- package/dist/ui/assets/provider-store-access-DV4kHL4p.js +1 -0
- package/dist/ui/assets/provider-store-access-xEJhUgjR.js +1 -0
- package/dist/ui/assets/providers-B-C_YTn6.js +1 -0
- package/dist/ui/assets/{proxied-fetch-CW9YdsrT.js → proxied-fetch-Bhc4pqzp.js} +1 -1
- package/dist/ui/assets/pyodide-BvA4c-59.js +3 -0
- package/dist/ui/assets/remote-cache-_bhYZSLy.js +1 -0
- package/dist/ui/assets/{remote-terminal-view-ChqlFNm7.js → remote-terminal-view-C1K2ToGt.js} +3 -3
- package/dist/ui/assets/{remote-vfs-client-Cc4yBMI0.js → remote-vfs-client-BwJhhtIV.js} +1 -1
- package/dist/ui/assets/secret-env-DcfTe28K.js +1 -0
- package/dist/ui/assets/slicc-editor-BdfBeQCF.js +12 -0
- package/dist/ui/assets/{spawn-7Vgp-lrm.js → spawn-D6ZYDHli.js} +1 -1
- package/dist/ui/assets/{sql-wasm-BbdRW4or.js → sql-wasm-Cu5Uk_6k.js} +1 -1
- package/dist/ui/assets/{src-BV-fJ2mM.js → src-CcMujGBk.js} +2 -2
- package/dist/ui/assets/src-CpdsjHiA.js +1 -0
- package/dist/ui/assets/store-BHgxxLww.js +1 -0
- package/dist/ui/assets/{sudo-CYttizEB.js → sudo-Dflnt4_G.js} +1 -1
- package/dist/ui/assets/tool-ui-N76-EdVc.js +1 -0
- package/dist/ui/assets/tool-ui-YOPqzMmL.js +1 -0
- package/dist/ui/assets/transform-messages-B3Q-Bwv-.js +1 -0
- package/dist/ui/assets/transform-messages-C1X1O3BY.js +1 -0
- package/dist/ui/assets/{tray-leave-runtime-BYZH2LNU.js → tray-leave-runtime-BhHEXpRy.js} +1 -1
- package/dist/ui/assets/tray-runtime-config-BRnpyDNS.js +1 -0
- package/dist/ui/assets/types-idfTVsM8.js +1 -0
- package/dist/ui/assets/{typescript-DY6vxmmv.js → typescript-qBO0Z4wm.js} +15 -15
- package/dist/ui/assets/upgrade-detection-B04kAu_0.js +1 -0
- package/dist/ui/assets/web-BMWiUYJ-.js +1 -0
- package/dist/ui/assets/{writable-vfs-client-lsN1qOSV.js → writable-vfs-client-DMYsajEE.js} +1 -1
- package/dist/ui/assets/ws-subscribers-Dzuxa2F7.js +1 -0
- package/dist/ui/assets/xai-grok-B6Nl7COG.js +1 -0
- package/dist/ui/assets/xai-grok-i7HD-5Tv.js +1 -0
- package/dist/ui/index.html +15 -1
- package/dist/ui/packages/webapp/index.html +15 -1
- package/package.json +6 -5
- package/dist/node-server/secrets/signing-s3.d.ts +0 -34
- package/dist/ui/assets/adobe-DwuDVWKR.js +0 -2
- package/dist/ui/assets/agent-bridge-CQ_WHXpS.js +0 -1
- package/dist/ui/assets/agent-message-to-chat-Bk83dal6.js +0 -7
- package/dist/ui/assets/azure-openai-589UnBaE.js +0 -1
- package/dist/ui/assets/azure-openai-BVD3rRyh.js +0 -1
- package/dist/ui/assets/azure-openai-responses-DDoPpQfz.js +0 -1
- package/dist/ui/assets/azure-openai-responses-DvPlhYRg.js +0 -1
- package/dist/ui/assets/biome_wasm-2BIO-fFD.js +0 -1
- package/dist/ui/assets/cdp-ws-page-bridge-D48c5VHQ.js +0 -1
- package/dist/ui/assets/common-DJglxtI9.js +0 -1
- package/dist/ui/assets/cost-command-Dqjx5BJ4.js +0 -1
- package/dist/ui/assets/esp32-UFl3lGuU.js +0 -1
- package/dist/ui/assets/esp32c3-CtBZCzN8.js +0 -1
- package/dist/ui/assets/esp8266-Cg5dZq5p.js +0 -1
- package/dist/ui/assets/esp8266-MLobtggU.js +0 -1
- package/dist/ui/assets/esptool-operations-PyMOLbEo.js +0 -12
- package/dist/ui/assets/github-BmiOv8pZ.js +0 -1
- package/dist/ui/assets/github-H8WCUoaG.js +0 -2
- package/dist/ui/assets/github-copilot-CFrKRCIh.js +0 -2
- package/dist/ui/assets/github-copilot-LZq-2nbm.js +0 -1
- package/dist/ui/assets/google-Bwhr3ElU.js +0 -1
- package/dist/ui/assets/google-CDEKJo6s.js +0 -1
- package/dist/ui/assets/google-shared-DUInnTRv.js +0 -11
- package/dist/ui/assets/google-vertex-DOk_o4Vo.js +0 -1
- package/dist/ui/assets/google-vertex-Dy07djME.js +0 -1
- package/dist/ui/assets/hosted-config-apply-CIYq4OE-.js +0 -1
- package/dist/ui/assets/intercepted-oauth-DYoA2kA8.js +0 -1
- package/dist/ui/assets/kernel-worker-xMdP33ug.js +0 -9678
- package/dist/ui/assets/lick-ws-bridge-DLXsmZ6H.js +0 -1
- package/dist/ui/assets/magick-wasm-BpDug9Pm.js +0 -1
- package/dist/ui/assets/main-BxzufWem.js +0 -1825
- package/dist/ui/assets/main-cherry-CV5ItRlu.js +0 -1
- package/dist/ui/assets/migration-run-195D_oov.js +0 -1
- package/dist/ui/assets/nodejs-156RsPtl.js +0 -1
- package/dist/ui/assets/oauth-DSEOvfNU.js +0 -1
- package/dist/ui/assets/oauth-bootstrap-CCTPtyS_.js +0 -2
- package/dist/ui/assets/oauth-service-Ctr2_Obu.js +0 -1
- package/dist/ui/assets/oauth-service-LEczdutD.js +0 -1
- package/dist/ui/assets/offscreen-client-Dswx1Ljm.js +0 -1
- package/dist/ui/assets/onboarding-orchestrator-8SmCagx8.js +0 -1
- package/dist/ui/assets/openai-codex-CYM3h5BG.js +0 -1
- package/dist/ui/assets/openai-codex-D-QWKpWb.js +0 -1
- package/dist/ui/assets/openai-codex-responses-CbtdwhQL.js +0 -7
- package/dist/ui/assets/openai-codex-responses-CnQXtoLP.js +0 -7
- package/dist/ui/assets/openai-completions-CbUcQcuU.js +0 -5
- package/dist/ui/assets/openai-responses-DBGxMDFy.js +0 -1
- package/dist/ui/assets/openai-responses-DomGQu-u.js +0 -1
- package/dist/ui/assets/openrouter-i7KtgZt3.js +0 -1
- package/dist/ui/assets/panel-rpc-handlers-BeUo4K-9.js +0 -2
- package/dist/ui/assets/provider-CuOCGXmD.js +0 -1
- package/dist/ui/assets/provider-U8Br2pQO.js +0 -2
- package/dist/ui/assets/provider-store-access-CRMelzXC.js +0 -1
- package/dist/ui/assets/provider-store-access-D9JW2Z9f.js +0 -1
- package/dist/ui/assets/pyodide-BQVwxCA4.js +0 -3
- package/dist/ui/assets/secret-env-mFCaJWuD.js +0 -1
- package/dist/ui/assets/slicc-editor-Bn_0-CZl.js +0 -12
- package/dist/ui/assets/store-DUcHEhum.js +0 -1
- package/dist/ui/assets/upgrade-detection-BmNgOg4g.js +0 -1
- package/dist/ui/assets/web-DRaGEaSq.js +0 -1
- package/dist/ui/assets/ws-subscribers-CxhSakhG.js +0 -1
- package/dist/ui/assets/xai-grok-C0UPkvUi.js +0 -1
- package/dist/ui/assets/xai-grok-DEapxZue.js +0 -1
|
@@ -0,0 +1,16 @@
|
|
|
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};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,c as t,r as n}from"./transform-messages-B3Q-Bwv-.js";import{t as r}from"./headers-DO1UzNKu.js";import{i,n as a,r as o,t as s}from"./github-copilot-headers-DZtWWv8W.js";import{n as c}from"./openai-Cn5LRPCm.js";import{t as l}from"./openai-prompt-cache-DXo9f3w5.js";import{n as u,r as d,t as f}from"./openai-responses-shared-CZOJCHE4.js";var p=new Set([`openai`,`openai-codex`,`opencode`]);function m(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function h(e){return{sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function g(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function _(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}var v=(t,n,i)=>{let a=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let o=i?.apiKey;if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=m(i?.cacheRetention)===`none`?void 0:i?.sessionId,c=b(t,n,o,i?.headers,s),l=x(t,n,i),u=await i?.onPayload?.(l,t);u!==void 0&&(l=u);let f={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:i?.maxRetries??0},{data:p,response:h}=await c.responses.create(l,f).withResponse();if(await i?.onResponse?.({status:h.status,headers:r(h.headers)},t),a.push({type:`start`,partial:e}),await d(p,e,a,t,{serviceTier:i?.serviceTier,applyServiceTierPricing:(e,n)=>C(e,n,t)}),i?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=i?.signal?.aborted?`aborted`:`error`,e.errorMessage=_(t),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a},y=(e,r,i)=>{let a=i?.apiKey;if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=n(e,i,a),s=i?.reasoning?t(e,i.reasoning):void 0,c=s===`off`?void 0:s;return v(e,r,{...o,reasoningEffort:c})};function b(e,t,n,r,l){let u=h(e),d={...e.headers};if(e.provider===`github-copilot`){let e=a(t.messages),n=s({messages:t.messages,hasImages:e});Object.assign(d,n)}l&&(u.sendSessionIdHeader&&(d.session_id=l),d[`x-client-request-id`]=l),r&&Object.assign(d,r);let f=e.provider===`cloudflare-ai-gateway`?{...d,Authorization:d.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:d;return new c({apiKey:n,baseURL:o(e.provider)?i(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function x(e,t,n){let r=f(e,t,p),i=m(n?.cacheRetention),a=h(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:l(n?.sessionId),prompt_cache_retention:g(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=u(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function S(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function C(e,t,n){let r=S(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)}export{v as streamOpenAIResponses,y as streamSimpleOpenAIResponses};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as e,c as t,r as n}from"./transform-messages-C1X1O3BY.js";import{n as r}from"./openai-i4HWKCeW.js";import{t as i}from"./headers-DO1UzNKu.js";import{i as a,n as o,r as s,t as c}from"./github-copilot-headers-DZtWWv8W.js";import{t as l}from"./openai-prompt-cache-DXo9f3w5.js";import{n as u,r as d,t as f}from"./openai-responses-shared-D4pZ3bEY.js";const p=new Set([`openai`,`openai-codex`,`opencode`]);function m(e){return e||(typeof process<`u`&&{}.PI_CACHE_RETENTION===`long`?`long`:`short`)}function h(e){return{sendSessionIdHeader:e.compat?.sendSessionIdHeader??!0,supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0}}function g(e,t){return t===`long`&&e.supportsLongCacheRetention?`24h`:void 0}function _(e){if(e instanceof Error){let t=e.status,n=typeof t==`number`?t:void 0;return n===void 0?e.message:`OpenAI API error (${n}): ${e.message}`}try{return JSON.stringify(e)}catch{return String(e)}}const v=(t,n,r)=>{let a=new e;return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()};try{let o=r?.apiKey;if(!o)throw Error(`No API key for provider: ${t.provider}`);let s=m(r?.cacheRetention)===`none`?void 0:r?.sessionId,c=b(t,n,o,r?.headers,s),l=x(t,n,r),u=await r?.onPayload?.(l,t);u!==void 0&&(l=u);let f={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:r?.maxRetries??0},{data:p,response:h}=await c.responses.create(l,f).withResponse();if(await r?.onResponse?.({status:h.status,headers:i(h.headers)},t),a.push({type:`start`,partial:e}),await d(p,e,a,t,{serviceTier:r?.serviceTier,applyServiceTierPricing:(e,n)=>C(e,n,t)}),r?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(`An unknown error occurred`);a.push({type:`done`,reason:e.stopReason,message:e}),a.end()}catch(t){for(let t of e.content)delete t.index,delete t.partialJson;e.stopReason=r?.signal?.aborted?`aborted`:`error`,e.errorMessage=_(t),a.push({type:`error`,reason:e.stopReason,error:e}),a.end()}})(),a},y=(e,r,i)=>{let a=i?.apiKey;if(!a)throw Error(`No API key for provider: ${e.provider}`);let o=n(e,i,a),s=i?.reasoning?t(e,i.reasoning):void 0,c=s===`off`?void 0:s;return v(e,r,{...o,reasoningEffort:c})};function b(e,t,n,i,l){let u=h(e),d={...e.headers};if(e.provider===`github-copilot`){let e=o(t.messages),n=c({messages:t.messages,hasImages:e});Object.assign(d,n)}l&&(u.sendSessionIdHeader&&(d.session_id=l),d[`x-client-request-id`]=l),i&&Object.assign(d,i);let f=e.provider===`cloudflare-ai-gateway`?{...d,Authorization:d.Authorization??null,"cf-aig-authorization":`Bearer ${n}`}:d;return new r({apiKey:n,baseURL:s(e.provider)?a(e):e.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:f})}function x(e,t,n){let r=f(e,t,p),i=m(n?.cacheRetention),a=h(e),o={model:e.id,input:r,stream:!0,prompt_cache_key:i===`none`?void 0:l(n?.sessionId),prompt_cache_retention:g(a,i),store:!1};return n?.maxTokens&&(o.max_output_tokens=n?.maxTokens),n?.temperature!==void 0&&(o.temperature=n?.temperature),n?.serviceTier!==void 0&&(o.service_tier=n.serviceTier),t.tools&&t.tools.length>0&&(o.tools=u(t.tools)),e.reasoning&&(n?.reasoningEffort||n?.reasoningSummary?(o.reasoning={effort:n?.reasoningEffort?e.thinkingLevelMap?.[n.reasoningEffort]??n.reasoningEffort:`medium`,summary:n?.reasoningSummary||`auto`},o.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(o.reasoning={effort:e.thinkingLevelMap?.off??`none`})),o}function S(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function C(e,t,n){let r=S(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)}export{v as streamOpenAIResponses,y as streamSimpleOpenAIResponses};
|
package/dist/ui/assets/{openai-responses-shared-CsK-8CQH.js → openai-responses-shared-CZOJCHE4.js}
RENAMED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`),i=t.content.some(e=>e.type===`image`),a=n.length>0,[o]=t.toolCallId.split(`|`),s;if(i&&e.input.includes(`image`)){let e=[];a&&e.push({type:`input_text`,text:r(n)});for(let n of t.content)n.type===`image`&&e.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=e}else s=r(a?n:`(see attached image)`);c.push({type:`function_call_output`,call_id:o,output:s})}f++}return c}function c(e,t){let n=t?.strict===void 0?!1:t.strict;return e.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:n}))}async function l(
|
|
1
|
+
import{s as e,t}from"./transform-messages-B3Q-Bwv-.js";import{n}from"./json-parse-BUunmmNl.js";import{t as r}from"./sanitize-unicode-DmIE6hZJ.js";import{t as i}from"./hash-yQufAZII.js";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function s(e,n,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=t(n.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&n.systemPrompt){let t=e.reasoning?`developer`:`system`;c.push({role:t,content:r(n.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:r(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api,l=0;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);n.push(t)}}else if(e.type===`text`){let t=e,a=o(t.textSignature),s=l===0?`msg_pi_${f}`:`msg_pi_${f}_${l}`;l++;let c=a?.id;c?c.length>64&&(c=`msg_${i(c)}`):c=s,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:r(t.text),annotations:[]}],status:`completed`,id:c,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[r,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments)})}if(n.length===0)continue;c.push(...n)}else if(t.role===`toolResult`){let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
+
`),i=t.content.some(e=>e.type===`image`),a=n.length>0,[o]=t.toolCallId.split(`|`),s;if(i&&e.input.includes(`image`)){let e=[];a&&e.push({type:`input_text`,text:r(n)});for(let n of t.content)n.type===`image`&&e.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=e}else s=r(a?n:`(see attached image)`);c.push({type:`function_call_output`,call_id:o,output:s})}f++}return c}function c(e,t){let n=t?.strict===void 0?!1:t.strict;return e.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:n}))}async function l(t,r,i,o,s){let c=null,l=null,d=r.content,f=()=>d.length-1;for await(let d of t)if(d.type===`response.created`)r.responseId=d.response.id;else if(d.type===`response.output_item.added`){let e=d.item;e.type===`reasoning`?(c=e,l={type:`thinking`,thinking:``},r.content.push(l),i.push({type:`thinking_start`,contentIndex:f(),partial:r})):e.type===`message`?(c=e,l={type:`text`,text:``},r.content.push(l),i.push({type:`text_start`,contentIndex:f(),partial:r})):e.type===`function_call`&&(c=e,l={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||``},r.content.push(l),i.push({type:`toolcall_start`,contentIndex:f(),partial:r}))}else if(d.type===`response.reasoning_summary_part.added`)c&&c.type===`reasoning`&&(c.summary=c.summary||[],c.summary.push(d.part));else if(d.type===`response.reasoning_summary_text.delta`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=d.delta,e.text+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.reasoning_summary_part.done`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=`
|
|
3
3
|
|
|
4
4
|
`,e.text+=`
|
|
5
5
|
|
|
6
6
|
`,i.push({type:`thinking_delta`,contentIndex:f(),delta:`
|
|
7
7
|
|
|
8
|
-
`,partial:r}))}}else if(d.type===`response.reasoning_text.delta`)c?.type===`reasoning`&&l?.type===`thinking`&&(l.thinking+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.content_part.added`)c?.type===`message`&&(c.content=c.content||[],(d.part.type===`output_text`||d.part.type===`refusal`)&&c.content.push(d.part));else if(d.type===`response.output_text.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`output_text`&&(l.text+=d.delta,e.text+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.refusal.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`refusal`&&(l.text+=d.delta,e.refusal+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.function_call_arguments.delta`)c?.type===`function_call`&&l?.type===`toolCall`&&(l.partialJson+=d.delta,l.arguments=
|
|
8
|
+
`,partial:r}))}}else if(d.type===`response.reasoning_text.delta`)c?.type===`reasoning`&&l?.type===`thinking`&&(l.thinking+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.content_part.added`)c?.type===`message`&&(c.content=c.content||[],(d.part.type===`output_text`||d.part.type===`refusal`)&&c.content.push(d.part));else if(d.type===`response.output_text.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`output_text`&&(l.text+=d.delta,e.text+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.refusal.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`refusal`&&(l.text+=d.delta,e.refusal+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.function_call_arguments.delta`)c?.type===`function_call`&&l?.type===`toolCall`&&(l.partialJson+=d.delta,l.arguments=n(l.partialJson),i.push({type:`toolcall_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.function_call_arguments.done`){if(c?.type===`function_call`&&l?.type===`toolCall`){let e=l.partialJson;if(l.partialJson=d.arguments,l.arguments=n(l.partialJson),d.arguments.startsWith(e)){let t=d.arguments.slice(e.length);t.length>0&&i.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:r})}}}else if(d.type===`response.output_item.done`){let e=d.item;if(e.type===`reasoning`&&l?.type===`thinking`){let t=e.summary?.map(e=>e.text).join(`
|
|
9
9
|
|
|
10
10
|
`)||``,n=e.content?.map(e=>e.text).join(`
|
|
11
11
|
|
|
12
|
-
`)||``;l.thinking=t||n||l.thinking,l.thinkingSignature=JSON.stringify(e),i.push({type:`thinking_end`,contentIndex:f(),content:l.thinking,partial:r}),l=null}else if(e.type===`message`&&l?.type===`text`)l.text=e.content.map(e=>e.type===`output_text`?e.text:e.refusal).join(``),l.textSignature=a(e.id,e.phase??void 0),i.push({type:`text_end`,contentIndex:f(),content:l.text,partial:r}),l=null;else if(e.type===`function_call`){let
|
|
12
|
+
`)||``;l.thinking=t||n||l.thinking,l.thinkingSignature=JSON.stringify(e),i.push({type:`thinking_end`,contentIndex:f(),content:l.thinking,partial:r}),l=null}else if(e.type===`message`&&l?.type===`text`)l.text=e.content.map(e=>e.type===`output_text`?e.text:e.refusal).join(``),l.textSignature=a(e.id,e.phase??void 0),i.push({type:`text_end`,contentIndex:f(),content:l.text,partial:r}),l=null;else if(e.type===`function_call`){let t=l?.type===`toolCall`&&l.partialJson?n(l.partialJson):n(e.arguments||`{}`),a;l?.type===`toolCall`?(l.arguments=t,delete l.partialJson,a=l):a={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:t},l=null,i.push({type:`toolcall_end`,contentIndex:f(),toolCall:a,partial:r})}}else if(d.type===`response.completed`){let t=d.response;if(t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details?.cached_tokens||0;r.usage={input:(t.usage.input_tokens||0)-e,output:t.usage.output_tokens||0,cacheRead:e,cacheWrite:0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(o,r.usage),s?.applyServiceTierPricing){let e=s.resolveServiceTier?s.resolveServiceTier(t?.service_tier,s.serviceTier):t?.service_tier??s.serviceTier;s.applyServiceTierPricing(r.usage,e)}r.stopReason=u(t?.status),r.content.some(e=>e.type===`toolCall`)&&r.stopReason===`stop`&&(r.stopReason=`toolUse`)}else if(d.type===`error`)throw Error(`Error Code ${d.code}: ${d.message}`||`Unknown error`);else if(d.type===`response.failed`){let e=d.response?.error,t=d.response?.incomplete_details,n=e?`${e.code||`unknown`}: ${e.message||`no message`}`:t?.reason?`incomplete: ${t.reason}`:`Unknown error (no error details in response)`;throw Error(n)}}function u(e){if(!e)return`stop`;switch(e){case`completed`:return`stop`;case`incomplete`:return`length`;case`failed`:case`cancelled`:return`error`;case`in_progress`:case`queued`:return`stop`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{c as n,l as r,s as t};
|
package/dist/ui/assets/{openai-responses-shared-DYSAljRs.js → openai-responses-shared-D4pZ3bEY.js}
RENAMED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{s as e,t}from"./transform-messages-C1X1O3BY.js";import{n}from"./json-parse-BIGBjpLL.js";import{t as r}from"./sanitize-unicode-DmIE6hZJ.js";import{t as i}from"./hash-yQufAZII.js";function a(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function o(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function s(e,n,a,s){let c=[],l=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},u=e=>{let t=`fc_${i(e)}`;return t.length>64?t.slice(0,64):t},d=t(n.messages,e,(t,n,r)=>{if(!a.has(e.provider)||!t.includes(`|`))return l(t);let[i,o]=t.split(`|`),s=l(i),c=r.provider!==e.provider||r.api!==e.api?u(o):l(o);return c.startsWith(`fc_`)||(c=l(`fc_${c}`)),`${s}|${c}`});if((s?.includeSystemPrompt??!0)&&n.systemPrompt){let t=e.reasoning?`developer`:`system`;c.push({role:t,content:r(n.systemPrompt)})}let f=0;for(let t of d){if(t.role===`user`)if(typeof t.content==`string`)c.push({role:`user`,content:[{type:`input_text`,text:r(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:r(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;c.push({role:`user`,content:e})}else if(t.role===`assistant`){let n=[],a=t,s=a.model!==e.id&&a.provider===e.provider&&a.api===e.api,l=0;for(let e of t.content)if(e.type===`thinking`){if(e.thinkingSignature){let t=JSON.parse(e.thinkingSignature);n.push(t)}}else if(e.type===`text`){let t=e,a=o(t.textSignature),s=l===0?`msg_pi_${f}`:`msg_pi_${f}_${l}`;l++;let c=a?.id;c?c.length>64&&(c=`msg_${i(c)}`):c=s,n.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:r(t.text),annotations:[]}],status:`completed`,id:c,phase:a?.phase})}else if(e.type===`toolCall`){let t=e,[r,i]=t.id.split(`|`),a=i;s&&a?.startsWith(`fc_`)&&(a=void 0),n.push({type:`function_call`,id:a,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments)})}if(n.length===0)continue;c.push(...n)}else if(t.role===`toolResult`){let n=t.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
2
|
`),i=t.content.some(e=>e.type===`image`),a=n.length>0,[o]=t.toolCallId.split(`|`),s;if(i&&e.input.includes(`image`)){let e=[];a&&e.push({type:`input_text`,text:r(n)});for(let n of t.content)n.type===`image`&&e.push({type:`input_image`,detail:`auto`,image_url:`data:${n.mimeType};base64,${n.data}`});s=e}else s=r(a?n:`(see attached image)`);c.push({type:`function_call_output`,call_id:o,output:s})}f++}return c}function c(e,t){let n=t?.strict===void 0?!1:t.strict;return e.map(e=>({type:`function`,name:e.name,description:e.description,parameters:e.parameters,strict:n}))}async function l(t,r,i,o,s){let c=null,l=null,d=r.content,f=()=>d.length-1;for await(let d of t)if(d.type===`response.created`)r.responseId=d.response.id;else if(d.type===`response.output_item.added`){let e=d.item;e.type===`reasoning`?(c=e,l={type:`thinking`,thinking:``},r.content.push(l),i.push({type:`thinking_start`,contentIndex:f(),partial:r})):e.type===`message`?(c=e,l={type:`text`,text:``},r.content.push(l),i.push({type:`text_start`,contentIndex:f(),partial:r})):e.type===`function_call`&&(c=e,l={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:{},partialJson:e.arguments||``},r.content.push(l),i.push({type:`toolcall_start`,contentIndex:f(),partial:r}))}else if(d.type===`response.reasoning_summary_part.added`)c&&c.type===`reasoning`&&(c.summary=c.summary||[],c.summary.push(d.part));else if(d.type===`response.reasoning_summary_text.delta`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=d.delta,e.text+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.reasoning_summary_part.done`){if(c?.type===`reasoning`&&l?.type===`thinking`){c.summary=c.summary||[];let e=c.summary[c.summary.length-1];e&&(l.thinking+=`
|
|
3
3
|
|
|
4
4
|
`,e.text+=`
|
|
5
5
|
|
|
6
6
|
`,i.push({type:`thinking_delta`,contentIndex:f(),delta:`
|
|
7
7
|
|
|
8
|
-
`,partial:r}))}}else if(d.type===`response.reasoning_text.delta`)c?.type===`reasoning`&&l?.type===`thinking`&&(l.thinking+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.content_part.added`)c?.type===`message`&&(c.content=c.content||[],(d.part.type===`output_text`||d.part.type===`refusal`)&&c.content.push(d.part));else if(d.type===`response.output_text.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`output_text`&&(l.text+=d.delta,e.text+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.refusal.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`refusal`&&(l.text+=d.delta,e.refusal+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.function_call_arguments.delta`)c?.type===`function_call`&&l?.type===`toolCall`&&(l.partialJson+=d.delta,l.arguments=
|
|
8
|
+
`,partial:r}))}}else if(d.type===`response.reasoning_text.delta`)c?.type===`reasoning`&&l?.type===`thinking`&&(l.thinking+=d.delta,i.push({type:`thinking_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.content_part.added`)c?.type===`message`&&(c.content=c.content||[],(d.part.type===`output_text`||d.part.type===`refusal`)&&c.content.push(d.part));else if(d.type===`response.output_text.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`output_text`&&(l.text+=d.delta,e.text+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.refusal.delta`){if(c?.type===`message`&&l?.type===`text`){if(!c.content||c.content.length===0)continue;let e=c.content[c.content.length-1];e?.type===`refusal`&&(l.text+=d.delta,e.refusal+=d.delta,i.push({type:`text_delta`,contentIndex:f(),delta:d.delta,partial:r}))}}else if(d.type===`response.function_call_arguments.delta`)c?.type===`function_call`&&l?.type===`toolCall`&&(l.partialJson+=d.delta,l.arguments=n(l.partialJson),i.push({type:`toolcall_delta`,contentIndex:f(),delta:d.delta,partial:r}));else if(d.type===`response.function_call_arguments.done`){if(c?.type===`function_call`&&l?.type===`toolCall`){let e=l.partialJson;if(l.partialJson=d.arguments,l.arguments=n(l.partialJson),d.arguments.startsWith(e)){let t=d.arguments.slice(e.length);t.length>0&&i.push({type:`toolcall_delta`,contentIndex:f(),delta:t,partial:r})}}}else if(d.type===`response.output_item.done`){let e=d.item;if(e.type===`reasoning`&&l?.type===`thinking`){let t=e.summary?.map(e=>e.text).join(`
|
|
9
9
|
|
|
10
|
-
`)||``,n=
|
|
10
|
+
`)||``,n=e.content?.map(e=>e.text).join(`
|
|
11
11
|
|
|
12
|
-
`)||``;l.thinking=
|
|
12
|
+
`)||``;l.thinking=t||n||l.thinking,l.thinkingSignature=JSON.stringify(e),i.push({type:`thinking_end`,contentIndex:f(),content:l.thinking,partial:r}),l=null}else if(e.type===`message`&&l?.type===`text`)l.text=e.content.map(e=>e.type===`output_text`?e.text:e.refusal).join(``),l.textSignature=a(e.id,e.phase??void 0),i.push({type:`text_end`,contentIndex:f(),content:l.text,partial:r}),l=null;else if(e.type===`function_call`){let t=l?.type===`toolCall`&&l.partialJson?n(l.partialJson):n(e.arguments||`{}`),a;l?.type===`toolCall`?(l.arguments=t,delete l.partialJson,a=l):a={type:`toolCall`,id:`${e.call_id}|${e.id}`,name:e.name,arguments:t},l=null,i.push({type:`toolcall_end`,contentIndex:f(),toolCall:a,partial:r})}}else if(d.type===`response.completed`){let t=d.response;if(t?.id&&(r.responseId=t.id),t?.usage){let e=t.usage.input_tokens_details?.cached_tokens||0;r.usage={input:(t.usage.input_tokens||0)-e,output:t.usage.output_tokens||0,cacheRead:e,cacheWrite:0,totalTokens:t.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(e(o,r.usage),s?.applyServiceTierPricing){let e=s.resolveServiceTier?s.resolveServiceTier(t?.service_tier,s.serviceTier):t?.service_tier??s.serviceTier;s.applyServiceTierPricing(r.usage,e)}r.stopReason=u(t?.status),r.content.some(e=>e.type===`toolCall`)&&r.stopReason===`stop`&&(r.stopReason=`toolUse`)}else if(d.type===`error`)throw Error(`Error Code ${d.code}: ${d.message}`||`Unknown error`);else if(d.type===`response.failed`){let e=d.response?.error,t=d.response?.incomplete_details,n=e?`${e.code||`unknown`}: ${e.message||`no message`}`:t?.reason?`incomplete: ${t.reason}`:`Unknown error (no error details in response)`;throw Error(n)}}function u(e){if(!e)return`stop`;switch(e){case`completed`:return`stop`;case`incomplete`:return`length`;case`failed`:case`cancelled`:return`error`;case`in_progress`:case`queued`:return`stop`;default:throw Error(`Unhandled stop reason: ${e}`)}}export{c as n,l as r,s as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{n as e}from"./openai-i4HWKCeW.js";import{t}from"./headers-DO1UzNKu.js";import{t as n}from"./sanitize-unicode-DmIE6hZJ.js";const r=async(e,n,r)=>{let s={api:e.api,provider:e.provider,model:e.id,output:[],stopReason:`stop`,timestamp:Date.now()};try{let c=r?.apiKey;if(!c)throw Error(`No API key for provider: ${e.provider}`);let l=i(e,c,r?.headers),u=a(e,n),d=await r?.onPayload?.(u,e);d!==void 0&&(u=d);let f={...r?.signal?{signal:r.signal}:{},...r?.timeoutMs===void 0?{}:{timeout:r.timeoutMs},maxRetries:r?.maxRetries??0},{data:p,response:m}=await l.chat.completions.create(u,f).withResponse();await r?.onResponse?.({status:m.status,headers:t(m.headers)},e);let h=p;s.responseId=h.id,h.usage&&(s.usage=o(h.usage,e));let g=h.choices[0];if(g){let e=g.message.content;typeof e==`string`&&e.length>0&&s.output.push({type:`text`,text:e});for(let e of g.message.images??[]){let t=typeof e.image_url==`string`?e.image_url:e.image_url?.url;if(!t?.startsWith(`data:`))continue;let n=t.match(/^data:([^;]+);base64,(.+)$/);n&&s.output.push({type:`image`,mimeType:n[1],data:n[2]})}}return s}catch(e){return s.stopReason=r?.signal?.aborted?`aborted`:`error`,s.errorMessage=e instanceof Error?e.message:JSON.stringify(e),s}};function i(t,n,r){return new e({apiKey:n,baseURL:t.baseUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{...t.headers,...r}})}function a(e,t){let r=t.input.map(e=>e.type===`text`?{type:`text`,text:n(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});return{model:e.id,messages:[{role:`user`,content:r}],stream:!1,modalities:e.output.includes(`text`)?[`image`,`text`]:[`image`]}}function o(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens||0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=i>0?Math.max(0,r-i):r,o=Math.max(0,n-a-i),s=e.completion_tokens||0,c={input:o,output:s,cacheRead:a,cacheWrite:i,totalTokens:o+s+a+i,cost:{input:t.cost.input/1e6*o,output:t.cost.output/1e6*s,cacheRead:t.cost.cacheRead/1e6*a,cacheWrite:t.cost.cacheWrite/1e6*i,total:0}};return c.cost.total=c.cost.input+c.cost.output+c.cost.cacheRead+c.cost.cacheWrite,c}export{r as generateImagesOpenRouter};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"./chunk-CMxvf4Kt.js";var t=e({PANEL_RPC_DEFAULT_TIMEOUT_MS:()=>i,createPanelRpcClient:()=>o,getPanelRpcClient:()=>c,hasLocalDom:()=>l,panelRpcChannelName:()=>a});const n=`slicc-panel-rpc`,r=15e3,i=r;function a(e){return e?`${n}:${e}`:n}function o(e={}){if(typeof BroadcastChannel!=`function`)return{call:()=>Promise.reject(Error(`panel-rpc: BroadcastChannel is unavailable`)),onEvent:()=>()=>{},registerPushTarget:()=>{},unregisterPushTarget:()=>{},dispose:()=>{}};let t=a(e.instanceId),n=new BroadcastChannel(t),i=new Map,o=new Map,c=new Map;n.addEventListener(`message`,e=>{let t=e.data;if(t?.type===`panel-rpc-event`){let e=c.get(t.channel);if(e)for(let n of e)try{n(t.payload)}catch(e){console.warn(`panel-rpc: event handler for '${t.channel}' threw:`,e instanceof Error?e.message:String(e))}return}if(t?.type===`panel-rpc-push`){if(t.op===`remote-cdp-event`){let e=t.payload;o.get(`${e.runtimeId}:${e.localTargetId}`)?.(e)}return}if(t?.type!==`panel-rpc-response`)return;let n=i.get(t.id);n&&(i.delete(t.id),clearTimeout(n.timer),typeof t.error==`string`?n.reject(Error(t.error)):n.resolve(t.result))});function l(e,t){let n=c.get(e);return n||(n=new Set,c.set(e,n)),n.add(t),()=>{let n=c.get(e);n&&(n.delete(t),n.size===0&&c.delete(e))}}function u(e,t,a={}){let o=s(),c=a.timeoutMs??r;return new Promise((r,a)=>{let s=setTimeout(()=>{i.delete(o),a(Error(`panel-rpc: op '${e}' timed out after ${c}ms`))},c);i.set(o,{resolve:r,reject:a,timer:s});let l={type:`panel-rpc-request`,id:o,op:e,payload:t};n.postMessage(l)})}function d(e,t){o.set(e,t)}function f(e){o.delete(e)}function p(){for(let[,e]of i)clearTimeout(e.timer),e.reject(Error(`panel-rpc: client disposed`));i.clear(),c.clear(),o.clear();try{n.close()}catch{}}return{call:u,onEvent:l,registerPushTarget:d,unregisterPushTarget:f,dispose:p}}function s(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`prpc-${crypto.randomUUID()}`:`prpc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function c(){return globalThis.__slicc_panelRpc??null}function l(){return typeof window<`u`&&typeof document<`u`}export{t as i,c as n,l as r,i as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/esptool-operations-CiX8mbpu.js","assets/chunk-aKtaBQYM.js","assets/preload-helper-zJ_50EbN.js","assets/rom-eeWiO07Z.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-zJ_50EbN.js";import{n as t,r as n}from"./hid-device-registry-D2LsJCRr.js";import{$ as r,A as i,B as a,C as o,D as s,E as c,F as l,G as u,H as d,I as f,J as p,K as m,L as h,M as g,N as _,O as v,P as y,Q as b,R as x,S as ee,T as S,V as C,W as w,X as T,Y as E,Z as D,b as O,et as k,k as A,m as j,o as M,q as N,v as P,w as F,x as I,y as te,z as L}from"./main-yZCsVpFH.js";function R(t={}){let n=new Map;return{"page-info":()=>({origin:window.location.origin,href:window.location.href,title:document.title||``}),screencapture:async({mimeType:e,quality:t})=>{let n=await Z(e,t),r=await n.arrayBuffer(),i=await Q(n);return{bytes:r,width:i.width,height:i.height,mimeType:e}},"speak-text":async({text:e,lang:t,voice:n,rate:r,pitch:i,volume:a})=>{if(typeof speechSynthesis>`u`)throw Error(`speechSynthesis is unavailable in this page`);return await new Promise((o,s)=>{let c=new SpeechSynthesisUtterance(e);if(t!==void 0&&(c.lang=t),r!==void 0&&(c.rate=r),i!==void 0&&(c.pitch=i),a!==void 0&&(c.volume=a),n){let e=speechSynthesis.getVoices().find(e=>e.name===n);e&&(c.voice=e)}c.onend=()=>o(),c.onerror=e=>s(Error(`speak: ${e.error||`utterance failed`}`)),speechSynthesis.speak(c)}),{done:!0}},"list-voices":async()=>{if(typeof speechSynthesis>`u`)throw Error(`speechSynthesis is unavailable in this page`);let e=speechSynthesis.getVoices();return e.length>0?{voices:e.map(X)}:{voices:(await new Promise(e=>{let t=()=>{speechSynthesis.removeEventListener(`voiceschanged`,t),e(speechSynthesis.getVoices())};speechSynthesis.addEventListener(`voiceschanged`,t),setTimeout(()=>{speechSynthesis.removeEventListener(`voiceschanged`,t),e(speechSynthesis.getVoices())},1e3)})).map(X)}},"play-audio":async({bytes:e,volume:t})=>{if(typeof AudioContext>`u`)throw Error(`Web Audio API is unavailable in this page`);let n=new AudioContext;try{let r=await n.decodeAudioData(e.slice(0)),i=n.createBufferSource();if(i.buffer=r,t!==void 0){let e=n.createGain();e.gain.value=Math.max(0,Math.min(1,t)),i.connect(e),e.connect(n.destination)}else i.connect(n.destination);await new Promise(e=>{i.onended=()=>e(),i.start()})}finally{try{await n.close()}catch{}}return{done:!0}},"play-chime":async({tone:e})=>{let t={success:[880,1320],error:[440,220],notify:[660,660]},[n,r]=t[e??`notify`]??t.notify;if(typeof AudioContext>`u`)throw Error(`Web Audio API is unavailable in this page`);let i=new AudioContext;try{let e=i.currentTime;for(let[t,a]of[n,r].entries()){let n=i.createOscillator();n.type=`sine`,n.frequency.value=a;let r=i.createGain();r.gain.setValueAtTime(1e-4,e+t*.18),r.gain.exponentialRampToValueAtTime(.2,e+t*.18+.02),r.gain.exponentialRampToValueAtTime(1e-4,e+t*.18+.18),n.connect(r),r.connect(i.destination),n.start(e+t*.18),n.stop(e+t*.18+.2)}await new Promise(e=>setTimeout(e,450))}finally{try{await i.close()}catch{}}return{done:!0}},"clipboard-read-text":async()=>{if(!navigator.clipboard?.readText)throw Error(`clipboard API unavailable`);return{text:await navigator.clipboard.readText()}},"clipboard-write-text":async({text:e})=>{if(!navigator.clipboard?.writeText)throw Error(`clipboard API unavailable`);return await $(),await navigator.clipboard.writeText(e),{done:!0}},"clipboard-write-image":async({bytes:e,mimeType:t})=>{if(!navigator.clipboard?.write||typeof ClipboardItem>`u`)throw Error(`clipboard image API unavailable`);let n,r=new Blob([e],{type:t});return n=t===`image/png`?r:await ne(r),await $(),await navigator.clipboard.write([new ClipboardItem({"image/png":n})]),{done:!0}},"window-open":async({url:e,target:t,features:n})=>({opened:window.open(e,t??`_blank`,n??`noopener,noreferrer`)!==null}),"oauth-popup":async({url:e})=>({redirectUrl:await Y(e)}),"capture-camera":async e=>await K(e),"enumerate-media-devices":async()=>{if(!navigator.mediaDevices?.enumerateDevices)throw Error(`enumerateDevices is not supported in this browser`);let e=await navigator.mediaDevices.enumerateDevices(),t=e=>({deviceId:e.deviceId,label:e.label||``,...e.groupId?{groupId:e.groupId}:{}});return{videoinputs:e.filter(e=>e.kind===`videoinput`).map(t),audioinputs:e.filter(e=>e.kind===`audioinput`).map(t)}},"tray-reset":async()=>{if(!t.resetTray)throw Error(`host reset: no active tray session to reset`);return await t.resetTray()},"tray-leave":async({workerBaseUrl:e,requestId:n})=>{if(!t.leaveTray)throw Error(`host leave: tray leave is not available in this environment`);return await t.leaveTray({workerBaseUrl:e,requestId:n})},"cherry-emit":async({runtimeId:e,name:n,detail:r})=>{if(!t.emitCherrySliccEvent)throw Error(`cherry-emit: not available in this environment`);return{delivered:t.emitCherrySliccEvent(e,n,r)}},"oauth-extras-set":({providerId:e,domains:t})=>(j(e,t),{storeAfter:M()}),"save-oauth-accounts":({accountsJson:e})=>(localStorage.setItem(`slicc_accounts`,e),{storedJson:localStorage.getItem(`slicc_accounts`)??e}),"usb-list":async()=>({devices:await o(z(),B())}),"usb-request":async({filters:e})=>({device:await c(z(),B(),e)}),"usb-device-info":({handle:e})=>({device:ee(z(),e)}),"usb-open":async({handle:e})=>(await F(z(),e),{done:!0}),"usb-close":async({handle:e})=>(await te(z(),e),{done:!0}),"usb-select-configuration":async({handle:e,configurationValue:t})=>(await v(z(),e,t),{done:!0}),"usb-claim-interface":async({handle:e,interfaceNumber:t})=>(await P(z(),e,t),{done:!0}),"usb-release-interface":async({handle:e,interfaceNumber:t})=>(await S(z(),e,t),{done:!0}),"usb-control-transfer-in":async({handle:e,setup:t,length:n})=>O(z(),e,t,n),"usb-control-transfer-out":async({handle:e,setup:t,bytes:n})=>I(z(),e,t,n),"usb-transfer-in":async({handle:e,endpointNumber:t,length:n})=>A(z(),e,t,n),"usb-transfer-out":async({handle:e,endpointNumber:t,bytes:n})=>i(z(),e,t,n),"usb-reset":async({handle:e})=>(await s(z(),e),{done:!0}),"hid-list":async()=>({devices:await p(V(),H())}),"hid-request":async({filters:e})=>({devices:await D(V(),H(),e)}),"hid-device-info":({handle:e})=>({device:N(V(),e)}),"hid-open":async({handle:e})=>(await E(V(),e),{done:!0}),"hid-close":async({handle:e})=>(await m(V(),e),{done:!0}),"hid-send-report":async({handle:e,reportId:t,bytes:n})=>(await r(V(),e,t,n),{done:!0}),"hid-send-feature-report":async({handle:e,reportId:t,bytes:n})=>(await b(V(),e,t,n),{done:!0}),"hid-receive-feature-report":async({handle:e,reportId:t})=>T(V(),e,t),"hid-subscribe-input-reports":async({handle:e})=>{n.get(e)?.();let r=await k(V(),e,n=>{t.emitEvent?.(`hid-input-report`,{handle:e,reportId:n.reportId,bytes:n.bytes})});return n.set(e,r),{done:!0}},"hid-unsubscribe-input-reports":({handle:e})=>(n.get(e)?.(),n.delete(e),{done:!0}),"serial-list":async()=>({devices:await h(U(),W())}),"serial-request":async({filters:e})=>({device:await a(U(),W(),e)}),"serial-device-info":({handle:e})=>({device:l(U(),e)}),"serial-open":async({handle:e,options:t})=>(await x(U(),e,t),{done:!0}),"serial-close":async({handle:e})=>(await y(U(),e),{done:!0}),"serial-read":async({handle:e,maxBytes:t,until:n,timeoutMs:r})=>{let i=await L(U(),e,{maxBytes:t,until:n?new Uint8Array(n):void 0,timeoutMs:r});return{bytes:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)}},"serial-write":async({handle:e,bytes:t})=>({bytesWritten:await d(U(),e,new Uint8Array(t))}),"serial-get-signals":async({handle:e})=>({signals:await f(U(),e)}),"serial-set-signals":async({handle:e,signals:t})=>(await C(U(),e,t),{done:!0}),"esptool-chip-info":async({handle:n,baudRate:r})=>(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolChipInfo(U(),n,r,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),"esptool-read-mac":async({handle:n,baudRate:r})=>(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolReadMac(U(),n,r,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),"esptool-erase-flash":async({handle:n,baudRate:r})=>(await(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolEraseFlash(U(),n,r,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),{done:!0}),"esptool-flash":async({handle:n,baudRate:r,eraseAll:i,segments:a})=>(await(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolFlash(U(),n,r,i,a.map(e=>({address:e.address,data:new Uint8Array(e.bytes)})),e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),{done:!0}),"esptool-read-flash":async({handle:n,baudRate:r,address:i,size:a})=>{let o=await(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolReadFlash(U(),n,r,i,a,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e}));return{bytes:o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}},"esptool-read-reg":async({handle:n,baudRate:r,address:i})=>(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolReadReg(U(),n,r,i,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),"esptool-flash-id":async({handle:n,baudRate:r})=>(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolFlashId(U(),n,r,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),"esptool-erase-region":async({handle:n,baudRate:r,address:i,size:a})=>(await(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolEraseRegion(U(),n,r,i,a,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),{done:!0}),"esptool-run":async({handle:n,baudRate:r})=>(await(await e(()=>import(`./esptool-operations-CiX8mbpu.js`),__vite__mapDeps([0,1,2,3]))).esptoolRun(U(),n,r,e=>t.emitEvent?.(`esptool-progress`,{handle:n,line:e})),{done:!0}),"list-remote-targets":async()=>t.listRemoteTargets?{targets:(await t.listRemoteTargets()).filter(e=>e.targetId.includes(`:`)).map(e=>({targetId:e.targetId,title:e.title,url:e.url}))}:{targets:[]},"remote-cdp-send":async({runtimeId:e,localTargetId:n,method:r,params:i,sessionId:a,timeout:o})=>{if(!t.remoteCdp)throw Error(`remote-cdp bridge not available`);return t.remoteCdp.send({runtimeId:e,localTargetId:n,method:r,params:i,sessionId:a,timeout:o})},"remote-cdp-subscribe":async({runtimeId:e,localTargetId:n,event:r})=>{if(!t.remoteCdp)throw Error(`remote-cdp bridge not available`);return t.remoteCdp.subscribe({runtimeId:e,localTargetId:n,event:r})},"remote-cdp-unsubscribe":async({runtimeId:e,localTargetId:n,event:r})=>{if(!t.remoteCdp)throw Error(`remote-cdp bridge not available`);return t.remoteCdp.unsubscribe({runtimeId:e,localTargetId:n,event:r})},"remote-cdp-detach":async({runtimeId:e,localTargetId:n})=>{if(!t.remoteCdp)throw Error(`remote-cdp bridge not available`);return t.remoteCdp.detach({runtimeId:e,localTargetId:n})},"remote-open-tab":async({runtimeId:e,url:n})=>{if(!t.remoteCdp)throw Error(`remote-cdp bridge not available`);return t.remoteCdp.openTab({runtimeId:e,url:n})}}}function z(){return _()}function B(){let e=g();if(!e)throw Error(`WebUSB is unavailable in this browser`);return e}function V(){return n()}function H(){let e=t();if(!e)throw Error(`WebHID is unavailable in this browser`);return e}function U(){return u()}function W(){let e=w();if(!e)throw Error(`Web Serial is unavailable in this browser`);return e}var G=1500;async function K(e){if(!navigator.mediaDevices?.getUserMedia)throw Error(`getUserMedia is not supported in this browser`);let t=e.mode===`photo`||e.captureVideo!==!1,n=!!e.captureAudio&&e.mode===`video`;if(!t&&!n)throw Error(`camera capture: at least one of video or audio must be requested`);let r=await J({wantVideo:t,videoDeviceId:t?await q(e.deviceId,`videoinput`):void 0,audioDeviceId:n?await q(e.audioDeviceId,`audioinput`):void 0,wantAudio:n,width:e.width,height:e.height,frameRate:e.frameRate,exact:!!e.exactSize});try{let n=null,i=0,a=0;if(t){n=document.createElement(`video`),n.srcObject=r,n.muted=!0,n.playsInline=!0;let e=n;await new Promise((t,n)=>{e.onloadedmetadata=()=>e.play().then(()=>t()).catch(n),e.onerror=()=>n(Error(`Failed to load camera stream`))}),await new Promise(e=>requestAnimationFrame(()=>e())),await new Promise(e=>requestAnimationFrame(()=>e())),i=e.videoWidth,a=e.videoHeight}if(e.mode===`photo`){if(!n)throw Error(`photo capture requires a video track`);let t=e.warmupMs??G;t>0&&await new Promise(e=>setTimeout(e,t));let r=document.createElement(`canvas`);r.width=i,r.height=a;let o=r.getContext(`2d`);if(!o)throw Error(`Failed to get canvas context`);o.drawImage(n,0,0,i,a);let s=await new Promise((t,n)=>{r.toBlob(e=>e?t(e):n(Error(`Failed to encode photo`)),e.mimeType,e.quality)});return{bytes:await s.arrayBuffer(),mimeType:s.type||e.mimeType,width:i,height:a}}let o=Math.max(100,Math.min(e.durationMs??5e3,6e4)),s=typeof MediaRecorder<`u`&&MediaRecorder.isTypeSupported(e.mimeType)?e.mimeType:`video/webm`,c=new MediaRecorder(r,{mimeType:s}),l=[];c.ondataavailable=e=>{e.data&&e.data.size>0&&l.push(e.data)};let u=new Promise(e=>{c.onstop=()=>e()});c.start(),await new Promise(e=>setTimeout(e,o)),c.stop(),await u;let d=new Blob(l,{type:s});return{bytes:await d.arrayBuffer(),mimeType:d.type||s,width:i,height:a,durationMs:o}}finally{r.getTracks().forEach(e=>{e.stop()})}}async function q(e,t){if(e===void 0||e===``)return;if(!/^\d+$/.test(e))return e;if(!navigator.mediaDevices?.enumerateDevices)return;let n=parseInt(e,10);return(await navigator.mediaDevices.enumerateDevices()).filter(e=>e.kind===t)[n]?.deviceId}async function J(e){let t=t=>{if(!e.wantVideo)return!1;let n={};return e.videoDeviceId&&(n.deviceId={exact:e.videoDeviceId}),e.width&&(n.width=t===`exact`?{exact:e.width}:{ideal:e.width}),e.height&&(n.height=t===`exact`?{exact:e.height}:{ideal:e.height}),e.frameRate&&(n.frameRate=t===`exact`?{exact:e.frameRate}:{ideal:e.frameRate}),Object.keys(n).length>0?n:!0},n=()=>e.wantAudio?e.audioDeviceId?{deviceId:{exact:e.audioDeviceId}}:!0:!1;try{return await navigator.mediaDevices.getUserMedia({video:t(e.exact?`exact`:`ideal`),audio:n()})}catch(r){let i=r?.name;if(!e.exact||i!==`OverconstrainedError`&&i!==`NotReadableError`)throw r;return console.warn(`panel-rpc:capture-camera: exact ${e.width??`?`}x${e.height??`?`}@${e.frameRate??`?`} unmet, falling back to ideal`),await navigator.mediaDevices.getUserMedia({video:t(`ideal`),audio:n()})}}function Y(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(`[panel-rpc:oauth-popup] 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),i=setInterval(async()=>{if(!r)try{let e=await fetch(`/api/oauth-result`);if(e.status===204||!e.ok)return;let n=await e.json();if(r)return;if(a(),n.error){console.error(`[panel-rpc:oauth-popup] Server relay OAuth error:`,n.error),t(null);return}t(n.redirectUrl??null)}catch(e){console.warn(`[panel-rpc:oauth-popup] Poll failed:`,e instanceof Error?e.message:String(e))}},1e3);let s=setTimeout(()=>{a();try{n?.close()}catch{}t(null)},12e4)})}function X(e){return{name:e.name,lang:e.lang,default:e.default}}async function Z(e,t){if(!navigator.mediaDevices?.getDisplayMedia)throw Error(`screen capture is not supported in this browser`);let n=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1});try{let r=document.createElement(`video`);r.srcObject=n,r.muted=!0,r.playsInline=!0,await new Promise((e,t)=>{r.onloadedmetadata=()=>r.play().then(()=>e()).catch(t),r.onerror=()=>t(Error(`Failed to load video stream`))}),await new Promise(e=>setTimeout(e,100));let i=r.videoWidth,a=r.videoHeight,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);if(!s)throw Error(`Failed to get canvas context`);return s.drawImage(r,0,0,i,a),await new Promise((n,r)=>{o.toBlob(e=>e?n(e):r(Error(`Failed to create image blob`)),e,t)})}finally{n.getTracks().forEach(e=>{e.stop()})}}async function Q(e){let t=URL.createObjectURL(e);try{let e=new Image;return await new Promise((n,r)=>{e.onload=()=>n(),e.onerror=()=>r(Error(`Failed to decode capture`)),e.src=t}),{width:e.naturalWidth,height:e.naturalHeight}}finally{URL.revokeObjectURL(t)}}async function ne(e){let t=URL.createObjectURL(e);try{let e=new Image;await new Promise((n,r)=>{e.onload=()=>n(),e.onerror=()=>r(Error(`Failed to load image for clipboard conversion`)),e.src=t});let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);return r.drawImage(e,0,0),await new Promise((e,t)=>{n.toBlob(n=>n?e(n):t(Error(`PNG re-encode failed`)),`image/png`)})}finally{URL.revokeObjectURL(t)}}async function $(e=5*6e4){typeof document>`u`||typeof document.hasFocus==`function`&&(document.hasFocus()||await new Promise((t,n)=>{let r=()=>{window.removeEventListener(`focus`,i),document.removeEventListener(`visibilitychange`,a),clearTimeout(o)},i=()=>{document.hasFocus()&&(r(),t())},a=()=>{document.visibilityState===`visible`&&document.hasFocus()&&(r(),t())},o=setTimeout(()=>{r(),n(Error(`timed out waiting for window focus`))},e);window.addEventListener(`focus`,i),document.addEventListener(`visibilitychange`,a)}))}export{R as createStandalonePanelRpcHandlers};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function e(e){if(!e||e===`/`)return`/`;e.startsWith(`/`)||(e=`/`+e);let t=e.split(`/`),n=[];for(let e of t)e===``||e===`.`||(e===`..`?n.pop():n.push(e));return`/`+n.join(`/`)}function t(t){let n=e(t);if(n===`/`)return{dir:`/`,base:``};let r=n.lastIndexOf(`/`);return{dir:r===0?`/`:n.slice(0,r),base:n.slice(r+1)}}function n(t){let n=e(t);return n===`/`?[]:n.slice(1).split(`/`)}function r(...t){return e(t.join(`/`))}export{t as i,e as n,n as r,r as t};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import"./tool-ui-YOPqzMmL.js";var e={directory:{title:`Mount local directory`,approve:`Select directory`},"usb-device":{title:`Connect USB device`,approve:`Select USB device`},"serial-port":{title:`Connect serial port`,approve:`Select serial port`},"hid-device":{title:`Connect HID device`,approve:`Select HID device`}};function t(t,n=[]){let r=e[t],i=n.length?` data-action-data='${JSON.stringify({filters:n}).replace(/'/g,`'`)}'`:``;return`
|
|
2
|
+
<div class="sprinkle-action-card">
|
|
3
|
+
<div class="sprinkle-action-card__header">${r.title} <span class="sprinkle-badge sprinkle-badge--notice">approval</span></div>
|
|
4
|
+
<div class="sprinkle-action-card__actions">
|
|
5
|
+
<button class="sprinkle-btn sprinkle-btn--secondary" data-action="deny">Deny</button>
|
|
6
|
+
<button class="sprinkle-btn sprinkle-btn--primary" data-action="approve" data-picker="${t}"${i}>${r.approve}</button>
|
|
7
|
+
</div>
|
|
8
|
+
</div>
|
|
9
|
+
`}export{t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=`modulepreload`,t=function(e){return`/`+e},n={},r=function(r,i,a){let o=Promise.resolve();if(i&&i.length>0){let r=document.getElementsByTagName(`link`),s=document.querySelector(`meta[property=csp-nonce]`),c=s?.nonce||s?.getAttribute(`nonce`);function l(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}o=l(i.map(i=>{if(i=t(i,a),i in n)return;n[i]=!0;let o=i.endsWith(`.css`),s=o?`[rel="stylesheet"]`:``;if(a)for(let e=r.length-1;e>=0;e--){let t=r[e];if(t.href===i&&(!o||t.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${i}"]${s}`))return;let l=document.createElement(`link`);if(l.rel=o?`stylesheet`:e,o||(l.as=`script`),l.crossOrigin=``,l.href=i,c&&l.setAttribute(`nonce`,c),document.head.appendChild(l),o)return new Promise((e,t)=>{l.addEventListener(`load`,e),l.addEventListener(`error`,()=>t(Error(`Unable to preload CSS for ${i}`)))})}))}function s(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return o.then(e=>{for(let t of e||[])t.status===`rejected`&&s(t.reason);return r().catch(s)})};export{r as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/main-yZCsVpFH.js","assets/chunk-aKtaBQYM.js","assets/modulepreload-polyfill-Dezn_h7o.js","assets/preload-helper-zJ_50EbN.js","assets/bedrock-camp-CWvhREqw.js","assets/transform-messages-B3Q-Bwv-.js","assets/json-parse-BUunmmNl.js","assets/logger-DDBAeTLF.js","assets/mime-types-B9LIwKG5.js","assets/mount-picker-popup-DncaR5N8.js","assets/path-utils-DU6QhF_k.js","assets/types-idfTVsM8.js","assets/hid-device-registry-D2LsJCRr.js","assets/picker-approval-tzbkMw-e.js","assets/tool-ui-YOPqzMmL.js","assets/clipboard-DgFtRQbq.js","assets/main-D683Koa8.css","assets/oauth-service-CFSmb2Xq.js","assets/proxied-fetch-Bhc4pqzp.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{t as e}from"./preload-helper-zJ_50EbN.js";import{t}from"./logger-DDBAeTLF.js";import{t as n}from"./types-idfTVsM8.js";import{dt as r,i,p as a,u as o}from"./main-yZCsVpFH.js";import{t as s}from"./global-db-CbuLl-zx.js";var c=t(`mcp-store`),l=`/workspace/.mcp/servers.json`,u=1,d=null,f=null;async function p(){return d||=await e(()=>import(`./main-yZCsVpFH.js`).then(e=>e.tt),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),d}async function m(e){if(e)return e;if(f&&f.dbName===`slicc-fs-global`)return f.instance;let{VirtualFS:t}=await p(),n=await t.create({dbName:s});return f={instance:n,dbName:s},n}function h(){return{version:u,servers:{}}}function g(e){if(!e||typeof e!=`object`)return h();let t=e,n=typeof t.version==`number`?t.version:u,r={};if(t.servers&&typeof t.servers==`object`)for(let[e,n]of Object.entries(t.servers)){if(!n||typeof n!=`object`)continue;let t=n;typeof t.url==`string`&&(r[e]=t)}return{version:n,servers:r}}async function _(e){try{let t=await(await m(e)).readFile(l,{encoding:`utf-8`});try{return g(JSON.parse(t))}catch(e){return c.warn(`servers.json is not valid JSON; treating as empty`,{error:e instanceof Error?e.message:String(e)}),h()}}catch(e){return e instanceof n&&e.code===`ENOENT`||c.warn(`Failed to read servers.json`,{error:e instanceof Error?e.message:String(e)}),h()}}async function v(e){return(await _(e)).servers}async function y(){let e=await v(),t=[];for(let[n,r]of Object.entries(e))!r?.url||!r.auth?.clientId||t.push({name:n,serverUrl:r.url,auth:r.auth});return t}var b=t(`mcp-oauth`);async function x(e,t,n){let r=new URL(e).origin,i=t??`${r}/.well-known/oauth-protected-resource`,a=null,o=null;b.debug(`Fetching PRM`,{prmUrl:i});try{let e=await n(i,{headers:{Accept:`application/json`}});if(!e.ok)o=`${e.status} ${e.statusText}`;else{let t=await e.json();!t.authorization_servers||t.authorization_servers.length===0?o=`lists no authorization_servers`:a=t}}catch(e){o=e instanceof Error?e.message:String(e)}let s,c,l;a?.authorization_servers&&a.authorization_servers.length>0?(s=a.authorization_servers[0].replace(/\/+$/,``),c=`${s}/.well-known/oauth-authorization-server`,l=`prm`,b.debug(`Discovery via PRM`,{prmUrl:i,asmUrl:c})):(s=r,c=`${r}/.well-known/oauth-authorization-server`,l=`asm-origin-fallback`,b.debug(`PRM unavailable; falling back to ASM at server origin`,{prmUrl:i,prmReason:o,asmUrl:c}));let u=null,d=null;b.debug(`Fetching ASM`,{asmUrl:c});try{let e=await n(c,{headers:{Accept:`application/json`}});e.ok?u=await e.json():d=`${e.status} ${e.statusText}`}catch(e){d=e instanceof Error?e.message:String(e)}if(!u)throw Error(l===`asm-origin-fallback`?`MCP OAuth discovery failed. PRM (${i}): ${o}. ASM fallback (${c}): ${d}.`:`ASM fetch failed: ${d} (${c})`);if(!u.authorization_endpoint||!u.token_endpoint)throw Error(l===`asm-origin-fallback`?`MCP OAuth discovery failed. PRM (${i}): ${o}. ASM fallback (${c}) is missing required endpoints (authorization_endpoint, token_endpoint).`:`ASM at ${c} is missing required endpoints`);return{issuer:u.issuer||s,authorizationEndpoint:u.authorization_endpoint,tokenEndpoint:u.token_endpoint,registrationEndpoint:u.registration_endpoint,supportedScopes:u.scopes_supported??a?.scopes_supported,codeChallengeMethods:u.code_challenge_methods_supported,grantTypes:u.grant_types_supported,discoveryPath:l}}function S(e){return!e||e.length===0||e.includes(`S256`)?`S256`:e.includes(`plain`)?`plain`:`S256`}function C(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function w(e){let t=new Uint8Array(32);crypto.getRandomValues(t);let n=C(t);if(e===`plain`)return{codeVerifier:n,codeChallenge:n,method:e};let r=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(n));return{codeVerifier:n,codeChallenge:C(new Uint8Array(r)),method:e}}function T(e){try{let t=new URL(e);return{code:t.searchParams.get(`code`),state:t.searchParams.get(`state`)}}catch{return{code:null,state:null}}}async function E(e){let t=await w(S(e.asMetadata.codeChallengeMethods)),n=C(crypto.getRandomValues(new Uint8Array(16))),r=new URLSearchParams({response_type:`code`,client_id:e.clientId,redirect_uri:e.redirectUri,code_challenge:t.codeChallenge,code_challenge_method:t.method,state:n});e.scope&&r.set(`scope`,e.scope);let i=`${e.asMetadata.authorizationEndpoint}?${r.toString()}`,a=await e.launcher(i);if(!a)throw Error(`MCP OAuth flow cancelled or timed out`);let{code:o,state:s}=T(a);if(!o)throw Error("MCP OAuth redirect missing `code` parameter");if(s!==n)throw Error(`MCP OAuth state mismatch — possible CSRF`);return O({tokenEndpoint:e.asMetadata.tokenEndpoint,clientId:e.clientId,code:o,codeVerifier:t.codeVerifier,redirectUri:e.redirectUri,fetchImpl:e.fetchImpl})}function D(e){if(e.error||!e.access_token)throw Error(`Token endpoint error: ${e.error??`no_access_token`}${e.error_description?` — ${e.error_description}`:``}`);return{accessToken:e.access_token,refreshToken:e.refresh_token,expiresAt:e.expires_in?Date.now()+e.expires_in*1e3:void 0,scope:e.scope,tokenType:e.token_type}}async function O(e){let t=new URLSearchParams({grant_type:`authorization_code`,code:e.code,redirect_uri:e.redirectUri,client_id:e.clientId,code_verifier:e.codeVerifier}).toString(),n=await e.fetchImpl(e.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:t}),r=await n.json();if(!n.ok&&!r.access_token)throw Error(`Token exchange failed: ${n.status} ${n.statusText}${r.error?` (${r.error})`:``}`);return D(r)}async function k(e){let t=new URLSearchParams({grant_type:`refresh_token`,refresh_token:e.refreshToken,client_id:e.clientId});e.scope&&t.set(`scope`,e.scope);let n=await e.fetchImpl(e.tokenEndpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`},body:t.toString()}),r=await n.json();if(!n.ok&&!r.access_token)throw Error(`Token refresh failed: ${n.status} ${n.statusText}${r.error?` (${r.error})`:``}`);return D(r)}var A=t(`mcp-provider`),j=`mcp:`;function M(){return typeof globalThis<`u`&&globalThis.indexedDB!==void 0}function N(e){return`${j}${e}`}var P=new Map,F=new Set;async function I(){let t=typeof chrome<`u`?chrome:void 0;if(t?.runtime?.id)return t.identity?.getRedirectURL?.(`mcp-callback`)??`https://${t.runtime.id}.chromiumapp.org/mcp-callback`;let{getOAuthPageOrigin:n}=await e(async()=>{let{getOAuthPageOrigin:e}=await import(`./oauth-service-CFSmb2Xq.js`);return{getOAuthPageOrigin:e}},__vite__mapDeps([17,3,0,1,2,4,5,6,7,8,9,10,11,12,13,14,15,16])),{origin:r}=await n();return`${r}/auth/callback`}async function L(t){if(t)return t;let{createProxiedFetch:n}=await e(async()=>{let{createProxiedFetch:e}=await import(`./proxied-fetch-Bhc4pqzp.js`);return{createProxiedFetch:e}},__vite__mapDeps([18,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])),r=n();return async(e,t)=>{let n=await r(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(n.body);return{ok:n.status>=200&&n.status<300,status:n.status,statusText:n.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>n.headers[e.toLowerCase()]??null}}}}async function R(e){let t=P.get(N(e.name));if(t)return t;let n=await L(e.fetchImpl),r=await x(e.serverUrl,void 0,n);return P.set(N(e.name),r),r}function z(e){let t=N(e.name),n=(()=>{try{return new URL(e.serverUrl).host}catch{return``}})();return{id:t,name:`MCP: ${e.name}`,description:`MCP server at ${e.serverUrl}`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:n?[n]:[],getModelIds:()=>[],onOAuthLogin:async(n,r)=>{let i=e.launcher??n,o=await L(e.fetchImpl),s=await E({asMetadata:await R(e),clientId:e.auth.clientId,scope:e.auth.scope,redirectUri:await I(),launcher:i,fetchImpl:o});await a({providerId:t,accessToken:s.accessToken,refreshToken:s.refreshToken,tokenExpiresAt:s.expiresAt}),r()},onSilentRenew:async()=>{if(!o(t))return null;let n=i().find(e=>e.providerId===t)?.refreshToken;if(!n)return A.info(`No refresh token for MCP provider, skipping silent renewal`,{id:t}),null;try{let r=await R(e),i=r.grantTypes??[];if(i.length>0&&!i.includes(`refresh_token`))return A.info(`AS does not advertise refresh_token grant; skipping silent renewal`,{id:t}),null;let o=await L(e.fetchImpl),s=await k({tokenEndpoint:r.tokenEndpoint,clientId:e.auth.clientId,refreshToken:n,scope:e.auth.scope,fetchImpl:o});return await a({providerId:t,accessToken:s.accessToken,refreshToken:s.refreshToken??n,tokenExpiresAt:s.expiresAt}),s.accessToken}catch(e){return A.warn(`MCP silent renewal failed`,{id:t,error:e instanceof Error?e.message:String(e)}),null}}}}function B(e){let t=N(e.name);F.has(t)||(r(z(e)),F.add(t),A.debug(`Registered MCP provider`,{id:t}))}async function V(){if(!M())return[];let{readMcpAuthEntries:t}=await e(async()=>{let{readMcpAuthEntries:e}=await import(`./provider-store-access-xEJhUgjR.js`);return{readMcpAuthEntries:e}},[]),n=await t(),r=[];for(let e of n)B({name:e.name,serverUrl:e.serverUrl,auth:e.auth}),r.push(N(e.name));return r}export{V as ensureAllMcpProvidersRegistered,y as t};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./logger-LESFN7Hj.js";import{m as t,s as n,t as r}from"./provider-settings-CY5NYsC9.js";import{i,s as a,t as o}from"./providers-B-C_YTn6.js";import{discoverAuth as s,refreshAccessToken as c,runAuthFlow as l}from"./oauth-Czw-MuuR.js";import{n as u}from"./store-BHgxxLww.js";const d=e(`mcp-provider`);function f(){return typeof globalThis<`u`&&globalThis.indexedDB!==void 0}function p(e){return`mcp:${e}`}const m=new Map,h=new Set;async function g(){let e=typeof chrome<`u`?chrome:void 0;if(e?.runtime?.id)return e.identity?.getRedirectURL?.(`mcp-callback`)??`https://${e.runtime.id}.chromiumapp.org/mcp-callback`;let{getOAuthPageOrigin:t}=await import(`./oauth-service-CSJo71ct.js`),{origin:n}=await t();return`${n}/auth/callback`}async function _(e){if(e)return e;let{createProxiedFetch:t}=await import(`./kernel-worker-Cb8hTQlK.js`).then(e=>e.m),n=t();return async(e,t)=>{let r=await n(e,{method:t?.method,headers:t?.headers,body:t?.body}),i=new TextDecoder().decode(r.body);return{ok:r.status>=200&&r.status<300,status:r.status,statusText:r.statusText,text:async()=>i,json:async()=>JSON.parse(i),headers:{get:e=>r.headers[e.toLowerCase()]??null}}}}async function v(e){let t=m.get(p(e.name));if(t)return t;let n=await _(e.fetchImpl),r=await s(e.serverUrl,void 0,n);return m.set(p(e.name),r),r}function y(e){let i=p(e.name),a=(()=>{try{return new URL(e.serverUrl).host}catch{return``}})();return{id:i,name:`MCP: ${e.name}`,description:`MCP server at ${e.serverUrl}`,requiresApiKey:!1,requiresBaseUrl:!1,isOAuth:!0,oauthTokenDomains:a?[a]:[],getModelIds:()=>[],onOAuthLogin:async(n,r)=>{let a=e.launcher??n,o=await _(e.fetchImpl),s=await l({asMetadata:await v(e),clientId:e.auth.clientId,scope:e.auth.scope,redirectUri:await g(),launcher:a,fetchImpl:o});await t({providerId:i,accessToken:s.accessToken,refreshToken:s.refreshToken,tokenExpiresAt:s.expiresAt}),r()},onSilentRenew:async()=>{if(!n(i))return null;let a=r().find(e=>e.providerId===i)?.refreshToken;if(!a)return d.info(`No refresh token for MCP provider, skipping silent renewal`,{id:i}),null;try{let n=await v(e),r=n.grantTypes??[];if(r.length>0&&!r.includes(`refresh_token`))return d.info(`AS does not advertise refresh_token grant; skipping silent renewal`,{id:i}),null;let o=await _(e.fetchImpl),s=await c({tokenEndpoint:n.tokenEndpoint,clientId:e.auth.clientId,refreshToken:a,scope:e.auth.scope,fetchImpl:o});return await t({providerId:i,accessToken:s.accessToken,refreshToken:s.refreshToken??a,tokenExpiresAt:s.expiresAt}),s.accessToken}catch(e){return d.warn(`MCP silent renewal failed`,{id:i,error:e instanceof Error?e.message:String(e)}),null}}}}function b(e){let t=p(e.name);h.has(t)||(i(y(e)),h.add(t),d.debug(`Registered MCP provider`,{id:t}))}async function x(e){let t=p(e);if(h.has(t)&&o(t))return!0;if(!f())return!1;let n=await u(e);return n?(b({name:e,serverUrl:n.serverUrl,auth:n.auth}),!0):!1}async function S(){if(!f())return[];let{readMcpAuthEntries:e}=await import(`./provider-store-access-DV4kHL4p.js`),t=await e(),n=[];for(let e of t)b({name:e.name,serverUrl:e.serverUrl,auth:e.auth}),n.push(p(e.name));return n}function C(e){let t=p(e);return h.delete(t),m.delete(t),a(t)}export{S as ensureAllMcpProvidersRegistered,x as ensureMcpProviderRegistered,b as registerMcpProvider,C as removeMcpProvider};
|