@cortex-agent/server 2026.10.28 → 2026.12.5
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/LICENSE +255 -21
- package/README.md +36 -7
- package/THIRD_PARTY_NOTICES.txt +1990 -593
- package/defaults/hooks/cortex-hook-api.mjs +2 -1
- package/defaults/hooks/quota-stop.mjs +37 -0
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
- package/defaults/prompts/clean-workspace.md +5 -0
- package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
- package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
- package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
- package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
- package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
- package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
- package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
- package/dist/chunks/chunk-24DH4IR5.js +4 -0
- package/dist/chunks/chunk-25XKBRDT.js +70 -0
- package/dist/chunks/chunk-2ABET62E.js +23 -0
- package/dist/chunks/chunk-2BVUA256.js +4 -0
- package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
- package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
- package/dist/chunks/chunk-335SSANX.js +4 -0
- package/dist/chunks/chunk-377OPTXX.js +17 -0
- package/dist/chunks/chunk-3EZNVLBF.js +129 -0
- package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
- package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
- package/dist/chunks/chunk-4HRI75GU.js +4 -0
- package/dist/chunks/chunk-4JBYLRPM.js +57 -0
- package/dist/chunks/chunk-4KKV7VKE.js +4 -0
- package/dist/chunks/chunk-4KQHDDC5.js +4 -0
- package/dist/chunks/chunk-4SWD4JMP.js +33 -0
- package/dist/chunks/chunk-52VCLZS5.js +4 -0
- package/dist/chunks/chunk-54P7TSY3.js +10 -0
- package/dist/chunks/chunk-5DVSAXOI.js +7 -0
- package/dist/chunks/chunk-5F3A62YS.js +4 -0
- package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
- package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
- package/dist/chunks/chunk-5UYVNA3W.js +4 -0
- package/dist/chunks/chunk-6G3OYMCV.js +21 -0
- package/dist/chunks/chunk-7GGPYU5E.js +30 -0
- package/dist/chunks/chunk-7TYSMLUV.js +4 -0
- package/dist/chunks/chunk-7W7VYUTK.js +5 -0
- package/dist/chunks/chunk-AXYAZTTN.js +6 -0
- package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
- package/dist/chunks/chunk-BKYP6AGM.js +8 -0
- package/dist/chunks/chunk-BVEDNESB.js +4 -0
- package/dist/chunks/chunk-BWDJS6A4.js +12 -0
- package/dist/chunks/chunk-C6YVF7EI.js +4 -0
- package/dist/chunks/chunk-CEJIYYVE.js +15 -0
- package/dist/chunks/chunk-CI2RHH74.js +50 -0
- package/dist/chunks/chunk-CMSOOLJB.js +4 -0
- package/dist/chunks/chunk-CSVTYYLP.js +4 -0
- package/dist/chunks/chunk-DE5EGVKG.js +6 -0
- package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
- package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
- package/dist/chunks/chunk-DYLBVUAU.js +4 -0
- package/dist/chunks/chunk-FDC2GRBK.js +27 -0
- package/dist/chunks/chunk-FE7HH5JS.js +18 -0
- package/dist/chunks/chunk-FYD57YRO.js +436 -0
- package/dist/chunks/chunk-G264APQN.js +5 -0
- package/dist/chunks/chunk-G4JYZFEO.js +11 -0
- package/dist/chunks/chunk-GFFM56U2.js +4 -0
- package/dist/chunks/chunk-GOS3P7KS.js +132 -0
- package/dist/chunks/chunk-HVN37UXD.js +4 -0
- package/dist/chunks/chunk-IA6IODY3.js +4 -0
- package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
- package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
- package/dist/chunks/chunk-IMMGYDAB.js +6 -0
- package/dist/chunks/chunk-IOWBF7UK.js +10 -0
- package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
- package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
- package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
- package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
- package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
- package/dist/chunks/chunk-JKL3AK5D.js +106 -0
- package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
- package/dist/chunks/chunk-KJUQCCB5.js +4 -0
- package/dist/chunks/chunk-KST6OY76.js +10 -0
- package/dist/chunks/chunk-KZSAFVSY.js +129 -0
- package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
- package/dist/chunks/chunk-LE6QPXN6.js +7 -0
- package/dist/chunks/chunk-LEAV3FFG.js +4 -0
- package/dist/chunks/chunk-LIIZI3HY.js +5 -0
- package/dist/chunks/chunk-LP72AF56.js +45 -0
- package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
- package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
- package/dist/chunks/chunk-NW4GW47L.js +4 -0
- package/dist/chunks/chunk-OALEJ6FG.js +60 -0
- package/dist/chunks/chunk-OIV4DIMB.js +4 -0
- package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
- package/dist/chunks/chunk-OZXMPBUX.js +4 -0
- package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
- package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
- package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
- package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
- package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
- package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
- package/dist/chunks/chunk-QXFWIL4C.js +4 -0
- package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
- package/dist/chunks/chunk-R6CGBSTC.js +22 -0
- package/dist/chunks/chunk-RG5GP4RB.js +5 -0
- package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
- package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
- package/dist/chunks/chunk-SAJD4EKE.js +10 -0
- package/dist/chunks/chunk-SDUS2H3E.js +4 -0
- package/dist/chunks/chunk-SIHGKM4E.js +4 -0
- package/dist/chunks/chunk-SKHFU5DI.js +4 -0
- package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
- package/dist/chunks/chunk-T54CZKNJ.js +6 -0
- package/dist/chunks/chunk-TKFFQNAP.js +19 -0
- package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
- package/dist/chunks/chunk-TRXLIL7V.js +4 -0
- package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
- package/dist/chunks/chunk-UHXPRU6G.js +10 -0
- package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
- package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
- package/dist/chunks/chunk-V7K3KNDM.js +4 -0
- package/dist/chunks/chunk-VHX2GHBF.js +4 -0
- package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
- package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
- package/dist/chunks/chunk-W34AK4SK.js +65 -0
- package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
- package/dist/chunks/chunk-WZC4TDDM.js +6 -0
- package/dist/chunks/chunk-WZYS2HAK.js +4 -0
- package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
- package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
- package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
- package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
- package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
- package/dist/chunks/chunk-YWPBE5LP.js +4 -0
- package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
- package/dist/chunks/chunk-ZD2M73XA.js +19 -0
- package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
- package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
- package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
- package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
- package/dist/chunks/cli-VB2N7HEK.js +55 -0
- package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
- package/dist/chunks/context-CI2FKEQE.js +4 -0
- package/dist/chunks/cost-CZRRSIUF.js +5 -0
- package/dist/chunks/dist-QCNQN6DY.js +4 -0
- package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
- package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
- package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
- package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
- package/dist/chunks/file-Y5G56IUT.js +4 -0
- package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
- package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
- package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
- package/dist/chunks/init-A6GY656J.js +4 -0
- package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
- package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
- package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
- package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
- package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
- package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
- package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
- package/dist/chunks/meta-JQH66YU7.js +4 -0
- package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
- package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
- package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
- package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
- package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
- package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
- package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
- package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
- package/dist/chunks/openai-responses-2SG757TL.js +6 -0
- package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
- package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
- package/dist/chunks/radius-THYKWV4E.js +4 -0
- package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
- package/dist/chunks/runner-5MKMRTIN.js +4 -0
- package/dist/chunks/runtime-DST3H5JP.js +4 -0
- package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
- package/dist/chunks/slack-R7SEJYMY.js +4 -0
- package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
- package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
- package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
- package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
- package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
- package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
- package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
- package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
- package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
- package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
- package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
- package/dist/chunks/workers-SQ2R32TK.js +4 -0
- package/dist/client-bundle/client.mjs +273 -93
- package/dist/client-bundle/manifest.json +2 -2
- package/dist/core/pi-sdk.js +1 -1
- package/dist/domain/auth/cc-auth-cli.js +1 -1
- package/dist/domain/mcp/bundled-server.js +1 -1
- package/dist/domain/mcp/feishu/client.js +4 -0
- package/dist/entry/app.js +151 -559
- package/dist/entry/browser-cli.js +10 -10
- package/dist/entry/cli.js +1 -1
- package/dist/entry/cortex-cli.js +1 -1
- package/dist/entry/daemon.js +4 -4
- package/dist/entry/hook-cli.js +2 -2
- package/dist/entry/production-app-bootstrap.js +1 -1
- package/dist/entry/production-evidence-export-cli.js +1 -1
- package/dist/entry/signal-cli.js +2 -2
- package/dist/tui/index.js +41 -41
- package/package.json +3 -3
- package/vendor/pi/CHANGELOG.md +330 -0
- package/vendor/pi/dist/codemode-worker.js +2 -0
- package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
- package/vendor/pi/dist/core/export-html/template.css +9 -0
- package/vendor/pi/dist/core/export-html/template.js +166 -46
- package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
- package/vendor/pi/dist/core/extensions/loader.js +1 -1
- package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
- package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
- package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
- package/vendor/pi/dist/utils/image-resize.js +1 -1
- package/vendor/pi/docs/cli.md +35 -12
- package/vendor/pi/docs/custom-provider.md +2 -0
- package/vendor/pi/docs/environment-variables.md +2 -0
- package/vendor/pi/docs/extensions.md +3192 -225
- package/vendor/pi/docs/keybindings.md +2 -2
- package/vendor/pi/docs/llama-cpp.md +27 -19
- package/vendor/pi/docs/mcp.md +6 -4
- package/vendor/pi/docs/message-types.md +1 -1
- package/vendor/pi/docs/models-configuration.md +9 -3
- package/vendor/pi/docs/models.md +2 -1
- package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
- package/vendor/pi/docs/packages.md +24 -0
- package/vendor/pi/docs/prompt-templates.md +1 -1
- package/vendor/pi/docs/providers.md +4 -2
- package/vendor/pi/docs/quickstart.md +7 -3
- package/vendor/pi/docs/rpc-commands.md +1 -1
- package/vendor/pi/docs/rpc.md +4 -2
- package/vendor/pi/docs/sessions.md +17 -3
- package/vendor/pi/docs/settings.md +6 -5
- package/vendor/pi/docs/slash-commands.md +3 -2
- package/vendor/pi/docs/terminal-setup.md +3 -1
- package/vendor/pi/docs/tmux.md +6 -0
- package/vendor/pi/docs/tui.md +4 -0
- package/vendor/pi/docs/windows.md +27 -0
- package/vendor/pi/examples/extensions/README.md +2 -1
- package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
- package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
- package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
- package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
- package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
- package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
- package/vendor/pi/examples/extensions/preset.ts +2 -0
- package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
- package/vendor/pi/examples/extensions/subagent/README.md +14 -11
- package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
- package/vendor/pi/examples/extensions/todo.ts +7 -0
- package/vendor/pi/examples/extensions/tools.ts +2 -0
- package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
- package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
- package/vendor/pi/examples/tsconfig.json +208 -0
- package/vendor/pi/package.json +15 -16
- package/vendor/pi/schemas/models.schema.json +66 -37
- package/vendor/pi/schemas/settings.schema.json +18 -1
- package/vendor/pi-ai/bedrock.js +1 -1
- package/vendor/pi-ai/oauth-load.js +1 -1
- package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
- package/web/dist/assets/index-D11wi0uG.js +540 -0
- package/web/dist/assets/index-JedYumhY.css +1 -0
- package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
- package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
- package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
- package/web/dist/index.html +2 -2
- package/web/dist/theme.css +22 -0
- package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
- package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
- package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
- package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
- package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
- package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
- package/dist/chunks/chunk-3F6WW7HR.js +0 -13
- package/dist/chunks/chunk-3OKHUVEM.js +0 -7
- package/dist/chunks/chunk-3YHOCPQU.js +0 -10
- package/dist/chunks/chunk-4EX2JJWB.js +0 -4
- package/dist/chunks/chunk-4LLH5OWM.js +0 -10
- package/dist/chunks/chunk-52T37Y47.js +0 -8
- package/dist/chunks/chunk-7MU2AKNM.js +0 -4
- package/dist/chunks/chunk-AAA3UBIS.js +0 -4
- package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
- package/dist/chunks/chunk-BKHDWCRT.js +0 -79
- package/dist/chunks/chunk-CQLH4UVX.js +0 -4
- package/dist/chunks/chunk-CVC66CFV.js +0 -33
- package/dist/chunks/chunk-D6UA4BZC.js +0 -19
- package/dist/chunks/chunk-DGMNI4AO.js +0 -4
- package/dist/chunks/chunk-DHSA5ACV.js +0 -125
- package/dist/chunks/chunk-DPQPXBTP.js +0 -68
- package/dist/chunks/chunk-DXBSQXJL.js +0 -18
- package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
- package/dist/chunks/chunk-EQITBTJC.js +0 -10
- package/dist/chunks/chunk-EXJA5RIX.js +0 -357
- package/dist/chunks/chunk-FF7UELTU.js +0 -4
- package/dist/chunks/chunk-FH74NME3.js +0 -115
- package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
- package/dist/chunks/chunk-FX6MOGLR.js +0 -11
- package/dist/chunks/chunk-G2V65UBA.js +0 -4
- package/dist/chunks/chunk-HGPBHTVD.js +0 -6
- package/dist/chunks/chunk-J5DVLUKY.js +0 -6
- package/dist/chunks/chunk-JW2HFMTF.js +0 -4
- package/dist/chunks/chunk-KDYEGGMW.js +0 -4
- package/dist/chunks/chunk-KIGMAATV.js +0 -23
- package/dist/chunks/chunk-KIU5FAPY.js +0 -5
- package/dist/chunks/chunk-KIWMQPH7.js +0 -739
- package/dist/chunks/chunk-L6VCIGWS.js +0 -11
- package/dist/chunks/chunk-LACGULCN.js +0 -10
- package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
- package/dist/chunks/chunk-MEPASGPP.js +0 -6
- package/dist/chunks/chunk-MFAEUHMV.js +0 -28
- package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
- package/dist/chunks/chunk-NKDMKRSB.js +0 -68
- package/dist/chunks/chunk-NKXV32S6.js +0 -4
- package/dist/chunks/chunk-NVX5IPRN.js +0 -4
- package/dist/chunks/chunk-O3JW2F7D.js +0 -8
- package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
- package/dist/chunks/chunk-OISO5JXB.js +0 -4
- package/dist/chunks/chunk-OPYXNSMY.js +0 -4
- package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
- package/dist/chunks/chunk-P52RMIYX.js +0 -6
- package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
- package/dist/chunks/chunk-PZMGBKUR.js +0 -13
- package/dist/chunks/chunk-PZMXHA6X.js +0 -9
- package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
- package/dist/chunks/chunk-QBKCAIJG.js +0 -4
- package/dist/chunks/chunk-QEOFEETJ.js +0 -4
- package/dist/chunks/chunk-QUUEQRIT.js +0 -4
- package/dist/chunks/chunk-RA6HKFBV.js +0 -4
- package/dist/chunks/chunk-REPYBMQS.js +0 -4
- package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
- package/dist/chunks/chunk-TAWLERZA.js +0 -4
- package/dist/chunks/chunk-TWAEABGG.js +0 -52
- package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
- package/dist/chunks/chunk-UD3NMUHR.js +0 -12
- package/dist/chunks/chunk-UNVEZI57.js +0 -4
- package/dist/chunks/chunk-VQUPKMDR.js +0 -4
- package/dist/chunks/chunk-W25TB3PU.js +0 -4
- package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
- package/dist/chunks/chunk-WEZWKMYU.js +0 -4
- package/dist/chunks/chunk-XAJLZR7C.js +0 -28
- package/dist/chunks/chunk-XH6FMP3N.js +0 -71
- package/dist/chunks/chunk-XSRZHN63.js +0 -4
- package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
- package/dist/chunks/chunk-YG7OEPR2.js +0 -6
- package/dist/chunks/chunk-YHIWOGVL.js +0 -4
- package/dist/chunks/chunk-YKKEI5GI.js +0 -4
- package/dist/chunks/chunk-YZSHTWNM.js +0 -92
- package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
- package/dist/chunks/cli-5DBTRMHU.js +0 -53
- package/dist/chunks/client-XOGYH5UR.js +0 -4
- package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
- package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
- package/dist/chunks/context-VCQH5OB6.js +0 -4
- package/dist/chunks/cost-PGGFI7QJ.js +0 -5
- package/dist/chunks/dist-PUKMZ7GW.js +0 -4
- package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
- package/dist/chunks/es5-VNTQPCKX.js +0 -4
- package/dist/chunks/file-7BN7RCAY.js +0 -4
- package/dist/chunks/gateway-UCRPMR75.js +0 -36
- package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
- package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
- package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
- package/dist/chunks/init-HA7FAQ73.js +0 -4
- package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
- package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
- package/dist/chunks/meta-KY3LNFV2.js +0 -4
- package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
- package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
- package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
- package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
- package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
- package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
- package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
- package/dist/chunks/radius-HXRZVBDB.js +0 -4
- package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
- package/dist/chunks/runner-PLVZDGHB.js +0 -4
- package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
- package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
- package/dist/chunks/slack-WAGSPZUX.js +0 -4
- package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
- package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
- package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
- package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
- package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
- package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
- package/dist/chunks/ui-view-O7PLANT7.js +0 -4
- package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
- package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
- package/dist/chunks/workers-XN4PSTH6.js +0 -4
- package/vendor/aistatus/gateway-cli.js +0 -21
- package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
- package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
- package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
- package/web/dist/assets/index-BHZpFXhc.js +0 -525
- package/web/dist/assets/index-DqWMdMkh.css +0 -1
- package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
- package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
import { createRequire as __cortexCreateRequire } from 'node:module';
|
|
2
|
-
const require = __cortexCreateRequire(import.meta.url);
|
|
3
|
-
const __cortexPackageRoot = new URL("../../", import.meta.url);
|
|
4
|
-
import{c as bd,d as Ad,e as wd}from"./chunk-WHC7AYZD.js";var yu=bd((X,ti)=>{"use strict";if(typeof ti<"u"&&ti!==globalThis.module&&typeof X<"u"&&ti.exports===X){Object.defineProperty(X,"__esModule",{value:!0}),X.findX509Credential=X.rememberX509Credential=X.findX509OAuthError=X.rememberX509OAuthError=X.isApprovedX509Client=X.markApprovedX509Client=X.isRetryableX509IssuerError=X.markRetryableX509IssuerError=X.isTransientX509ConnectionError=X.markTransientX509ConnectionError=X.rememberRegisteredX509Transport=X.findRegisteredX509Transport=void 0;let r=new WeakMap,e=new WeakSet,t=new WeakSet,n=new WeakSet,s=new WeakMap,o=new WeakMap;X.findRegisteredX509Transport=WeakMap.prototype.get.bind(r),X.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(r),X.markTransientX509ConnectionError=WeakSet.prototype.add.bind(e),X.isTransientX509ConnectionError=WeakSet.prototype.has.bind(e),X.markRetryableX509IssuerError=WeakSet.prototype.add.bind(t),X.isRetryableX509IssuerError=WeakSet.prototype.has.bind(t),X.markApprovedX509Client=WeakSet.prototype.add.bind(n),X.isApprovedX509Client=WeakSet.prototype.has.bind(n),X.rememberX509OAuthError=WeakMap.prototype.set.bind(s),X.findX509OAuthError=WeakMap.prototype.get.bind(s),X.rememberX509Credential=WeakMap.prototype.set.bind(o),X.findX509Credential=WeakMap.prototype.get.bind(o)}});function b(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t}function a(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var Je=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return Je=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function mt(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Js=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e="cause"in r,t=new Error(r.message,e?{cause:r.cause}:{});return r.stack&&(t.stack=r.stack),e&&!Object.prototype.hasOwnProperty.call(t,"cause")&&(t.cause=r.cause),r.name&&(t.name=r.name),t}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var h=class extends Error{},z=class r extends h{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new De({message:n,cause:Js(t)});let o=t?.error;return e===400?new st(e,o,n,s):e===401?new $t(e,o,n,s):e===403?new jt(e,o,n,s):e===404?new Lt(e,o,n,s):e===409?new Mt(e,o,n,s):e===422?new Bt(e,o,n,s):e===429?new Dt(e,o,n,s):e>=500?new Nt(e,o,n,s):new r(e,o,n,s)}},Y=class extends z{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},De=class extends z{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},re=class extends De{constructor({message:e}={}){super({message:e??"Request timed out."})}},st=class extends z{},$t=class extends z{},jt=class extends z{},Lt=class extends z{},Mt=class extends z{},Bt=class extends z{},Dt=class extends z{},Nt=class extends z{},Ft=class extends h{constructor(){super("Could not parse response content as the length limit was reached")}},Wt=class extends h{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Oe=class extends Error{constructor(e){super(e)}},Ne=class extends z{constructor(e,t,n){let s="OAuth2 authentication error",o;if(t&&typeof t=="object"){let i=t;o=i.error;let c=i.error_description;c&&typeof c=="string"?s=c:o&&(s=o)}super(e,t,s,n),this.error_code=o}},gr=class extends h{constructor(e,t,n){super(e),this.provider=t,this.cause=n}};var Pd=/^[a-z][a-z0-9+.-]*:/i,Ec=r=>Pd.test(r),be=r=>(be=Array.isArray,be(r)),kc=be;function Vs(r){return typeof r!="object"?{}:r??{}}function Zi(r){if(!r)return!0;for(let e in r)return!1;return!0}function $(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function _e(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var ea=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new h(`${r} must be an integer`);if(e<0)throw new h(`${r} must be a positive integer`);return e};var Cc=r=>{try{return JSON.parse(r)}catch{return}};var pn=(r,...e)=>new Promise((t,n)=>{let s=[...new Set(e.filter(m=>m!=null))],o,i=!1,c=()=>{for(let m of s)try{m.removeEventListener("abort",d)}catch{}},u=m=>{i||(i=!0,o!==void 0&&(clearTimeout(o),o=void 0),c(),m())},d=()=>{u(()=>n())};if(s.some(m=>m.aborted)){d();return}o=setTimeout(()=>{u(t)},r);for(let m of s){if(i)break;try{m.addEventListener("abort",d,{once:!0})}catch(y){u(()=>n(y))}}s.some(m=>m.aborted)&&d()});var hn=globalThis,Ko=typeof hn.FinalizationRegistry=="function"?new hn.FinalizationRegistry(r=>{try{r()}catch{}}):void 0,Tc=new WeakMap,Gs=new WeakMap;function xd(r,e,t){let n=Gs.get(r);if(!n){let o=new Set,i=()=>{Gs.delete(r);for(let c of o)t.unregister(c),c.deref()?.();o.clear()};n={callbacks:o,abort:i},r.addEventListener("abort",i,{once:!0}),Gs.set(r,n)}let s=n;return s.callbacks.add(e),()=>{s.callbacks.delete(e),t.unregister(e),s.callbacks.size===0&&(Gs.get(r)===s&&Gs.delete(r),r.removeEventListener("abort",s.abort))}}function Sd(r,e,t){r.addEventListener("abort",()=>e.deref()?.delete(t),{once:!0})}function ta(r,e,t){if(typeof hn.WeakRef=="function"&&Ko&&!t.aborted){let n=Tc.get(r);n||(n=new Set,Tc.set(r,n)),n.add(e),Sd(t,new hn.WeakRef(n),e)}}function $c(r,e,t){if(r.aborted)return e(),()=>{};if(typeof hn.WeakRef!="function"||!Ko)return r.addEventListener("abort",e,{once:!0}),()=>r.removeEventListener("abort",e);let n=new hn.WeakRef(e),s=xd(r,n,Ko);return Ko.register(e,s,n),ta(t,e,t),s}function Ys(){if(typeof fetch<"u")return fetch;throw new 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 ra(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function Qs(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return ra({start(){},async pull(t){let{done:n,value:s}=await e.next();n?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function zo(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function _t(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Lc;function ye(r){let e;return(Lc??(e=new globalThis.TextEncoder,Lc=e.encode.bind(e)))(r)}var Mc;function Bc(r){let e;return(Mc??(e=new globalThis.TextDecoder,Mc=e.decode.bind(e)))(r)}var na,ne,G,Z,ot,br,Nc,Zs=64*1024,Ar=class{constructor(){na.add(this),ne.set(this,void 0),G.set(this,void 0),Z.set(this,void 0),ot.set(this,void 0),br.set(this,void 0),b(this,ne,new Uint8Array,"f"),b(this,G,0,"f"),b(this,Z,0,"f"),b(this,ot,0,"f"),b(this,br,!1,"f")}decode(e){if(e==null)return[];let t;if(e instanceof ArrayBuffer?t=new Uint8Array(e):typeof e=="string"?t=ye(e):t=e,t.length===0)return[];if(a(this,br,"f")&&(b(this,br,!1,"f"),t[0]===10&&(t=t.subarray(1)),t.length===0))return[];a(this,na,"m",Nc).call(this,t);let n=[],s;for(;(s=Rd(a(this,ne,"f"),a(this,ot,"f"),a(this,Z,"f")))!=null;){let o=Bc(a(this,ne,"f").subarray(a(this,G,"f"),s.preceding));n.push(o),b(this,G,s.index,"f"),s.carriage&&(a(this,G,"f")<a(this,Z,"f")&&a(this,ne,"f")[a(this,G,"f")]===10?b(this,G,a(this,G,"f")+1,"f"):a(this,G,"f")===a(this,Z,"f")&&b(this,br,!0,"f")),b(this,ot,a(this,G,"f"),"f")}if(b(this,ot,a(this,Z,"f"),"f"),a(this,G,"f")===a(this,Z,"f"))b(this,G,0,"f"),b(this,Z,0,"f"),b(this,ot,0,"f"),a(this,ne,"f").length>Zs&&b(this,ne,new Uint8Array,"f");else if(n.length>0&&a(this,ne,"f").length>Zs){let o=a(this,Z,"f")-a(this,G,"f");if(o<=Zs||a(this,ne,"f").length>o*4){let i=o<=Zs?Math.min(Math.max(o*2,256),Zs):o*2,c=new Uint8Array(i);c.set(a(this,ne,"f").subarray(a(this,G,"f"),a(this,Z,"f"))),b(this,ne,c,"f"),b(this,G,0,"f"),b(this,Z,o,"f"),b(this,ot,o,"f")}}return n}flush(){return b(this,br,!1,"f"),a(this,G,"f")===a(this,Z,"f")?[]:this.decode(`
|
|
5
|
-
`)}};ne=new WeakMap,G=new WeakMap,Z=new WeakMap,ot=new WeakMap,br=new WeakMap,na=new WeakSet,Nc=function(e){if(a(this,Z,"f")+e.length>a(this,ne,"f").length){let t=a(this,Z,"f")-a(this,G,"f");if(a(this,G,"f")>=a(this,ne,"f").length/2&&t+e.length<=a(this,ne,"f").length)a(this,ne,"f").copyWithin(0,a(this,G,"f"),a(this,Z,"f"));else{let n=Math.max(a(this,ne,"f").length*2,t+e.length,256),s=new Uint8Array(n);s.set(a(this,ne,"f").subarray(a(this,G,"f"),a(this,Z,"f"))),b(this,ne,s,"f")}b(this,ot,a(this,ot,"f")-a(this,G,"f"),"f"),b(this,Z,t,"f"),b(this,G,0,"f")}a(this,ne,"f").set(e,a(this,Z,"f")),b(this,Z,a(this,Z,"f")+e.length,"f")};Ar.NEWLINE_CHARS=new Set([`
|
|
6
|
-
`,"\r"]);Ar.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Rd(r,e,t){for(let o=e;o<t;o++){if(r[o]===10)return{preceding:o,index:o+1,carriage:!1};if(r[o]===13)return{preceding:o,index:o+1,carriage:!0}}return null}function Fc(r){for(let e=0;e<r.length-1;e++){let t=Dc(r,e);if(t>0){let n=e+t,s=Dc(r,n);if(s>0)return n+s}}return-1}function Dc(r,e){return r[e]===10?1:r[e]===13?r[e+1]===10?2:1:0}var Ho={off:0,error:200,warn:300,info:400,debug:500},sa=(r,e,t)=>{if(r){if($(Ho,r))return r;ee(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Ho))}`)}};function eo(){}function Xo(r,e,t){return!e||Ho[r]>Ho[t]?eo:e[r].bind(e)}var vd={error:eo,warn:eo,info:eo,debug:eo},Wc=new WeakMap;function ee(r){let e=r.logger,t=r.logLevel??"off";if(!e)return vd;let n=Wc.get(e);if(n&&n[0]===t)return n[1];let s={error:Xo("error",e,t),warn:Xo("warn",e,t),info:Xo("info",e,t),debug:Xo("debug",e,t)};return Wc.set(e,[t,s]),s}var Uc=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","signingsecret","xamzsecuritytoken","xamzsignature","xamzcredential"]);function to(r){let e=r.toLowerCase().replace(/[-_]/gu,"");return Uc.has(e)||Uc.has(e.replace(/^x/u,""))}var Od=new Set(["authorization","proxy-authorization","api-key","x-api-key","x-amz-security-token","cookie","set-cookie","x-session-token","x-session-id","x-auth-token","x-id-token"]);function Vo(r){return Od.has(r.toLowerCase().replace(/_/gu,"-"))||to(r)}function Jo(r){let e=new URL(r);e.username="",e.password="",e.hash="";for(let t of e.searchParams.keys())to(t)&&e.searchParams.set(t,"***");return e.href}var yt=r=>{if(r.options){if(r.options={...r.options},delete r.options.headers,r.options.path){let e=r.options.path,t=new URL(Jo(new URL(e,"https://redacted.invalid").href));r.options.path=t.origin==="https://redacted.invalid"?`${e.startsWith("/")?"/":""}${t.pathname.slice(1)}${t.search}`:t.href}r.options.query&&(r.options.query=Object.fromEntries(Object.entries(r.options.query).map(([e,t])=>[e,to(e)?"***":t])))}return r.url&&(r.url=Jo(r.url)),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,Vo(e)?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r};var Go,Yo,Qo,oa;function Ed(r){return!(r instanceof z)&&mt(r)}function qc(){let r=[],e=0,t=!1;return{get length(){return r.length-e},get canceled(){return t},enqueue(n){t||r.push(n)},dequeue(){if(e===r.length)return;let n=r[e];return r[e]=void 0,e+=1,e===r.length?(r=[],e=0):e>=1024&&e*2>=r.length&&(r=r.slice(e),e=0),n},cancel(){t=!0,r.length=0,e=0}}}var Ee=class r{constructor(e,t,n){Go.add(this),Yo.set(this,void 0),Qo.set(this,!1),this.iterator=e,this.controller=t,b(this,Yo,n,"f")}static fromSSEResponse(e,t,n,s){let o=!1,i=n?ee(n):console;async function*c(){if(o)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let u=!1,d=!1,m=Cd(e,t),y=m.return.bind(m);m.return=p=>(d||t.abort(),y(p));try{for await(let p of m){if(p.data==="[DONE]"){d=!0;break}if(p.event===null||!p.event.startsWith("thread.")){let g;try{g=JSON.parse(p.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if(p.event==="error")throw new z(void 0,g?.error??g,void 0,e.headers);if(g&&g.error)throw new z(void 0,g.error,void 0,e.headers);yield s?{event:p.event,data:g}:g}else{let g;try{g=JSON.parse(p.data)}catch{throw i.error("Could not parse message into JSON:"),i.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}yield{event:p.event,data:g}}}u=!0}catch(p){if(d||Ed(p)||t.signal.aborted&&p===t.signal.reason)return;throw p}finally{u||t.abort()}}return new r(c,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*o(){let c=new Ar,u=e.getReader(),d=!1,m,y=()=>{m??(m=u.cancel()),m.catch(()=>{})};t.signal.addEventListener("abort",y,{once:!0});try{if(t.signal.aborted){y();return}for(;;){let{value:p,done:g}=await u.read();if(g){d=!0;break}if(t.signal.aborted)return;for(let A of c.decode(p)){if(t.signal.aborted)return;yield A}}if(t.signal.aborted)return;for(let p of c.flush()){if(t.signal.aborted)return;yield p}}finally{t.signal.removeEventListener("abort",y),d||y(),u.releaseLock()}}async function*i(){if(s)throw new h("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let c=!1;try{for await(let u of o())if(u){let d;try{d=JSON.parse(u)}catch(m){throw m instanceof SyntaxError?new SyntaxError("Error reading response: malformed newline-delimited JSON."):m}yield d}c=!0}catch(u){if(t.signal.aborted||mt(u))return;throw u}finally{c||t.abort()}}return new r(i,t,n)}[(Yo=new WeakMap,Qo=new WeakMap,Go=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){let{controller:e}=this,t=qc(),n=qc(),s=this.iterator(),o=c=>({next:()=>{if(c.canceled)return Promise.resolve({value:void 0,done:!0});if(c.length===0){let u=s.next();t.enqueue(u),n.enqueue(u)}return c.dequeue()},return:async()=>(c.canceled||(c.cancel(),t.canceled&&n.canceled&&await a(this,Go,"m",oa).call(this,s,e)),{value:void 0,done:!0})}),i=c=>{let u=new r(()=>o(c),e,a(this,Yo,"f"));return b(u,Qo,!0,"f"),u};return[i(t),i(n)]}toReadableStream(){let{controller:e}=this,t,n,s=()=>n??(n=a(this,Go,"m",oa).call(this,t,e));return ra({start:async()=>{t=this[Symbol.asyncIterator]()},async pull(o){try{let{value:i,done:c}=await t.next();if(c)return o.close();let u=ye(JSON.stringify(i)+`
|
|
7
|
-
`);o.enqueue(u)}catch(i){o.error(i),s().catch(()=>{})}},cancel:s})}};oa=async function(e,t){let n=e.return;n&&(a(this,Qo,"f")||t.abort(),await Reflect.apply(n,e,[]))};function kd(r,e){let t=typeof r.getReader=="function"?r.getReader():void 0,n=t?{next:()=>t.read(),return:()=>t.cancel()}:zo(r)[Symbol.asyncIterator](),s={value:void 0,done:!0},o=!1,i=!1,c,u,d=()=>new Promise(g=>{u=g}),m=()=>{if(i||o)return c;i=!0;try{c=Promise.resolve(n.return?.())}catch(g){c=Promise.reject(g)}return c.catch(()=>{}),c},y=()=>{queueMicrotask(()=>{u?.(),m()})};return{iterator:{async next(){if(e.aborted)return s;let g=d().then(()=>s);try{let A=await Promise.race([n.next(),g]);return e.aborted?s:A.done?(o=!0,s):{value:A.value,done:!1}}catch(A){if(e.aborted&&(mt(A)||A===e.reason))return s;throw A}finally{u=void 0}},async return(){let g=m();if(g&&!e.aborted){let A=d();try{e.aborted||await Promise.race([g,A])}finally{u=void 0}}return s},[Symbol.asyncIterator](){return this}},start(){e.addEventListener("abort",y,{once:!0}),e.aborted&&y()},async cleanup(g){let A;try{e.removeEventListener("abort",y)}catch(w){A=w}if(!o){let w=m();if(w&&!g&&!e.aborted)try{await w}catch(S){A??(A=S)}}if(t)try{t.releaseLock()}catch(w){A??(A=w)}if(A!==void 0&&!g&&!e.aborted)throw A}}}async function*Cd(r,e){if(!r.body)throw e.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative"?new h("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 h("Attempted to iterate over a response with no body");let t=new ia,n=new Ar,{signal:s}=e,o=kd(r.body,s),i=!1;try{o.start();for await(let u of $d(o.iterator)){if(s.aborted)return;for(let d of n.decode(u)){if(s.aborted)return;let m=t.decode(d);m&&(yield m)}}if(s.aborted)return;for(let u of n.flush()){if(s.aborted)return;let d=t.decode(u);d&&(yield d)}if(s.aborted)return;let c=t.flush();c&&(yield c)}catch(c){if(i=!0,!s.aborted||!mt(c)&&c!==s.reason)throw c}finally{await o.cleanup(i)}}var Td=3;async function*$d(r){let e=new Uint8Array,t=0,n=0,s=0;for await(let o of r){if(o==null)continue;let i;if(o instanceof ArrayBuffer?i=new Uint8Array(o):typeof o=="string"?i=ye(o):i=o,n+i.length>e.length){let u=n-t;if(t>=e.length/2&&u+i.length<=e.length)e.copyWithin(0,t,n);else{let d=new Uint8Array(Math.max(e.length*2,u+i.length));d.set(e.subarray(t,n)),e=d}s-=t,t=0,n=u}e.set(i,n),n+=i.length;let c;for(;(c=Fc(e.subarray(s,n)))!==-1;)c+=s,yield e.slice(t,c),t=c,s=t;s=Math.max(t,n-Td)}n>t&&(yield e.slice(t,n))}var ia=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.slice(0,-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
8
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,,n]=jd(e,":"),s=n;return s.startsWith(" ")&&(s=s.slice(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}flush(){return this.decode("")}};function jd(r,e){let t=r.indexOf(e);return t!==-1?[r.slice(0,t),e,r.slice(t+e.length)]:[r,"",""]}async function wr(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,i,c=await(async()=>{if(e.options.stream)return ee(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData):Ee.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let d=t.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(d?.includes("application/json")||d?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let g=await t.text();if(!g)return;let A=JSON.parse(g);return i=g.length,ro(A,t)}return await t.text()})().catch(u=>{throw Ld(u,e.controller.signal)});return r.logLevel==="debug"&&ee(r).debug(`[${n}] response parsed`,yt({retryOfRequestLogID:s,url:t.url,status:t.status,body:i===void 0?c:{type:"json",length:i},durationMs:Date.now()-o})),c}function Ld(r,e){if(!e.aborted||r!==e.reason||mt(r))return r;let t="This operation was aborted",n=globalThis.DOMException;return typeof n=="function"?new n(t,"AbortError"):Object.assign(new Error(t),{name:"AbortError"})}function ro(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Ut="7.19.0";var Hc=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Md(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Bd=()=>{let r=Md();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":zc(Deno.build.os),"X-Stainless-Arch":Kc(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":Ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":zc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Kc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Dd();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Dd(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/\bEdg(?:e|A|iOS)?\b(?:\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/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var Kc=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",zc=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Xc,Jc=()=>Xc??(Xc=Bd());var no=new WeakMap;function Vc(r,e){let t=no.get(r);return t||(t=new Set,no.set(r,t)),t.add(e),()=>{let n=no.get(r);n&&(n.delete(e),n.size===0&&no.delete(r))}}var Gc=({headers:r,body:e})=>{let t=typeof e=="object"&&e!==null?no.get(e):void 0,n;if(!t||t.size===0)n=JSON.stringify(e);else{let s=[...t];n=JSON.stringify(e,function(o,i){let c=i;for(let u of s){let d=u.value(this,o,c);d!==void 0&&(c=d)}return c});for(let o of s)o.complete()}return{bodyHeaders:{"content-type":"application/json"},body:n}};var aa="RFC3986",ca=String,ua={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:ca},Yc="RFC1738";var Qc,Zc=(r,e)=>{let t=Qc??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return Qc=t,t(r,e)};var it=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var la=1024,eu=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,c=>"%26%23"+Number.parseInt(c.slice(2),16)+"%3B");let i="";for(let c=0;c<o.length;){let u=Math.min((Math.floor(c/la)+1)*la,o.length);u<o.length&&o.codePointAt(u-1)>65535&&(u+=1);let d=o.length>=la?o.slice(c,u):o,m=[];for(let y=0;y<d.length;++y){let p=d.charCodeAt(y);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===Yc&&(p===40||p===41)){m[m.length]=d.charAt(y);continue}if(p<128){m[m.length]=it[p];continue}if(p<2048){m[m.length]=it[192|p>>6]+it[128|p&63];continue}if(p<55296||p>=57344){m[m.length]=it[224|p>>12]+it[128|p>>6&63]+it[128|p&63];continue}y+=1,p=65536+((p&1023)<<10|d.charCodeAt(y)&1023),m[m.length]=it[240|p>>18]+it[128|p>>12&63]+it[128|p>>6&63]+it[128|p&63]}i+=m.join(""),c=u}return i};function tu(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function da(r,e){if(be(r)){let t=[];for(let n of r)t.push(e(n));return t}return e(r)}var nu={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},su=function(e,t){Array.prototype.push.apply(e,be(t)?t:[t])},ru,ue={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:eu,encodeValuesOnly:!1,format:aa,formatter:ca,indices:!1,serializeDate(r){return(ru??(ru=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Fd(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var fa={};function ou(r,e,t,n,s,o,i,c,u,d,m,y,p,g,A,w,S,E){let P=r,L=E,I=0,T=!1;for(;(L=L.get(fa))!==void 0&&!T;){let v=L.get(r);if(I+=1,v!==void 0){if(v===I)throw new RangeError("Cyclic object value");T=!0}L.get(fa)===void 0&&(I=0)}if(typeof d=="function"?P=d(e,P):P instanceof Date?P=p?.(P):t==="comma"&&be(P)&&(P=da(P,v=>v instanceof Date?p?.(v):v)),P===null){if(o)return u&&!w?u(e,ue.encoder,S,"key",g):e;P=""}if(Fd(P)||tu(P)){if(u){let v=w?e:u(e,ue.encoder,S,"key",g);return[A?.(v)+"="+A?.(u(P,ue.encoder,S,"value",g))]}return[A?.(e)+"="+A?.(String(P))]}let x=[];if(P===void 0)return x;let M;if(t==="comma"&&be(P))w&&u&&(P=da(P,u)),M=[{value:P.length>0?P.join(",")||null:void 0}];else if(be(d))M=d;else{let v=Object.keys(P);m&&v.sort(m),M=v}let k=c?String(e).replace(/\./g,"%2E"):String(e),O=n&&be(P)&&P.length===1?k+"[]":k;if(s&&be(P)&&P.length===0)return O+"[]";for(let v of M){let K=typeof v=="object"&&v.value!==void 0?v.value:P[v];if(i&&K===null)continue;let D=y&&c?v.replace(/\./g,"%2E"):v,N;be(P)?N=typeof t=="function"?t(O,D):O:N=O+(y?"."+D:"["+D+"]"),E.set(r,I);let q=new WeakMap([[fa,E]]);su(x,ou(K,N,t,n,s,o,i,c,t==="comma"&&w&&be(P)?null:u,d,m,y,p,g,A,w,S,q))}return x}function Wd(r=ue){if(r.allowEmptyArrays!==void 0&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(r.encodeDotInKeys!==void 0&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&r.encoder!==void 0&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||ue.charset;if(r.charset!==void 0&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=aa;if(r.format!==void 0){if(!Zc(ua,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=ua[t],s=ue.filter;(typeof r.filter=="function"||be(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in nu?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=ue.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i;return r.allowDots===void 0?i=r.encodeDotInKeys?!0:ue.allowDots:i=!!r.allowDots,{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:ue.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:ue.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:ue.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:r.delimiter===void 0?ue.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:ue.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:ue.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:ue.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:ue.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:ue.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:ue.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:ue.strictNullHandling}}function iu(r,e={}){let t=r,n=Wd(e),s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):be(n.filter)&&(o=n.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let c=nu[n.arrayFormat],u=c==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);let d=new WeakMap;for(let p of s)n.skipNulls&&t[p]===null||su(i,ou(t[p],p,c,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d));let m=i.join(n.delimiter),y=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(y+=n.charset==="iso-8859-1"?"utf8=%26%2310003%3B&":"utf8=%E2%9C%93&"),m.length>0?y+m:""}function au(r){return iu(r,{arrayFormat:"brackets"})}var qd=new Map([["global","https://api.openai.com/v1"],["us","https://us.api.openai.com/v1"],["eu","https://eu.api.openai.com/v1"],["ae","https://ae.api.openai.com/v1"]]);function pa(r){if(r.dataResidency===null||r.dataResidency===void 0)return;if($(r,"baseURL"))throw new h("The `dataResidency` and `baseURL` options are mutually exclusive.");let e=qd.get(r.dataResidency);if(e===void 0)throw new h("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return e}function ha(r,e){if(r!=null)throw new h(`${e} does not support \`dataResidency\`.`)}var so,Ir=class r extends Promise{constructor(e,t,n=wr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,so.set(this,void 0),b(this,so,e,"f")}_thenUnwrap(e){return new r(a(this,so,"f"),this.responsePromise,async(t,n)=>ro(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.parsedPromise=this.responsePromise.then(e=>this.parseResponse(a(this,so,"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)}};so=new WeakMap;var Zo,Pr=class{constructor(e,t,n,s){Zo.set(this,void 0),b(this,Zo,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new h("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,Zo,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Zo=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},oo=class extends Ir{constructor(e,t,n){super(e,t,async(s,o)=>new n(s,o.response,await wr(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},le=class extends Pr{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},R=class extends Pr{constructor(e,t,n,s){super(e,t,n,s),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:{...Vs(this.options.query),after:t}}:null}},F=class extends Pr{constructor(e,t,n,s){super(e,t,n,s),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:{...Vs(this.options.query),after:e}}:null}},Q=class extends Pr{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Vs(this.options.query),after:e}}:null}},mn=class extends Pr{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Vs(this.options.query),page:e}}:null}};var zd={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Xd="urn:ietf:params:oauth:grant-type:token-exchange",Hd=.5;function Jd(r,e){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new h("Token exchange response has invalid 'expires_in' field");let t=Date.now(),n=t+r*1e3;if(!Number.isSafeInteger(n)||n<=t)throw new h("Token exchange response has invalid 'expires_in' field");let s=n-(performance.now()-e);if(s<=t)throw new h("Workload identity token expired before its exchange completed.");return s}function Vd(r,e,t){let n=(t??1200)*1e3,s=Math.min(n,e*1e3*Hd);return r-s}var cu=Response.prototype,Gd=cu.arrayBuffer;function Yd(r,e){let t=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(e===r||typeof t!="function"||Object.getOwnPropertyDescriptor(t,"name")?.value!=="Response"||Object.getOwnPropertyDescriptor(t,"prototype")?.value!==e)return!1;let n=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);return(n?.value==="Response"||typeof n?.get=="function")&&typeof Object.getOwnPropertyDescriptor(e,"headers")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"ok")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"status")?.get=="function"}function Qd(r,e){if(r===e)return!0;let t=Object.getOwnPropertyDescriptor(r,"constructor")?.value;return e!==null&&Object.getPrototypeOf(e)===r&&typeof t=="function"&&Object.getOwnPropertyDescriptor(t,"name")?.value==="Body"&&Object.getOwnPropertyDescriptor(t,"prototype")?.value===r}function Zd(r){let e=globalThis;return new TextDecoder("utf-8",{ignoreBOM:typeof e.Bun?.version=="string"}).decode(r)}async function ef(r){let e,t=null;for(let s=0,o=r;o!==null&&s<16&&o!==cu;o=Object.getPrototypeOf(o),s+=1){Yd(r,o)&&(t=o);let i=Object.getOwnPropertyDescriptor(o,"json");if(!i)continue;if(typeof i.value!="function")break;let c=Object.getOwnPropertyDescriptor(o,"text")?.value;if(typeof c=="function"&&Qd(o,t)){e=c;break}return i.value.call(r)}let n=e===void 0?Zd(await Gd.call(r)):await e.call(r);try{return JSON.parse(n)}catch{throw new SyntaxError("Token exchange response contains invalid JSON")}}function tf(r){return typeof globalThis.Bun?.version=="string"?/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(r):/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(r)}var ei=class r{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl="https://auth.openai.com/oauth/token";let{identityProviderId:n,serviceAccountId:s,clientId:o,refreshBufferSeconds:i,provider:c}=e;this.config={identityProviderId:n,serviceAccountId:s,...o===void 0?{}:{clientId:o},...i===void 0?{}:{refreshBufferSeconds:i},provider:{tokenType:c.tokenType,getToken:c.getToken.bind(c)}},this.fetch=t??Ys()}async getToken(){if(!this.cachedToken||r.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;let e=this.refreshToken(this.tokenGeneration);this.refreshPromise=e;try{return await e}finally{this.refreshPromise===e&&(this.refreshPromise=null)}}if(r.needsRefresh(this.cachedToken)&&!this.refreshPromise){let e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){let t=await this.config.provider.getToken(),n={grant_type:Xd,subject_token:t,subject_token_type:zd[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(n.client_id=this.config.clientId);let s=performance.now(),o=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),redirect:"manual"});if(!o.ok){let m=await o.text(),y;try{y=JSON.parse(m)}catch{}throw o.status===400||o.status===401||o.status===403?new Ne(o.status,y,o.headers):z.generate(o.status,y,`Token exchange failed with status ${o.status}`,o.headers)}let i=await ef(o),c=typeof i=="object"&&i!==null&&"access_token"in i?i.access_token:void 0;if(typeof c!="string"||c.trim().length===0||tf(c))throw new h("Token exchange response missing 'access_token' field");let u=i.expires_in??3600,d=Jd(u,s);return this.tokenGeneration===e&&(this.cachedToken={token:c,expiresAt:d,refreshAt:Vd(d,u,this.config.refreshBufferSeconds)}),c}static isTokenExpired(e){return Date.now()>=e.expiresAt}static needsRefresh(e){return Date.now()>=e.refreshAt}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}};var uu="https://mtls.api.openai.com/v1";function _n(r){let e;try{e=new URL(r)}catch{throw new h("X.509 workload identity requires the approved global mTLS API origin.")}if(e.origin!=="https://mtls.api.openai.com"||e.username||e.password)throw new h("X.509 workload identity requires the approved global mTLS API origin.");for(let t of e.searchParams.keys())if(to(t))throw new h("X.509 workload identity cannot send conflicting query authentication credentials.");return e}var lu=Symbol("brand.privateNullableHeaders"),rf=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*nf(r){if(!r)return;if(lu in r){let{values:s,nulls:o}=r;yield*s.entries();for(let i of o)yield[i,null];return}let e=!1,t,n=Symbol.iterator in r?r[Symbol.iterator]:void 0;typeof n=="function"?t={[Symbol.iterator]:()=>n.call(r)}:(e=!0,t=Object.entries(r??{}));for(let s of t){let o=s[0];if(typeof o!="string")throw new TypeError("expected header name to be a string");let i=kc(s[1])?s[1]:[s[1]],c=!1;for(let u of i)u!==void 0&&(e&&!c&&(c=!0,yield[o,null]),yield[o,u])}}var _=r=>{let e=new Headers,t=new Set;for(let n of r){let s=new Set;for(let[o,i]of nf(n)){if(!rf.test(o))throw new TypeError(`Header name must be a valid HTTP token ["${o}"]`);let c=o.toLowerCase();s.has(c)||(e.delete(c),s.add(c)),i===null?(e.delete(c),t.add(c)):(e.append(c,i),t.delete(c))}}return{[lu]:!0,values:e,nulls:t}};var ma={};Ad(ma,{findRegisteredX509Transport:()=>sf,findX509Credential:()=>_f,findX509OAuthError:()=>hf,isApprovedX509Client:()=>ff,isRetryableX509IssuerError:()=>lf,isTransientX509ConnectionError:()=>cf,markApprovedX509Client:()=>df,markRetryableX509IssuerError:()=>uf,markTransientX509ConnectionError:()=>af,rememberRegisteredX509Transport:()=>of,rememberX509Credential:()=>mf,rememberX509OAuthError:()=>pf});var du=new WeakMap,fu=new WeakSet,pu=new WeakSet,hu=new WeakSet,mu=new WeakMap,_u=new WeakMap,sf=WeakMap.prototype.get.bind(du),of=WeakMap.prototype.set.bind(du),af=WeakSet.prototype.add.bind(fu),cf=WeakSet.prototype.has.bind(fu),uf=WeakSet.prototype.add.bind(pu),lf=WeakSet.prototype.has.bind(pu),df=WeakSet.prototype.add.bind(hu),ff=WeakSet.prototype.has.bind(hu),pf=WeakMap.prototype.set.bind(mu),hf=WeakMap.prototype.get.bind(mu),mf=WeakMap.prototype.set.bind(_u),_f=WeakMap.prototype.get.bind(_u);var _a=wd(yu(),1),yf=typeof _a.findRegisteredX509Transport=="function"?_a:ma,{findRegisteredX509Transport:gu,rememberRegisteredX509Transport:xy,markTransientX509ConnectionError:Sy,isTransientX509ConnectionError:ri,markRetryableX509IssuerError:Ry,isRetryableX509IssuerError:ya,markApprovedX509Client:bu,isApprovedX509Client:gf,rememberX509OAuthError:vy,findX509OAuthError:Au,rememberX509Credential:Oy,findX509Credential:wu}=yf;function Iu(r){if(!r||typeof r!="object")throw new h("X.509 workload identity requires an approved X.509 transport capability.");let e=gu(r);if(!e)throw new h("X.509 workload identity requires an approved X.509 transport capability.");return e}var U,Ie,xr,Sr,at,Fe,bt,At,de,Rr,gt,Ue,We,Ru,si,vu,Pu,Ou,Eu,xu,ku,H,ba,bf=["dispatcher","agent","client","tls","proxy"],yn=(r,e)=>Headers.prototype.get.call(r,e),Af=1200*1e3,Su=1e3,ni=r=>{let e=new Y;return Object.defineProperty(e,"cause",{value:r.reason,writable:!0,configurable:!0}),e};function ga(r){for(let e of Headers.prototype.keys.call(r)){let t=e.toLowerCase().split("_").join("-");if(t!=="authorization"&&Vo(t)||t==="host")throw new h("X.509 workload identity cannot send conflicting authentication credentials.")}}function wf(r,e){let t=new AbortController,n=r===void 0?void 0:setTimeout(()=>t.abort(new re),r),s=n;typeof s=="object"&&s!==null&&"unref"in s&&typeof s.unref=="function"&&s.unref();let o=()=>t.abort(e?.reason);return e?.addEventListener("abort",o,{once:!0}),e?.aborted&&o(),{signal:t.signal,dispose:()=>{e?.removeEventListener("abort",o),n&&clearTimeout(n)}}}function If(r,e){let t,n=new Promise((s,o)=>{t=()=>o(e.reason),e.addEventListener("abort",t,{once:!0}),e.aborted&&t()});return{result:Promise.race([r.promise,n]),dispose:()=>{t&&e.removeEventListener("abort",t)}}}function oi(r){if(!r||typeof r!="object")return!1;let e=r;for(;e!==null&&e!==Object.prototype;){let n=Object.getOwnPropertyDescriptor(e,"provider");if(n){if(!("value"in n)||n.value!==void 0)return!1;break}e=Object.getPrototypeOf(e)}let t=r;for(;t!==null&&t!==Object.prototype;){let n=Object.getOwnPropertyDescriptor(t,"type");if(n){if(!("value"in n))throw new h("X.509 workload identity type must be a plain data property.");return n.value==="x509"}t=Object.getPrototypeOf(t)}return!1}function Aa(r){if(!r)return;for(let t of bf)if($(r,t))throw new h("X.509 workload identity cannot override its approved transport capability.");let e=Object.getOwnPropertyDescriptor(r,"redirect")?.value;if(e!==void 0&&e!=="manual")throw new h("X.509 workload identity requests require manual redirects.")}function io(r){if(Aa(r),r&&["body","headers","method","signal"].some(e=>$(r,e)))throw new h("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.")}function wa(r){io(r);let e={...r};return io(e),e}var Ae=class{constructor(e,t,n,s){if(U.add(this),xr.set(this,void 0),Sr.set(this,void 0),at.set(this,void 0),Fe.set(this,void 0),bt.set(this,void 0),At.set(this,void 0),de.set(this,void 0),Rr.set(this,void 0),gt.set(this,void 0),Ue.set(this,void 0),We.set(this,0),b(this,de,Iu(t),"f"),b(this,xr,e.identityProviderId,"f"),b(this,Sr,e.serviceAccountId,"f"),b(this,at,e.refreshBufferMs,"f"),b(this,Fe,e.refreshBufferSeconds,"f"),b(this,bt,n,"f"),b(this,At,s,"f"),a(this,at,"f")!==void 0&&a(this,Fe,"f")!==void 0)throw new h("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");if(a(this,at,"f")!==void 0&&(!Number.isSafeInteger(a(this,at,"f"))||a(this,at,"f")<0))throw new h("X.509 workload identity requires a nonnegative integer refreshBufferMs.");if(a(this,Fe,"f")!==void 0&&(!Number.isSafeInteger(a(this,Fe,"f"))||a(this,Fe,"f")<0||!Number.isSafeInteger(a(this,Fe,"f")*1e3)))throw new h("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");b(this,Rr,a(this,Fe,"f")===void 0?a(this,at,"f")??Af:a(this,Fe,"f")*1e3,"f")}identitySnapshot(){return{type:"x509",identityProviderId:a(this,xr,"f"),serviceAccountId:a(this,Sr,"f"),...a(this,at,"f")===void 0?{}:{refreshBufferMs:a(this,at,"f")},...a(this,Fe,"f")===void 0?{}:{refreshBufferSeconds:a(this,Fe,"f")}}}static shouldAuthenticate(e,t,n=e.headers){return!_([t,n]).nulls.has("authorization")}snapshotHeaders(e,t){let n=a(this,U,"m",H).call(this);return n.defaultHeaders??(n.defaultHeaders=_([e])),n.requestHeaders??(n.requestHeaders=_([t])),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:t}=a(this,U,"m",H).call(this);if(!e||!t)throw new h("X.509 workload identity requires snapshotted request headers.");return{defaultHeaders:e,requestHeaders:t}}snapshotTenant(e,t){if(e!==a(this,bt,"f")||t!==a(this,At,"f"))throw new h("X.509 workload identity cannot override its enrolled organization or project.");let n=a(this,U,"m",H).call(this);return n.tenant={organization:e,project:t},n.tenant}tenantSnapshot(){let{tenant:e}=a(this,U,"m",H).call(this);if(!e)throw new h("X.509 workload identity requires snapshotted tenant selectors.");return e}snapshotAPIURL(e){_n(e),a(this,U,"m",H).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=a(this,U,"m",H).call(this);if(e===void 0)throw new h("X.509 workload identity requires a snapshotted API destination.");return e}snapshotRequest(e,t,n){var s;(s=a(this,U,"m",H).call(this)).request??(s.request={signal:e,timeout:t,fetchOptions:n})}requestSnapshot(){let{request:e}=a(this,U,"m",H).call(this);if(!e)throw new h("X.509 workload identity requires snapshotted request settings.");return e}beginRequestPreparation(){let e=a(this,U,"m",H).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){a(this,U,"m",H).call(this).phase="planning"}beginRequestNetwork(){let e=a(this,U,"m",H).call(this);e.deadlineArmed?e.preparationStartedAt!==void 0&&(e.monotonicStartedAt+=performance.now()-e.preparationStartedAt,e.wallStartedAt+=Date.now()-(e.preparationWallStartedAt??Date.now()),delete e.preparationStartedAt,delete e.preparationWallStartedAt):(e.wallStartedAt=Date.now(),e.monotonicStartedAt=performance.now(),e.deadlineArmed=!0)}isPlanningRequest(){return a(this,U,"m",H).call(this).phase==="planning"}authorizePlannedRequest(e,t,n,s=!1){let o=a(this,U,"m",H).call(this),i=Object.getOwnPropertyDescriptor(t,"headers"),c=Object.getOwnPropertyDescriptor(t,"body"),u=Object.getOwnPropertyDescriptor(t,"signal"),d=Object.getOwnPropertyDescriptor(t,"redirect");if(o.phase!=="planning"||!i||!(i.value instanceof Headers)||!c&&"body"in t||[c,u,d].some(y=>y&&!("value"in y)))throw new h("X.509 workload identity requires an approved final request.");this.snapshotAPIURL(e),Aa(t);try{ga(i.value)}catch{throw new h("X.509 workload identity cannot use caller-supplied authentication credentials.")}if(yn(i.value,"Authorization")!==null)throw new h("X.509 workload identity cannot use caller-supplied authorization credentials.");if(a(this,U,"m",ba).call(this,i.value),!s&&(u?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new h("X.509 workload identity must preserve its approved request signal.");let m=this.requestSnapshot();o.request={...m,timeout:Math.min(m.timeout,n)},o.phase="authorizing"}ownRequestBody(e,t){e instanceof ReadableStream&&e!==t&&(a(this,U,"m",H).call(this).materializedBody=e)}static isStreamingRequestBody(e){return globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream||typeof e=="object"&&e!==null&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")}retireRequestBody(){let e=a(this,U,"m",H).call(this),t=e.materializedBody;delete e.materializedBody,t&&a(Ie,Ie,"m",Ru).call(Ie,t)}releaseRequestBody(e){let t=a(this,U,"m",H).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?a(this,U,"m",H).call(this).effectiveSignal=e:delete a(this,U,"m",H).call(this).effectiveSignal}effectiveSignal(){let e=a(this,U,"m",H).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,t){return a(this,de,"f").run(async()=>{let n=a(this,de,"f").current();if(!n)throw new h("X.509 workload identity requires an active certificate request scope.");n.owner=this,n.requestOwner=t;try{return await e()}finally{this.retireRequestBody(),this.releaseRequestCredentials(),delete n.requestOwner,delete n.owner}})}inRequest(e){let t=a(this,de,"f").current();return t?.owner===this&&t.requestOwner===e&&t.phase!=="authorizing"}matches(e){return a(this,de,"f")===a(e,de,"f")&&a(this,xr,"f")===a(e,xr,"f")&&a(this,Sr,"f")===a(e,Sr,"f")&&a(this,bt,"f")===a(e,bt,"f")&&a(this,At,"f")===a(e,At,"f")&&a(this,Rr,"f")===a(e,Rr,"f")}continuation(){let{wallStartedAt:e,monotonicStartedAt:t,deadlineArmed:n,request:s,requestOwner:o,effectiveSignal:i}=a(this,U,"m",H).call(this),c={wallStartedAt:e,monotonicStartedAt:t,owner:this,...n?{deadlineArmed:n}:{},...s?{request:s}:{},...i?{effectiveSignal:i}:{},...o?{requestOwner:o}:{}};return u=>a(this,de,"f").resume(c,async()=>{try{return await u()}finally{this.releaseRequestCredentials(),delete c.requestOwner,delete c.owner}})}releaseRequestCredentials(){let e=a(this,U,"m",H).call(this);delete e.request,delete e.phase,delete e.deadlineArmed,delete e.preparationStartedAt,delete e.preparationWallStartedAt,delete e.effectiveSignal,delete e.materializedBody,delete e.apiURL,delete e.tenant,delete e.token,delete e.defaultHeaders,delete e.requestHeaders,delete e.tokenGeneration,delete e.headers,delete e.authorization}requestStartedAt(e){return a(this,de,"f").current()?.wallStartedAt}usedWorkloadToken(e){return a(this,de,"f").current()?.token!==void 0}remainingTimeout(e,t){let n=a(this,de,"f").current();if(n===void 0)return t;let s=t-(performance.now()-n.monotonicStartedAt);if(s<=0)throw new re;return s}async waitForRetry(e,t){try{await a(this,de,"f").sleep(e,t)}catch(n){throw t?.aborted?ni(t):n}}static isRetryableFailure(e){return typeof e=="object"&&e!==null&&(ri(e)||ya(e))}static retryHeaders(e){if(!e||typeof e!="object"||!ya(e))return;let t=Object.getOwnPropertyDescriptor(e,"headers")?.value;return t instanceof Headers?t:void 0}async getToken(e,t){let n=t?t.signal:e?.signal;if(n?.aborted)throw ni(n);e&&io(t?t.fetchOptions:e.fetchOptions),a(this,U,"m",ku).call(this,t);let s=e?a(this,U,"m",H).call(this):void 0,o=a(this,gt,"f");if(o&&performance.now()<o.refreshAt&&Date.now()<o.wallRefreshAt)return a(Ie,Ie,"m",si).call(Ie,s,o);let i=t&&e?this.remainingTimeout(e,t.timeout):t?.timeout,{signal:c,dispose:u}=wf(i,n);if(n?.aborted)throw u(),ni(n);let d=a(this,Ue,"f")??a(this,U,"m",Eu).call(this);d.waiters+=1;let m=If(d,c);try{let y=await m.result,p=a(this,gt,"f");if(!p||p.accessToken!==y.accessToken)throw new Y;return a(Ie,Ie,"m",si).call(Ie,s,p)}catch(y){return await a(this,U,"m",vu).call(this,y,d,o,s,e,t)}finally{m.dispose(),u(),d.waiters-=1,a(this,U,"m",Ou).call(this,d)}}invalidateToken(){let e=a(this,de,"f").current();if(!e?.token||a(this,gt,"f")?.accessToken!==e.token||a(this,gt,"f").generation!==e.tokenGeneration)return;b(this,We,a(this,We,"f")+1,"f"),b(this,gt,void 0,"f");let t=a(this,Ue,"f");b(this,Ue,void 0,"f"),t?.controller.abort(new Y)}bindRequest(e,t,n){if(!(t.headers instanceof Headers))throw new h("X.509 workload identity requires the original workload authorization headers.");let s=a(this,U,"m",H).call(this),{token:o}=s,i=e.__security??{bearerAuth:!0},c=o?`Bearer ${o}`:null;!o&&i.adminAPIKeyAuth&&n!==null&&yn(t.headers,"Authorization")!==null&&(c=new Headers({Authorization:`Bearer ${n}`}).get("Authorization")),s.headers=t.headers,s.authorization=c,this.assertRequest(t)}adoptRequestHeaders(e){let t=a(this,U,"m",H).call(this),n=t.headers;if(!(n instanceof Headers)||!(e.headers instanceof Headers))throw new h("X.509 workload identity must preserve its issued workload authorization.");t.headers=e.headers;try{this.assertRequest(e)}catch(s){throw t.headers=n,s}}assertRequest(e){let{headers:t}=e;if(!(t instanceof Headers))throw new h("X.509 workload identity must preserve its issued workload authorization.");let n=a(this,de,"f").current();if(!n||n.headers!==t||n.authorization===void 0||yn(t,"Authorization")!==n.authorization)throw new h("X.509 workload identity must preserve its issued workload authorization.");a(this,U,"m",ba).call(this,t),ga(t)}fetch(){return async(e,t={})=>{let n=_n(typeof e=="string"||e instanceof URL?e:e.url);Aa(t),this.assertRequest(t);let s=t.headers;if(!(s instanceof Headers))throw new h("X.509 workload identity must preserve its issued workload authorization.");let o=new Headers([...Headers.prototype.entries.call(s)]);return ga(o),t.headers=o,t.redirect="manual",await a(this,de,"f").dispatch(n,t)}}};Ie=Ae,xr=new WeakMap,Sr=new WeakMap,at=new WeakMap,Fe=new WeakMap,bt=new WeakMap,At=new WeakMap,de=new WeakMap,Rr=new WeakMap,gt=new WeakMap,Ue=new WeakMap,We=new WeakMap,U=new WeakSet,Ru=async function(e){try{await _t(e)}catch{}},si=function(e,t){return e&&(e.token=t.accessToken,e.tokenGeneration=t.generation),t.accessToken},vu=async function(e,t,n,s,o,i){let c=i?i.signal:o?.signal;if(c?.aborted)throw ni(c);if(t.controller.signal.aborted&&t.generation!==a(this,We,"f"))return await this.getToken(o,i);let u=a(this,U,"m",Pu).call(this,e,n,s);if(u!==void 0)return u;if(e&&typeof e=="object"&&!(e instanceof Ne)){let d=Au(e);if(d)throw new Ne(d.status,d.error,d.headers)}throw e},Pu=function(e,t,n){if(!t||t!==a(this,gt,"f")||performance.now()>=t.expiresAt||Date.now()>=t.wallExpiresAt||!Ie.isRetryableFailure(e))return;let s=Ie.retryHeaders(e),o=s?.get("retry-after-ms"),i=o?Number(o):void 0,c=s?.get("retry-after");if(c&&(i===void 0||Number.isNaN(i))){let d=Number(c);i=Number.isNaN(d)?Date.parse(c)-Date.now():d*1e3}let u=i!==void 0&&Number.isFinite(i)&&i>=0&&i<=6e4?Math.max(Su,i):Su;return t.refreshAt=Math.min(t.expiresAt,performance.now()+u),t.wallRefreshAt=Math.min(t.wallExpiresAt,Date.now()+u),a(Ie,Ie,"m",si).call(Ie,n,t)},Ou=function(e){e.waiters!==0||a(this,Ue,"f")!==e||queueMicrotask(()=>{e.waiters===0&&a(this,Ue,"f")===e&&(b(this,Ue,void 0,"f"),b(this,We,a(this,We,"f")+1,"f"),e.controller.abort(new Y))})},Eu=function(){let e=new AbortController,t=a(this,We,"f"),n={controller:e,generation:t,waiters:0,promise:a(this,U,"m",xu).call(this,e,t)};return b(this,Ue,n,"f"),n},xu=async function(e,t){let n=performance.now(),s=Date.now();try{let o=await a(this,de,"f").exchange(a(this,xr,"f"),a(this,Sr,"f"),e.signal),i=o.expiresIn*1e3,c=n+i,u=s+i;if(performance.now()>=c||Date.now()>=u)throw new h("X.509 workload identity token expired before its exchange completed.");if(a(this,We,"f")!==t||e.signal.aborted||a(this,Ue,"f")?.controller!==e)throw new Y;return b(this,We,a(this,We,"f")+1,"f"),b(this,gt,{accessToken:o.accessToken,generation:a(this,We,"f"),expiresAt:c,refreshAt:c-Math.min(a(this,Rr,"f"),i/2),wallExpiresAt:u,wallRefreshAt:u-Math.min(a(this,Rr,"f"),i/2)},"f"),o}finally{a(this,Ue,"f")?.controller===e&&b(this,Ue,void 0,"f")}},ku=function(e){if(!e)return;if(e.organization!==a(this,bt,"f")||e.project!==a(this,At,"f"))throw new h("X.509 workload identity cannot override its enrolled organization or project.");_n(e.apiURL);let t=_([e.defaultHeaders,e.requestHeaders]);if(a(this,bt,"f")!==null&&t.nulls.has("openai-organization")||a(this,At,"f")!==null&&t.nulls.has("openai-project"))throw new h("X.509 workload identity cannot omit its enrolled organization or project.");for(let n of t.values.keys()){let s=n.toLowerCase().split("_").join("-");if((s==="openai-organization"||s==="openai-project")&&(n!==s||yn(t.values,n)!==(s==="openai-organization"?e.organization:e.project)))throw new h("X.509 workload identity cannot override its enrolled organization or project.");if(Vo(s)||s==="host")throw new h("X.509 workload identity cannot use caller-supplied authentication credentials.")}},H=function(){let e=a(this,de,"f").current();if(!e||e.owner!==this)throw new h("X.509 workload identity requires an active certificate request scope.");return e},ba=function(e){if(yn(e,"OpenAI-Organization")!==a(this,bt,"f")||yn(e,"OpenAI-Project")!==a(this,At,"f"))throw new h("X.509 workload identity cannot override its enrolled organization or project.");for(let t of Headers.prototype.keys.call(e)){let n=t.toLowerCase().split("_").join("-");if((n==="openai-organization"||n==="openai-project")&&t!==n)throw new h("X.509 workload identity cannot override its enrolled organization or project.")}};function Cu(r){let{credential:e}=r;if(e===void 0)return{credential:e,options:r};let t=wu(e);if(!t)throw new h("An X.509 credential must be created by the SDK authentication helper.");let n=["apiKey","adminAPIKey","workloadIdentity","x509Transport"].filter(s=>{let o=r[s];return o!=null});if(n.length>0)throw new h(`The \`credential\` option cannot be combined with ${n.map(s=>`\`${s}\``).join(", ")}.`);return{credential:e,options:{...r,apiKey:null,adminAPIKey:null,baseURL:r.baseURL??null,organization:r.organization??null,project:r.project??null,workloadIdentity:t.identity,x509Transport:t.transport}}}function Pf({apiKey:r,adminAPIKey:e}){return r!=null||e!=null}function xf(r,e){let t=r.provider,n=e.credential??e.workloadIdentity,s=e.provider??(n?void 0:t);return s!==t&&(delete r.baseURL,delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions,delete r.fetch),s&&(delete r.apiKey,delete r.adminAPIKey,delete r.credential,delete r.workloadIdentity,delete r.x509Transport,delete r.baseURL),s}function Tu(r,e,t,n){let s=$(e,"workloadIdentity")?e.workloadIdentity:r.workloadIdentity,o=t!==void 0&&(Pf(e)&&e.workloadIdentity===void 0||e.provider!==void 0);t!==void 0&&$(e,"workloadIdentity")&&delete r.x509Transport;let i=t!==void 0&&!o&&e.credential===void 0&&!$(e,"workloadIdentity")&&!$(e,"x509Transport")?t:void 0,c=e.credential===void 0?i:e.credential,u=c!==void 0||!o&&oi(s);return n!==u&&(delete r.fetch,delete r.baseURL,delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions,u?r.apiKey=null:(delete r.x509Transport,o&&delete r.workloadIdentity)),c!==void 0&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.x509Transport,r.credential=c,e.credential!==void 0&&(delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions)),{credential:c,provider:xf(r,e)}}var ju=Symbol("brand.privateStreamingFile");function ai(r,e,t){if(typeof e!="string"||!e)throw new TypeError("toStreamingFile requires a non-empty file name");let n=t?.type;return n&&Nu(n),{[ju]:!0,data:r,name:e,...n?{type:n}:{}}}var Ra=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&Number.parseInt(r.versions.node.split("."),10)<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function wt(r,e,t){return Ra(),new File(r,e??"unknown_file",t)}function vr(r,e){if(typeof r!="object"||r===null)return;let t="name"in r?r.name:void 0,n=t&&String(t)||"filename"in r&&r.filename&&String(r.filename);if(n)return e?.stripFilename===!1?Lu(n):ao(n);let s="url"in r&&r.url&&String(r.url);if(s)try{return ao(new URL(s).pathname)}catch{return ao(s)}let o="path"in r&&r.path&&String(r.path);return o?ao(o):void 0}function ao(r){return r.split(/[\\/]/).pop()||void 0}function Lu(r){let e=r.replace(/\\/g,"/");if(e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.split("/").includes(".."))throw new TypeError("Upload file name must be a safe relative path without parent directory segments");return e}var Sf=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get;function va(r){try{return Sf?.call(r)!==void 0}catch{return!1}}var gn=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",qt=async(r,e,t)=>Pa(r.body)?ii(r.body)?Bu(r,t):{...r,body:await Mu(r.body,e,t)}:r,se=async(r,e,t)=>ii(r.body)?Bu(r,t):{...r,body:await Mu(r.body,e,t)},$u=new WeakMap;function Rf(r){let e=typeof r=="function"?r:r.fetch,t=$u.get(e);if(t)return t;let n=(async()=>{try{let s;if("Response"in e)s=e.Response;else{let i=await e("data:,");await i.arrayBuffer(),s=i.constructor}let o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return $u.set(e,n),n}var Mu=async(r,e,t={})=>{if(!await Rf(e))throw new 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(r||{}).map(([s,o])=>Sa(n,s,o,t))),n},ci=r=>r instanceof Blob,Oa=r=>typeof r=="object"&&r!==null&&"getReader"in r&&typeof r.getReader=="function",uo=r=>typeof r=="object"&&r!==null&&ju in r,ui=r=>typeof r=="object"&&r!==null&&(r instanceof Response||gn(r)||Oa(r)||uo(r)||ci(r)),ii=r=>{if(uo(r)||gn(r)||Oa(r))return!0;if(Array.isArray(r))return r.some(ii);if(r&&typeof r=="object"&&!ci(r)&&!(r instanceof Response)){for(let e of Object.keys(r))if(ii(r[e]))return!0}return!1},Pa=r=>{if(ui(r))return!0;if(Array.isArray(r))return r.some(Pa);if(r&&typeof r=="object"){for(let e of Object.keys(r))if(Pa(r[e]))return!0}return!1},vf=(r,e)=>{let t=[];for(let n of r)ui(n.value)&&!e.has(n.value)&&e.set(n.value,Du(n.value,{stripFilenames:!1})),t.push(n);return t},Bu=(r,e={})=>{let t=Ef(r.body),n=e.stripFilenames===!1?new WeakMap:void 0,s=n?vf(t,n):t,o=`openai-${Math.random().toString(36).slice(2)}`,i=Qs(Of(s,o,e,n));return{...r,body:i,headers:_([{"content-type":`multipart/form-data; boundary=${o}`},r.headers])}};async function*Of(r,e,t,n){for await(let{key:s,value:o}of r){if(ui(o)){let i=n?.get(o)??Du(o,t),c=kf(o);yield ye(`--${e}\r
|
|
9
|
-
`),yield ye(`Content-Disposition: form-data; name="${Ia(s)}"; filename="${Ia(i)}"\r
|
|
10
|
-
Content-Type: ${c}\r
|
|
11
|
-
\r
|
|
12
|
-
`),yield*co(Cf(o))}else yield ye(`--${e}\r
|
|
13
|
-
`),yield ye(`Content-Disposition: form-data; name="${Ia(s)}"\r
|
|
14
|
-
\r
|
|
15
|
-
${String(o)}`);yield ye(`\r
|
|
16
|
-
`)}yield ye(`--${e}--\r
|
|
17
|
-
`)}function*Ef(r){if(!(!r||typeof r!="object"))for(let[e,t]of Object.entries(r))yield*xa(e,t)}function*xa(r,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${r}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||ui(e))yield{key:r,value:e};else if(Array.isArray(e))for(let t of e)yield*xa(r+"[]",t);else if(typeof e=="object")for(let[t,n]of Object.entries(e))yield*xa(`${r}[${t}]`,n);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function Du(r,e){if(uo(r)){let{name:t}=r;if(typeof t!="string"||!t)throw new TypeError("Streaming upload file name must be a non-empty string");return e.stripFilenames===!1?Lu(t):ao(t)??"unknown_file"}return vr(r,{stripFilename:e.stripFilenames})??"unknown_file"}function kf(r){let e;return uo(r)||ci(r)?{type:e}=r:r instanceof Response&&(e=r.headers.get("content-type")??void 0),Nu(e||"application/octet-stream")}function Nu(r){if(typeof r!="string")throw new TypeError("Streaming upload content type must be a string");for(let e=0;e<r.length;e+=1){let t=r.codePointAt(e)??0;if(t<=31||t===127)throw new TypeError("Streaming upload content type must not contain control characters")}return r}function Cf(r){return uo(r)?r.data:r}async function*co(r){if(typeof r=="string")yield ye(r);else if(ArrayBuffer.isView(r))yield new Uint8Array(r.buffer,r.byteOffset,r.byteLength);else if(va(r))yield new Uint8Array(r);else if(r instanceof Response)yield*co(r.body||await r.blob());else if(r instanceof Blob)typeof r.stream=="function"?yield*co(r.stream()):yield new Uint8Array(await r.arrayBuffer());else if(Oa(r))for await(let e of zo(r))yield*co(e);else if(gn(r))for await(let e of r)yield*co(e);else throw new TypeError(`Invalid streaming file chunk: ${String(r)}`)}function Ia(r){return Array.from(r,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e==='"'||e==="\\"?encodeURIComponent(e):e}).join("")}var Sa=async(r,e,t,n)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response){let s=await t.blob();r.append(e,wt([s],vr(t,{stripFilename:n.stripFilenames}),{type:s.type}))}else if(gn(t))r.append(e,wt([await new Response(Qs(t)).blob()],vr(t,{stripFilename:n.stripFilenames})));else if(ci(t)){let s=vr(t,{stripFilename:n.stripFilenames});s===void 0?r.append(e,t):r.append(e,t,s)}else if(Array.isArray(t)){let s=await Promise.all(t.map(async o=>{let i=new FormData;return await Sa(i,e+"[]",o,n),i}));for(let o of s)if(o)for(let[i,c]of o.entries())r.append(i,c)}else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,o])=>Sa(r,`${e}[${s}]`,o,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Fu=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Tf=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Fu(r),$f=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",jf=(r,e)=>e?.type!=null&&e.type!==r.type||e?.lastModified!=null&&e.lastModified!==r.lastModified||e?.endings!=null,Lf=(r,e,t)=>(e==null||e===r.name)&&!jf(r,t);async function li(r,e,t){if(Ra(),r=await r,Tf(r)){let s={...t,type:t?.type??r.type,lastModified:t?.lastModified??r.lastModified};return r instanceof File?Lf(r,e,t)?r:wt([r],e??r.name,s):wt([await r.arrayBuffer()],e??r.name,s)}if($f(r)){let s=await r.blob();e??(e=vr(r));let o=t?.type===void 0&&s.type?{...t,type:s.type}:t;return wt(await Ea(s),e,o)}let n=await Ea(r);if(e??(e=vr(r)),t?.type===void 0){let s=n.find(o=>typeof o=="object"&&"type"in o&&!!o.type);s&&(t={...t,type:s.type})}return wt(n,e,t)}async function Ea(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||va(r))e.push(r);else if(Fu(r))e.push(r instanceof Blob?r:new Blob([await r.arrayBuffer()],{type:r.type}));else if(gn(r))for await(let t of r)e.push(...await Ea(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Mf(r)}`)}return e}function Mf(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var f=class{constructor(e){this._client=e}};function Uu(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Wu=Object.freeze(Object.create(null)),Df=(r=Uu)=>function(t,...n){if(t.length===1)return t[0];let s=!1,o=[],i="";for(let m=0;m<t.length;m+=1)if(m in t){let y=t[m];/[?#]/.test(y)&&(s=!0);let p=n[m],g=(s?encodeURIComponent:r)(""+p);m!==n.length&&(p==null||typeof p=="object"&&p.toString===Object.getPrototypeOf(Object.getPrototypeOf(p.hasOwnProperty??Wu)??Wu)?.toString)&&(g=p+"",o.push({start:i.length+y.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(p).slice(8,-1)} is not a valid path parameter`})),i+=y+(m===n.length?"":g)}let c=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=u.exec(c))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((m,y)=>m.start-y.start),o.length>0){let m=0,y="";for(let p of o){let g=" ".repeat(p.start-m),A="^".repeat(p.length);m=p.start+p.length,y+=g+A}throw new h(`Path parameters result in path with invalid segments:
|
|
18
|
-
${o.map(p=>p.error).join(`
|
|
19
|
-
`)}
|
|
20
|
-
${i}
|
|
21
|
-
${y}`)}return i},l=Df(Uu);var Or=class extends f{list(e,t={},n){return this._client.getAPIList(l`/chat/completions/${e}/messages`,R,{query:t,...n,__security:{bearerAuth:!0}})}};function ct(r){return r!==void 0&&"function"in r&&r.function!==void 0}function Ff(r){return r?.$brand==="auto-parseable-response-format"}function ut(r){return Ff(r)||r?.type==="json_schema"}function It(r,e){if(!ut(r))return null;if(typeof r=="object"&&r!==null&&"$parseRaw"in r&&typeof r.$parseRaw=="function")return r.$parseRaw(e);try{return JSON.parse(e)}catch(t){throw t instanceof SyntaxError?new SyntaxError("Error reading response: invalid structured output JSON."):t}}function Ve(r){return r?.$brand==="auto-parseable-tool"}function qu(r,e){return!e||!Ca(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:lo(r,e)}function lo(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new Ft;if(n.finish_reason==="content_filter")throw new Wt;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>Uf(e,s))??void 0}:void 0,parsed:n.message.content!==null&&n.message.content!==void 0&&!n.message.refusal&&(n.message.content!==""||!n.message.tool_calls?.length&&!n.message.function_call)?Wf(e,n.message.content):null}}});return{...r,choices:t}}function Wf(r,e){return It(r.response_format,e)}function Uf(r,e){if(e.type==="custom")return e;if(e.type!=="function"){let s=e.type;throw new h(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${s}\``)}let t=r.tools?.find(s=>ct(s)&&s.function?.name===e.function.name),n=null;return Ve(t)?n=t.$parseRaw(e.function.arguments):t?.function.strict&&(n=It({type:"json_schema",$parseRaw:void 0},e.function.arguments)),{...e,function:{...e.function,parsed_arguments:n}}}function di(r,e){if(!r||!("tools"in r)||!r.tools||e.type!=="function")return!1;let t=r.tools?.find(n=>ct(n)&&n.function?.name===e.function?.name);return ct(t)&&(Ve(t)||t?.function.strict||!1)}function Ca(r){return ut(r.response_format)?!0:r.tools?.some(e=>Ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function Ku(r){for(let e of r??[])if(e.type!=="custom"){if(e.type!=="function"){let t=e.type;throw new h(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${t}\``)}if(e.function.strict!==!0)throw new h(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Pt=r=>r?.role==="assistant",fo=r=>r?.role==="tool";var ke,hi,mi,yo,ho,_i,go,qe,bo,Ao,mo,bn,Kt,Er,gi,bi,An,kr,Ba,Yu,Da,Qu,Na,yi,Zu,zu=4096,_o=8*1024*1024,qf=4096,wo=256,Kf=JSON.stringify,zf=JSON.parse,Ta=new WeakSet,Xf=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,Hf=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,Jf=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,Xu=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,Vf=Date.prototype.getTime,Gf=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,Yf=typeof SharedArrayBuffer=="function"?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,po=Object.getOwnPropertyDescriptor(new Error("native stack descriptor"),"stack"),lt=Function.prototype.toString,Qf=Object.prototype.toString,fi=Object.getOwnPropertyDescriptor(Error,"isError"),Hu=fi&&"value"in fi&&typeof fi.value=="function"?fi.value:void 0,Zf=lt.call(Error),ep=lt.call(Date),tp=lt.call(Function),Ai=new Set([De.prototype,re.prototype,z.prototype,h.prototype,Y.prototype,$t.prototype,st.prototype,Mt.prototype,Wt.prototype,Nt.prototype,Oe.prototype,Ft.prototype,Lt.prototype,Ne.prototype,jt.prototype,Dt.prototype,gr.prototype,Bt.prototype]),el=new Set,tl=new Map,Ju=new WeakMap;function rp(){if(!(typeof process>"u"))try{let r=Object.getOwnPropertyDescriptor(process,"getBuiltinModule");if(!r||!("value"in r)||typeof r.value!="function")return;let e=Reflect.apply(r.value,process,["node:util"]);if(typeof e!="object"||e===null)return;let t=Object.getOwnPropertyDescriptor(e,"types");if(!t||!("value"in t)||typeof t.value!="object"||t.value===null)return;let n=Object.getOwnPropertyDescriptor(t.value,"isProxy");return!n||!("value"in n)||typeof n.value!="function"?void 0:n.value}catch{return}}var np=rp();function wi(r){if(typeof r!="function")return;let e=Object.getOwnPropertyDescriptor(r,"prototype");if(!e||!("value"in e)||typeof e.value!="object"&&typeof e.value!="function")return;Ai.add(e.value);let t=lt.call(r);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(t)&&e.configurable===!1&&e.writable===!1){el.add(t);let n=new Map;for(let s of Reflect.ownKeys(e.value)){let o=Object.getOwnPropertyDescriptor(e.value,s);o&&n.set(s,o)}tl.set(t,n)}}for(let r of[Object,Function,Array,Date,Map,Set,ArrayBuffer,DataView,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array])wi(r);for(let r of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){let e=Object.getOwnPropertyDescriptor(globalThis,r);e&&"value"in e&&wi(e.value)}var $a=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");$a&&"value"in $a&&wi($a.value);typeof Buffer=="function"&&wi(Buffer);var sp=(()=>{if(typeof Blob=="function")try{let r=new Blob([]);for(let e of Object.getOwnPropertySymbols(r)){let t=Object.getOwnPropertyDescriptor(r,e);if(t&&"value"in t&&typeof t.value=="object"&&t.value)return Object.getPrototypeOf(t.value)}}catch{return}})(),op=Map.prototype.entries,ip=Set.prototype.values,pi=typeof Headers=="function"?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,Vu=pi&&"value"in pi&&typeof pi.value=="function"?pi.value:void 0,ap=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);function Ii(r){let e=Object.getOwnPropertyDescriptor(r,"constructor");if(!e||!("value"in e)||typeof e.value!="function")return;let t=e.value,n=lt.call(t),s=tl.get(n);if(!el.has(n)||!s)return;let o=Object.getOwnPropertyDescriptor(t,"prototype");if(!(!o||!("value"in o)||o.value!==r||o.configurable!==!1||o.writable!==!1))return{constructor:t,descriptors:s,functionPrototype:Object.getPrototypeOf(t)}}function cp(r){return Ai.has(r)||Ii(r)!==void 0}function ja(r,e,t){if(e===void 0)return r===void 0;if(typeof r!="function"||typeof e!="function")return!1;let n=lt.call(e);if(lt.call(r)!==n)return!1;let s=Object.getPrototypeOf(r);if(s===t)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n))return!1;let o=Ii(s);return o!==void 0&<.call(o.constructor)===tp}function up(r,e,t){return!e||r.configurable!==e.configurable||r.enumerable!==e.enumerable||"value"in r!="value"in e?!1:"value"in r&&"value"in e?r.writable!==e.writable?!1:typeof e.value=="function"?ja(r.value,e.value,t):e.value!==null&&typeof e.value=="object"?!1:Object.is(r.value,e.value):ja(r.get,e.get,t)&&ja(r.set,e.set,t)}function Gu(r){if(Hu)return Hu.call(Error,r);let e=r;for(let t=0;e!==null&&t<wo;t+=1){if(Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))return!1;e=Object.getPrototypeOf(e)}return e===null&&Qf.call(r)==="[object Error]"}function lp(r,e){if(typeof e.get!="function"||typeof e.set!="function")return;let t=Object.getPrototypeOf(r);for(let n=0;t!==null&&n<wo;n+=1){let s=Object.getOwnPropertyDescriptor(t,"constructor");if(s&&"value"in s&&typeof s.value=="function"){let o=s.value;if(lt.call(o)===Zf&&cp(t)){let i=Object.getPrototypeOf(o);return Object.getPrototypeOf(e.get)===i&&Object.getPrototypeOf(e.set)===i?{constructor:o,prototype:t}:void 0}}t=Object.getPrototypeOf(t)}}function dp(r,e){if(!Gu(r))return!1;if(po&&!("value"in po)&&typeof po.get=="function"&&Object.prototype.isPrototypeOf.call(Error.prototype,r)&&e.get===po.get&&e.set===po.set)return!0;let t=lp(r,e);if(!t)return!1;let n=Ju.get(t.prototype);if(!n){let s=Reflect.construct(t.constructor,[]);if(typeof s!="object"||s===null||!Gu(s)||Object.getPrototypeOf(s)!==t.prototype||(n=Object.getOwnPropertyDescriptor(s,"stack"),!n||"value"in n||typeof n.get!="function"||typeof n.set!="function"))return!1;Ju.set(t.prototype,n)}return e.get===n.get&&e.set===n.set}function La(){let r=[],e=0;return{get length(){return r.length-e},enqueue(t){r.push(t)},dequeue(){if(e===r.length)return;let t=r[e];return r[e]=void 0,e+=1,e===r.length?(r=[],e=0):e>=1024&&e*2>=r.length&&(r=r.slice(e),e=0),t},clear(){r=[],e=0}}}function fp(r){let e=Object.getPrototypeOf(r);for(let t=0;e!==null&&t<wo;t+=1){if(e===Date.prototype)return"Date";if(!Ai.has(e)){let s=Object.getOwnPropertyDescriptor(e,"constructor");if(s&&"value"in s&&typeof s.value=="function"&<.call(s.value)===ep&&Ii(e))return"Date"}let n=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);if(n&&"value"in n&&typeof n.value=="string"&&ap.has(n.value))return n.value;e=Object.getPrototypeOf(e)}}function pp(r,e,t){if(ArrayBuffer.isView(r)){let c,u="typed-array";try{c=Xf?.call(r)}catch{u="data-view",c=Jf?.call(r)}return typeof c!="object"||c===null?{bytes:Number.POSITIVE_INFINITY,kind:u}:(e(c,t+1),{bytes:0,kind:u})}let n=fp(r);if(!n)return;let s,o="buffer";switch(n){case"ArrayBuffer":{s=Gf;break}case"SharedArrayBuffer":{s=Yf;break}case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(Vf,r,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}let i=s?.call(r);return{bytes:typeof i=="number"&&Number.isSafeInteger(i)&&i>=0?i:Number.POSITIVE_INFINITY,kind:o}}function hp(r,e,t){if(e==="map"){for(let[n,s]of op.call(r))if(!t(n,8)||!t(s,8))return!1}if(e==="set"){for(let n of ip.call(r))if(!t(n,8))return!1}if(e==="headers"){if(!Vu)return!1;for(let[n,s]of Vu.call(r))if(!t(n,8)||!t(s,8))return!1}return!0}function mp(r,e,t){if(Array.isArray(r)){let s=Object.getOwnPropertyDescriptor(r,"length"),o=s&&"value"in s?s.value:void 0;if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>Math.floor(t/16))return}if(e!=="typed-array")return Reflect.ownKeys(r);let n=Hf?.call(r);if(!(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>qf))return Reflect.ownKeys(r).filter(s=>{if(typeof s!="string")return!0;let o=Number(s);return!Number.isInteger(o)||o<0||o>=n||String(o)!==s})}function rl(r,e,t,n,s,o){let i=mp(r,e,n());if(i===void 0)return!1;for(let c of i){if(!s(typeof c=="string"?c.length*2+8:8))return!1;typeof c=="symbol"&&o(c,t+1);let u=Object.getOwnPropertyDescriptor(r,c);if(!u)return!1;if(!("value"in u)){if(c==="stack"&&dp(r,u))continue;return!1}o(u.value,t+1,e==="blob")}return!0}function _p(r,e,t,n,s,o,i,c){let u=Object.getPrototypeOf(r);for(let d=e+1;u!==null;d+=1){if(d>=wo)return!1;if(Ai.has(u)||t&&u===sp)return!0;if(n.has(u))return i(u,d),s()>=0;n.add(u);let m=u;if(!c(m,()=>{if(!o(16))return!1;let p=Ii(m);if(!p)return rl(m,void 0,d,s,o,i);for(let g of Reflect.ownKeys(m)){let A=Object.getOwnPropertyDescriptor(m,g);if(!A)return!1;if(!up(A,p.descriptors.get(g),p.functionPrototype)){if(!o(typeof g=="string"?g.length*2+8:8)||!("value"in A))return!1;typeof g=="symbol"&&i(g,d+1),i(A.value,d+1)}}return s()>=0}))return!1;u=Object.getPrototypeOf(m)}return!0}var yp=32,gp=32,nl=8,sl=16,bp=128*1024;function Ma(r,e){let t=0,n=0,s=new WeakSet,o=new Set,i=new Set,c=new Map,u,d=()=>e-t,m=w=>!Number.isSafeInteger(w)||w<0?(t=e+1,!1):(t+=w,u?u.bytes+=w:n+=w,t<=e),y=w=>{u?u.edges.add(w):i.add(w)},p=(w,S)=>{y(w);let E={bytes:0,edges:new Set};c.set(w,E);let P=u;u=E;try{return S()}finally{u=P}},g=w=>{if(o.has(w)){y(w),m(8);return}o.add(w),p(w,()=>{if(!Xu)return!1;let S=Reflect.apply(Xu,w,[]);return m(8+(S?.length??0)*2)})||(t=e+1)},A=(w,S,E=!1)=>{if(!(t>e)){if(typeof w=="string"){m(w.length*2);return}if(typeof w=="symbol"){g(w);return}if(typeof w=="function"){t=e+1;return}if(w===null||typeof w!="object"){m(8);return}if(np?.(w)){t=e+1;return}if(S>=wo){t=e+1;return}if(s.has(w)){y(w),m(8);return}s.add(w),p(w,()=>{if(!m(16))return!1;let P=pp(w,A,S);return!_p(w,S,E,s,d,m,A,p)||P!==void 0&&!m(P.bytes)||!hp(w,P?.kind,(L,I)=>m(I)?(A(L,S+1),t<=e):!1)?!1:rl(w,P?.kind,S,d,m,A)})||(t=e+1)}};try{A(r,0)}catch{return}return t<=e?{scalarBytes:n,roots:i,nodes:c}:void 0}function Ap(r,e){if(r.size!==e.size)return!1;for(let t of r)if(!e.has(t))return!1;return!0}function Fa(r,e){return r.bytes+gp+r.edges.size*nl+e*sl}function Wa(r){return yp+r.scalarBytes+r.roots.size*nl}function wp(r,e,t,n){let s=new Set,o=[...r];for(;o.length;){if(n.remaining-=1,n.remaining<0)return;let i=o.pop();if(s.has(i))continue;let c=e.get(i)??t.get(i);if(!c)return;s.add(i);for(let u of c.edges)o.push(u)}return s}function Ua(r,e,t,n,s){let o=n.get(r);if(o)return s&&(o.node=s),o;let i=s??e.nodes.get(r)??t.get(r);if(!i)return;let c={node:i,ownerDelta:0};return n.set(r,c),c}function Ip(r,e,t,n,s){let o=new Set([r]);for(let[i,c]of e.nodes){if(s.remaining-=1,s.remaining<0)return;let u=t.get(i);if(!u)continue;let d=!Ap(u.edges,c.edges);if((u.bytes!==c.bytes||d)&&Ua(i,e,t,n,c),!!d)for(let m of u.owners){if(s.remaining-=1,s.remaining<0)return;o.add(m)}}return o}function Pp(r,e,t,n,s,o){for(let i of r.identities){if(o.remaining-=1,o.remaining<0)return!1;if(!e.has(i)){let c=Ua(i,t,n,s);if(!c)return!1;c.ownerDelta-=1}}for(let i of e){if(o.remaining-=1,o.remaining<0)return!1;if(!r.identities.has(i)){let c=Ua(i,t,n,s);if(!c)return!1;c.ownerDelta+=1}}return!0}function xp(r,e,t,n,s,o){let i=new Map;for(let c of t){let u=c===r?e.roots:c.roots,d=wp(u,e.nodes,n,o);if(!d||!Pp(c,d,e,n,s,o))return;i.set(c,d)}return i}function Sp(r,e,t,n,s,o){let i=r-(n?0:Wa(e))+Wa(t);for(let[c,u]of s){let d=o.get(c),m=(d?.owners.size??0)+u.ownerDelta;if(m<0)return;d&&(i-=Fa(d,d.owners.size)),m&&(i+=Fa(u.node,m))}return Number.isSafeInteger(i)&&i>=0&&i<=_o?i:void 0}function Rp(r,e,t){for(let[n,s]of e){let o=r.get(n);(o?.owners.size??0)+s.ownerDelta&&(o?(o.bytes=s.node.bytes,o.edges=s.node.edges):r.set(n,{bytes:s.node.bytes,edges:s.node.edges,owners:new Set}))}for(let[n,s]of t){for(let o of n.identities)s.has(o)||r.get(o)?.owners.delete(n);for(let o of s)n.identities.has(o)||r.get(o).owners.add(n);n.identities=s}for(let n of e.keys())r.get(n)?.owners.size===0&&r.delete(n)}function vp(){let r=new Map,e=0,t=(s,o,i)=>{let c={remaining:bp},u=new Map,d=Ip(s,o,r,u,c);if(!d)return!1;let m=xp(s,o,d,r,u,c);if(!m)return!1;let y=Sp(e,s,o,i,u,r);return y===void 0?!1:(Rp(r,u,m),s.scalarBytes=o.scalarBytes,s.roots=o.roots,e=y,!0)};return{retain(s){let o={scalarBytes:0,roots:new Set,identities:new Set};return t(o,s,!0)?o:void 0},refresh(s,o){return t(s,o,!1)},release:s=>{e-=Wa(s);for(let o of s.identities){let i=r.get(o);i?.owners.delete(s)&&(e-=sl,i.owners.size===0&&(e-=Fa(i,0),r.delete(o)))}s.identities.clear()},clear(){r.clear(),e=0}}}var zt=class{constructor(){ke.add(this),this.controller=new AbortController,hi.set(this,void 0),mi.set(this,()=>{}),yo.set(this,()=>{}),ho.set(this,void 0),_i.set(this,()=>{}),go.set(this,()=>{}),qe.set(this,Object.create(null)),bo.set(this,[]),Ao.set(this,new WeakMap),mo.set(this,new Set),bn.set(this,new Set),Kt.set(this,0),Er.set(this,!1),gi.set(this,!1),bi.set(this,!1),An.set(this,!1),kr.set(this,void 0),b(this,hi,new Promise((e,t)=>{b(this,mi,e,"f"),b(this,yo,t,"f")}),"f"),b(this,ho,new Promise((e,t)=>{b(this,_i,e,"f"),b(this,go,t,"f")}),"f"),a(this,hi,"f").catch(()=>{}),a(this,ho,"f").catch(()=>{})}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(n=>{t=!0,a(this,ke,"m",yi).call(this,n)}).then(()=>{if(!t){try{this._emitFinal()}catch(n){a(this,ke,"m",yi).call(this,n);return}this._emit("end")}})},0)}_connected(){this.ended||(a(this,mi,"f").call(this),this._emit("connect"))}get ended(){return a(this,Er,"f")}get errored(){return a(this,gi,"f")}get aborted(){return a(this,bi,"f")}abort(){this.controller.abort()}_userAbortError(){let e=new Y;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){a(this,ke,"m",Ba).call(this,e);return}if(a(this,bo,"f").some(n=>n.signal===e))return;let t=()=>a(this,ke,"m",Ba).call(this,e);e.addEventListener("abort",t,{once:!0}),a(this,bo,"f").push({signal:e,listener:t})}on(e,t){var n;return((n=a(this,qe,"f"))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=a(this,qe,"f")[e];if(!n)return this;let s=a(this,Ao,"f").get(t);if(s?.event===e&&!s.registration.removed&&!s.registration.detached)return a(this,ke,"m",Qu).call(this,e,s.registration),this;let o=n.findIndex(i=>!i.removed&&i.listener===t);return o!==-1&&n.splice(o,1),this}once(e,t){var n;return((n=a(this,qe,"f"))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{b(this,An,!0,"f");let s=i=>{this.off(e,o),n(i)},o=(...i)=>{e!=="error"&&this.off("error",s),t(i.length>1?i:i[0])};e!=="error"&&a(this,ke,"m",Da).call(this,"error",s),a(this,ke,"m",Da).call(this,e,o)})}events(e){return this._createIterator(t=>{let n=(...s)=>{Ta.add(s);try{t(s)}finally{Ta.delete(s)}};return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!=="error",rejectOnAbort:e!=="abort"})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:n=!0,onReturn:s}={}){let o=La(),i=La(),c=La(),u=vp(),d=this.ended,m,y=!1,p=()=>{},g=()=>({value:void 0,done:!0}),A=()=>{for(;c.length;)c.dequeue().resolve(g())},w=()=>{!m||y||!c.length||(y=!0,c.dequeue().reject(m))},S=()=>{p(),this.off("end",M),t&&this.off("error",T),n&&this.off("abort",T)},E=k=>{k.active=!1,k.check&&(a(this,bn,"f").delete(k.check),k.check=void 0)},P=(k=!1)=>{if(k){for(;i.length;)E(i.dequeue());o.clear(),u.clear()}let O=new h(`Event stream iterator buffer limit exceeded (${zu} events or ${_o} bytes); consume events as they arrive.`);try{a(this,ke,"m",yi).call(this,O)}finally{this.controller.abort()}return O},L=(k,O)=>{if(!O.active||a(this,Er,"f"))return;let v=Ma(k,_o);(!v||!u.refresh(O.retention,v))&&P(!0)},I=k=>{if(d)return;let O=c.dequeue();if(O)O.resolve({value:k,done:!1});else{if(o.length>=zu){P();return}let v=Ma(k,_o),K=v&&u.retain(v);if(!K){P();return}if(typeof k=="object"&&k!==null&&Ta.has(k)){let q=k;for(let ge=0;ge<q.length;ge+=1){let W=q[ge];typeof W=="string"&&(q[ge]=zf(Kf(W)))}}let D={retention:K,active:!0,check:void 0};o.enqueue(k),i.enqueue(D);let N=()=>{D.check=void 0,L(k,D)};D.check=N,a(this,bn,"f").add(N)}},T=k=>{m=k,o.length||w()},x=()=>{if(m)return;let k=a(this,kr,"f");k&&(k.kind==="error"?t:n)&&(m=k.error)},M=()=>{d=!0,x(),S(),o.length||(w(),A())};return d||(p=e(I),this.on("end",M),t&&this.on("error",T),n&&this.on("abort",T)),{next:()=>{if(o.length){let k=o.dequeue(),O=i.dequeue();E(O);let v=Ma(k,_o);if(!v||!u.refresh(O.retention,v)){let K=P(!0);return y=!0,Promise.reject(K)}return u.release(O.retention),Promise.resolve({value:k,done:!1})}return(d||this.ended)&&x(),m&&!y?(y=!0,Promise.reject(m)):d?Promise.resolve(g()):new Promise((k,O)=>{c.enqueue({resolve:k,reject:O})})},return:()=>{for(d=!0,y=!0;i.length;)E(i.dequeue());return o.clear(),u.clear(),S(),A(),s&&(this.done().catch(()=>{}),s()),Promise.resolve(g())},[Symbol.asyncIterator](){return this}}}async done(){b(this,An,!0,"f"),await a(this,ho,"f")}_hasListeners(e){return!!a(this,qe,"f")[e]?.some(t=>!t.removed)}_emit(e,...t){if(a(this,Er,"f"))return;e==="end"&&(a(this,ke,"m",Yu).call(this),b(this,Er,!0,"f"),a(this,_i,"f").call(this));let n=a(this,qe,"f")[e],s,o=!1;try{if(n){a(this,qe,"f")[e]=n.filter(i=>(i.once&&(i.detached=!0),!i.once&&!i.removed)),b(this,Kt,a(this,Kt,"f")+1,"f");try{for(let i of n)if(!i.removed){let{listener:c}=i;c(...t)}}finally{if(b(this,Kt,a(this,Kt,"f")-1,"f"),a(this,Kt,"f")===0){a(this,ke,"m",Na).call(this);for(let i of a(this,bn,"f"))a(this,bn,"f").delete(i),a(this,Er,"f")||i()}}}}catch(i){s=i,o=!0}try{a(this,ke,"m",Zu).call(this,e,t,!!n?.length)}catch(i){o||(s=i,o=!0)}if(o)throw s}_emitFinal(){}};hi=new WeakMap,mi=new WeakMap,yo=new WeakMap,ho=new WeakMap,_i=new WeakMap,go=new WeakMap,qe=new WeakMap,bo=new WeakMap,Ao=new WeakMap,mo=new WeakMap,bn=new WeakMap,Kt=new WeakMap,Er=new WeakMap,gi=new WeakMap,bi=new WeakMap,An=new WeakMap,kr=new WeakMap,ke=new WeakSet,Ba=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},Yu=function(){for(let{signal:e,listener:t}of a(this,bo,"f").splice(0))e.removeEventListener("abort",t)},Da=function(e,t){let n=a(this,qe,"f")[e],s=n?.length??0;this.once(e,t);let o=a(this,qe,"f")[e],[i]=o?.slice(-1)??[];(n===void 0||o===n)&&o?.length===s+1&&i?.listener===t&&i.once&&a(this,Ao,"f").set(t,{event:e,registration:i})},Qu=function(e,t){t.removed||(t.removed=!0,a(this,Ao,"f").delete(t.listener),a(this,mo,"f").add(e),a(this,Kt,"f")===0&&a(this,ke,"m",Na).call(this))},Na=function(){for(let e of a(this,mo,"f")){let t=e,n=a(this,qe,"f")[t];n&&(a(this,qe,"f")[t]=n.filter(s=>!s.removed))}a(this,mo,"f").clear()},yi=function(e){if(b(this,gi,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=this._userAbortError()),e instanceof Y)return b(this,bi,!0,"f"),this._emit("abort",e);if(e instanceof h)return this._emit("error",e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new h(String(e)))},Zu=function(e,t,n){if(e==="abort"){let s=t[0];b(this,kr,a(this,kr,"f")??{kind:"abort",error:s},"f"),!a(this,An,"f")&&!n&&Promise.reject(s),a(this,yo,"f").call(this,s),a(this,go,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];b(this,kr,a(this,kr,"f")??{kind:"error",error:s},"f"),!a(this,An,"f")&&!n&&Promise.reject(s),a(this,yo,"f").call(this,s),a(this,go,"f").call(this,s),this._emit("end")}};function ol(r){return typeof r.parse=="function"}var Pe,Cr,Pi,xi,qa,Si,Ka,za,Xa,Ha,il,al,Op=10;function Ep(r){for(let e of r.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${Je()}`)}function kp(r){if(!Pt(r))return r;let e={role:"assistant"};return r.audio!=null&&(e.audio={id:r.audio.id}),r.content!==void 0&&(e.content=r.content),r.function_call!=null&&(e.function_call=r.function_call),r.name!==void 0&&(e.name=r.name),r.refusal!=null&&(e.refusal=r.refusal),r.tool_calls!==void 0&&(e.tool_calls=r.tool_calls.map(t=>t.type==="custom"?{id:t.id,type:t.type,custom:{input:t.custom.input,name:t.custom.name}}:{id:t.id,type:t.type,function:{arguments:t.function.arguments,name:t.function.name}})),e}var Tr=class extends zt{constructor(){super(...arguments),Pe.add(this),this._chatCompletions=[],Pi.set(this,!1),xi.set(this,!1),this.messages=[]}_addChatCompletion(e){b(this,Pi,!this.controller.signal.aborted,"f"),Ep(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,n=!0){if(n&&!("content"in e)&&(e.content=null),this.messages.push(e),t){if(this._emit("message",e),fo(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Pt(e)&&e.tool_calls)for(let s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new h("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),a(this,Pe,"m",qa).call(this)}async finalMessage(){return await this.done(),a(this,Pe,"m",Si).call(this)}async finalFunctionToolCall(){return await this.done(),a(this,Pe,"m",Ka).call(this)}async finalFunctionToolCallResult(){return await this.done(),a(this,Pe,"m",za).call(this)}async totalUsage(){return await this.done(),a(this,Pe,"m",Xa).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){a(this,xi,"f")&&a(this,Pe,"m",Ha).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=a(this,Pe,"m",Si).call(this);t&&this._emit("finalMessage",t);let n=a(this,Pe,"m",qa).call(this);n&&this._emit("finalContent",n);let s=a(this,Pe,"m",Ka).call(this);s&&this._emit("finalFunctionToolCall",s);let o=a(this,Pe,"m",za).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",a(this,Pe,"m",Xa).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),a(Cr,Cr,"m",il).call(Cr,t);let s=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(lo(s,t))}async _runChatCompletion(e,t,n){for(let s of t.messages)this._addMessage(s,!1,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,s){let o="tool",{tool_choice:i="auto",stream:c,toolContext:u,...d}=t,m=u,y=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:p=Op,afterCompletion:g}=s||{},A=async I=>{g!=null&&(b(this,xi,!0,"f"),await g(I,n),a(this,Pe,"m",Ha).call(this))},w=t.tools.map(I=>{if(Ve(I)){if(!I.$callback)throw new h("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:I.$callback,name:I.function.name,description:I.function.description||"",parameters:I.function.parameters,parse:I.$parseRaw,strict:!0}}}return I}),S=Object.create(null);for(let I of w)I.type==="function"&&(S[I.function.name||I.function.function.name]=I.function);let E="tools"in t?w.map(I=>I.type==="function"?{type:"function",function:{name:I.function.name||I.function.function.name,parameters:I.function.parameters,description:I.function.description,strict:I.function.strict}}:I):void 0;for(let I of t.messages)this._addMessage(I,!1,!1);let P=!1,L=async I=>{let T=P;if(P=!1,I.type!=="function")return{message:void 0,functionCalled:!1};let x=I.id,{name:M,arguments:k}=I.function,O=S[M];if(!O){let D=`Invalid tool_call: ${JSON.stringify(M)}. Available options are: ${Object.keys(S).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:x,content:D},functionCalled:!1}}if(y&&y!==M){let D=`Invalid tool_call: ${JSON.stringify(M)}. ${JSON.stringify(y)} requested. Please try again`;return{message:{role:o,tool_call_id:x,content:D},functionCalled:!1}}let v;if(ol(O)){let D;try{D=await O.parse(k)}catch(N){if(this.controller.signal.aborted)throw this._userAbortError();let q=N instanceof Error?N.message:String(N);return{message:{role:o,tool_call_id:x,content:q},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{v=await O.function(D,n,m)}catch(N){throw this.controller.signal.aborted&&Object.is(N,this.controller.signal.reason)?this._userAbortError():N}}else{if(this.controller.signal.aborted&&!T)throw this._userAbortError();try{v=await O.function(k,n,m)}catch(D){throw this.controller.signal.aborted&&Object.is(D,this.controller.signal.reason)?this._userAbortError():D}}let K=a(Cr,Cr,"m",al).call(Cr,v);return{message:{role:o,tool_call_id:x,content:K},functionCalled:!0}};for(let I=0;I<p;++I){let T=await this._createChatCompletion(e,{...d,tool_choice:i,tools:E,messages:this.messages.map(kp)},s);P=this.controller.signal.aborted&&a(this,Pi,"f");let x=T.choices[0]?.message;if(!x)throw new h("missing message in ChatCompletion response");if(!x.tool_calls?.length){await A(T);return}if(y||t.parallel_tool_calls===!1)for(let M of x.tool_calls){let k=await L(M);if(k.message&&this._addMessage(k.message),this.controller.signal.aborted)throw this._userAbortError();if(y&&k.functionCalled){await A(T);return}}else{let M=await Promise.allSettled(x.tool_calls.map(L));if(!this.controller.signal.aborted){for(let k of M)if(k.status==="rejected")throw k.reason}for(let k of M)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await A(T)}}};Cr=Tr,Pi=new WeakMap,xi=new WeakMap,Pe=new WeakSet,qa=function(){return a(this,Pe,"m",Si).call(this).content??null},Si=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Pt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new h("stream ended without producing a ChatCompletionMessage with role=assistant")},Ka=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Pt(t)&&t?.tool_calls?.length)for(let n=t.tool_calls.length-1;n>=0;n--){let s=t.tool_calls[n];if(s?.type==="function")return s.function}}},za=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(fo(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},Xa=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},Ha=function(){if(this.controller.signal.aborted)throw this._userAbortError()},il=function(e){if(e.n!=null&&e.n>1)throw new h("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},al=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Io=class r extends Tr{static runTools(e,t,n){let s=new r,o={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,o)),s}_addMessage(e,t=!0,n=!0){super._addMessage(e,t,n),t&&Pt(e)&&e.content&&this._emit("content",e.content)}};var fe={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},Ja=class extends Error{},Po=class extends Error{};function Cp(r,e=fe.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Tp(r.trim(),e)}var Tp=(r,e)=>{let t=r.length,n=0,s=p=>{throw new Ja(`${p} at position ${n}`)},o=p=>{throw new Po(`${p} at position ${n}`)},i=()=>(y(),n>=t&&s("Unexpected end of input"),r[n]==='"'?c():r[n]==="{"?u():r[n]==="["?d():r.substring(n,n+4)==="null"||fe.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||fe.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||fe.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||fe.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||fe.MINUS_INFINITY&e&&t-n>1&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||fe.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,Number.NaN):m()),c=()=>{let p=n,g=!1;for(n++;n<t&&(r[n]!=='"'||g&&r[n-1]==="\\");)g=r[n]==="\\"?!g:!1,n++;if(r.charAt(n)==='"')try{return JSON.parse(r.substring(p,++n-Number(g)))}catch(A){o(String(A))}else if(fe.STR&e)try{return JSON.parse(r.substring(p,n-Number(g))+'"')}catch{return JSON.parse(r.substring(p,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,y();let p={};try{for(;r[n]!=="}";){if(y(),n>=t&&fe.OBJ&e)return p;let g=c();y(),n++;try{let A=i();Object.defineProperty(p,g,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(fe.OBJ&e)return p;throw A}y(),r[n]===","&&n++}}catch{if(fe.OBJ&e)return p;s("Expected '}' at end of object")}return n++,p},d=()=>{n++;let p=[];try{for(;r[n]!=="]";)p.push(i()),y(),r[n]===","&&n++}catch{if(fe.ARR&e)return p;s("Expected ']' at end of array")}return n++,p},m=()=>{if(n===0){r==="-"&&fe.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(A){if(fe.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(A))}}let p=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n===t&&!(fe.NUM&e)&&s("Unterminated number literal");let g=r.substring(p,n);try{return JSON.parse(g)}catch{g==="-"&&fe.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(g.substring(0,g.lastIndexOf("e")))}catch(A){o(String(A))}}},y=()=>{for(;n<t&&`
|
|
22
|
-
\r `.includes(r[n]);)n++};return i()},cl=r=>Cp(r,fe.ALL^fe.NUM);var J,oe,Ri,Xt,$r,xe,Ke,$e,Va,wn,Ga,Ya,Qa,In,xo,ul;function ll(r){try{return cl(r)}catch(e){if(e instanceof Po||e instanceof SyntaxError)return It({type:"json_schema",$parseRaw:void 0},r);throw e}}var uc="chat.completion.chunk.message:";function _l(r,e,t){let n={type:"message",message:e,...t?{tool_call_ids:t}:{}};return{id:r.id,choices:[],created:r.created,model:r.model,object:`${uc}${JSON.stringify(n)}`}}function $p(r){return"type"in r&&r.type==="message"&&"message"in r||"object"in r&&typeof r.object=="string"&&r.object.startsWith(uc)}function jp(r){return"type"in r?r:JSON.parse(r.object.slice(uc.length))}var vi=128,Ht=128,Lp=16*1024*1024,Mp=65536,lc=128,yl=64*1024*1024,dl=1024;function oc(){return{bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1}}function ic(r,e,t,n){if(e.fragments>=Mp)throw new h("Chat completion stream exceeded its structured JSON fragment limit");let s=0,{depth:o,escaped:i,has_non_whitespace:c,in_string:u}=r,d=!1,m=!0;for(let p of t){let g=s,A=p.codePointAt(0);if(m&&r.pending_high_surrogate&&A>=56320&&A<=57343||A<=127?s+=1:A<=2047?s+=2:A<=65535?s+=3:s+=4,m=!1,e.bytes+s>Lp)throw new h("Chat completion stream exceeded its structured JSON byte limit");if(n&&n.work+s>yl)throw n.work+=g,new h("Chat completion stream exceeded its structured JSON parse-work limit");if(p!==" "&&p!==`
|
|
23
|
-
`&&p!=="\r"&&p!==" "&&(c=!0),u){i?i=!1:p==="\\"?i=!0:p==='"'&&(u=!1,d||(d=o===0));continue}if(p==='"')u=!0;else if(p==="{"||p==="["){if(o+=1,o>lc)throw new h("Chat completion stream exceeded its structured JSON nesting depth limit")}else(p==="}"||p==="]")&&o>0&&(o-=1,d||(d=o===0))}if(r.bytes+=s,r.fragments+=1,r.depth=o,r.escaped=i,r.has_non_whitespace=c,r.in_string=u,t.length>0){let p=t.codePointAt(t.length-1)??0;r.pending_high_surrogate=p>=55296&&p<=56319}if(e.bytes+=s,e.fragments+=1,n&&(n.work+=s),!c||s===0)return!1;let y=Math.max(dl,Math.floor(r.last_parsed_bytes/2));return!(r.bytes>dl&&!d&&r.bytes-r.last_parsed_bytes<y)}function ac(r,e){return e.work+r.bytes>yl?!1:(e.work+=r.bytes,r.work+=r.bytes,r.last_parsed_bytes=r.bytes,!0)}function ze(r,e){let t=Object.getOwnPropertyDescriptor(r,e);if(!t){let n=Object.getPrototypeOf(r);for(let s=0;n!==null;s+=1){if(s>=lc||Object.getOwnPropertyDescriptor(n,e))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");n=Object.getPrototypeOf(n)}return}if(!("value"in t)||typeof t.value!="string"&&t.value!==null&&t.value!==void 0)throw new h("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}function So(r){let e=Object.getOwnPropertyDescriptor(r,"message");if(!e||!("value"in e)||typeof e.value!="object"||e.value===null)throw new h("Chat completion stream contains an unsafe structured JSON snapshot");return e.value}function fl(r,e,t,n){let s=Object.getOwnPropertyDescriptor(r,e);if(!s){let i=Object.getPrototypeOf(r);for(let c=0;i!==null;c+=1){if(c>=lc||Object.getOwnPropertyDescriptor(i,e))throw new h(`Chat completion stream contains an unsafe snapshot ${n} collection`);i=Object.getPrototypeOf(i)}return}if(!("value"in s)||!Array.isArray(s.value))throw new h(`Chat completion stream contains an unsafe snapshot ${n} collection`);let o=Object.getOwnPropertyDescriptor(s.value,"length");if(!o||!("value"in o)||!Number.isSafeInteger(o.value)||o.value>t)throw new h(`Chat completion stream exceeded its snapshot ${n} limit`);return s.value}function Za(r,e){let t=Object.getOwnPropertyDescriptor(r,e);if(t){if(!("value"in t))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}}function pl(r,e,t,n){let s=Object.getOwnPropertyDescriptor(r,"length"),o=s&&"value"in s?s.value:void 0;if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>e)throw new h(`Chat completion stream exceeded its snapshot ${t} limit`);let i=[];i.length=o;for(let c=0;c<o;c+=1){let u=Object.getOwnPropertyDescriptor(r,c);if(u){if(!("value"in u))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");i[c]=n(u.value,c)}}return i}function jr(r,e,t){let n=oc(),s=e??{bytes:0,fragments:0,work:0};if(ic(n,s,r,t),!ac(n,s))throw new h("Chat completion stream exceeded its structured JSON parse-work limit");return r}function Oi(r){let e=Object.getOwnPropertyDescriptor(r,"type"),t=Object.getOwnPropertyDescriptor(r,"function");if(!e||!("value"in e)||e.value!=="function"||!t||!("value"in t)||typeof t.value!="object"||t.value===null)return;let n=Object.getOwnPropertyDescriptor(t.value,"name");if(!(!n||!("value"in n)||typeof n.value!="string"||n.value.length===0))return{type:"function",name:n.value}}function ec(r,e){let t=Oi(r);if(!t||t.name!==e.name||t.type!==e.type)throw new h("Chat completion stream contains a changed tool call identity")}function Ro(r,e){return Object.prototype.propertyIsEnumerable.call(e,"__proto__")&&!$(r,"__proto__")&&Object.defineProperty(r,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(r,e)}function vo(r,e=[]){let t=Object.getOwnPropertyDescriptors(r);for(let n of e){let s=t[n];!s&&!(n in r)||(t[n]={value:s&&"value"in s?s.value:Reflect.get(r,n,r),enumerable:s?.enumerable??!1,configurable:s?.configurable??!0,writable:s&&"writable"in s?s.writable:!1})}return Object.create(Object.getPrototypeOf(r),t)}function Bp(r){let e=vo(r);if(r.tools){let t=[],n=Object.getOwnPropertyDescriptor(r.tools,"length"),s=n&&"value"in n?n.value:void 0,o=typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?Math.min(s,Ht):0;for(let i=0;i<o;i+=1){let c=Object.getOwnPropertyDescriptor(r.tools,String(i));if(!c||!("value"in c)){t.length=i+1;continue}let u=c.value,d=vo(u,["type","$brand","$parseRaw","$callback","function"]),m=Object.getOwnPropertyDescriptors(d);if(ct(d)){let y=m.function;m.function={...y&&"value"in y?y:{configurable:!0,enumerable:!0,writable:!0},value:vo(d.function,["name","strict"])}}t[i]=Object.create(Object.getPrototypeOf(u),m)}e.tools=t}return r.response_format&&(e.response_format=vo(r.response_format,["type","$brand","$parseRaw"])),e}var tc=4096,rc=JSON.stringify,Dp=1024*1024,Np=64,nc=Symbol("omitted serialized parser value"),pe=Symbol("unsafe serialized parser value");function gl(r,e){let t=new WeakSet,n=o=>!Number.isSafeInteger(o)||o<0||e.bytes+o>Dp?!1:(e.bytes+=o,!0),s=(o,i)=>{if(i>Np||e.nodes>=tc)return pe;if(e.nodes+=1,o===void 0||typeof o=="function"||typeof o=="symbol")return nc;if(typeof o=="bigint")return pe;if(o===null||typeof o=="boolean"||typeof o=="number"){let d=rc(o);return typeof d=="string"&&n(d.length)?d:pe}if(typeof o=="string")return n(o.length*6+2)?rc(o):pe;if(typeof o!="object"||t.has(o))return pe;let c=Array.isArray(o),u=Object.getPrototypeOf(o);if(c&&u!==Array.prototype||!c&&u!==null&&u!==Object.prototype)return pe;for(let d=o;d!==null;d=Object.getPrototypeOf(d)){let m=Object.getOwnPropertyDescriptor(d,"toJSON");if(m){if(!("value"in m)||typeof m.value=="function")return pe;break}}t.add(o);try{if(!n(2))return pe;if(c){let p=Object.getOwnPropertyDescriptor(o,"length"),g=p&&"value"in p?p.value:void 0;if(typeof g!="number"||!Number.isSafeInteger(g)||g<0||g>tc-e.nodes)return pe;let A=[];for(let w=0;w<g;w+=1){let S=String(w),E=Object.getOwnPropertyDescriptor(o,S);if(!E){if(Object.getOwnPropertyDescriptor(Array.prototype,S)||Object.getOwnPropertyDescriptor(Object.prototype,S)||(e.nodes+=1,!n(4)))return pe;A.push("null");continue}if(!("value"in E))return pe;let P=s(E.value,i+1);if(P===pe)return P;A.push(P===nc?"null":P)}return`[${A.join(",")}]`}let d=Reflect.ownKeys(o);if(d.length>tc-e.nodes)return pe;let m=[];for(let p of d){if(typeof p!="string")continue;let g=Object.getOwnPropertyDescriptor(o,p);if(!g)return pe;if(g.enumerable){if(!("value"in g))return pe;m.push([p,g.value])}}m.sort(([p],[g])=>p===g?0:p<g?-1:1);let y=[];for(let[p,g]of m){let A=s(g,i+1);if(A===pe)return A;if(A!==nc){if(!n(p.length*6+3))return pe;y.push(`${rc(p)}:${A}`)}}return`{${y.join(",")}}`}finally{t.delete(o)}};try{let o=s(r,0);return typeof o=="string"?o:void 0}catch{return}}function hl(r,e,t,n){let s=Object.getOwnPropertyDescriptor(e,"$parseRaw"),o=Object.getOwnPropertyDescriptor(t,n);if(!s||!("value"in s)||typeof s.value!="function"||!o||!("value"in o))return;let i=gl(o.value,{nodes:0,bytes:0});i!==void 0&&r.set(e,i)}function ml(r,e,t,n,s){let o=e&&r.get(e),i=Object.getOwnPropertyDescriptor(t,n);return o!==void 0&&i!==void 0&&"value"in i&&gl(s,{nodes:0,bytes:0})===o}function Pn(r,e){return r&&"value"in r?{...r,value:e}:{configurable:!0,enumerable:!0,writable:!0,value:e}}function cc(r,e,t){for(let n of t){let s=r[n];!s&&!(n in e)||(r[n]=s&&"value"in s?{...s,value:void 0}:{configurable:s?.configurable??!0,enumerable:s?.enumerable??!1,writable:!1,value:void 0})}}function Fp(r){let e=r.source??{type:r.type,...r.type==="function"?{function:{}}:{}},t=Object.getOwnPropertyDescriptors(e);if(t.type=Pn(t.type,r.type),r.type!=="function"||!r.function)return t.function&&(t.function=Pn(t.function,void 0)),cc(t,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),t);let n=t.function,s=n&&"value"in n&&typeof n.value=="object"&&n.value!==null?n.value:{},o=Object.getOwnPropertyDescriptors(s);return o.name=Pn(o.name,r.function.name),o.strict=Pn(o.strict,r.function.strict),t.function=Pn(n,Object.create(Object.getPrototypeOf(s),o)),r.function.schemaMatches||cc(t,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),t)}function Wp(r){let e=r.source??{type:r.type},t=Object.getOwnPropertyDescriptors(e);return t.type=Pn(t.type,r.type),(r.type!=="json_schema"||!r.source||!r.schemaMatches)&&cc(t,e,["$brand","$parseRaw"]),Object.create(Object.getPrototypeOf(e),t)}function sc(r,e){let t=Object.getOwnPropertyDescriptor(r,e);if(!t||!("value"in t))return;let{value:n}=t;return typeof n=="object"&&n!==null?n:void 0}function Up(r,e,t){let n=new WeakMap,s=new WeakMap;if(r.tools)for(let g=0;g<r.tools.length&&g<Ht;g+=1){let A=sc(r.tools,String(g)),w=e.tools?.[g];if(A&&w){n.set(A,w);let S=sc(w,"function");S&&hl(s,w,S,"parameters")}}e.response_format&&hl(s,e.response_format,e.response_format,"json_schema");let o,i,c,u,d=[],m=new WeakMap,y=new Map,p=new WeakMap;return Vc(r,{value(g,A,w){if(!o&&A===""&&typeof w=="object"&&w!==null){o=w,i=void 0,c=void 0,u=void 0,d=[],m=new WeakMap,y=new Map,p=new WeakMap;return}if(g===o&&A==="response_format"){typeof w=="object"&&w!==null&&(c=w,u={source:sc(g,A)===r.response_format?e.response_format:void 0,schemaMatches:!1});return}if(g===o&&A==="tools")return Array.isArray(w)?(i=new Proxy(w,{get(P,L){let I=Reflect.get(P,L,P);if(typeof L=="string"){let T=Number(L);Number.isSafeInteger(T)&&T>=0&&T<Ht&&String(T)===L&&y.set(T,typeof I=="object"&&I!==null?I:void 0)}return I}}),i):void 0;if(g===i){let P=Number(A);if(!Number.isSafeInteger(P)||P<0||P>=Ht||typeof w!="object"||w===null)return;let L=y.get(P),T={source:L?n.get(L):void 0};d[P]=T,m.set(w,T);return}let S=m.get(g);if(S){if(A==="type"&&typeof w=="string")S.type=w;else if(A==="function"&&typeof w=="object"&&w!==null){let P={source:S.source,schemaMatches:!1};S.function=P,p.set(w,P)}return}if(g===c&&u){A==="type"&&typeof w=="string"?u.type=w:A==="json_schema"&&(u.schemaMatches=ml(s,u.source,g,A,w));return}let E=p.get(g);E&&(A==="name"&&typeof w=="string"?E.name=w:A==="strict"&&typeof w=="boolean"?E.strict=w:A==="parameters"&&(E.schemaMatches=ml(s,E.source,g,A,w)))},complete(){if(!o)return;let g=vo(e);if(i){let A=[];for(let w=0;w<d.length;w+=1){let S=d[w];S&&(A[w]=Fp(S))}g.tools=A}else delete g.tools;u?g.response_format=Wp(u):delete g.response_format,t(g),o=void 0,i=void 0,c=void 0,u=void 0,d=[],m=new WeakMap,y=new Map,p=new WeakMap}})}var Lr=class r extends Tr{constructor(e){super(),J.add(this),oe.set(this,void 0),Ri.set(this,!1),Xt.set(this,void 0),$r.set(this,void 0),xe.set(this,void 0),Ke.set(this,void 0),$e.set(this,void 0),b(this,oe,e,"f"),b(this,Xt,new Set,"f"),b(this,$r,[],"f"),b(this,Ke,!1,"f");let t=e?.tools,n=t&&Object.getOwnPropertyDescriptor(t,"length"),s=n&&"value"in n?n.value:void 0;if(t&&typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)for(let o=0;o<Math.min(s,Ht);o+=1){let i=Object.getOwnPropertyDescriptor(t,String(o));if(!i||!("value"in i))continue;let c=i.value;if(ct(c)&&(Ve(c)||c.function.strict===!0)){b(this,Ke,!0,"f");break}}b(this,$e,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return a(this,xe,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new r(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}_runTools(e,t,n,s){return b(this,Ri,!0,"f"),super._runTools(e,t,n,s)}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0};b(this,oe,s,"f"),a(this,J,"m",Va).call(this);let o=Bp(s);b(this,oe,o,"f"),b(this,Ke,o.tools?.some(u=>ct(u)&&(Ve(u)||u.function.strict===!0))??!1,"f");let i=s.tools||s.response_format?Up(s,o,u=>{b(this,oe,u,"f"),b(this,Ke,u.tools?.some(d=>ct(d)&&(Ve(d)||d.function.strict===!0))??!1,"f")}):void 0,c=await e.chat.completions.create(s,{...n,signal:this.controller.signal}).finally(i);this._connected();for await(let u of c)a(this,J,"m",Ga).call(this,u);if(c.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(a(this,J,"m",xo).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,J,"m",Va).call(this),this._connected();let n=Ee.fromReadableStream(e,this.controller),s;for await(let i of n){if("error"in i&&$(i,"error")&&typeof i.error=="object"&&i.error!==null)throw new z(void 0,i.error,void 0,void 0);if($p(i)){let u=jp(i);if(a(this,xe,"f")){let d=a(this,xe,"f").choices[0]?.message.tool_calls;for(let[m,y]of u.tool_call_ids?.entries()??[]){let p=d?.[m];p&&y&&(p.id=y)}this._addChatCompletion(a(this,J,"m",xo).call(this)),s=void 0}this._addMessage(u.message);continue}let c=i;s&&c.id&&s!==c.id&&this._addChatCompletion(a(this,J,"m",xo).call(this)),a(this,J,"m",Ga).call(this,c),c.id&&(s=c.id)}if(n.controller.signal?.aborted)throw this._userAbortError();if(a(this,xe,"f"))return this._addChatCompletion(a(this,J,"m",xo).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new h("request ended without sending any chunks")}[(oe=new WeakMap,Ri=new WeakMap,Xt=new WeakMap,$r=new WeakMap,xe=new WeakMap,Ke=new WeakMap,$e=new WeakMap,J=new WeakSet,Va=function(){this.ended||(b(this,Xt,new Set,"f"),b(this,xe,void 0,"f"),b(this,$e,{bytes:0,fragments:0,work:0},"f"))},wn=function(t){let n=a(this,$r,"f")[t.index];return n||(n={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},a(this,$r,"f")[t.index]=n,n)},Ga=function(t){if(this.ended)return;let n=new WeakMap,s=a(this,J,"m",ul).call(this,t,n);this._emit("chunk",t,s);for(let o of t.choices){let i=n.get(o),c=s.choices[i?.index??o.index],u=i?.tool_calls??[],{delta:d}=o,m=ut(a(this,oe,"f")?.response_format),y=m||a(this,Ke,"f"),p=y?So(c):c.message,g=y?ze(p,"refusal"):p.refusal,w=!g&&m?ze(p,"content"):p.content;d?.content!=null&&p.role==="assistant"&&w&&(this._emit("content",d.content,w),this._emit("content.delta",{delta:d.content,snapshot:w,parsed:p.parsed})),d?.refusal!=null&&p.role==="assistant"&&g&&this._emit("refusal.delta",{delta:d.refusal,snapshot:g}),o.logprobs?.content!=null&&p.role==="assistant"&&this._emit("logprobs.content.delta",{content:o.logprobs?.content,snapshot:c.logprobs?.content??[]}),o.logprobs?.refusal!=null&&p.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:o.logprobs?.refusal,snapshot:c.logprobs?.refusal??[]});let S=a(this,J,"m",wn).call(this,c);c.finish_reason&&(a(this,J,"m",Qa).call(this,c),S.current_tool_call_index!=null&&a(this,J,"m",Ya).call(this,c,S.current_tool_call_index));for(let E of u)S.current_tool_call_index!==E.index&&(a(this,J,"m",Qa).call(this,c),S.current_tool_call_index!=null&&a(this,J,"m",Ya).call(this,c,S.current_tool_call_index)),S.current_tool_call_index=E.index;for(let E of u){let P=p.tool_calls?.[E.index];if(P?.type)if(P.type==="function"){let L=S.tool_call_identities.get(E.index),I;if(L?.parseable){let T=ze(P.function,"arguments");if(typeof T!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");I=T}else I=P.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:P.function.name,index:E.index,arguments:I,parsed_arguments:P.function.parsed_arguments,arguments_delta:E.arguments_delta})}else P.type!=="custom"&&P}}},Ya=function(t,n){let s=a(this,J,"m",wn).call(this,t);if(s.done_tool_calls.has(n))return;let i=(a(this,Ke,"f")?So(t):t.message).tool_calls?.[n];if(!i)throw new Error("no tool call snapshot");let c=s.tool_call_identities.get(n);if(c&&ec(i,c),!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){let u=a(this,oe,"f")?.tools?.find(p=>ct(p)&&p.function.name===i.function.name),d=null,m=Ve(u)||u?.function.strict===!0,y;if(m){a(this,xe,"f")&&a(this,J,"m",In).call(this,a(this,xe,"f"));let p=ze(i.function,"arguments");if(typeof p!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");y=p}else y=i.function.arguments;Ve(u)?d=u.$parseRaw(jr(y)):u?.function.strict&&(d=It({type:"json_schema",$parseRaw:void 0},jr(y))),t.finish_reason&&s.done_tool_calls.add(n),this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:n,arguments:y,parsed_arguments:d})}else i.type!=="custom"&&i},Qa=function(t){let n=a(this,J,"m",wn).call(this,t),s=ut(a(this,oe,"f")?.response_format),o=s||a(this,Ke,"f"),i=o?So(t):t.message,c=o?ze(i,"refusal"):i.refusal,u=!c&&s,d=u?ze(i,"content"):i.content;d!=null&&(d!==""||!c&&!i.tool_calls?.length&&!i.function_call)&&!n.content_done&&(u&&a(this,xe,"f")&&a(this,J,"m",In).call(this,a(this,xe,"f")),n.content_done=!0,this._emit("content.done",{content:d,parsed:c?null:It(a(this,oe,"f")?.response_format,u?jr(d):d)})),c&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:c})),t.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},In=function(t){let n={bytes:0,fragments:0,work:0},s=ut(a(this,oe,"f")?.response_format),o=new WeakMap,i=fl(t,"choices",vi,"choice");if(!i)throw new h("Chat completion stream contains an unsafe snapshot choice collection");for(let c=0;c<i.length;c+=1){let u=Za(i,c);if(!u)continue;let d=So(u),m=ze(d,"refusal"),y=ze(d,"content"),p=new Map,g=fl(d,"tool_calls",Ht,"tool-call");o.set(u,Object.freeze({message:d,content:y,refusal:m,toolCallCollection:g,toolCalls:p}));let A=a(this,$r,"f")[u.index];s&&!m&&typeof y=="string"&&jr(y,n,a(this,$e,"f"));for(let[w,S]of A?.tool_call_identities??[]){let E=g&&Za(g,w);if(!E)throw new h("Chat completion stream contains a changed tool call identity");ec(E,S)}if(a(this,Ke,"f"))for(let w=0;w<(g?.length??0);w+=1){let S=Za(g,w);if(!S)continue;let E=Oi(S);if(!E){let T=Object.getOwnPropertyDescriptor(S,"type");if(T&&!("value"in T))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");if(T?.value!=="function")continue;let x=Object.getOwnPropertyDescriptor(S,"function");if(x&&!("value"in x))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");if(x&&typeof x.value=="object"&&x.value!==null){let M=Object.getOwnPropertyDescriptor(x.value,"name");if(M&&!("value"in M))throw new h("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!di(a(this,oe,"f"),{type:E.type,function:{name:E.name}}))continue;let P=Object.getOwnPropertyDescriptor(S,"function");if(!P||!("value"in P))throw new h("Chat completion stream contains an unsafe structured JSON snapshot");let L=P.value,I=ze(L,"arguments");if(typeof I!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");jr(I,n,a(this,$e,"f")),p.set(w,Object.freeze({tool:S,function:L,type:E.type,name:E.name,arguments:I}))}}return o},xo=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=a(this,xe,"f");if(!t)throw new h("request ended without sending any chunks");let n=a(this,J,"m",In).call(this,t),s=a(this,Xt,"f");return b(this,Xt,new Set,"f"),b(this,xe,void 0,"f"),b(this,$r,[],"f"),qp(t,a(this,oe,"f"),s,n)},ul=function(t,n){var s,o,i,c,u;let d=a(this,xe,"f"),{choices:m,obfuscation:y,...p}=t;if(d)t.id&&Ro(d,p);else{let w={...p,choices:[]};b(this,xe,w,"f"),d=w}let g=a(this,oe,"f")?.n,A=typeof g=="number"&&Number.isSafeInteger(g)&&g>0?Math.min(g,vi):vi;for(let w of t.choices){let{delta:S,finish_reason:E,index:P,logprobs:L=null,...I}=w,T=[];if(n.set(w,Object.freeze({index:P,tool_calls:T})),!Number.isSafeInteger(P)||P<0||P>=A)throw new h(`Chat completion stream contains an invalid choice index: ${P}`);let x=d.choices[P];if(!x){let W={finish_reason:E,index:P,message:{},logprobs:null,...I};d.choices[P]=W,x=W}if((ut(a(this,oe,"f")?.response_format)||a(this,Ke,"f"))&&ze(So(x),"refusal"),L)if(x.logprobs){let{content:W,refusal:tt,...te}=L;Ro(x.logprobs,te),W&&((s=x.logprobs).content??(s.content=[]),x.logprobs.content.push(...W)),tt&&((o=x.logprobs).refusal??(o.refusal=[]),x.logprobs.refusal.push(...tt))}else x.logprobs={...L},L.content&&(x.logprobs.content=[...L.content]),L.refusal&&(x.logprobs.refusal=[...L.refusal]);if(E&&(x.finish_reason=E,a(this,oe,"f")&&(a(this,Ri,"f")||Ca(a(this,oe,"f"))))){if(E==="length")throw new Ft;if(E==="content_filter")throw new Wt}if(Ro(x,I),!S){Object.freeze(T);continue}a(this,Xt,"f").delete(P);let{audio:M,content:k,refusal:O,function_call:v,role:K,...D}=S,{tool_calls:N,...q}=D,ge=$(D,"tool_calls")?N:S.tool_calls;if(Ro(x.message,q),M?.expires_at!=null&&M.id==null&&M.data==null&&M.transcript==null&&k==null&&O==null&&v==null&&K==null&&ge==null&&Object.keys(q).length===0&&a(this,Xt,"f").add(P),O&&(x.message.refusal=(x.message.refusal||"")+O),K&&(x.message.role=K),M){let W=(i=x.message).audio??(i.audio={});M.id!=null&&(W.id=M.id),M.data!=null&&(W.data=(W.data??"")+M.data),M.transcript!=null&&(W.transcript=(W.transcript??"")+M.transcript),M.expires_at!=null&&(W.expires_at=M.expires_at)}if(v&&(x.message.function_call?(v.name&&(x.message.function_call.name=v.name),v.arguments&&((c=x.message.function_call).arguments??(c.arguments=""),x.message.function_call.arguments+=v.arguments)):x.message.function_call=v),k!=null)if(!x.message.refusal&&ut(a(this,oe,"f")?.response_format)){let W=a(this,J,"m",wn).call(this,x),tt=W.content_parse_state??(W.content_parse_state=oc()),te=ic(tt,a(this,$e,"f"),k);x.message.content=(ze(x.message,"content")||"")+k,tt.has_non_whitespace?te&&ac(tt,a(this,$e,"f"))?(a(this,J,"m",In).call(this,d),x.message.parsed=ll(jr(x.message.content))):k.length>0&&(x.message.parsed=null):x.message.parsed=null}else x.message.content=(x.message.content||"")+k;if(ge){let W=(u=x.message).tool_calls??(u.tool_calls=[]);for(let tt of ge){let{index:te,id:qo,type:dn,function:fn,custom:ht,...Yi}=tt;if(!Number.isSafeInteger(te)||te<0||te>=Ht)throw new h(`Chat completion stream contains an invalid tool call index: ${te}`);let Le="",ce=W[te]??(W[te]={}),He=fn?.name,rt=a(this,Ke,"f")?a(this,J,"m",wn).call(this,x):void 0,Me=rt?.tool_call_identities.get(te);if(Me&&(ec(ce,Me),dn!==void 0&&dn!==Me.type||He!==void 0&&He!==Me.name))throw new h("Chat completion stream contains a changed tool call identity");if(Ro(ce,Yi),qo&&(ce.id=qo),dn&&(ce.type=dn),ht){let ve=ce.custom??(ce.custom={name:ht.name??"",input:""});ht.name&&(ve.name=ht.name),ht.input&&(ve.input+=ht.input)}if(fn){let ve=ce.function??(ce.function={name:He??"",arguments:""});if(He&&(ve.name=He),rt&&!Me){let Be=Oi(ce),Qi=Be&&a(this,oe,"f")?.tools?.find(nt=>ct(nt)&&nt.function.name===Be.name);if(Be&&(Me={...Be,parseable:Qi!==void 0&&di(a(this,oe,"f"),{type:Be.type,function:{name:Be.name}})},rt.tool_call_identities.set(te,Me),!Me.parseable)){let nt=rt.tool_call_parse_states.get(te);nt&&(a(this,$e,"f").bytes-=nt.bytes,a(this,$e,"f").fragments-=nt.fragments,a(this,$e,"f").work-=nt.work,rt.tool_call_parse_states.delete(te))}}let Tt=fn.arguments;if(Tt!=null)if(Le=Tt,rt&&Me?.parseable!==!1){let Be=rt.tool_call_parse_states.get(te);Be||(Be=oc(),rt.tool_call_parse_states.set(te,Be));let Qi=ic(Be,a(this,$e,"f"),Tt),nt=ze(ve,"arguments");if(typeof nt!="string")throw new h("Chat completion stream contains an unsafe structured JSON snapshot");ve.arguments=nt+Tt,Qi&&Me?.parseable===!0&&ac(Be,a(this,$e,"f"))?(a(this,J,"m",In).call(this,d),ve.parsed_arguments=ll(jr(ve.arguments))):Tt.length>0&&$(ve,"parsed_arguments")&&(ve.parsed_arguments=void 0)}else ve.arguments+=Tt}T.push(Object.freeze({index:te,arguments_delta:Le}))}}Object.freeze(T)}return d},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=n=>e(n);return this.on("chunk",t),()=>this.off("chunk",t)},{onReturn:()=>this.abort()})}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function qp(r,e,t,n){let{id:s,choices:o,created:i,model:c,system_fingerprint:u,...d}=r,m={...d,id:s,choices:pl(o,vi,"choice",y=>{let p=n.get(y);if(!p)throw new h("Chat completion stream contains an unsafe structured JSON snapshot");let g=new Proxy(y,{get(D,N,q){return N==="message"?p.message:Reflect.get(D,N,q)}}),{message:A,finish_reason:w,index:S,logprobs:E,...P}=g,L=new Proxy(A,{get(D,N,q){return N==="content"?p.content:N==="refusal"?p.refusal:N==="tool_calls"?p.toolCallCollection:Reflect.get(D,N,q)}}),{content:I=null,function_call:T,tool_calls:x,audio:M,...k}=L,O=w??(t.has(S)&&Kp(M)?"stop":null);if(!O)throw new h(`missing finish_reason for choice ${S}`);let v=M?{audio:M}:{},K=L.role;if(!K)throw new h(`missing role for choice ${S}`);if(T){let{arguments:D,name:N}=T;if(D==null)throw new h(`missing function_call.arguments for choice ${S}`);if(!N)throw new h(`missing function_call.name for choice ${S}`);return{...P,message:{...v,content:I,function_call:{arguments:D,name:N},role:K,refusal:L.refusal??null},finish_reason:O,index:S,logprobs:E}}return x?{...P,index:S,finish_reason:O,logprobs:E,message:{...k,...v,role:K,content:I,refusal:L.refusal??null,tool_calls:pl(x,Ht,"tool-call",(D,N)=>{let q=p.toolCalls.get(N);if(!q){let Le=Oi(D);if(Le&&di(e,{type:Le.type,function:{name:Le.name}}))throw new h("Chat completion stream contains an unsafe structured JSON snapshot")}if(q&&q.tool!==D)throw new h("Chat completion stream contains a changed tool call identity");let ge=q&&new Proxy(q.function,{get(Le,ce,He){return ce==="arguments"?q.arguments:ce==="name"?q.name:Reflect.get(Le,ce,He)}}),W=q&&ge?new Proxy(D,{get(Le,ce,He){return ce==="type"?q.type:ce==="function"?ge:Reflect.get(Le,ce,He)}}):D;if(W.type==null)throw new h(`missing choices[${S}].tool_calls[${N}].type`);if(W.type==="custom"){let{custom:Le,type:ce,id:He,...rt}=W,{input:Me="",name:ve,...Tt}=Le||{};if(ve==null)throw new h(`missing choices[${S}].tool_calls[${N}].custom.name`);return{...rt,id:He||`call_${Je()}`,type:ce,custom:{...Tt,name:ve,input:Me}}}let{function:tt,type:te,id:qo,...dn}=W,{arguments:fn,name:ht,...Yi}=tt||{};if(ht==null)throw new h(`missing choices[${S}].tool_calls[${N}].function.name`);if(fn==null)throw new h(`missing choices[${S}].tool_calls[${N}].function.arguments`);return{...dn,id:qo||`call_${Je()}`,type:te,function:{...Yi,name:ht,arguments:fn}}})}}:{...P,message:{...k,...v,content:I,role:K,refusal:L.refusal??null},finish_reason:O,index:S,logprobs:E}}),created:i,model:c,object:"chat.completion",...u?{system_fingerprint:u}:{}};return qu(m,e)}function Kp(r){return r?.id!=null&&r.data!=null&&r.transcript!=null&&r.expires_at!=null}var Oo=class r extends Lr{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e,t,n=this._createIterator(o=>{let i=u=>{e=u,o(u)},c=u=>{if(Pt(u)){t=u.tool_calls?.map(d=>d.id);return}if(fo(u)){if(!e)throw new h("cannot serialize a tool message before receiving any chunks");o(_l(e,u,t)),t=void 0}};return this.on("chunk",i),this.on("message",c),()=>{this.off("chunk",i),this.off("message",c)}},{onReturn:()=>this.abort()});return new Ee(()=>n,this.controller).toReadableStream()}static runTools(e,t,n){let s=new r(t),o={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,o)),s}};var xt=class extends f{constructor(){super(...arguments),this.messages=new Or(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Ku(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap(n=>lo(n,e))}runTools(e,t){return e.stream?Oo.runTools(this._client,e,t):Io.runTools(this._client,e,t)}stream(e,t){return Lr.createChatCompletion(this._client,e,t)}};xt.Messages=Or;var Jt=class extends f{constructor(){super(...arguments),this.completions=new xt(this._client)}};Jt.Completions=xt;var xn=class extends f{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",R,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Sn=class extends f{list(e={},t){return this._client.getAPIList("/organization/audit_logs",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Rn=class extends f{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(l`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",le,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",le,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var vn=class extends f{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}};var On=class extends f{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var En=class extends f{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",Q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var kn=class extends f{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Cn=class extends f{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}};var Tn=class extends f{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var $n=class extends f{create(e,t,n){return this._client.post(l`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(l`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/groups/${e}/roles`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(l`/organization/groups/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var jn=class extends f{create(e,t,n){return this._client.post(l`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(l`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/groups/${e}/users`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:s}=t;return this._client.delete(l`/organization/groups/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends f{constructor(){super(...arguments),this.users=new jn(this._client),this.roles=new $n(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",Q,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Vt.Users=jn;Vt.Roles=$n;var Ln=class extends f{retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/api_keys`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Mn=class extends f{list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/certificates`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(l`/organization/projects/${e}/certificates/activate`,le,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(l`/organization/projects/${e}/certificates/deactivate`,le,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}};var Bn=class extends f{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}};var Dn=class extends f{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}};var Nn=class extends f{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Fn=class extends f{listRateLimits(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/rate_limits`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/rate_limits/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}};var Wn=class extends f{create(e,t,n){return this._client.post(l`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/projects/${s}/roles/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/projects/${e}/roles`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/projects/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Un=class extends f{create(e,t,n){return this._client.post(l`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/spend_alerts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/spend_alerts`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var qn=class extends f{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Kn=class extends f{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/projects/${s}/groups/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,group_id:o}=t;return this._client.get(l`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(l`/projects/${s}/groups/${e}/roles`,Q,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,group_id:o}=t;return this._client.delete(l`/projects/${s}/groups/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Mr=class extends f{constructor(){super(...arguments),this.roles=new Kn(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,...o}=t;return this._client.get(l`/organization/projects/${s}/groups/${e}`,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/groups`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Mr.Roles=Kn;var zn=class extends f{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/service_accounts/${e}/api_keys`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}};var Br=class extends f{constructor(){super(...arguments),this.apiKeys=new zn(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/service_accounts/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/service_accounts`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Br.APIKeys=zn;var Xn=class extends f{create(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/projects/${s}/users/${e}/roles`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s,user_id:o}=t;return this._client.get(l`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:s,...o}=t;return this._client.getAPIList(l`/projects/${s}/users/${e}/roles`,Q,{query:o,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s,user_id:o}=t;return this._client.delete(l`/projects/${s}/users/${o}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Dr=class extends f{constructor(){super(...arguments),this.roles=new Xn(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:s,...o}=t;return this._client.post(l`/organization/projects/${s}/users/${e}`,{body:o,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/projects/${e}/users`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Dr.Roles=Xn;var he=class extends f{constructor(){super(...arguments),this.users=new Dr(this._client),this.serviceAccounts=new Br(this._client),this.apiKeys=new Ln(this._client),this.rateLimits=new Fn(this._client),this.modelPermissions=new Nn(this._client),this.hostedToolPermissions=new Dn(this._client),this.groups=new Mr(this._client),this.roles=new Wn(this._client),this.dataRetention=new Bn(this._client),this.spendLimit=new qn(this._client),this.spendAlerts=new Un(this._client),this.certificates=new Mn(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(l`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(l`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};he.Users=Dr;he.ServiceAccounts=Br;he.APIKeys=Ln;he.RateLimits=Fn;he.ModelPermissions=Nn;he.HostedToolPermissions=Dn;he.Groups=Mr;he.Roles=Wn;he.DataRetention=Bn;he.SpendLimit=qn;he.SpendAlerts=Un;he.Certificates=Mn;var Hn=class extends f{create(e,t,n){return this._client.post(l`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:s}=t;return this._client.get(l`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/organization/users/${e}/roles`,Q,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:s}=t;return this._client.delete(l`/organization/users/${s}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var Nr=class extends f{constructor(){super(...arguments),this.roles=new Hn(this._client)}retrieve(e,t){return this._client.get(l`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(l`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(l`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Nr.Roles=Hn;var me=class extends f{constructor(){super(...arguments),this.auditLogs=new Sn(this._client),this.adminAPIKeys=new xn(this._client),this.usage=new Tn(this._client),this.invites=new On(this._client),this.users=new Nr(this._client),this.groups=new Vt(this._client),this.roles=new En(this._client),this.dataRetention=new vn(this._client),this.spendLimit=new Cn(this._client),this.spendAlerts=new kn(this._client),this.certificates=new Rn(this._client),this.projects=new he(this._client)}};me.AuditLogs=Sn;me.AdminAPIKeys=xn;me.Usage=Tn;me.Invites=On;me.Users=Nr;me.Groups=Vt;me.Roles=En;me.DataRetention=vn;me.SpendLimit=Cn;me.SpendAlerts=kn;me.Certificates=Rn;me.Projects=he;var Gt=class extends f{constructor(){super(...arguments),this.organization=new me(this._client)}};Gt.Organization=me;var Jn=class extends f{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Vn=class extends f{create(e,t){return this._client.post("/audio/transcriptions",se({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var Gn=class extends f{create(e,t){return this._client.post("/audio/translations",se({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var dt=class extends f{constructor(){super(...arguments),this.transcriptions=new Vn(this._client),this.translations=new Gn(this._client),this.speech=new Jn(this._client)}};dt.Transcriptions=Vn;dt.Translations=Gn;dt.Speech=Jn;var Fr=class extends f{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",R,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var Yn=class extends f{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/assistants/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Qn=class extends f{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Zn=class extends f{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Yt=class extends f{constructor(){super(...arguments),this.sessions=new Qn(this._client),this.transcriptionSessions=new Zn(this._client)}};Yt.Sessions=Qn;Yt.TranscriptionSessions=Zn;var es=class extends f{create(e,t,n){return this._client.post(l`/agents/environments/${e}/files`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/environments/${e}/files`,mn,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var ts=class extends f{create(e={},t){return this._client.post("/agents/environments/templates",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/agents/environments/templates/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(l`/agents/environments/templates/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/environments/templates",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/agents/environments/templates/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var Qt=class extends f{constructor(){super(...arguments),this.files=new es(this._client),this.templates=new ts(this._client)}retrieve(e,t){return this._client.get(l`/agents/environments/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};Qt.Files=es;Qt.Templates=ts;var rs,Ei,Wr,ki,Ci=class{constructor(){rs.set(this,void 0),Ei.set(this,!1),Wr.set(this,new Set),ki.set(this,new Set)}accept(e){if(a(this,Wr,"f").has(e.event_id))return!1;if(a(this,Wr,"f").size===1024){let t=a(this,Wr,"f").values().next();t.done||a(this,Wr,"f").delete(t.value)}return a(this,Wr,"f").add(e.event_id),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&a(this,rs,"f")===void 0&&b(this,rs,e.turn_id,"f"),(e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled")&&a(this,rs,"f")!==void 0&&e.turn_id===a(this,rs,"f")&&b(this,Ei,!0,"f"),!0}terminal(e){return e.type==="agent.session.failed"||e.type==="agent.session.idle"&&a(this,Ei,"f")}call(e){if(e.type!=="agent.session.turn.item.added"||e.item.type!=="function_call")return;let t=e.item,n=JSON.stringify([t.turn_id,t.call_id]);if(!a(this,ki,"f").has(n))return a(this,ki,"f").add(n),t}};rs=new WeakMap,Ei=new WeakMap,Wr=new WeakMap,ki=new WeakMap;var ie,Ti,ns,$i,ji,Ur,qr,Li,Mi,ss,Eo,wl,bl,Ge,dc,fc,Al;function $h(r){if(!_e(r))return!1;let e=r,t;if(e.type==="input_text")t="text";else if(e.type==="input_image")t="image_url";else return!1;return $(e,"type")&&$(e,t)&&typeof e[t]=="string"}function jh(r){if(r===null)return null;if(typeof r=="string"||Array.isArray(r)&&r.every($h))return r;throw new h("Tool output must be text, content, a JSON object, or null")}function Lh(r,e){let t=_e(e)?JSON.stringify(e):e,n=JSON.stringify(t);if(n===void 0)throw new h("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:r.turn_id,call_id:r.call_id,success:!0,output:jh(typeof t=="string"?t:JSON.parse(n))}}async function Mh(r){try{await r?.body?.cancel()}catch{}}var Bi=class{constructor(e,t,n,s){ie.add(this),this.controller=new AbortController,Ti.set(this,!1),ns.set(this,void 0),$i.set(this,void 0),ji.set(this,!1),Ur.set(this,void 0),qr.set(this,void 0),Li.set(this,void 0),Mi.set(this,void 0),ss.set(this,void 0),Eo.set(this,void 0);let o=typeof n.input=="string"?[{role:"user",content:[{type:"input_text",text:n.input}]}]:n.input;if(n.input.length===0)throw new h("input must not be empty");b(this,Ur,e,"f"),b(this,qr,t,"f"),b(this,Li,{type:"agent.session.input.message",input:o},"f"),b(this,Mi,new Map(Object.entries(n.toolHandlers??{})),"f");let i=_([s?.headers]);b(this,ss,i.nulls.has("idempotency-key")?void 0:i.values.get("idempotency-key")??n.idempotencyKey??s?.idempotencyKey??Je(),"f"),i.values.delete("idempotency-key"),i.nulls.delete("idempotency-key");let{idempotencyKey:c,...u}=s??{};b(this,Eo,{...u,headers:i},"f")}abort(e){this.controller.abort(e),a(this,ns,"f")?.controller.abort(this.controller.signal.reason),a(this,ji,"f")||Mh(a(this,$i,"f"))}[(Ti=new WeakMap,ns=new WeakMap,$i=new WeakMap,ji=new WeakMap,Ur=new WeakMap,qr=new WeakMap,Li=new WeakMap,Mi=new WeakMap,ss=new WeakMap,Eo=new WeakMap,ie=new WeakSet,Symbol.asyncIterator)](){if(a(this,Ti,"f"))throw new h("An AgentSessionStream can only be consumed once");return b(this,Ti,!0,"f"),a(this,ie,"m",wl).call(this)}};wl=async function*(){let e=a(this,Eo,"f").signal,t=()=>this.abort(e?.aborted?e.reason:this.controller.signal.reason);e?.addEventListener("abort",t,{once:!0}),this.controller.signal.addEventListener("abort",t,{once:!0});let n={...a(this,Eo,"f"),signal:this.controller.signal},s=new Ci;try{if(e?.aborted&&this.abort(e.reason),a(this,ie,"m",Ge).call(this),(await a(this,Ur,"f").retrieve(a(this,qr,"f"),n)).status!=="idle")throw new h("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let i=await a(this,Ur,"f").events.stream(a(this,qr,"f"),n).withResponse();b(this,ns,i.data,"f"),b(this,$i,i.response,"f"),a(this,ie,"m",Ge).call(this),await a(this,Ur,"f").events.create(a(this,qr,"f"),{events:[a(this,Li,"f")],...a(this,ss,"f")===void 0?{}:{"Idempotency-Key":a(this,ss,"f")}},{...n,headers:_([n.headers,{"Idempotency-Key":a(this,ss,"f")??null}])}),a(this,ie,"m",Ge).call(this),b(this,ji,!0,"f");for await(let c of a(this,ns,"f")){if(a(this,ie,"m",Ge).call(this),!s.accept(c))continue;let u=s.terminal(c),d=s.call(c),m=d&&a(this,Mi,"f").get(d.name),y=d&&m?structuredClone(d):void 0;if(u&&a(this,ns,"f").controller.abort(),yield c,u)return;if(a(this,ie,"m",Ge).call(this),!y||!m)continue;let p=await a(this,ie,"m",bl).call(this,y,m);a(this,ie,"m",Ge).call(this),await a(this,ie,"m",Al).call(this,p,n)}throw a(this,ie,"m",Ge).call(this),new h("Session event stream ended before the turn reached idle or failed")}finally{e?.removeEventListener("abort",t),this.controller.signal.removeEventListener("abort",t),this.abort()}},bl=async function(e,t){try{let n=typeof e.arguments=="string"?JSON.parse(e.arguments):e.arguments;if(!_e(n))throw new h("Function arguments must be a JSON object");return Lh(e,await a(this,ie,"m",fc).call(this,()=>t(n)))}catch{return a(this,ie,"m",Ge).call(this),{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!1,error:"Tool handler failed."}}},Ge=function(){if(this.controller.signal.aborted)throw a(this,ie,"m",dc).call(this)},dc=function(){let e=new Y;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e},fc=async function(e){let t,n=new Promise((s,o)=>{t=()=>o(a(this,ie,"m",dc).call(this)),this.controller.signal.addEventListener("abort",t,{once:!0})});try{a(this,ie,"m",Ge).call(this);let s=async()=>await e();return await Promise.race([s(),n])}finally{t&&this.controller.signal.removeEventListener("abort",t)}},Al=async function r(e,t,n=Je(),s=0){a(this,ie,"m",Ge).call(this);try{await a(this,Ur,"f").events.create(a(this,qr,"f"),{events:[e],"Idempotency-Key":n},t)}catch(o){let i=[100,300,600][s];if(i===void 0||!(o instanceof st)||o.code!=="invalid_request_error"||!o.error||!("message"in o.error)||o.error.message!==`Unknown pending tool call: ${e.call_id}`)throw o;let c;try{await a(this,ie,"m",fc).call(this,()=>new Promise(u=>{c=setTimeout(u,i)}))}finally{c!==void 0&&clearTimeout(c)}await a(this,ie,"m",r).call(this,e,t,n,s+1)}};var os=class extends f{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/artifacts`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{session_id:s}=t;return this._client.delete(l`/agents/sessions/${s}/artifacts/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}content(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/artifacts/${e}/content`,{...n,headers:_([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var is=class extends f{create(e,t,n){let{"Idempotency-Key":s,...o}=t;return this._client.post(l`/agents/sessions/${e}/events`,{body:o,...n,headers:_([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...s!=null?{"Idempotency-Key":s}:void 0},n?.headers]),__security:{bearerAuth:!0}})}stream(e,t){return this._client.get(l`/agents/sessions/${e}/events`,{...t,headers:_([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},t?.headers]),stream:!0,__security:{bearerAuth:!0}})}};var as=class extends f{list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/items`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var cs=class extends f{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/turns/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/turns`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var us=class extends f{list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${e}/items`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var ls=class extends f{list(e,t,n){let{session_id:s,subagent_id:o,...i}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${o}/turns/${e}/items`,R,{query:i,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var Kr=class extends f{constructor(){super(...arguments),this.items=new ls(this._client)}retrieve(e,t,n){let{session_id:s,subagent_id:o}=t;return this._client.get(l`/agents/sessions/${s}/subagents/${o}/turns/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{session_id:s,...o}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${e}/turns`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};Kr.Items=ls;var Zt=class extends f{constructor(){super(...arguments),this.items=new us(this._client),this.turns=new Kr(this._client)}retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/subagents/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/agents/sessions/${e}/subagents`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};Zt.Items=us;Zt.Turns=Kr;var Ye=class extends f{constructor(){super(...arguments),this.subagents=new Zt(this._client),this.artifacts=new os(this._client),this.items=new as(this._client),this.events=new is(this._client),this.turns=new cs(this._client)}stream(e,t,n){return new Bi(this,e,t,n)}create(e,t){return this._client.post("/agents/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/agents/sessions/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(l`/agents/sessions/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents/sessions",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/agents/sessions/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};Ye.Subagents=Zt;Ye.Artifacts=os;Ye.Items=as;Ye.Events=is;Ye.Turns=cs;var ds=class extends f{create(e,t,n){return this._client.post(l`/vaults/${e}/credentials`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vault_id:s}=t;return this._client.get(l`/vaults/${s}/credentials/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vault_id:s,...o}=t;return this._client.post(l`/vaults/${s}/credentials/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/vaults/${e}/credentials`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vault_id:s}=t;return this._client.delete(l`/vaults/${s}/credentials/${e}`,{...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var zr=class extends f{constructor(){super(...arguments),this.credentials=new ds(this._client)}create(e={},t){return this._client.post("/vaults",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/vaults/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vaults",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/vaults/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};zr.Credentials=ds;var St=class extends f{constructor(){super(...arguments),this.environments=new Qt(this._client),this.vaults=new zr(this._client),this.sessions=new Ye(this._client)}create(e,t){return this._client.post("/agents",{body:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/agents/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(l`/agents/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/agents",R,{query:e,...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/agents/${e}`,{...t,headers:_([{"OpenAI-Beta":"agents=v1"},t?.headers]),__security:{bearerAuth:!0}})}};St.Environments=Qt;St.Vaults=zr;St.Sessions=Ye;var fs=class extends f{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var ps=class extends f{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",F,{query:e,...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,F,{query:t,...n,headers:_([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})}};var er=class extends f{constructor(){super(...arguments),this.sessions=new fs(this._client),this.threads=new ps(this._client)}};er.Sessions=fs;er.Threads=ps;var hs=class extends f{list(e,t={},n){let{betas:s,...o}=t??{};return this._client.getAPIList(l`/responses/${e}/input_items?beta=true`,R,{query:o,...n,headers:_([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}};var ms=class extends f{count(e={},t){let{betas:n,...s}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:s,...t,headers:_([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var tr=class extends f{constructor(){super(...arguments),this.inputItems=new hs(this._client),this.inputTokens=new ms(this._client)}create(e,t){let{betas:n,...s}=e;return this._client.post("/responses?beta=true",{body:s,...t,headers:_([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:s,...o}=t??{};return this._client.get(l`/responses/${e}?beta=true`,{query:o,...n,headers:_([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:s}=t??{};return this._client.delete(l`/responses/${e}?beta=true`,{...n,headers:_([{Accept:"*/*",...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:s}=t??{};return this._client.post(l`/responses/${e}/cancel?beta=true`,{...n,headers:_([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...s}=e;return this._client.post("/responses/compact?beta=true",{body:s,...t,headers:_([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};tr.InputItems=hs;tr.InputTokens=ms;var _s=class extends f{create(e,t,n){return this._client.post(l`/threads/${e}/messages`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/threads/${e}/messages`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var ys=class extends f{retrieve(e,t,n){let{thread_id:s,run_id:o,...i}=t;return this._client.get(l`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:s,...o}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var Di=r=>{if(typeof globalThis.Buffer<"u"){let e=globalThis.Buffer.from(r,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof atob<"u"){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}throw new h("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Il=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");if(e.length%Float32Array.BYTES_PER_ELEMENT!==0)throw new RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};var Se=r=>{try{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0}catch{return}};var xl=1024,nm=65536;function sm(r){switch(r){case"value":case"arguments":case"input":case"text":case"content":case"annotations":case"metadata":case"name":case"role":case"status":case"tool_calls":case"step_details":return r;default:return"unknown"}}var ko=new WeakMap,rr=new WeakSet;function Sl(r){return{arrays:new Map,cacheArrays:r,records:new WeakMap}}function Rl(r){for(let[e,t]of r.arrays)t.cacheable&&!rr.has(e)?ko.set(e,{length:t.length,ownEntryCount:t.ownEntryCount}):ko.delete(e)}function Pl(r){return typeof r=="string"||typeof r=="number"}function vl(r,e){return e.every(Pl)&&r.every(Pl)}function om(r){let e=0;for(let t of Object.keys(r)){let n=Number(t);Number.isSafeInteger(n)&&n>=0&&n<r.length&&String(n)===t&&(e+=1)}return e}function im(r,e,t){return e?t?.length===r.length?t.ownEntryCount:om(r):0}function am(r,e,t){let{index:n}=r;if(e==="array"&&n==null)throw new Error("Expected array delta entry to have an `index` property");if(e==="array"&&typeof n!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(n)||n<0||n>=t+xl||n>=nm){let s=typeof n=="number"?n:"unknown";throw new h(`Assistant stream delta contains an invalid ${e} index: ${s}`)}return n}function Ol(r,e,t,n,s){let o=n.arrays.get(r);if(!o){let i=n.cacheArrays&&!rr.has(r),c=i?ko.get(r):void 0;o={baselineLength:r.length,cacheable:i,enforceSparseHoleBudget:i,entries:new Map,length:r.length,ownEntryCount:im(r,i,c)},n.arrays.set(r,o)}for(let i of e){if(!_e(i))throw new Error("Expected array delta entry to be an object but got an invalid value");let c=am(i,t,o.baselineLength),u;o.entries.has(c)?u=o.entries.get(c):$(r,c)?(u=r[c],u==null&&o.entries.set(c,i)):(o.entries.set(c,i),o.ownEntryCount+=1);let d=Math.max(o.length,c+1);if(o.enforceSparseHoleBudget&&d-o.ownEntryCount>xl)throw new h(`Assistant stream delta contains an invalid ${t} index: ${c}`);_e(u)&&s(u,i,n),o.length=d}}function Ni(r,e,t){let n=t.records.get(r);for(let[s,o]of Object.entries(e)){if(s==="index"||s==="type")continue;let i;if(n?.has(s)?i=n.get(s):$(r,s)&&(i=r[s]),i==null){n||(n=new Map,t.records.set(r,n)),n.set(s,o);continue}_e(i)&&_e(o)?Ni(i,o,t):Array.isArray(i)&&Array.isArray(o)&&!vl(i,o)&&Ol(i,o,"array",t,Ni)}}function Fi(r){return(_e(r)||Array.isArray(r))&&rr.has(r)}function Qe(r){if(!(!_e(r)&&!Array.isArray(r)||rr.has(r))){rr.add(r),Array.isArray(r)&&ko.delete(r);for(let e of Reflect.ownKeys(r)){let t=Object.getOwnPropertyDescriptor(r,e);t&&"value"in t&&Qe(t.value)}}}function hc(r,e,t){rr.has(r)&&Qe(t),Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}function cm(r){let{index:e}=r;if(e==null)throw new Error("Expected array delta entry to have an `index` property");if(typeof e!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return e}function um(r,e,t){if(vl(r,e)){r.push(...e),ko.delete(r);return}for(let n of e){if(!_e(n))throw new Error("Expected array delta entry to be an object but got an invalid value");let s=cm(n);if($(r,s)){let o=r[s];o==null?(rr.has(r)&&Qe(n),r[s]=n):r[s]=t(o,n)}else hc(r,s,n)}}function pc(r,e){let t=rr.has(r);for(let[n,s]of Object.entries(e)){if(n==="__proto__"||n==="constructor"||n==="prototype")throw new h(`Assistant stream delta contains an unsafe property: ${n}`);if(!$(r,n)){t&&Qe(s),r[n]=s;continue}let o=r[n];if(o==null){t&&Qe(s),r[n]=s;continue}if(n==="index"||n==="type"){r[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(_e(o)&&_e(s))o=pc(o,s);else if(Array.isArray(o)&&Array.isArray(s)){um(o,s,pc);continue}else throw new TypeError(`Unhandled record type: ${sm(n)}`);r[n]=o}return r}function Co(r){if(!(!_e(r)&&!Array.isArray(r)))for(let[e,t]of Object.entries(r)){if(e==="__proto__"||e==="constructor"||e==="prototype")throw new h(`Assistant stream delta contains an unsafe property: ${e}`);Co(t)}}function Wi(r,e,t=!1){Co(e);let n=r,s=e,o=Sl(t&&!Fi(r));return Ni(n,s,o),pc(n,s),Rl(o),r}function El(r,e,t,n=!0){Co(e);let s=Sl(n&&!Fi(r));return Ol(r,e,t,s,Ni),()=>Rl(s)}var j,Re,nr,Xe,As,bs,we,Rt,Hr,sr,vt,Xr,Ce,$o,jo,or,Lo,Mo,kl,gs,Cl,To,Tl,$l,ae,jl,Ll,Ml,Bl,Dl;function lm(r){let e=Object.getOwnPropertyDescriptor(r,"event"),t=Object.getOwnPropertyDescriptor(r,"data"),n=Reflect.get(r,"event",r),s=Reflect.get(r,"data",r),o=s;if(n==="thread.message.created"||n==="thread.message.in_progress"||n==="thread.message.delta"||n==="thread.message.completed"||n==="thread.message.incomplete"||n==="thread.run.step.created"||n==="thread.run.step.in_progress"||n==="thread.run.step.delta"||n==="thread.run.step.completed"||n==="thread.run.step.failed"||n==="thread.run.step.cancelled"||n==="thread.run.step.expired"){let u=Object.getOwnPropertyDescriptor(s,"id");if(u&&"value"in u&&s.id!==u.value){let d=u.value;o=new Proxy(s,{get(m,y){return y==="id"?d:Reflect.get(m,y,m)}})}}let i=Object.freeze({event:n,data:o}),c=e!==void 0&&"value"in e&&e.value===n&&t!==void 0&&"value"in t&&t.value===s&&o===s;return{event:i,exposedEvent:c?r:{event:n,data:o}}}var ir=class r extends zt{constructor(){super(...arguments),j.add(this),Re.set(this,Object.create(null)),nr.set(this,new Map),Xe.set(this,void 0),As.set(this,Object.create(null)),bs.set(this,new Map),we.set(this,void 0),Rt.set(this,void 0),Hr.set(this,void 0),sr.set(this,void 0),vt.set(this,void 0),Xr.set(this,void 0),Ce.set(this,void 0),$o.set(this,void 0),jo.set(this,void 0),or.set(this,void 0)}[(Re=new WeakMap,nr=new WeakMap,Xe=new WeakMap,As=new WeakMap,bs=new WeakMap,we=new WeakMap,Rt=new WeakMap,Hr=new WeakMap,sr=new WeakMap,vt=new WeakMap,Xr=new WeakMap,Ce=new WeakMap,$o=new WeakMap,jo=new WeakMap,or=new WeakMap,j=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=n=>e(structuredClone(n));return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=Ee.fromReadableStream(e,this.controller);for await(let s of n)a(this,j,"m",Lo).call(this,s);if(n.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).call(this))}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let o=new r;return o._run(()=>o._runToolAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}async _createToolAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},i=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let c of i)a(this,j,"m",Lo).call(this,c);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).call(this))}static createThreadAssistantStream(e,t,n){let s=new r;return s._run(()=>s._threadAssistantStream(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static createAssistantStream(e,t,n,s){let o=new r;return o._run(()=>o._runAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),o}currentEvent(){return Qe(a(this,$o,"f")),a(this,$o,"f")}currentRun(){return Qe(a(this,jo,"f")),a(this,jo,"f")}currentMessageSnapshot(){return Qe(a(this,we,"f")),a(this,we,"f")}currentRunStepSnapshot(){return Qe(a(this,or,"f")),a(this,or,"f")}async finalRunSteps(){return await this.done(),Object.values(a(this,Re,"f"))}async finalMessages(){return await this.done(),Object.values(a(this,As,"f"))}async finalRun(){if(await this.done(),!a(this,Hr,"f"))throw new Error("Final run was not received.");return a(this,Hr,"f")}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0},o=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let i of o)a(this,j,"m",Lo).call(this,i);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).call(this))}async _createAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let o={...n,stream:!0},i=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let c of i)a(this,j,"m",Lo).call(this,c);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(a(this,j,"m",Mo).call(this))}static accumulateDelta(e,t){return Wi(e,t)}_addRun(e){return a(this,j,"m",ae).call(this,"run",e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}};Lo=function(e){if(this.ended)return;let{event:t,exposedEvent:n}=lm(e),s,o,i,c;switch(t.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{s=a(this,j,"m",Cl).call(this,t),o=t.data;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":{i=a(this,j,"m",kl).call(this,t),c=t.data;break}}switch(b(this,$o,n,"f"),a(this,j,"m",jl).call(this,n),s!==void 0&&o!==void 0&&a(this,j,"m",To).call(this,o,s),i!==void 0&&c!==void 0&&a(this,j,"m",gs).call(this,c,i),i===void 0&&a(this,Xe,"f")!==void 0&&a(this,or,"f")&&a(this,j,"m",gs).call(this,a(this,or,"f"),a(this,Xe,"f")),t.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":{a(this,j,"m",Dl).call(this,t);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":{if(i===void 0)throw new h("Received assistant run-step event without a canonical run-step ID");let u=a(this,Re,"f")[i];u&&a(this,j,"m",gs).call(this,u,i),a(this,j,"m",$l).call(this,t,i),a(this,j,"m",gs).call(this,t.data,i);let d=a(this,Re,"f")[i];d&&a(this,j,"m",gs).call(this,d,i);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{if(s!==void 0&&a(this,we,"f")&&a(this,j,"m",To).call(this,a(this,we,"f"),s),a(this,j,"m",Tl).call(this,t),s!==void 0){a(this,j,"m",To).call(this,t.data,s);let u=a(this,As,"f")[s];u&&a(this,j,"m",To).call(this,u,s)}break}case"error":throw new z(void 0,t.data,void 0,void 0);default:}},Mo=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");if(!a(this,Hr,"f"))throw new Error("Final run has not been received");return a(this,Hr,"f")},kl=function(e){let t=Object.getOwnPropertyDescriptor(e.data,"id"),n=t&&"value"in t?t.value:void 0;if(typeof n!="string"||n.length===0)throw new h("Received assistant run-step event with an invalid run-step ID");if(e.event==="thread.run.step.delta"){let s=e.data.delta;if(s&&$(s,"id"))throw new h("Run-step deltas must not contain an id field")}if(e.event==="thread.run.step.created"){if(a(this,Xe,"f")!==void 0)throw new h(`Received run-step creation for "${n}" before the active run step "${a(this,Xe,"f")}" reached a terminal state`);if($(a(this,Re,"f"),n)||a(this,nr,"f").has(n))throw new h(`Received run-step creation for run step "${n}", which has already been created`);return b(this,Xe,n,"f"),a(this,nr,"f").set(n,n),n}if(a(this,Xe,"f")!==void 0){if(n!==a(this,Xe,"f"))throw new h(`Received ${e.event} for run step "${n}", which does not match the active run step "${a(this,Xe,"f")}"`);return n}if(e.event==="thread.run.step.delta")throw $(a(this,Re,"f"),n)?new h(`Received run-step delta for "${n}" with no active run step`):new h("Received a RunStepDelta before creation of a snapshot");if($(a(this,Re,"f"),n)||a(this,nr,"f").has(n))throw new h(`Received run-step event for run step "${n}", which has already been created`);return a(this,nr,"f").set(n,n),e.event==="thread.run.step.in_progress"&&b(this,Xe,n,"f"),n},gs=function(e,t){let n=Object.getOwnPropertyDescriptor(e,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!="string"||s.length===0)throw new h("Received assistant run-step event with an invalid run-step ID");let o=a(this,nr,"f").get(s);if(o!==void 0&&o!==t)throw new h(`Received run-step creation for run step "${s}", which has already been created`);a(this,nr,"f").set(s,t)},Cl=function(e){let t=Object.getOwnPropertyDescriptor(e.data,"id"),n=t&&"value"in t?t.value:void 0;if(typeof n!="string"||n.length===0)throw new h("Received assistant message event with an invalid message ID");if(e.event==="thread.message.created"){if(a(this,we,"f"))throw new h(`Received message creation for "${n}" before the active message "${a(this,Rt,"f")}" reached a terminal state`);if($(a(this,As,"f"),n)||a(this,bs,"f").has(n))throw new h(`Received message creation for message "${n}", which has already been created`);return b(this,Rt,n,"f"),a(this,bs,"f").set(n,n),n}if(!a(this,we,"f"))throw e.event==="thread.message.delta"?new h("Received a delta with no existing snapshot (there should be one from message creation)"):new h("Received thread message event with no existing snapshot");if(n!==a(this,Rt,"f"))throw new h(`Received ${e.event} for message "${n}", which does not match the active message "${a(this,Rt,"f")}"`);return n},To=function(e,t){let n=Object.getOwnPropertyDescriptor(e,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!="string"||s.length===0)throw new h("Received assistant message event with an invalid message ID");let o=a(this,bs,"f").get(s);if(o!==void 0&&o!==t)throw new h(`Received message creation for message "${s}", which has already been created`);a(this,bs,"f").set(s,t)},Tl=function(e){let[t,n]=a(this,j,"m",Ml).call(this,e,a(this,we,"f"));if(b(this,we,t,"f"),!a(this,Rt,"f"))throw new h("Received thread message event with no active message ID");a(this,As,"f")[a(this,Rt,"f")]=t;for(let s of n){let o=t.content[s.index];o?.type==="text"&&a(this,j,"m",ae).call(this,"textCreated",o.text)}switch(e.event){case"thread.message.created":{b(this,sr,void 0,"f"),b(this,vt,void 0,"f"),a(this,j,"m",ae).call(this,"messageCreated",e.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(a(this,j,"m",ae).call(this,"messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type==="text"&&s.text){let o=s.text,i=t.content[s.index];if(i&&i.type==="text")a(this,j,"m",ae).call(this,"textDelta",o,i.text);else throw new Error("The snapshot associated with this text delta is not text or missing")}if(s.index!==a(this,sr,"f")){if(a(this,vt,"f"))switch(a(this,vt,"f").type){case"text":{a(this,j,"m",ae).call(this,"textDone",a(this,vt,"f").text,a(this,we,"f"));break}case"image_file":{a(this,j,"m",ae).call(this,"imageFileDone",a(this,vt,"f").image_file,a(this,we,"f"));break}}b(this,sr,s.index,"f")}b(this,vt,t.content[s.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(a(this,sr,"f")!==void 0){let s=e.data.content[a(this,sr,"f")];if(s)switch(s.type){case"image_file":{a(this,j,"m",ae).call(this,"imageFileDone",s.image_file,a(this,we,"f"));break}case"text":{a(this,j,"m",ae).call(this,"textDone",s.text,a(this,we,"f"));break}}}a(this,we,"f")&&a(this,j,"m",ae).call(this,"messageDone",e.data),b(this,sr,void 0,"f"),b(this,vt,void 0,"f"),b(this,we,void 0,"f"),b(this,Rt,void 0,"f")}}},$l=function(e,t){let n=a(this,j,"m",Ll).call(this,e,t);switch(b(this,or,n,"f"),e.event){case"thread.run.step.created":{b(this,Xr,void 0,"f"),b(this,Ce,void 0,"f"),a(this,j,"m",ae).call(this,"runStepCreated",e.data);break}case"thread.run.step.delta":{let s=e.data.delta;if(s.step_details&&s.step_details.type==="tool_calls"&&s.step_details.tool_calls&&n.step_details.type==="tool_calls")for(let o of s.step_details.tool_calls)o.index===a(this,Xr,"f")?a(this,j,"m",ae).call(this,"toolCallDelta",o,n.step_details.tool_calls[o.index]):(a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallDone",a(this,Ce,"f")),b(this,Xr,o.index,"f"),b(this,Ce,n.step_details.tool_calls[o.index],"f"),a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallCreated",a(this,Ce,"f")));a(this,j,"m",ae).call(this,"runStepDelta",e.data.delta,n);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{b(this,or,void 0,"f"),b(this,Xe,void 0,"f"),e.data.step_details.type==="tool_calls"&&a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallDone",a(this,Ce,"f")),a(this,j,"m",ae).call(this,"runStepDone",e.data,n),b(this,Xr,void 0,"f"),b(this,Ce,void 0,"f");break}case"thread.run.step.in_progress":break}},ae=function(e,...t){if(this._hasListeners(e))for(let n of t)Qe(n);this._emit(e,...t)},jl=function(e){a(this,j,"m",ae).call(this,"event",e)},Ll=function(e,t){switch(e.event){case"thread.run.step.created":return a(this,Re,"f")[t]=e.data,e.data;case"thread.run.step.delta":{let n=a(this,Re,"f")[t];if(!n)throw new Error("Received a RunStepDelta before creation of a snapshot");let s=e.data.delta;if(s){if($(s,"id"))throw new h("Run-step deltas must not contain an id field");let o=Wi(n,s,!0);a(this,Re,"f")[t]=o}return a(this,Re,"f")[t]}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":{a(this,Re,"f")[t]=e.data;break}}if(a(this,Re,"f")[t])return a(this,Re,"f")[t];throw new Error("No snapshot available")},Ml=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":{if(!t)throw new Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content){Co(s.delta);let o=!Fi(t),i=El(t.content,s.delta.content,"content",o);for(let c of s.delta.content)if($(t.content,c.index)){let u=t.content[c.index];t.content[c.index]=a(this,j,"m",Bl).call(this,c,u,o)}else hc(t.content,c.index,c),n.push(c);i()}return[t,n]}case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":{if(t)return[e.event==="thread.message.in_progress"?t:e.data,n];throw new Error("Received thread message event with no existing snapshot")}}throw new Error("Tried to accumulate a non-message event")},Bl=function(e,t,n){return Wi(t,e,n)},Dl=function(e){switch(b(this,jo,e.data,"f"),e.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":{b(this,Hr,e.data,"f"),a(this,Ce,"f")&&a(this,j,"m",ae).call(this,"toolCallDone",a(this,Ce,"f")),b(this,Xr,void 0,"f"),b(this,Ce,void 0,"f");break}case"thread.run.cancelling":break}};function dm(r,e){return new Promise((t,n)=>{let s,o,i=!1,c=m=>{try{e.removeEventListener("abort",m)}catch{}},u=()=>{if(s!==void 0&&(clearTimeout(s),s=void 0),o){let m=o;o=void 0,c(m)}},d=()=>{if(!i){i=!0,u();try{let m=new Y;Object.defineProperty(m,"cause",{value:e.reason,writable:!0,configurable:!0}),n(m)}catch(m){n(m)}}};if(e.aborted){d();return}s=setTimeout(()=>{i||(i=!0,u(),t())},r),o=d;try{e.addEventListener("abort",d,{once:!0}),i?c(d):e.aborted&&d()}catch(m){i?c(d):(i=!0,u(),n(m))}})}async function Bo(r,e,t,n){let s=_([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await r(s).withResponse(),{status:c}=o;if(e.includes(c)){let u=5e3,d=n?.pollIntervalMs;if(d||d===0)u=d;else{let y=i.headers.get("openai-poll-after-ms");if(y){let p=Number.parseInt(y);Number.isNaN(p)||(u=p)}}let m=n&&Object.prototype.propertyIsEnumerable.call(n,"signal")?n.signal:void 0;await(m?dm(u,m):pn(u))}else if(t.includes(c))return o}}function Nl(r,e,t,n){return Bo(s=>r.retrieve(e,t,{...n,headers:{...n?.headers,...s}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],n)}var Jr=class extends f{constructor(){super(...arguments),this.steps=new ys(this._client)}create(e,t,n){let{include:s,...o}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:s,...o}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/threads/${e}/runs`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return ir.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){return await Nl(this,e,t,n)}stream(e,t,n){return ir.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...o}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return ir.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Jr.Steps=ys;var ar=class extends f{constructor(){super(...arguments),this.runs=new Jr(this._client),this.messages=new _s(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/threads/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!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 ir.createThreadAssistantStream(e,this._client.beta.threads,t)}};ar.Runs=Jr;ar.Messages=_s;var je=class extends f{constructor(){super(...arguments),this.realtime=new Yt(this._client),this.agents=new St(this._client),this.responses=new tr(this._client),this.chatkit=new er(this._client),this.assistants=new Yn(this._client),this.threads=new ar(this._client)}};je.Realtime=Yt;je.Agents=St;je.Responses=tr;je.ChatKit=er;je.Assistants=Yn;je.Threads=ar;var Vr=class extends f{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var ws=class extends f{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...n,headers:_([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Gr=class extends f{constructor(){super(...arguments),this.content=new ws(this._client)}create(e,t,n){return this._client.post(l`/containers/${e}/files`,qt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/containers/${e}/files`,R,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};Gr.Content=ws;var cr=class extends f{constructor(){super(...arguments),this.files=new Gr(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};cr.Files=Gr;var Yr=class extends f{create(e,t){return this._client.post("/content_provenance_checks",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}};var Is=class extends f{create(e,t,n){let{include:s,...o}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:o,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:s,...o}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:o,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/conversations/${e}/items`,F,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,{...n,__security:{bearerAuth:!0}})}};var ur=class extends f{constructor(){super(...arguments),this.items=new Is(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};ur.Items=Is;function Fl(r,e,t){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&ee(r).debug("embeddings/user defined encoding_format:",e.encoding_format);let i={body:{...e,encoding_format:s},...t,__security:{bearerAuth:!0}},c=r.post("/embeddings",i);return n?c:(ee(r).debug("embeddings/decoding base64 embeddings from base64"),c._thenUnwrap(u=>{let d=u?.data;if(d!==void 0){if(!Array.isArray(d))throw new TypeError("Expected embeddings response data to be an array");let{length:m}=d;for(let y=0;y<m;y+=1)if(y in d){let p=d[y],{embedding:g}=p;if(Array.isArray(g))continue;p.embedding=Il(g)}}return u}))}var Qr=class extends f{create(e,t){return Fl(this._client,e,t)}};var Ps=class extends f{retrieve(e,t,n){let{eval_id:s,run_id:o}=t;return this._client.get(l`/evals/${s}/runs/${o}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:s,...o}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,R,{query:o,...n,__security:{bearerAuth:!0}})}};var Zr=class extends f{constructor(){super(...arguments),this.outputItems=new Ps(this._client)}create(e,t,n){return this._client.post(l`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/evals/${e}/runs`,R,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Zr.OutputItems=Ps;var lr=class extends f{constructor(){super(...arguments),this.runs=new Zr(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};lr.Runs=Zr;async function Wl(r,e,t,n){let s=new Set(["processed","error","deleted"]),o=performance.now(),i=await r.retrieve(e);for(;!i.status||!s.has(i.status);)if(await pn(t),i=await r.retrieve(e),performance.now()-o>n)throw new re({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}var en=class extends f{create(e,t){return this._client.post("/files",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){return await Wl(this,e,t,n)}};var xs=class extends f{};var Ss=class extends f{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}};var tn=class extends f{constructor(){super(...arguments),this.graders=new Ss(this._client)}};tn.Graders=Ss;var Rs=class extends f{create(e,t,n){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,le,{body:t,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,F,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};var rn=class extends f{constructor(){super(...arguments),this.permissions=new Rs(this._client)}};rn.Permissions=Rs;var vs=class extends f{list(e,t={},n){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,R,{query:t,...n,__security:{bearerAuth:!0}})}};var nn=class extends f{constructor(){super(...arguments),this.checkpoints=new vs(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,R,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};nn.Checkpoints=vs;var Ze=class extends f{constructor(){super(...arguments),this.methods=new xs(this._client),this.jobs=new nn(this._client),this.checkpoints=new rn(this._client),this.alpha=new tn(this._client)}};Ze.Methods=xs;Ze.Jobs=nn;Ze.Checkpoints=rn;Ze.Alpha=tn;var Os=class extends f{};var dr=class extends f{constructor(){super(...arguments),this.graderModels=new Os(this._client)}};dr.GraderModels=Os;var sn=class extends f{createVariation(e,t){return this._client.post("/images/variations",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",se({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Es=class extends f{accept(e,t,n){return this._client.post(l`/live/sessions/${e}/accept`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,t){return this._client.get(l`/live/sessions/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,t,n){return this._client.post(l`/live/sessions/${e}/fork`,{body:t,...n,__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(l`/live/sessions/${e}/hangup`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(l`/live/sessions/${e}/refer`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t,n){return this._client.post(l`/live/sessions/${e}/reject`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var ks=class extends f{};var Cs=class extends f{};var ft=class extends f{constructor(){super(...arguments),this.sideband=new Cs(this._client),this.forks=new ks(this._client),this.sessions=new Es(this._client)}create(e,t){return this._client.post("/live/sessions",{body:e,...t,__security:{bearerAuth:!0}})}};ft.Sideband=Cs;ft.Forks=ks;ft.Sessions=Es;var on=class extends f{retrieve(e,t){return this._client.get(l`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",le,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var an=class extends f{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};async function Ul(r,e,t,n=null){if(r.body===null||typeof r.body!="object"||Array.isArray(r.body))throw new TypeError("Multipart request body must be an object");let s=Object.fromEntries(Object.entries(r.body).filter(([,u])=>u!==void 0));if(n!==null&&Object.keys(s).length===1&&Object.prototype.hasOwnProperty.call(s,n)){let u=s[n];if(typeof u!="string")throw new TypeError("Raw multipart alternative must be a string");return{...r,body:u,headers:_([r.headers,{"content-type":t[n].content_type}])}}let o=[];for(let[u,d]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(s,u))continue;let m=s[u],y=d.json?JSON.stringify(m):m;if(typeof y!="string")throw new TypeError(`Multipart field ${u} must encode as a string`);o.push([u,wt([y],"",{type:d.content_type})]),delete s[u]}let c=(await se({...r,body:s},e)).body;if(!(c instanceof FormData))throw await c.cancel(),new TypeError("Unexpected streaming upload in typed multipart request body");for(let[u,d]of o)c.append(u,d,"");return{...r,body:c,headers:_([r.headers,{"content-type":null}])}}var Ts=class extends f{create(e,t){return this._client.post("/realtime/calls",Ul({body:e,...t,headers:_([{Accept:"application/sdp"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp"))}accept(e,t,n){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...n,headers:_([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})}};var $s=class extends f{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ot=class extends f{constructor(){super(...arguments),this.clientSecrets=new $s(this._client),this.calls=new Ts(this._client)}};Ot.ClientSecrets=$s;Ot.Calls=Ts;function ql(r,e){if(!e||!$m(e)){let t={...r,output_parsed:null,output:r.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)};return Kl(r,t)&&js(t),t}return _c(r,e)}function _c(r,e){let t=!r.status||r.status==="completed",n=r.output.map(o=>{if(o.type==="function_call")return t?Lm(e,o):{...o,parsed_arguments:null};if(o.type==="message"){let i=o.content.map(c=>c.type==="output_text"?{...c,parsed:t?Tm(e,c.text):null}:c);return{...o,content:i}}return o}),s={...r,output:n};return Kl(r,s)&&js(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let o of s.output)if(o.type==="message"){for(let i of o.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),s}function Tm(r,e){return It(r.text?.format,e)}function $m(r){return ut(r.text?.format)?!0:Array.isArray(r.tools)&&r.tools.some(e=>mc(e)||e.type==="function"&&e.strict===!0||e.type==="namespace"&&e.tools.some(t=>t.type==="function"&&(mc(t)||t.strict===!0)))}function mc(r){return r?.$brand==="auto-parseable-tool"}function jm(r,e,t){for(let n of r)if(t==null){if(n.type==="function"&&n.name===e)return n}else if(n.type==="namespace"&&n.name===t)return n.tools.find(s=>s.type==="function"&&s.name===e)}function Lm(r,e){let t=jm(r.tools??[],e.name,e.namespace),n=null;return mc(t)?n=t.$parseRaw(e.arguments):t?.strict&&(n=It({type:"json_schema",$parseRaw:void 0},e.arguments)),{...e,parsed_arguments:n}}function Kl(r,e){return!Object.getOwnPropertyDescriptor(r,"output_text")||e.output_text==null}function js(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var Ls=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw new RangeError(`missing output at index ${e}`);let n=this.capacity+e,s=t-(this.values[n]??0);if(s!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+s,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw new RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,s=0;for(;t<n;)t%2===1&&(s+=this.values[t]??0,t+=1),n%2===1&&(n-=1,s+=this.values[n]??0),t=Math.floor(t/2),n=Math.floor(n/2);return s}grow(){let e=this.capacity;this.capacity*=2;let t=Array.from({length:this.capacity*2},()=>0);for(let n=0;n<this.size;n+=1)t[this.capacity+n]=this.values[e+n]??0;for(let n=this.capacity-1;n>0;n-=1)t[n]=(t[n*2]??0)+(t[n*2+1]??0);this.values=t}};function yc(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Ls}}function Ms(r,e){if(e.type!=="message")return"";let t="";for(let n of e.content)n.type==="output_text"&&(t+=n.text);return r.outputTextLengths.set(e,t.length),t}function fr(r,e){if(r.canonicalSnapshot===e)return;let t=new Ls,n="";for(let s of e.output){let o=Ms(r,s);n+=o,t.append(o.length)}e.output_text=n,r.outputTextIndex=t,r.canonicalSnapshot=e}function Xl(r,e){r.canonicalSnapshot=void 0,r.outputTextLengths=new WeakMap,r.outputTextIndex=new Ls;let t=structuredClone(e);return!Object.getOwnPropertyDescriptor(t,"output_text")||t.output_text===null||t.output_text===void 0?fr(r,t):t.output.length===0&&t.output_text===""&&(r.canonicalSnapshot=t),t}function Do(r,e,t,n,s){let o=r.outputTextLengths.get(e);if(o!==void 0){let i=o-n.length+s.length;r.outputTextLengths.set(e,i),r.outputTextIndex.update(t,i)}}function zl(r,e,t){if(e.length===0){r.output_text+=t;return}r.output_text=r.output_text.slice(0,r.output_text.length-e.length)+t}function Mm(r,e,t,n){if(t===void 0||e?.type!=="message")return 0;if(t<e.content.length-t-1){let i=0;for(let c=0;c<t;c+=1){let u=e.content[c];u?.type==="output_text"&&(i+=u.text.length)}return i}let s=0;for(let i=t+1;i<e.content.length;i+=1){let c=e.content[i];c?.type==="output_text"&&(s+=c.text.length)}return(r.outputTextLengths.get(e)??Ms(r,e).length)-s-n.length}function Bs(r,e,t,n,s,o){if(n===s)return;let i=e.output[t];if(t===e.output.length-1&&(o===void 0||i?.type==="message"&&o===i.content.length-1)){zl(e,n,s);return}let c=Mm(r,i,o,s),u=r.outputTextIndex.prefixSum(t)+c;if(u+n.length===e.output_text.length){zl(e,n,s);return}e.output_text=e.output_text.slice(0,u)+s+e.output_text.slice(u+n.length)}var gc=new WeakMap;function pr(r,e,t,n=!1){if(!Array.isArray(r)||!Number.isSafeInteger(e)||e<0||e>r.length||(e===r.length?!n||e in r:!$(r,e)))throw new h(`missing ${t} at index ${e}`)}function qi(r,e,t){if(e!==r.length)throw new h(`missing ${t} at index ${e}`);pr(r,e,t,!0)}function B(r,e){pr(r.output,e,"output");let t=r.output[e];if(!t)throw new h(`missing output at index ${e}`);return t}function bc(r){return r.type==="function_call"||r.type==="custom_tool_call"||r.type==="shell_call"||r.type==="shell_call_output"}function Ki(r,e){if(!$(r,"type")||typeof r.type!="string")throw new h(`expected an own output item type for ${e}`);let t=r.type==="function_call"||r.type==="custom_tool_call",n=[];if($(r,"id")){if(typeof r.id!="string"||r.id.length===0)throw new h(`expected a non-empty output item id for ${e}`);n.push(`id:${r.id}`)}else if(!t)throw new h(`expected a non-empty output item id for ${e}`);if(bc(r)){if(!$(r,"call_id")||typeof r.call_id!="string"||r.call_id.length===0)throw new h(`expected a non-empty output item call_id for ${e}`);n.push(`call:${r.type}:${r.call_id}`)}return n}function Vl(r,e){for(let t of e)if(r.has(t))throw new h(`duplicate output item identity '${t}'`)}function Gl(r,e){Vl(r,e);for(let t of e)r.add(t)}function Yl(r){let e={snapshot:r,output:r.output,length:r.output.length,identities:new Set};for(let t=0;t<r.output.length;t+=1){let n=B(r,t);Gl(e.identities,Ki(n,"response snapshot"))}return e}function Bm(r,e){let t=gc.get(r);if(t&&t.snapshot===e&&t.output===e.output&&t.length===e.output.length)return t;let n=Yl(e);return gc.set(r,n),n}function Hl(r,e){let t=yc(),n=Xl(t,e),s=Yl(n);return r.canonicalSnapshot=t.canonicalSnapshot,r.outputTextLengths=t.outputTextLengths,r.outputTextIndex=t.outputTextIndex,gc.set(r,s),n}var Ac={"response.output_text.delta":"message","response.output_text.done":"message","response.output_text.annotation.added":"message","response.refusal.delta":"message","response.refusal.done":"message","response.function_call_arguments.delta":"function_call","response.function_call_arguments.done":"function_call","response.custom_tool_call_input.delta":"custom_tool_call","response.custom_tool_call_input.done":"custom_tool_call","response.mcp_call_arguments.delta":"mcp_call","response.mcp_call_arguments.done":"mcp_call","response.mcp_call.in_progress":"mcp_call","response.mcp_call.completed":"mcp_call","response.mcp_call.failed":"mcp_call","response.shell_call_output_content.delta":"shell_call_output","response.shell_call_output_content.done":"shell_call_output","response.reasoning_text.delta":"reasoning","response.reasoning_text.done":"reasoning","response.reasoning_summary_part.added":"reasoning","response.reasoning_summary_part.done":"reasoning","response.reasoning_summary_text.delta":"reasoning","response.reasoning_summary_text.done":"reasoning","response.code_interpreter_call_code.delta":"code_interpreter_call","response.code_interpreter_call_code.done":"code_interpreter_call","response.code_interpreter_call.in_progress":"code_interpreter_call","response.code_interpreter_call.interpreting":"code_interpreter_call","response.code_interpreter_call.completed":"code_interpreter_call","response.file_search_call.in_progress":"file_search_call","response.file_search_call.searching":"file_search_call","response.file_search_call.completed":"file_search_call","response.web_search_call.in_progress":"web_search_call","response.web_search_call.searching":"web_search_call","response.web_search_call.completed":"web_search_call","response.image_generation_call.in_progress":"image_generation_call","response.image_generation_call.generating":"image_generation_call","response.image_generation_call.completed":"image_generation_call","response.image_generation_call.partial_image":"image_generation_call","response.mcp_list_tools.in_progress":"mcp_list_tools","response.mcp_list_tools.completed":"mcp_list_tools","response.mcp_list_tools.failed":"mcp_list_tools","response.compaction.compacting":"compaction"};function Dm(r){return r.type==="response.content_part.added"||r.type==="response.content_part.done"?r.part.type==="reasoning_text"?"reasoning":"message":Ac[r.type]}function Nm(r,e){let t=B(e,r.output_index),n=r.item;if(Ki(t,r.type),Ki(n,r.type),!$(n,"type")||t.type!==n.type)throw new h(`expected output item type '${t.type}', got '${n.type}'`);let s=$(t,"id")?t.id:void 0,o=$(n,"id")?n.id:void 0;if(s!==o)throw new h(`expected output item id '${s}', got '${o}'`);if(bc(t)&&bc(n)&&t.call_id!==n.call_id)throw new h(`expected output item call_id '${t.call_id}', got '${n.call_id}'`)}function Fm(r,e,t){if(r.type==="response.output_item.done"){Nm(r,e);return}if(t&&(r.type==="response.shell_call_command.added"||r.type==="response.shell_call_command.delta"||r.type==="response.shell_call_command.done")){let c=B(e,r.output_index);if(!$(c,"type")||c.type!=="shell_call")throw new h(`expected output item type 'shell_call', got '${c.type}'`);return}if(r.type!=="response.content_part.added"&&r.type!=="response.content_part.done"&&!$(Ac,r.type))return;let n=r;if(!$(r,"item_id")||typeof n.item_id!="string"||n.item_id.length===0)throw new h(`expected a non-empty item_id for ${r.type}`);let s=B(e,n.output_index),o=$(s,"id")?s.id:void 0;if(o!==n.item_id)throw new h(`expected item_id '${o}', got '${n.item_id}'`);let i=Dm(n);if(s.type!==i)throw new h(`expected output item type '${i}', got '${s.type}'`)}function Te(r,e){pr(r,e,"content");let t=r[e];if(!t)throw new h(`missing content at index ${e}`);return t}function Jl(r,e,t){let n=r.output.find(s=>s.type==="shell_call"&&s.call_id===e.call_id);for(n?pr(n.action.commands,t,"command"):pr(e.output,t,"content",!0);e.output.length<=t;)e.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return Te(e.output,t)}function Wm(r){return new Set(r)}var Um=Wm(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.compaction.compacting","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);function Ui(r){throw new h("Unhandled response stream event: unknown")}var qm=["item_id","output_index","content_index","annotation_index","command_index","summary_index"];function Km(r){let e;try{e=Object.getOwnPropertyDescriptor(r,"type")}catch{return Ui(r)}let t=e?.value;if(typeof t!="string"||!Um.has(t))return Ui(r);let n=new Map([["type",t]]);if(t==="response.output_item.added"||t==="response.output_item.done"||t==="response.content_part.added"||t==="response.content_part.done"||t==="response.shell_call_command.added"||t==="response.shell_call_command.delta"||t==="response.shell_call_command.done"||$(Ac,t))try{for(let o of qm){let i=Object.getOwnPropertyDescriptor(r,o);n.set(o,i?r[o]:void 0)}t==="response.output_item.done"?n.set("item",structuredClone(r.item)):(t==="response.content_part.added"||t==="response.content_part.done")&&n.set("part",structuredClone(r.part))}catch{return Ui(r)}return new Proxy(r,{get(o,i){return n.has(i)?n.get(i):Reflect.get(o,i,o)}})}function zm(r,e,t){switch(r.type){case"response.output_item.added":{qi(e.output,r.output_index,"output");let n=Bm(t,e),s=structuredClone(r.item),o=Ki(s,r.type);Vl(n.identities,o),s.type==="message"&&fr(t,e),e.output.push(s),Gl(n.identities,o),n.length=e.output.length;let i=Ms(t,s);return t.canonicalSnapshot===e&&t.outputTextIndex.append(i.length),i&&(e.output_text+=i),!0}case"response.output_item.done":{let n=B(e,r.output_index),s=Ms(t,n),o=r.item;(n.type==="message"||o.type==="message")&&fr(t,e),e.output[r.output_index]=o;let i=Ms(t,o);return t.canonicalSnapshot===e&&t.outputTextIndex.update(r.output_index,i.length),Bs(t,e,r.output_index,s,i),!0}default:return!1}}function Xm(r,e,t){switch(r.type){case"response.content_part.added":{let n=B(e,r.output_index),{type:s}=n,{part:o}=r;if(s==="message"&&o.type!=="reasoning_text"){qi(n.content,r.content_index,"content");let i=o;i.type==="output_text"&&fr(t,e),n.content.push(i),i.type==="output_text"&&(Do(t,n,r.output_index,"",i.text),Bs(t,e,r.output_index,"",i.text,r.content_index))}else if(s==="reasoning"&&o.type==="reasoning_text"){let i=n.content??[];qi(i,r.content_index,"content"),n.content||(n.content=i),i.push(o)}return!0}default:return!1}}function Hm(r,e,t){switch(r.type){case"response.content_part.done":{let n=B(e,r.output_index),{part:s}=r;if(n.type==="message"&&s.type!=="reasoning_text"){let o=Te(n.content,r.content_index),i=o.type==="output_text"?o.text:"",c=s;(o.type==="output_text"||c.type==="output_text")&&fr(t,e),n.content[r.content_index]=c;let u=c.type==="output_text"?c.text:"";Do(t,n,r.output_index,i,u),Bs(t,e,r.output_index,i,u,r.content_index)}else if(n.type==="reasoning"&&s.type==="reasoning_text"){let{content:o}=n;if(!o)throw new h(`missing content at index ${r.content_index}`);Te(o,r.content_index),o[r.content_index]=s}return!0}default:return!1}}function Jm(r,e,t){switch(r.type){case"response.output_text.delta":{let n=B(e,r.output_index);if(n.type==="message"){let s=Te(n.content,r.content_index);if(s.type!=="output_text")throw new h(`expected content to be 'output_text', got ${s.type}`);let o=s.text;fr(t,e),s.text=o+r.delta,Do(t,n,r.output_index,o,s.text),r.output_index===e.output.length-1&&r.content_index===n.content.length-1?e.output_text+=r.delta:Bs(t,e,r.output_index,o,s.text,r.content_index)}return!0}case"response.output_text.done":{let n=B(e,r.output_index);if(n.type==="message"){let s=Te(n.content,r.content_index);if(s.type!=="output_text")throw new h(`expected content to be 'output_text', got ${s.type}`);let o=s.text;fr(t,e),s.text=r.text,Do(t,n,r.output_index,o,r.text),Bs(t,e,r.output_index,o,r.text,r.content_index)}return!0}case"response.output_text.annotation.added":{let n=B(e,r.output_index);if(n.type==="message"){let s=Te(n.content,r.content_index);if(s.type!=="output_text")throw new h(`expected content to be 'output_text', got ${s.type}`);pr(s.annotations,r.annotation_index,"annotation",!0),s.annotations[r.annotation_index]=structuredClone(r.annotation)}return!0}default:return!1}}function Vm(r,e){switch(r.type){case"response.refusal.delta":{let t=B(e,r.output_index);if(t.type==="message"){let n=Te(t.content,r.content_index);if(n.type!=="refusal")throw new h(`expected content to be 'refusal', got ${n.type}`);n.refusal+=r.delta}return!0}case"response.refusal.done":{let t=B(e,r.output_index);if(t.type==="message"){let n=Te(t.content,r.content_index);if(n.type!=="refusal")throw new h(`expected content to be 'refusal', got ${n.type}`);n.refusal=r.refusal}return!0}case"response.function_call_arguments.delta":{let t=B(e,r.output_index);return t.type==="function_call"&&(t.arguments+=r.delta),!0}case"response.function_call_arguments.done":{let t=B(e,r.output_index);return t.type==="function_call"&&(t.arguments=r.arguments),!0}case"response.custom_tool_call_input.delta":{let t=B(e,r.output_index);return t.type==="custom_tool_call"&&(t.input+=r.delta),!0}case"response.custom_tool_call_input.done":{let t=B(e,r.output_index);return t.type==="custom_tool_call"&&(t.input=r.input),!0}case"response.mcp_call_arguments.delta":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.arguments+=r.delta),!0}case"response.mcp_call_arguments.done":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.arguments=r.arguments),!0}default:return!1}}function Gm(r,e){switch(r.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let t=B(e,r.output_index);if(t.type==="shell_call"){let n=r.type==="response.shell_call_command.added";pr(t.action.commands,r.command_index,"command",n),t.action.commands[r.command_index]=r.command}return!0}case"response.shell_call_command.delta":{let t=B(e,r.output_index);return t.type==="shell_call"&&(pr(t.action.commands,r.command_index,"command"),t.action.commands[r.command_index]+=r.delta),!0}case"response.shell_call_output_content.delta":{let t=B(e,r.output_index);if(t.type==="shell_call_output"){let n=Jl(e,t,r.command_index);n.stdout+=r.delta.stdout??"",n.stderr+=r.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{let t=B(e,r.output_index);if(t.type==="shell_call_output"){let n=Te(r.output,0);Jl(e,t,r.command_index),t.output[r.command_index]=structuredClone(n)}return!0}default:return!1}}function Ym(r,e){switch(r.type){case"response.reasoning_text.delta":{let t=B(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new h(`missing content at index ${r.content_index}`);let n=Te(t.content,r.content_index);if(n.type!=="reasoning_text")throw new h(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=r.delta}return!0}case"response.reasoning_text.done":{let t=B(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new h(`missing content at index ${r.content_index}`);let n=Te(t.content,r.content_index);if(n.type!=="reasoning_text")throw new h(`expected content to be 'reasoning_text', got ${n.type}`);n.text=r.text}return!0}case"response.reasoning_summary_part.added":{let t=B(e,r.output_index);return t.type==="reasoning"&&(qi(t.summary,r.summary_index,"content"),t.summary.push(structuredClone(r.part))),!0}case"response.reasoning_summary_part.done":{let t=B(e,r.output_index);return t.type==="reasoning"&&(Te(t.summary,r.summary_index),t.summary[r.summary_index]=structuredClone(r.part)),!0}case"response.reasoning_summary_text.delta":{let t=B(e,r.output_index);if(t.type==="reasoning"){let n=Te(t.summary,r.summary_index);n.text+=r.delta}return!0}case"response.reasoning_summary_text.done":{let t=B(e,r.output_index);if(t.type==="reasoning"){let n=Te(t.summary,r.summary_index);n.text=r.text}return!0}default:return!1}}function Qm(r,e){switch(r.type){case"response.code_interpreter_call_code.delta":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.code=(t.code??"")+r.delta),!0}case"response.code_interpreter_call_code.done":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.code=r.code),!0}case"response.code_interpreter_call.in_progress":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="in_progress"),!0}case"response.code_interpreter_call.interpreting":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="interpreting"),!0}case"response.code_interpreter_call.completed":{let t=B(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="completed"),!0}default:return!1}}function Zm(r,e){switch(r.type){case"response.file_search_call.in_progress":{let t=B(e,r.output_index);return t.type==="file_search_call"&&(t.status="in_progress"),!0}case"response.file_search_call.searching":{let t=B(e,r.output_index);return t.type==="file_search_call"&&(t.status="searching"),!0}case"response.file_search_call.completed":{let t=B(e,r.output_index);return t.type==="file_search_call"&&(t.status="completed"),!0}case"response.web_search_call.in_progress":{let t=B(e,r.output_index);return t.type==="web_search_call"&&(t.status="in_progress"),!0}case"response.web_search_call.searching":{let t=B(e,r.output_index);return t.type==="web_search_call"&&(t.status="searching"),!0}case"response.web_search_call.completed":{let t=B(e,r.output_index);return t.type==="web_search_call"&&(t.status="completed"),!0}default:return!1}}function e_(r,e){switch(r.type){case"response.image_generation_call.in_progress":{let t=B(e,r.output_index);return t.type==="image_generation_call"&&(t.status="in_progress"),!0}case"response.image_generation_call.generating":{let t=B(e,r.output_index);return t.type==="image_generation_call"&&(t.status="generating"),!0}case"response.image_generation_call.completed":{let t=B(e,r.output_index);return t.type==="image_generation_call"&&(t.status="completed"),!0}case"response.mcp_call.in_progress":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.status="in_progress"),!0}case"response.mcp_call.completed":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.status="completed"),!0}case"response.mcp_call.failed":{let t=B(e,r.output_index);return t.type==="mcp_call"&&(t.status="failed"),!0}default:return!1}}function t_(r){switch(r.type){case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":return!0;default:return!1}}function r_(r){switch(r.type){case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.compaction.compacting":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":return!0;default:return!1}}function zi(){return yc()}function Ql(r,e,t,n=!1,s){let o=Km(r);if(s&&o.type!=="keepalive"&&s(o),!e){if(o.type!=="response.created")throw new h(`When snapshot hasn't been set yet, expected 'response.created' event, got ${o.type}`);return Hl(t,o.response)}return Fm(o,e,n),zm(o,e,t)||Xm(o,e,t)||Hm(o,e,t)||Jm(o,e,t)||Vm(o,e)||Gm(o,e)||Ym(o,e)||Qm(o,e)||Zm(o,e)||e_(o,e)?e:t_(o)?Hl(t,o.response):r_(o)?e:Ui(o)}var hr,Xi,cn,Hi,No,wc,Ic,Pc,Ji=class r extends zt{constructor(e){super(),hr.add(this),Xi.set(this,void 0),cn.set(this,void 0),Hi.set(this,void 0),No.set(this,zi()),b(this,Xi,e,"f")}static createResponse(e,t,n){let s=new r(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),a(this,hr,"m",wc).call(this);let s,o=null;"response_id"in t?(s=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):s=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let i of s)a(this,hr,"m",Ic).call(this,i,o);if(s.controller.signal?.aborted)throw this._userAbortError();return a(this,hr,"m",Pc).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,hr,"m",wc).call(this),this._connected();let n=Ee.fromReadableStream(e,this.controller);for await(let s of n)a(this,hr,"m",Ic).call(this,s,null);if(n.controller.signal?.aborted)throw this._userAbortError();return a(this,hr,"m",Pc).call(this)}[(Xi=new WeakMap,cn=new WeakMap,Hi=new WeakMap,No=new WeakMap,hr=new WeakSet,wc=function(){this.ended||(b(this,cn,void 0,"f"),b(this,No,zi(),"f"))},Ic=function(t,n){if(this.ended)return;let s=(c,u)=>{(n==null||u.sequence_number>n)&&this._emit(c,u)};if(t.type==="error"){let c="error"in t&&typeof t.error=="object"&&t.error!==null?t.error:t;throw new z(void 0,c,t.message,void 0)}let o=t,i=Ql(t,a(this,cn,"f"),a(this,No,"f"),!0,c=>{o=c});switch(b(this,cn,i,"f"),s("event",t),o.type){case"response.output_text.delta":{let c=i.output[o.output_index];if(!c)throw new h(`missing output at index ${o.output_index}`);if(c.type==="message"){let u=c.content[o.content_index];if(!u)throw new h(`missing content at index ${o.content_index}`);if(u.type!=="output_text")throw new h(`expected content to be 'output_text', got ${u.type}`);s("response.output_text.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,content_index:o.content_index,snapshot:u.text})}break}case"response.function_call_arguments.delta":{let c=i.output[o.output_index];if(!c)throw new h(`missing output at index ${o.output_index}`);c.type==="function_call"&&s("response.function_call_arguments.delta",{...o,type:o.type,item_id:o.item_id,output_index:o.output_index,snapshot:c.arguments});break}default:{s(o.type,t);break}}},Pc=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=a(this,cn,"f");if(!t)throw new h("request ended without sending any events");b(this,cn,void 0,"f"),b(this,No,zi(),"f");let n=n_(t,a(this,Xi,"f"));return b(this,Hi,n,"f"),n},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=n=>e(n);return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=a(this,Hi,"f");if(!e)throw new h("stream ended without producing a Response");return e}};function n_(r,e){return ql(r,e)}var Ds=class extends f{list(e,t={},n){return this._client.getAPIList(l`/responses/${e}/input_items`,R,{query:t,...n,__security:{bearerAuth:!0}})}};var Ns=class extends f{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var pt=class extends f{constructor(){super(...arguments),this.inputItems=new Ds(this._client),this.inputTokens=new Ns(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&js(n),n))}retrieve(e,t={},n){return this._client.get(l`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&js(s),s))}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>_c(n,e))}stream(e,t){return Ji.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};pt.InputItems=Ds;pt.InputTokens=Ns;var Fs=class extends f{retrieve(e,t){return this._client.get(l`/safety/alerts/${e}`,{...t,__security:{bearerAuth:!0}})}};var mr=class extends f{constructor(){super(...arguments),this.alerts=new Fs(this._client)}};mr.Alerts=Fs;var Ws=class extends f{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Us=class extends f{retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...n,headers:_([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var un=class extends f{constructor(){super(...arguments),this.content=new Us(this._client)}create(e,t={},n){return this._client.post(l`/skills/${e}/versions`,qt({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/skills/${e}/versions`,R,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};un.Content=Us;var Et=class extends f{constructor(){super(...arguments),this.content=new Ws(this._client),this.versions=new un(this._client)}create(e={},t){return this._client.post("/skills",qt({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(l`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};Et.Content=Ws;Et.Versions=un;var qs=class extends f{create(e,t,n){return this._client.post(l`/uploads/${e}/parts`,se({body:t,...n,__security:{bearerAuth:!0}},this._client))}};var _r=class extends f{constructor(){super(...arguments),this.parts=new qs(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(l`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};_r.Parts=qs;function Zl(r,e,t,n){return Bo(s=>r.retrieve(t,{vector_store_id:e},{...n,headers:s}),["in_progress"],["failed","cancelled","completed"],n)}function ed(r,e,t,n){return Bo(s=>r.retrieve(t,{vector_store_id:e},{...n,headers:s}),["in_progress"],["failed","cancelled","completed"],n)}var td=async r=>{let e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length)throw Object.defineProperty(new Error(`${t.length} promise(s) failed`),"rejections",{configurable:!0,value:t.map(({reason:s})=>s),writable:!0});let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};async function rd(r,e,t,n,s,o){if(n==null||n.length===0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=o?.maxConcurrency??5,c=Math.min(i,n.length);if(c===0)throw new RangeError("maxConcurrency must be greater than 0");let u=n.values(),d=[...s];async function m(p){for(let g of p){let A=await e.files.create({file:g,purpose:"assistants"},o);d.push(A.id)}}let y=[];y.length=c;for(let p=0;p<y.length;p+=1)y[p]=m(u);return await td(y),await r.createAndPoll(t,{file_ids:d},o)}var Ks=class extends f{create(e,t,n){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...o}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,R,{query:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){return await ed(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){return await rd(this,this._client,e,t,n,s)}};var zs=class extends f{create(e,t,n){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:s,...o}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(l`/vector_stores/${e}/files`,R,{query:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){return await Zl(this,e,t,n)}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,le,{...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};var kt=class extends f{constructor(){super(...arguments),this.files=new zs(this._client),this.fileBatches=new Ks(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(l`/vector_stores/${e}`,{body:t,...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(l`/vector_stores/${e}/search`,le,{body:t,method:"post",...n,headers:_([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})}};kt.Files=zs;kt.FileBatches=Ks;var ln=class extends f{create(e,t){return this._client.post("/videos",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",F,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(l`/videos/${e}/content`,{query:t,...n,headers:_([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",se({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(l`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(l`/videos/${e}/remix`,qt({body:t,...n,__security:{bearerAuth:!0}},this._client))}};var nd=32,p_=32;function xc(r){return r.split(" ",nd+1).length>nd}function*Sc(r){let e=0;for(;e<=r.length;){let t=r.indexOf(" ",e),n=r.slice(e,t===-1?void 0:t);if(yield n.startsWith("v1,")?n.slice(3):n,t===-1)break;e=t+1}}function sd(r){try{let e=Di(r);return e.byteLength===p_?e:void 0}catch{return}}function h_(r){for(let e of Sc(r)){let t=sd(e);if(t)return t}}function m_(r,e,t){let n=t;for(let s of Sc(r)){let o=sd(s);if(!o)continue;let i=0;for(let[c,u]of o.entries())i|=u^(e[c]??0);i===0&&(n=o)}return n}async function od(r,e,t,n,s,o){let i=Number.parseInt(t,10);if(Number.isNaN(i))throw new Oe("Invalid webhook timestamp format");let c=Math.floor(Date.now()/1e3);if(c-i>o)throw new Oe("Webhook timestamp is too old");if(i>c+o)throw new Oe("Webhook timestamp is too new");let u=xc(e),d=u?h_(e):void 0;if(u&&!d)throw new Oe("The given webhook signature does not match the expected signature");let m=Uint8Array.from(s.startsWith("whsec_")?Di(s.slice(6)):ye(s)),y=n?`${n}.${t}.${r}`:`${t}.${r}`,p=Uint8Array.from(ye(y)),g=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,u?["sign","verify"]:["verify"]);if(u&&d){let A=new Uint8Array(await crypto.subtle.sign("HMAC",g,p)),w=m_(e,A,d);try{if(await crypto.subtle.verify("HMAC",g,Uint8Array.from(w),p))return}catch{}throw new Oe("The given webhook signature does not match the expected signature")}for(let A of Sc(e))try{let w=Uint8Array.from(Di(A));if(await crypto.subtle.verify("HMAC",g,w,p))return}catch{}throw new Oe("The given webhook signature does not match the expected signature")}var Xs=class extends f{list(e){return this._client.get("/webhook_event_types",{...e,__security:{bearerAuth:!0}})}};var Hs,id,Vi,yr=class extends f{constructor(){super(...arguments),Hs.add(this),this.eventTypes=new Xs(this._client)}create(e,t){return this._client.post("/webhook_endpoints",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(l`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(l`/webhook_endpoints/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/webhook_endpoints",R,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(l`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}rotateSecret(e,t={},n){return this._client.post(l`/webhook_endpoints/${e}/rotate_secret`,{body:t,...n,__security:{bearerAuth:!0}})}test(e,t,n){return this._client.post(l`/webhook_endpoints/${e}/test`,{body:t,...n,__security:{bearerAuth:!0}})}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle?.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");a(this,Hs,"m",id).call(this,n);let o=_([t]).values,i=a(this,Hs,"m",Vi).call(this,o,"webhook-signature"),c=a(this,Hs,"m",Vi).call(this,o,"webhook-timestamp"),u=a(this,Hs,"m",Vi).call(this,o,"webhook-id");if(xc(i)&&typeof crypto.subtle.sign!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");return await od(e,i,c,u,n,s)}};Hs=new WeakSet,id=function(e){if(typeof e!="string"||e.length===0)throw new 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")},Vi=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};yr.EventTypes=Xs;async function Rc(r){let e,t=await r._callApiKey(n=>{e=n});return{apiKey:e===void 0?r.apiKey:e,isProvider:t}}var cd=Symbol.for("openai.node.providerDefinitions.v1"),ud=globalThis,ld=ud[cd],dd=ld??new WeakMap;ld||Object.defineProperty(ud,cd,{value:dd});function fd(r){let e=dd.get(r);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var vc,et,Fo,V,Gi,Ct,Uo,Wo,_d;function pd(){if(Hc())return!0;let r=globalThis;return typeof r.WorkerGlobalScope=="function"&&r instanceof r.WorkerGlobalScope&&typeof r.WorkerNavigator=="function"&&r.navigator instanceof r.WorkerNavigator&&typeof r.navigator?.userAgent=="string"&&r.navigator.userAgent!=="Cloudflare-Workers"&&r.process?.versions?.node===void 0&&r.Deno===void 0&&r.Bun===void 0&&r.EdgeRuntime===void 0&&r.WebSocketPair===void 0}var y_="workload-identity-auth",hd=Symbol("inheritedDataResidencySelection"),C=class{constructor(e={}){vc.add(this),Fo.set(this,void 0),V.set(this,void 0),Gi.set(this,void 0),Ct.set(this,void 0),Uo.set(this,!1),Wo.set(this,new WeakMap),this.completions=new Vr(this),this.chat=new Jt(this),this.embeddings=new Qr(this),this.files=new en(this),this.images=new sn(this),this.contentProvenanceChecks=new Yr(this),this.audio=new dt(this),this.moderations=new an(this),this.models=new on(this),this.fineTuning=new Ze(this),this.graders=new dr(this),this.vectorStores=new kt(this),this.safety=new mr(this),this.webhooks=new yr(this),this.beta=new je(this),this.batches=new Fr(this),this.uploads=new _r(this),this.admin=new Gt(this),this.responses=new pt(this),this.live=new ft(this),this.realtime=new Ot(this),this.conversations=new ur(this),this.evals=new lr(this),this.containers=new cr(this),this.skills=new Et(this),this.videos=new ln(this);let{credential:t,options:n}=Cu(e);e=n;let s=pa(e),o=e.provider,{baseURL:i=o?null:Se("OPENAI_BASE_URL"),dataResidency:c,[hd]:u=!1,apiKey:d=o?null:Se("OPENAI_API_KEY")??null,adminAPIKey:m=o?null:Se("OPENAI_ADMIN_KEY")??null,organization:y=o?null:Se("OPENAI_ORG_ID")??null,project:p=o?null:Se("OPENAI_PROJECT_ID")??null,webhookSecret:g=Se("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:A,x509Transport:w,credential:S,...E}=e;if(o){let O=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter(v=>(v==="workloadIdentity"?A:e[v])!=null);if(O.length)throw new h(`The \`provider\` option cannot be used with ${O.map(v=>`\`${v}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let P=oi(A)?{x509:A,legacy:void 0}:{x509:void 0,legacy:A},L=P.x509,I=L!==void 0,T=o?fd(o):void 0,x={apiKey:d,adminAPIKey:m,organization:y,project:p,webhookSecret:g,workloadIdentity:A,x509Transport:w,provider:o,...E,baseURL:T?.baseURL??s??(i||(I?uu:"https://api.openai.com/v1"))};if(w&&!I)throw new h("An X.509 transport requires an X.509 workload identity.");if(I){if(s!==void 0||u)throw new h("X.509 workload identity does not support data residency selection.");if(e.fetch!==void 0)throw new h("X.509 workload identity does not support a custom fetch implementation.");if(_n(x.baseURL),io(x.fetchOptions),this.fetchWithAuth!==et.prototype.fetchWithAuth||this.fetchWithTimeout!==et.prototype.fetchWithTimeout)throw new h("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(d&&A)throw new h("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!T&&!d&&!m&&!A)throw new h("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!x.dangerouslyAllowBrowser&&pd())throw new h(`It looks like you're running in a browser-like environment.
|
|
24
|
-
|
|
25
|
-
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
26
|
-
If you understand the risks and have appropriate mitigations in place,
|
|
27
|
-
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
28
|
-
|
|
29
|
-
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
30
|
-
|
|
31
|
-
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
32
|
-
`);this.baseURL=x.baseURL,b(this,Uo,s!==void 0||u,"f"),this.timeout=x.timeout??et.DEFAULT_TIMEOUT,this.logger=x.logger??console;let M="warn";this.logLevel=M,this.logLevel=sa(x.logLevel,"ClientOptions.logLevel",this)??sa(Se("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??M,this.fetchOptions=x.fetchOptions,this.maxRetries=x.maxRetries??2,this.fetch=x.fetch??Ys(),b(this,Fo,Gc,"f");let k=o||t?void 0:Se("OPENAI_CUSTOM_HEADERS");if(k){let O={};for(let v of k.split(`
|
|
33
|
-
`)){let K=v.indexOf(":");K>=0&&(O[v.substring(0,K).trim()]=v.substring(K+1).trim())}x.defaultHeaders=_([O,x.defaultHeaders])}if(this._options=x,this._provider=T,L){let O=new Ae(L,w,y,p);this._workloadIdentityAuth=O,b(this,V,O,"f"),b(this,Gi,t,"f"),b(this,Ct,O.fetch(),"f"),this.fetch=a(this,Ct,"f"),bu(this)}else P.legacy&&(this._workloadIdentityAuth=new ei(P.legacy,this.fetch));this.apiKey=typeof d=="string"?d:null,this.adminAPIKey=m,this.organization=y,this.project=p,this.webhookSecret=g}withOptions(e){let t=pa(e),n=a(this,V,"f"),s={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:a(this,V,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:n?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:o,provider:i}=Tu(s,e,a(this,Gi,"f"),n!==void 0);t!==void 0&&delete s.baseURL;let c={...s,...e,credential:o,provider:i,[hd]:a(this,Uo,"f")&&t===void 0&&!$(e,"baseURL")&&e.credential===void 0&&!i},u=new this.constructor(c);return i&&new URL(u.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(u._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),u.fetchOptions=e.fetchOptions,u.fetch=e.fetch??Ys(),u.organization=e.organization??null,u.project=e.project??null),a(this,V,"f")&&a(u,V,"f")&&this.baseURL===u.baseURL&&a(this,V,"f").matches(a(u,V,"f"))&&(u._workloadIdentityAuth=a(this,V,"f"),b(u,V,a(this,V,"f"),"f"),b(u,Ct,a(this,Ct,"f"),"f")),u}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e){return Object.fromEntries(_([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]).values)}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return(a(this,V,"f")??this._workloadIdentityAuth)instanceof Ae&&t.adminAPIKeyAuth&&this.adminAPIKey!==null?await this.adminAPIKeyAuth(e):_([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=a(this,V,"f")??this._workloadIdentityAuth;if(t){if(t instanceof Ae){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==et.prototype.fetchWithAuth||this.fetchWithTimeout!==et.prototype.fetchWithTimeout))throw new h("X.509 workload identity does not support overridden fetch dispatch hooks.");let o=t.headerSnapshots();if(!Ae.shouldAuthenticate(e,o.defaultHeaders,o.requestHeaders))return}let s=t instanceof Ae?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken();return _([{Authorization:`Bearer ${s}`}])}let{apiKey:n}=await Rc(this);if(n!=null)return _([{Authorization:`Bearer ${n}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return _([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return au(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${Je()}`}makeStatusError(e,t,n,s){let o=t&&typeof t=="object"&&t.error==null?{error:t}:t;return z.generate(e,o,n,s)}_hasApiKeyProvider(){return typeof this._options.apiKey=="function"}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;let t=this._options.apiKey;if(typeof t!="function")return e?.(this.apiKey),!1;let n;try{n=await t()}catch(s){throw s instanceof h?s:new h(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new h(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,e?.(this.apiKey),!0}buildURL(e,t,n){let s=!a(this,vc,"m",_d).call(this)&&n||this.baseURL,o=Ec(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery(),c=Object.fromEntries(o.searchParams);return(!Zi(i)||!Zi(c))&&(t={...c,...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}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(s=>({method:e,path:t,...s})))}request(e,t=null){let n=a(this,V,"f")??this._workloadIdentityAuth,s=n instanceof Ae?Promise.resolve(e).then(o=>n.runRequest(()=>this.makeRequest(o,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(s)}responsePromise(e,t=(n,s)=>this.parseResponseWithTimeout(n,s)){let n=new Ir(this,e,(s,o)=>{let i=a(this,Wo,"f").get(o.controller)?.continueRequest;return i?i(()=>t(s,o)):t(s,o)});return n.withResponse=async()=>{let s=await n,{response:o}=await e;return{data:s,response:o,request_id:o.headers.get("x-request-id")}},n._thenUnwrap=s=>this.responsePromise(e,async(o,i)=>ro(s(await t(o,i),i),i.response)),n}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||t.response.status===204||t.response.headers.get("content-length")==="0")return wr(e,t);for(;;){let n=a(this,Wo,"f").get(t.controller),s=n?.timeout??t.options.timeout??this.timeout,o=n?.authentication,i=o?t.controller.signal:t.options.signal,c=()=>o&&i?this._makeUserAbortError(i):new Y,u;try{u=o?.remainingTimeout(t.options,s)??Math.max(0,t.startTime+s-Date.now())}catch(p){let g=i?.aborted?c():void 0;throw t.controller.abort(),_t(t.response.body).catch(()=>{}),g??p}let d,m,y=!1;try{if(i?.aborted&&n?.helperMethod!=="runTools")throw c();let p=new Promise((g,A)=>{d=setTimeout(()=>{y=!0,t.controller.abort(),A(new re)},u),i&&(m=()=>{y||A(c())},i.addEventListener("abort",m,{once:!0}))});return await Promise.race([wr(e,t),p])}catch(p){if(i?.aborted&&!y)throw c();if(!y)throw o&&p instanceof SyntaxError?new SyntaxError("X.509 workload identity API response contains invalid JSON."):o&&!(p instanceof h)?new De({message:"X.509 workload identity API response body could not be read."}):p;let g=n?.retriesRemaining??0;if(!g||n?.hasStreamingBody||t.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&t.options.body instanceof globalThis.ReadableStream||typeof t.options.body=="object"&&t.options.body!==null&&(Symbol.asyncIterator in t.options.body||Symbol.iterator in t.options.body&&"next"in t.options.body&&typeof t.options.body.next=="function"))throw new re;d!==void 0&&clearTimeout(d),m&&i?.removeEventListener("abort",m),m=void 0;let A=await this.retryRequest(t.options,g,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,A)}finally{d!==void 0&&clearTimeout(d),m&&i?.removeEventListener("abort",m)}}}async readX509ResponseError(e,t,n,s,o){let i=new AbortController,c=s.signal,u=!1,d=()=>i.abort(c.reason);c.addEventListener("abort",d,{once:!0}),c.aborted&&d();try{let m=o.remainingTimeout(t,n),y=o.waitForRetry(m,i.signal).then(()=>{throw new re}),p=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),y]);if(c.aborted)throw this._makeUserAbortError(c);return p}catch(m){throw m instanceof re&&(u=!c.aborted,s.abort(),_t(e.body).catch(()=>{})),c.aborted&&!u?this._makeUserAbortError(c):m}finally{c.removeEventListener("abort",d),i.abort()}}async makeRequest(e,t,n){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o);let i=a(this,V,"f");i?.beginRequestPreparation(),await this.prepareOptions(s),i?.beginRequestPlanning();let c;try{let O=await this.buildRequest(s,{retryCount:o-t});if(c={req:O.req,url:O.url,timeout:O.timeout},i){ea("timeout",c.timeout),i.authorizePlannedRequest(c.url,c.req,c.timeout),Ae.isStreamingRequestBody(c.req.body)&&(s.__metadata={...s.__metadata,hasStreamingBody:!0}),await this.prepareRequest(c.req,{url:c.url,options:s}),await this._provider?.prepareRequest?.(c.req,{url:c.url,options:s}),i.beginRequestPlanning(),i.authorizePlannedRequest(c.url,c.req,c.timeout,!0),Ae.isStreamingRequestBody(c.req.body)&&(s.__metadata={...s.__metadata,hasStreamingBody:!0});let v=i.requestSnapshot().signal;if(v?.aborted||c.req.signal?.aborted)throw this._makeUserAbortError(v?.aborted?v:c.req.signal);i.setEffectiveSignal(c.req.signal||v?md(c.req.signal??v,v).signal:void 0),i.beginRequestNetwork();let K=s.__security??{bearerAuth:!0},D=await this.authHeaders(s,K),N=i.headerSnapshots(),q=_([N.defaultHeaders,N.requestHeaders]);for(let[ge,W]of D?.values??[])!q.nulls.has(ge)&&!c.req.headers.has(ge)&&c.req.headers.set(ge,W);this.validateHeaders(_([q,c.req.headers]),K)}}catch(O){if(i?.retireRequestBody(),i&&t&&!s.__metadata?.hasStreamingBody&&Ae.isRetryableFailure(O))return await this.retryRequest(s,t,n??"x509-token-exchange",Ae.retryHeaders(O));throw O}let{req:u,url:d}=c,m=i?Math.min(c.timeout,i.requestSnapshot().timeout):c.timeout;i?.bindRequest(s,u,this.adminAPIKey);let y=s.__metadata?.hasStreamingBody===!0;i||(await this.prepareRequest(u,{url:d,options:s}),await this._provider?.prepareRequest?.(u,{url:d,options:s})),i?.adoptRequestHeaders(u),i&&Ae.isStreamingRequestBody(u.body)&&(y=!0);let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=n===void 0?"":`, retryOf: ${n}`,A=i?.requestStartedAt(s)??Date.now();if(this.logLevel==="debug"){let O=typeof u.body=="string"?{type:"string",length:u.body.length}:u.body;ee(this).debug(`[${p}] sending request`,yt({retryOfRequestLogID:n,method:s.method,url:d,options:i?{body:O,...i.requestSnapshot()}:{...s,body:O},headers:u.headers}))}let w=i?i.requestSnapshot().signal:s.signal;if(w?.aborted||u.signal?.aborted)throw this._makeUserAbortError(w?.aborted?w:u.signal);let S=s.__security??{bearerAuth:!0},E=i||this.fetchWithTimeout===et.prototype.fetchWithTimeout?md(u.signal??(i?w:void 0),i?w:void 0):new AbortController,P=i?.remainingTimeout(s,m)??m,L=i?et.prototype.fetchWithAuth:this.fetchWithAuth;i?.releaseRequestBody(u.body);let I=await L.call(this,d,u,P,E,S).catch(Js),T=Date.now();if(I instanceof globalThis.Error){let O=`retrying, ${t} attempts remaining`;if(w?.aborted||u.signal?.aborted)throw this._makeUserAbortError(w?.aborted?w:u.signal);let v=mt(I)||/timed? ?out/i.test(String(I)+("cause"in I?String(I.cause):""));if(t&&!y&&(!i||ri(I)))return ee(this).info(`[${p}] connection ${v?"timed out":"failed"} - ${O}`),ee(this).debug(`[${p}] connection ${v?"timed out":"failed"} (${O})`,yt({retryOfRequestLogID:n,url:d,durationMs:T-A,message:i?"X.509 workload identity API connection failed.":I.message})),this.retryRequest(s,t,n??p,void 0,u.signal);let K=y?"error; streaming body cannot be retried":"error; no more retries left";if(ee(this).info(`[${p}] connection ${v?"timed out":"failed"} - ${K}`),ee(this).debug(`[${p}] connection ${v?"timed out":"failed"} (${K})`,yt({retryOfRequestLogID:n,url:d,durationMs:T-A,message:i?"X.509 workload identity API connection failed.":I.message})),I instanceof Ne||I instanceof gr)throw I;if(v){let D="cause"in I?I.cause:void 0,q=typeof D=="object"&&D!==null&&"code"in D&&D.code==="UND_ERR_HEADERS_TIMEOUT"?new re({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new re;throw i?new re:Object.assign(q,{cause:I})}throw i?new De({message:"X.509 workload identity API connection failed."}):new De({message:g_(I),cause:I})}let x=[...I.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,v])=>", "+O+": "+JSON.stringify(v)).join(""),M=`[${p}${g}${x}] ${u.method} ${Jo(d)} ${I.ok?"succeeded":"failed"} with status ${I.status} in ${T-A}ms`;if(!I.ok){let O=I.status===401&&i&&S.bearerAuth&&i.usedWorkloadToken(s);if(O&&i.invalidateToken(),I.status===401&&(i||this._workloadIdentityAuth)&&S.bearerAuth&&(!i||i.usedWorkloadToken(s))&&(!i||t>0)&&!y&&!s.__metadata?.workloadIdentityTokenRefreshed){i?_t(I.body).catch(()=>{}):(await _t(I.body),this._workloadIdentityAuth?.invalidateToken());let W={...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(W,i?t-1:t,n??p)}let v=O&&s.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(I);if(t&&v&&!y){let W=`retrying, ${t} attempts remaining`;return i?_t(I.body).catch(()=>{}):await _t(I.body),ee(this).info(`${M} - ${W}`),ee(this).debug(`[${p}] response error (${W})`,yt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,durationMs:T-A})),this.retryRequest(s,t,n??p,I.headers,u.signal)}let K=v?y?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";ee(this).info(`${M} - ${K}`);let D=i?await this.readX509ResponseError(I,s,m,E,i):await I.text().catch(W=>Js(W).message),N=Cc(D),q=N?void 0:D;throw ee(this).debug(`[${p}] response error (${K})`,yt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,message:q,durationMs:Date.now()-A})),this.makeStatusError(I.status,N,q,I.headers)}ee(this).info(M),ee(this).debug(`[${p}] response start`,yt({retryOfRequestLogID:n,url:I.url,status:I.status,headers:I.headers,durationMs:T-A}));let k=i?.continuation();return i?.releaseRequestCredentials(),a(this,Wo,"f").set(E,{timeout:m,retriesRemaining:t,hasStreamingBody:y,...i?{authentication:i}:{},helperMethod:s.__metadata?.helperMethod,...k?{continueRequest:k}:{}}),{response:I,options:s,controller:E,requestSignal:u.signal,requestLogID:p,retryOfRequestLogID:n,startTime:A}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=a(this,V,"f")??this._workloadIdentityAuth,s=n instanceof Ae?Promise.resolve(t).then(c=>n.runRequest(()=>this.makeRequest(c,null,void 0),this)):this.makeRequest(t,null,void 0),o=new oo(this,s,e),i=this.responsePromise(s,async(c,u)=>{let d=await this.parseResponseWithTimeout(c,u);return new e(c,u.response,d,u.options)});return o.then=i.then.bind(i),o.catch=i.catch.bind(i),o.finally=i.finally.bind(i),o.withResponse=i.withResponse.bind(i),o._thenUnwrap=i._thenUnwrap.bind(i),o}async fetchWithAuth(e,t,n,s,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!a(this,Ct,"f")&&o.bearerAuth){let u=t.headers;if(u.get("Authorization")===`Bearer ${y_}`){let m=await this._workloadIdentityAuth.getToken();u.set("Authorization",`Bearer ${m}`)}}return await(a(this,Ct,"f")?et.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,n,s)}async fetchWithTimeout(e,t,n,s){let{signal:o,method:i,...c}=t||{},u=this._makeAbort(s),d=!!o&&yd.get(s)===o,m=o&&!d?$c(o,u,s.signal):void 0,y=setTimeout(u,n),p=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,g={signal:s.signal,...p?{duplex:"half"}:{},method:"GET",...c};i&&(g.method=i.toUpperCase());try{let A=await(a(this,Ct,"f")??this.fetch).call(void 0,e,g);return m&&ta(A.body??A,u,s.signal),A}catch(A){throw m?.(),A}finally{clearTimeout(y)}}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,s,o=e.signal){let i,c=s?.get("retry-after-ms");if(c){let m=parseFloat(c);Number.isNaN(m)||(i=m)}let u=s?.get("retry-after");if(u&&i===void 0){let m=parseFloat(u);Number.isNaN(m)?i=Date.parse(u)-Date.now():i=m*1e3}if(i===void 0||!Number.isFinite(i)||i<0||i>60*1e3){let m=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,m)}let d=a(this,V,"f");if(d){let m=d.remainingTimeout(e,d.requestSnapshot().timeout);if(i>=m)throw new re}if(d)await d.waitForRetry(i,d.effectiveSignal());else{let m=o===e.signal?[o]:[o,e.signal];try{await pn(i,...m)}catch(y){let p=m.find(g=>g?.aborted);throw p?this._makeUserAbortError(p):y}}return this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),c=1-Math.random()*.25;return i*c*1e3}async buildRequest(e,{retryCount:t=0}={}){if(a(this,V,"f")&&!a(this,V,"f").inRequest(this)){let T=a(this,V,"f");return await T.runRequest(async()=>{let x=await et.prototype.buildRequest.call(this,e,{retryCount:t});return T.releaseRequestBody(x.req.body),x},this)}let n={...e},s=a(this,V,"f"),o=s?.snapshotTenant(this.organization,this.project),i=s?.snapshotHeaders(this._options.defaultHeaders,n.headers);i&&(n.headers=i.requestHeaders);let c=s?wa(this.fetchOptions):void 0,u=s?wa(n.fetchOptions):void 0,{method:d,path:m,query:y,defaultBaseURL:p}=n,g=this.buildURL(m,y,p);s?.snapshotAPIURL(g);let A="timeout"in n;if(A&&ea("timeout",n.timeout),n.timeout=n.timeout??this.timeout,s&&u&&s.snapshotRequest(n.signal,n.timeout,u),s){let T=s.requestSnapshot();n.timeout=T.timeout,T.signal===void 0?delete n.signal:n.signal=T.signal}let w=this._provider||s?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),{bodyHeaders:S,body:E,isStreamingBody:P}=this.buildBody({options:n});P&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},s?.ownRequestBody(E,n.body));let L=await this.buildHeaders({options:e,method:d,bodyHeaders:S,authenticationHeaders:w,retryCount:t,x509Headers:i,x509Timeout:A?n.timeout:void 0,x509Tenant:o});return{req:{method:d,headers:L,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&E instanceof globalThis.ReadableStream&&{duplex:"half"},...E&&{body:E},...(s?c:this.fetchOptions)??{},...(s?u:n.fetchOptions)??{}},url:g,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,authenticationHeaders:s,retryCount:o,x509Headers:i,x509Timeout:c,x509Tenant:u}){let d={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),d[this.idempotencyHeader]=e.idempotencyKey);let m=e.__metadata?.helperMethod,y=i?c:e.timeout,p=_([d,{Accept:"application/json",...pd()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(o),...y?{"X-Stainless-Timeout":String(Math.trunc(y/1e3))}:{},...Jc(),...typeof m=="string"?{"X-Stainless-Helper-Method":m}:{},"OpenAI-Organization":u?u.organization:this.organization,"OpenAI-Project":u?u.project:this.project},a(this,V,"f")&&!a(this,V,"f").isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):s,i?.defaultHeaders??this._options.defaultHeaders,n,i?.requestHeaders??e.headers]);return!this._provider&&!a(this,V,"f")?.isPlanningRequest()&&this.validateHeaders(p,e.__security??{bearerAuth:!0}),p.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new Y;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&"body"in e?{...a(this,Fo,"f").call(this,{body:t,headers:_([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let s=_([n]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,i=!o&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&s.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!i}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Qs(t),isStreamingBody:!0}:typeof t=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...a(this,Fo,"f").call(this,{body:t,headers:s}),isStreamingBody:!1}}};et=C,Fo=new WeakMap,V=new WeakMap,Gi=new WeakMap,Ct=new WeakMap,Uo=new WeakMap,Wo=new WeakMap,vc=new WeakSet,_d=function(){return a(this,Uo,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=et;C.DEFAULT_TIMEOUT=6e5;C.OpenAIError=h;C.APIError=z;C.APIConnectionError=De;C.APIConnectionTimeoutError=re;C.APIUserAbortError=Y;C.NotFoundError=Lt;C.ConflictError=Mt;C.RateLimitError=Dt;C.BadRequestError=st;C.AuthenticationError=$t;C.InternalServerError=Nt;C.PermissionDeniedError=jt;C.UnprocessableEntityError=Bt;C.InvalidWebhookSignatureError=Oe;C.toFile=li;C.toStreamingFile=ai;C.Completions=Vr;C.Chat=Jt;C.Embeddings=Qr;C.Files=en;C.Images=sn;C.ContentProvenanceChecks=Yr;C.Audio=dt;C.Moderations=an;C.Models=on;C.FineTuning=Ze;C.Graders=dr;C.VectorStores=kt;C.Safety=mr;C.Webhooks=yr;C.Beta=je;C.Batches=Fr;C.Uploads=_r;C.Admin=Gt;C.Responses=pt;C.Live=ft;C.Realtime=Ot;C.Conversations=ur;C.Evals=lr;C.Containers=cr;C.Skills=Et;C.Videos=ln;C.ConversationCursorPage=F;C.CursorPage=R;C.NextCursorPage=Q;C.Page=le;C.TokenPage=mn;var yd=new WeakMap;function md(r,e){let t=new AbortController;if(!r)return t;let n=globalThis.AbortSignal;if(typeof n?.any!="function"||!(r instanceof n))return t;try{let s=[t.signal,r];e&&e!==r&&s.push(e);let o=n.any(s);Object.defineProperty(t,"signal",{value:o,configurable:!0}),yd.set(t,r)}catch{}return t}function g_(r){if(b_(r))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function b_(r){let e=r;for(let t=0;t<8&&e&&typeof e=="object";t++){let n=e;if(n.code==="UND_ERR_INVALID_ARG"&&typeof n.message=="string"&&n.message.includes("invalid onRequestStart method"))return!0;e=n.cause}return!1}var Oc=class extends C{constructor({baseURL:e=Se("OPENAI_BASE_URL"),apiKey:t=Se("AZURE_OPENAI_API_KEY"),apiVersion:n=Se("OPENAI_API_VERSION"),endpoint:s,deployment:o,azureADTokenProvider:i,dangerouslyAllowBrowser:c,dataResidency:u,...d}={}){if(ha(u,"AzureOpenAI"),!n)throw new h("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 i=="function"&&(c??(c=!0)),!i&&!t)throw new h("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&t)throw new h("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(d.defaultQuery={...d.defaultQuery,"api-version":n},e){if(s)throw new h("baseURL and endpoint are mutually exclusive")}else{if(s||(s=process.env.AZURE_OPENAI_ENDPOINT),!s)throw new h("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let m=s.length;for(;m>0&&s[m-1]==="/";)m--;e=`${s.slice(0,m)}/openai`}super({apiKey:i??t,baseURL:e,...d,...c===void 0?{}:{dangerouslyAllowBrowser:c}}),this.apiVersion="",this.apiVersion=n,this.deploymentName=o}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};return $(e,"endpoint")&&e.endpoint!==void 0&&!$(e,"baseURL")&&(t.baseURL=void 0),super.withOptions(t)}async buildRequest(e,t={}){if(w_.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!_e(e.body))throw new Error("Expected request body to be an object");let s=this.deploymentName||e.body.model||e.__metadata?.model;s!==void 0&&!A_(this.baseURL)&&(e.path=l`/deployments/${s}`+e.path)}let n=await super.buildRequest(e,t);return n.req.headers.has("api-key")&&(n.req.redirect="manual"),n}async fetchWithAuth(e,t,n,s,o){return new Headers(t.headers).has("api-key")&&(t.redirect="manual"),super.fetchWithAuth(e,t,n,s,o)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey=="string"?_([{"api-key":this.apiKey}]):super.authHeaders(e,n)}};function A_(r){try{return new URL(r).pathname.split("/").includes("deployments")}catch{return!1}}var w_=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var gd=Symbol.for("openai.privateBedrockClient");var I_;I_=gd;export{C as a,Oc as b};
|