sliccy 6.220.0 → 6.221.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -1
- package/dist/ui/.vite/manifest.json +413 -337
- package/dist/ui/assets/{SKILL-53i4JhqF.js → SKILL-Dc61Cgar.js} +1 -1
- package/dist/ui/assets/{account-store-Cl-FqDg2.js → account-store-B2Mwo19V.js} +1 -1
- package/dist/ui/assets/{account-store-CPtYzXW6.js → account-store-D2qVGeJK.js} +1 -1
- package/dist/ui/assets/adobe-Do3JK9jW.js +1 -0
- package/dist/ui/assets/adobe-JyWfWNAu.js +2 -0
- package/dist/ui/assets/{agent-panels-D8EphX6Z.js → agent-panels-CQw3Vwen.js} +1 -1
- package/dist/ui/assets/{almost-bash-shell-headless-1Osh0Z8C.js → almost-bash-shell-headless-v6MOtcGE.js} +36 -36
- package/dist/ui/assets/anthropic-messages-BQDpVj5-.js +40 -0
- package/dist/ui/assets/anthropic-messages-D7QmbErx.js +41 -0
- package/dist/ui/assets/{apply-layout-DDkQHScp.js → apply-layout-DbTmIBwc.js} +1 -1
- package/dist/ui/assets/{apps-CYhZkZhV.js → apps-qb7bKyr1.js} +1 -1
- package/dist/ui/assets/azure-openai-Bj-zzoTG.js +18 -0
- package/dist/ui/assets/{azure-openai-C8OX-0Yv.js → azure-openai-Bu0apIga.js} +10 -10
- package/dist/ui/assets/azure-openai-responses-DwCXOjFG.js +1 -0
- package/dist/ui/assets/azure-openai-responses-G-8bxNz-.js +1 -0
- package/dist/ui/assets/{backend-hostfs-DLGJSflr.js → backend-hostfs-BmWaOgHz.js} +1 -1
- package/dist/ui/assets/bedrock-camp-BO4bq8jC.js +1 -0
- package/dist/ui/assets/bedrock-camp-BxEHTfqF.js +1 -0
- package/dist/ui/assets/bedrock-camp-compat-B1oHsbyo.js +1 -0
- package/dist/ui/assets/bedrock-camp-compat-ByR2ly4i.js +1 -0
- package/dist/ui/assets/bedrock-camp-extra-models-BYrxX19D.js +1 -0
- package/dist/ui/assets/bedrock-camp-extra-models-DIuCBjcJ.js +1 -0
- package/dist/ui/assets/build-Dnkjpm_v.js +3 -0
- package/dist/ui/assets/{cdp-Ckvzmp8B.js → cdp-BH7EuuoV.js} +1 -1
- package/dist/ui/assets/cerebras-aV-XFwMx.js +1 -0
- package/dist/ui/assets/cerebras-weZokZBn.js +1 -0
- package/dist/ui/assets/cloudflare-workers-ai-system-one-B80gCcMI.js +1 -0
- package/dist/ui/assets/cloudflare-workers-ai-system-one-CGZSnw-N.js +1 -0
- package/dist/ui/assets/compat-CGK4SwF8.js +1 -0
- package/dist/ui/assets/compat-DpI6NrfX.js +2 -0
- package/dist/ui/assets/{composer-speech-BBc1XkYd.js → composer-speech-B88OEyUX.js} +1 -1
- package/dist/ui/assets/{connect-surface-BRbaHldo.js → connect-surface-D7vES-9B.js} +1 -1
- package/dist/ui/assets/context-CrZ58_Xy.js +1 -0
- package/dist/ui/assets/context-compaction-BwnPiNO2.js +58 -0
- package/dist/ui/assets/core-DXD5e-Tl.js +62 -0
- package/dist/ui/assets/core-E6pC-3NP.js +36 -0
- package/dist/ui/assets/diagnostics-Cag7MsZI.js +1 -0
- package/dist/ui/assets/{directed-approval-BWUFnlaC.js → directed-approval-BYJSQuBg.js} +1 -1
- package/dist/ui/assets/{edit-BnFODSzt.js → edit-dC5128uh.js} +2 -2
- package/dist/ui/assets/{emscripten-vfs-hook-yLP6dJtB.js → emscripten-vfs-hook-BP4LWJBC.js} +1 -1
- package/dist/ui/assets/{emscripten-vfs-hook-ctdnPZVN.js → emscripten-vfs-hook-CM0S0x26.js} +1 -1
- package/dist/ui/assets/{ensure-speech-assets-BI-zTzno.js → ensure-speech-assets-CWdvNimN.js} +1 -1
- package/dist/ui/assets/error-CJ3RHG07.js +1 -0
- package/dist/ui/assets/{frozen-archive-writer-BZ76mOLL.js → frozen-archive-writer-7zKO8xQD.js} +1 -1
- package/dist/ui/assets/{fs-CPOlAGHF.js → fs-COEFCJ8h.js} +2 -2
- package/dist/ui/assets/{fs-C3ewd7zM.js → fs-KXO6FdC3.js} +1 -1
- package/dist/ui/assets/{gelatiere-store-D-qUWaKm.js → gelatiere-store-COyadUR8.js} +1 -1
- package/dist/ui/assets/{gelatiere-unit-HNzB0CJ8.js → gelatiere-unit-CWJLfU86.js} +1 -1
- package/dist/ui/assets/{github-BIZEUSeE.js → github-C8xriJoe.js} +2 -2
- package/dist/ui/assets/{github-DqsPFEa7.js → github-DSE7HeLE.js} +1 -1
- package/dist/ui/assets/{github-auth-Dyywp0XK.js → github-auth-BFEw6TGZ.js} +1 -1
- package/dist/ui/assets/{github-copilot-BVkNwGDF.js → github-copilot-C4_LIKPd.js} +1 -1
- package/dist/ui/assets/{github-copilot-C-DftX7y.js → github-copilot-Dhki0he4.js} +1 -1
- package/dist/ui/assets/{github-install-DhfQgSHk.js → github-install-BECj7dG6.js} +1 -1
- package/dist/ui/assets/{github-zip-Bkjwx2jz.js → github-zip-CAITdmtz.js} +1 -1
- package/dist/ui/assets/google-generative-ai-D9UyU26L.js +1 -0
- package/dist/ui/assets/google-generative-ai-Du392shL.js +1 -0
- package/dist/ui/assets/google-shared-BY5yoa_V.js +704 -0
- package/dist/ui/assets/google-shared-DdtTASAI.js +8 -0
- package/dist/ui/assets/google-vertex-Bg8F0X9t.js +1 -0
- package/dist/ui/assets/google-vertex-CdMgLwMO.js +1 -0
- package/dist/ui/assets/{guest-tool-gate-BT-aJI8_.js → guest-tool-gate-Df5NH2fw.js} +1 -1
- package/dist/ui/assets/headers-FK4rgixo.js +1 -0
- package/dist/ui/assets/{hear-CIpNY63f.js → hear-BdP-glDP.js} +1 -1
- package/dist/ui/assets/{help-BukbR0D0.js → help-D3Cds9fx.js} +1 -1
- package/dist/ui/assets/{idle-compaction-CwYw083A.js → idle-compaction-DJzPVZ_I.js} +1 -1
- package/dist/ui/assets/{installer-BFRw_lRf.js → installer-mmgzhb2I.js} +1 -1
- package/dist/ui/assets/{interrupted-work-recovery-Ci9VV5oX.js → interrupted-work-recovery-DUcRwxv3.js} +1 -1
- package/dist/ui/assets/{ipk-mamba-UJdZm2KK.js → ipk-mamba-BeOU110W.js} +1 -1
- package/dist/ui/assets/{js-realm-worker-C3pS4nWP.js → js-realm-worker-BKhESKOL.js} +9 -9
- package/dist/ui/assets/{jsh-executor-DJ08VhaN.js → jsh-executor-BZ3blx0d.js} +2 -2
- package/dist/ui/assets/{kernel-worker-CmBiahAZ.js → kernel-worker-B8kxIeFM.js} +72 -72
- package/dist/ui/assets/{legacy-api-aliases-DoI0tM7F.js → legacy-api-aliases-C3FCSzcU.js} +1 -1
- package/dist/ui/assets/{legacy-api-aliases-jKEvBgOL.js → legacy-api-aliases-DvlNmb0H.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-DfuaXcGI.js → lick-ws-bridge-CnYPcMy8.js} +1 -1
- package/dist/ui/assets/{lick-ws-bridge-DUBZZFMr.js → lick-ws-bridge-D34MTpFX.js} +1 -1
- package/dist/ui/assets/{live-session-curation-eYKAR5xE.js → live-session-curation-GMTDEygc.js} +1 -1
- package/dist/ui/assets/{live-session-snapshot-D5Sooner.js → live-session-snapshot-CBK8eM9y.js} +1 -1
- package/dist/ui/assets/local-llm-CqjYBu9W.js +2 -0
- package/dist/ui/assets/local-llm-qnREArcP.js +2 -0
- package/dist/ui/assets/{main-8USr6q37.js → main-DTdP6wOZ.js} +3 -3
- package/dist/ui/assets/{main-cherry-CmbogfhO.js → main-cherry-CeJWJmuD.js} +1 -1
- package/dist/ui/assets/{memory-curation-seam-i2jIitmU.js → memory-curation-seam-Cf8-OrWA.js} +1 -1
- package/dist/ui/assets/{memory-health-CAJ3GwFC.js → memory-health-DQ91v7IT.js} +1 -1
- package/dist/ui/assets/{memory-write-execute-8BwvKQHC.js → memory-write-execute-DuoO_5Yx.js} +1 -1
- package/dist/ui/assets/{merge-folded-cost-into-frozen-DCwSAakf.js → merge-folded-cost-into-frozen-BFQY7iX9.js} +1 -1
- package/dist/ui/assets/mistral-conversations-BuGMUreY.js +4 -0
- package/dist/ui/assets/mistral-conversations-mDbyUUlz.js +4 -0
- package/dist/ui/assets/models-CET5SEuw.js +8 -0
- package/dist/ui/assets/models-Xc0Gclrk.js +8 -0
- package/dist/ui/assets/{mount-CSNiw0gw.js → mount-DMt0lJZu.js} +1 -1
- package/dist/ui/assets/{mount-CaZBT6Qv.js → mount-DcJDGSR2.js} +3 -3
- package/dist/ui/assets/{new-session-oP5qFRj5.js → new-session-CVLaQspu.js} +2 -2
- package/dist/ui/assets/node.browser-DFtqp6Hr.js +1 -0
- package/dist/ui/assets/node.browser-Dcfsk-1p.js +1 -0
- package/dist/ui/assets/node.browser-GVOB1YIR.js +1 -0
- package/dist/ui/assets/node.browser-QAQ2vzf3.js +1 -0
- package/dist/ui/assets/{oauth-bootstrap-DywNUo8g.js → oauth-bootstrap-ni8ciMEf.js} +2 -2
- package/dist/ui/assets/{onboarding-orchestrator-s94oEY8i.js → onboarding-orchestrator-C8CJmPGj.js} +1 -1
- package/dist/ui/assets/openai-CmkcIaBM.js +19 -0
- package/dist/ui/assets/openai-codex-AU0lfekU.js +1 -0
- package/dist/ui/assets/openai-codex-DSK2KvAD.js +1 -0
- package/dist/ui/assets/openai-codex-responses-5eRWG6Hs.js +9 -0
- package/dist/ui/assets/openai-codex-responses-CFxSFpD7.js +9 -0
- package/dist/ui/assets/openai-completions-BwkWCvBF.js +5 -0
- package/dist/ui/assets/openai-completions-ClFxp0yS.js +5 -0
- package/dist/ui/assets/openai-responses-DBslh_TV.js +1 -0
- package/dist/ui/assets/openai-responses-QWbZjbon.js +1 -0
- package/dist/ui/assets/openai-responses-shared-Bq_dykNL.js +10 -0
- package/dist/ui/assets/openai-responses-shared-reKIfrYK.js +10 -0
- package/dist/ui/assets/openai-zaDKJgTh.js +19 -0
- package/dist/ui/assets/openrouter-A_X2tymZ.js +1 -0
- package/dist/ui/assets/openrouter-B9XZIMKs.js +1 -0
- package/dist/ui/assets/openrouter-free-Ci_Kt5lC.js +1 -0
- package/dist/ui/assets/openrouter-free-CvFgLRIy.js +1 -0
- package/dist/ui/assets/{openrouter-images-BAtqv3Im.js → openrouter-images-B46AzZkc.js} +1 -1
- package/dist/ui/assets/{openrouter-images-Du3tMEQa.js → openrouter-images-Bw1M-QW6.js} +1 -1
- package/dist/ui/assets/{openrouter-models-Cfi7qjq5.js → openrouter-models-Nin8rMTE.js} +1 -1
- package/dist/ui/assets/{openrouter-models-DyyLIGVe.js → openrouter-models-Wk5vhQDW.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-Bj_L5M3b.js → openrouter-oauth-B0Ol0yhk.js} +1 -1
- package/dist/ui/assets/{openrouter-oauth-BtOSulAG.js → openrouter-oauth-B_iwF9ln.js} +1 -1
- package/dist/ui/assets/openrouter.models-B2N_zHqH.js +1 -0
- package/dist/ui/assets/openrouter.models-DsSG76zx.js +1 -0
- package/dist/ui/assets/{opfs-mount-CnfXosX_.js → opfs-mount-RZtGopmY.js} +1 -1
- package/dist/ui/assets/{panel-rpc-handlers-txfCPZNY.js → panel-rpc-handlers-B6AhsHhs.js} +2 -2
- package/dist/ui/assets/{panelize-shell-jKLhcD44.js → panelize-shell-70KvETjZ.js} +1 -1
- package/dist/ui/assets/pi-edit-execution-CJtk8sw0.js +2 -0
- package/dist/ui/assets/pi-messages-BMxZw_ob.js +7 -0
- package/dist/ui/assets/pi-messages-F6N-eNkX.js +7 -0
- package/dist/ui/assets/pi-transcript-context-4pjVPiVC.js +1 -0
- package/dist/ui/assets/pi-transcript-context-miZCMig3.js +1 -0
- package/dist/ui/assets/{process-worker-7-U7pJ31.js → process-worker-HvQno7jm.js} +2 -2
- package/dist/ui/assets/{provider-DU5qXtgs.js → provider-Bs4Et5O_.js} +2 -2
- package/dist/ui/assets/{provider-CiPG2QqU.js → provider-CX1UiJik.js} +1 -1
- package/dist/ui/assets/{provider-settings-CYtZYE0m.js → provider-settings-CFZUbX2e.js} +1 -1
- package/dist/ui/assets/provider-store-access-BFgLO_g6.js +1 -0
- package/dist/ui/assets/provider-store-access-f1lNHnJI.js +1 -0
- package/dist/ui/assets/{providers-3Vh9AkCt.js → providers-BtQOBppt.js} +1 -1
- package/dist/ui/assets/providers-Wi_lqleP.js +2 -0
- package/dist/ui/assets/{py-live-vfs-BCSnlFm0.js → py-live-vfs-DTm_2cNW.js} +1 -1
- package/dist/ui/assets/{py-live-vfs-D_X8Ts9M.js → py-live-vfs-hH5t4grO.js} +1 -1
- package/dist/ui/assets/{py-realm-worker-vN-Y0duM.js → py-realm-worker-BJhAN3Hi.js} +1 -1
- package/dist/ui/assets/{quick-llm-DZblyqJ_.js → quick-llm-BpxAni9c.js} +1 -1
- package/dist/ui/assets/{realm-inprocess-xfgVdnu2.js → realm-inprocess-BF9_K14I.js} +2 -2
- package/dist/ui/assets/{realm-sync-transport-BD8czJdC.js → realm-sync-transport-DwPCYtlC.js} +1 -1
- package/dist/ui/assets/{realm-unhandled-rejections-8FfA1Gxn.js → realm-unhandled-rejections-BGF0Okqr.js} +1 -1
- package/dist/ui/assets/{realm-unhandled-rejections-DYtt6P4B.js → realm-unhandled-rejections-xk9BsiKY.js} +1 -1
- package/dist/ui/assets/{recovery-screen-07Mn3nGq.js → recovery-screen-Dzsgw1RN.js} +1 -1
- package/dist/ui/assets/{remote-terminal-view-qKI_Uk-3.js → remote-terminal-view-BCN7YR5Y.js} +2 -2
- package/dist/ui/assets/{require-guards-jYsd9xiG.js → require-guards-CdMtRPQA.js} +1 -1
- package/dist/ui/assets/{restore-Wbg4rqS8.js → restore-DFV7_wMh.js} +1 -1
- package/dist/ui/assets/{run-D6J4u7Dw.js → run-2rGtFSt6.js} +1 -1
- package/dist/ui/assets/{run-MUMHxwWH.js → run-C2d9mxQz.js} +1 -1
- package/dist/ui/assets/{run-BqyPtei-.js → run-D2G8sKeo.js} +2 -2
- package/dist/ui/assets/run-D3vqibrN.js +17 -0
- package/dist/ui/assets/{run-CLjtjzEy.js → run-DA_-Rx4v.js} +2 -2
- package/dist/ui/assets/{run-vaI9AZHT.js → run-DmrQxYlF.js} +1 -1
- package/dist/ui/assets/{run-DqJvJNya.js → run-cn2mHzVB.js} +1 -1
- package/dist/ui/assets/{session-command-memory-2oP0GfW4.js → session-command-memory-BcLXdVg5.js} +2 -2
- package/dist/ui/assets/{session-jsonl-D_aKJXyR.js → session-jsonl-DKzlDIQJ.js} +1 -1
- package/dist/ui/assets/{session-jsonl-CAjcgY95.js → session-jsonl-DRz05-g5.js} +1 -1
- package/dist/ui/assets/{session-search-index-BnZt5Q3i.js → session-search-index-CPRo0fFD.js} +1 -1
- package/dist/ui/assets/{setup-feature-flags-remote-CVKiJ3Dt.js → setup-feature-flags-remote-Dc6A4xq5.js} +1 -1
- package/dist/ui/assets/{setup-model-catalog-CDVDbpgE.js → setup-model-catalog-CeWYXOuD.js} +1 -1
- package/dist/ui/assets/{signed-fetch-xwKpuY0p.js → signed-fetch-B9--1Sbs.js} +1 -1
- package/dist/ui/assets/{silent-renew-backoff-aQDTrjJz.js → silent-renew-backoff-Brhzt-2Y.js} +1 -1
- package/dist/ui/assets/slicc-version-B2ZW_oO6.js +1 -0
- package/dist/ui/assets/{snapshot-9ScYN3qc.js → snapshot-LqMhHHjy.js} +1 -1
- package/dist/ui/assets/{snapshot-features-BPVDwE7j.js → snapshot-features-Ca5MHUK-.js} +1 -1
- package/dist/ui/assets/{soundscape-BMSIxpf9.js → soundscape-3lHcTWI7.js} +1 -1
- package/dist/ui/assets/{speak-CZpoPzFy.js → speak-AuaRZ9RV.js} +1 -1
- package/dist/ui/assets/{sprinkle-manager-CtJTUHgd.js → sprinkle-manager-B5ESfcO_.js} +1 -1
- package/dist/ui/assets/{sprinkle-renderer-BHhs9N3d.js → sprinkle-renderer-Csn9J6Z5.js} +1 -1
- package/dist/ui/assets/{state-e2oZ6Uk0.js → state-OwNN8wRL.js} +1 -1
- package/dist/ui/assets/{store-98kKUKyW.js → store-B8Cu7TgC.js} +1 -1
- package/dist/ui/assets/{store-Cln3HWXL.js → store-CNGE200d.js} +1 -1
- package/dist/ui/assets/{sudo-BMKSeLdQ.js → sudo-DDmfHCP-.js} +1 -1
- package/dist/ui/assets/{supervisor-DkcJwuTP.js → supervisor-BPjH6eIV.js} +1 -1
- package/dist/ui/assets/{sync-dialog-DWXFfvJ0.js → sync-dialog-P0BsR-1C.js} +1 -1
- package/dist/ui/assets/sync-exec-dispatch-BvwkIQoA.js +1 -0
- package/dist/ui/assets/{sync-sab-responder-CKgRMoHC.js → sync-sab-responder-CvWMn8kd.js} +1 -1
- package/dist/ui/assets/system-one-shared-BS-hdRg3.js +1 -0
- package/dist/ui/assets/system-one-shared-CQIk1iab.js +1 -0
- package/dist/ui/assets/temperature-support-0nztUM0u.js +1 -0
- package/dist/ui/assets/temperature-support-DhoZT6gU.js +1 -0
- package/dist/ui/assets/transform-messages-BeurHGV0.js +1 -0
- package/dist/ui/assets/transform-messages-k2mfzJwY.js +1 -0
- package/dist/ui/assets/{transformers-env-DnBVlojJ.js → transformers-env-B-2L_cqg.js} +1 -1
- package/dist/ui/assets/{tray-leader-6JyRjLk0.js → tray-leader-BI85j-VK.js} +1 -1
- package/dist/ui/assets/{tray-leave-runtime-Csg3aRUD.js → tray-leave-runtime-CWcDrmwo.js} +1 -1
- package/dist/ui/assets/{tray-sidecar-DJyUo816.js → tray-sidecar-CEaCIR55.js} +1 -1
- package/dist/ui/assets/{turn-journal-B1HjlARv.js → turn-journal-B-yFOK6T.js} +1 -1
- package/dist/ui/assets/typesafe-system-one-DOrmiuDo.js +1 -0
- package/dist/ui/assets/typesafe-system-one-gYUpO8qi.js +1 -0
- package/dist/ui/assets/{upgrade-detection-h9mE8Ptk.js → upgrade-detection-B5IYaD4P.js} +1 -1
- package/dist/ui/assets/{upskill-lick-skip-CN91n2bj.js → upskill-lick-skip-rIPcwgSX.js} +1 -1
- package/dist/ui/assets/{voice-reply-C8ecYofJ.js → voice-reply-Cws4_16u.js} +1 -1
- package/dist/ui/assets/wasi-runtime-DW6RmgCp.js +3 -0
- package/dist/ui/assets/{wc-attach-WGYvrgeT.js → wc-attach-C-62Si-C.js} +2 -2
- package/dist/ui/assets/{wc-browser-DbbvyoTT.js → wc-browser-CIYdab1x.js} +1 -1
- package/dist/ui/assets/{wc-computers-CXuo01dJ.js → wc-computers-BRLX-kpC.js} +1 -1
- package/dist/ui/assets/{wc-detached-C-JbZAhi.js → wc-detached-BeC2BoGY.js} +1 -1
- package/dist/ui/assets/{wc-extension-BmNmrGiQ.js → wc-extension-BQLBYRka.js} +2 -2
- package/dist/ui/assets/{wc-follower-oauth-BTgKLLqf.js → wc-follower-oauth-C4XExhiW.js} +1 -1
- package/dist/ui/assets/{wc-follower-BSGRMfbg.js → wc-follower-twuoHFZy.js} +3 -3
- package/dist/ui/assets/{wc-gelatiere-BILpTJsl.js → wc-gelatiere-HbuVcW1u.js} +1 -1
- package/dist/ui/assets/{wc-live-Cl_0tOQ-.js → wc-live-CURCXRjN.js} +5 -5
- package/dist/ui/assets/{wc-nav-DLBMXPAF.js → wc-nav-BPCDmahJ.js} +2 -2
- package/dist/ui/assets/{wc-onboarding-CC4I43ZL.js → wc-onboarding-CzMJiZTs.js} +2 -2
- package/dist/ui/assets/{wc-permissions-BQMxdSLj.js → wc-permissions-B3T6lGtA.js} +2 -2
- package/dist/ui/assets/{wc-placeholder-BWUSBXo3.js → wc-placeholder-CZNqET9L.js} +3 -3
- package/dist/ui/assets/{wc-secret-request-DEP2cfjm.js → wc-secret-request-63pTOQSv.js} +1 -1
- package/dist/ui/assets/{wc-settings-C3CIZZw-.js → wc-settings-MinrKaHc.js} +3 -3
- package/dist/ui/assets/{wc-shell-BJTnAxDb.js → wc-shell-DS_Mu0N6.js} +3 -3
- package/dist/ui/assets/{wc-shortcut-config-BWOMjx1B.js → wc-shortcut-config-DyTx_bns.js} +1 -1
- package/dist/ui/assets/{wc-sprinkles-3R7yEaKB.js → wc-sprinkles-CO_LJ5Xq.js} +2 -2
- package/dist/ui/assets/{wc-transcript-export-Ce2jKH_F.js → wc-transcript-export-Bw8zgf3y.js} +2 -2
- package/dist/ui/assets/{wc-tray-CYYxNUcK.js → wc-tray-CflJ-7e8.js} +4 -4
- package/dist/ui/assets/welcome-detection-Gq5HaOhO.js +1 -0
- package/dist/ui/assets/{whisper-session-B60X5T1B.js → whisper-session-B9U00uOk.js} +2 -2
- package/dist/ui/assets/xai-grok-50hqAIoW.js +1 -0
- package/dist/ui/assets/xai-grok-DFdAejIW.js +1 -0
- package/dist/ui/index.html +10 -10
- package/dist/ui/llm-proxy-sw.js +1 -1
- package/dist/ui/packages/webapp/index.html +10 -10
- package/package.json +2 -2
- package/dist/ui/assets/adobe-BeBRKE0L.js +0 -2
- package/dist/ui/assets/adobe-BrXpxUlh.js +0 -1
- package/dist/ui/assets/anthropic-messages-BSDk2GuG.js +0 -39
- package/dist/ui/assets/anthropic-messages-DkH6AeKE.js +0 -39
- package/dist/ui/assets/azure-openai-FqtiJilI.js +0 -18
- package/dist/ui/assets/azure-openai-responses-1_xTsvfT.js +0 -1
- package/dist/ui/assets/azure-openai-responses-BlGLmNYQ.js +0 -1
- package/dist/ui/assets/bedrock-camp-Bvjec9dO.js +0 -1
- package/dist/ui/assets/bedrock-camp-L-_-pBFh.js +0 -1
- package/dist/ui/assets/bedrock-camp-compat-C64_Hwco.js +0 -1
- package/dist/ui/assets/bedrock-camp-compat-DC2y4xqC.js +0 -1
- package/dist/ui/assets/bedrock-camp-extra-models-BTmBqN9L.js +0 -1
- package/dist/ui/assets/bedrock-camp-extra-models-Dg0hblqu.js +0 -1
- package/dist/ui/assets/build-BRNa03GH.js +0 -3
- package/dist/ui/assets/cerebras-B45pfuRX.js +0 -1
- package/dist/ui/assets/cerebras-DmzPOFQ_.js +0 -1
- package/dist/ui/assets/compat-Dy2zIWAW.js +0 -2
- package/dist/ui/assets/compat-uEPf6-XW.js +0 -1
- package/dist/ui/assets/context-compaction-Dpr7xgBZ.js +0 -58
- package/dist/ui/assets/core-BOHj4mqw.js +0 -36
- package/dist/ui/assets/core-CbbeQz7g.js +0 -62
- package/dist/ui/assets/deferred-tools-C1IEsG5C.js +0 -1
- package/dist/ui/assets/deferred-tools-DNuoafg8.js +0 -1
- package/dist/ui/assets/diagnostics-DN_idNHx.js +0 -1
- package/dist/ui/assets/google-generative-ai-_Gek_V8v.js +0 -1
- package/dist/ui/assets/google-generative-ai-hxrHAC1o.js +0 -1
- package/dist/ui/assets/google-shared-CokPjXyL.js +0 -11
- package/dist/ui/assets/google-shared-DWlqA-Ds.js +0 -371
- package/dist/ui/assets/google-vertex-BF9Vjq0f.js +0 -1
- package/dist/ui/assets/google-vertex-CQDksBdc.js +0 -1
- package/dist/ui/assets/headers-CbDaTl3c.js +0 -1
- package/dist/ui/assets/local-llm-BIp2HhiA.js +0 -2
- package/dist/ui/assets/local-llm-Csax_zi_.js +0 -2
- package/dist/ui/assets/mistral-conversations-2yMfObrW.js +0 -4
- package/dist/ui/assets/mistral-conversations-s2SRnikE.js +0 -4
- package/dist/ui/assets/models-4WTk3EBD.js +0 -1
- package/dist/ui/assets/models-YdybRRvT.js +0 -1
- package/dist/ui/assets/openai-BKEGagiR.js +0 -17
- package/dist/ui/assets/openai-Bgt_f1Dp.js +0 -17
- package/dist/ui/assets/openai-codex-CsbcxAwK.js +0 -1
- package/dist/ui/assets/openai-codex-Izb1oUMi.js +0 -1
- package/dist/ui/assets/openai-codex-responses-BM2lIIbg.js +0 -7
- package/dist/ui/assets/openai-codex-responses-BQyKdhMP.js +0 -7
- package/dist/ui/assets/openai-completions-9XqUnTtF.js +0 -5
- package/dist/ui/assets/openai-completions-CkwaxmCT.js +0 -5
- package/dist/ui/assets/openai-responses-B3CeQssC.js +0 -1
- package/dist/ui/assets/openai-responses-CZLQAwyI.js +0 -1
- package/dist/ui/assets/openai-responses-shared-CdC6rVE7.js +0 -10
- package/dist/ui/assets/openai-responses-shared-WWsNeoEn.js +0 -10
- package/dist/ui/assets/openrouter-CMhrvGEI.js +0 -1
- package/dist/ui/assets/openrouter-CuxKI9sw.js +0 -1
- package/dist/ui/assets/openrouter-free-AYsgMf78.js +0 -1
- package/dist/ui/assets/openrouter-free-DN-d1p7u.js +0 -1
- package/dist/ui/assets/openrouter.models-B-zmcypy.js +0 -1
- package/dist/ui/assets/openrouter.models-sZoBa1pg.js +0 -1
- package/dist/ui/assets/pi-edit-execution-DH85YBq5.js +0 -2
- package/dist/ui/assets/pi-messages-BZZiqwtu.js +0 -7
- package/dist/ui/assets/pi-messages-Caj3Sz7n.js +0 -7
- package/dist/ui/assets/provider-store-access-05KdIOnd.js +0 -1
- package/dist/ui/assets/provider-store-access-Dnk3gXiV.js +0 -1
- package/dist/ui/assets/providers-D-gHhkUb.js +0 -2
- package/dist/ui/assets/run-DYdVr3s9.js +0 -17
- package/dist/ui/assets/slicc-version-C_dEkbAr.js +0 -1
- package/dist/ui/assets/sync-exec-dispatch-DvIKQEFv.js +0 -1
- package/dist/ui/assets/temperature-support-CIu8ekGh.js +0 -1
- package/dist/ui/assets/temperature-support-D3pN575q.js +0 -1
- package/dist/ui/assets/transform-messages-BsQjTIEJ.js +0 -1
- package/dist/ui/assets/transform-messages-Jn8bw4-u.js +0 -1
- package/dist/ui/assets/wasi-runtime-2IxB3dc0.js +0 -1
- package/dist/ui/assets/welcome-detection-BiAdqlNi.js +0 -1
- package/dist/ui/assets/xai-grok-9zAL3G19.js +0 -1
- package/dist/ui/assets/xai-grok-aVv0829R.js +0 -1
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import{a as e}from"./diagnostics-
|
|
2
|
-
`)}};T=new WeakMap,E=new WeakMap,D=new WeakMap,O=new WeakMap,
|
|
3
|
-
`,`\r`]),
|
|
4
|
-
`);t.enqueue(i)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}};async function*
|
|
5
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,,n]=Ke(e,`:`),r=n;return r.startsWith(` `)&&(r=r.slice(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function Ke(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.slice(0,n),t,e.slice(n+t.length)]}async function qe(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):Ve.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();if(r?.includes(`application/json`)||r?.endsWith(`+json`)){if(n.headers.get(`content-length`)===`0`)return;let e=await n.text();return e?Ye(JSON.parse(e),n):void 0}return await n.text()})().catch(e=>{throw Je(e,t.controller.signal)});return k(e).debug(`[${r}] response parsed`,ze({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function Je(e,t){if(!t.aborted||e!==t.reason||u(e))return e;let n=`This operation was aborted`,r=globalThis.DOMException;return typeof r==`function`?new r(n,`AbortError`):Object.assign(Error(n),{name:`AbortError`})}function Ye(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var Xe=`7.5.0`,Ze=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function Qe(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var $e=()=>{let e=Qe();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":nt(Deno.build.os),"X-Stainless-Arch":tt(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":Xe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":nt(globalThis.process.platform??`unknown`),"X-Stainless-Arch":tt(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=et();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Xe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function et(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var tt=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,nt=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),rt,it=()=>rt??=$e(),at=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),ot=`RFC3986`,st=String,ct={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:st},lt,ut=(e,t)=>{let n=lt??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return lt=n,n(e,t)},A=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),dt=1024,ft=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,e=>`%26%23`+Number.parseInt(e.slice(2),16)+`%3B`);let o=``;for(let e=0;e<a.length;){let t=Math.min((Math.floor(e/dt)+1)*dt,a.length);t<a.length&&a.codePointAt(t-1)>65535&&(t+=1);let n=a.length>=dt?a.slice(e,t):a,r=[];for(let e=0;e<n.length;++e){let t=n.charCodeAt(e);if(t===45||t===46||t===95||t===126||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||i===`RFC1738`&&(t===40||t===41)){r[r.length]=n.charAt(e);continue}if(t<128){r[r.length]=A[t];continue}if(t<2048){r[r.length]=A[192|t>>6]+A[128|t&63];continue}if(t<55296||t>=57344){r[r.length]=A[224|t>>12]+A[128|t>>6&63]+A[128|t&63];continue}e+=1,t=65536+((t&1023)<<10|n.charCodeAt(e)&1023),r[r.length]=A[240|t>>18]+A[128|t>>12&63]+A[128|t>>6&63]+A[128|t&63]}o+=r.join(``),e=t}return o};function pt(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function mt(e,t){if(S(e)){let n=[];for(let r of e)n.push(t(r));return n}return t(e)}var ht={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},gt=function(e,t){Array.prototype.push.apply(e,S(t)?t:[t])},_t,j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:ft,encodeValuesOnly:!1,format:ot,formatter:st,indices:!1,serializeDate(e){return(_t??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function vt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var yt={};function bt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(yt))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(yt)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&S(v)&&(v=mt(v,e=>e instanceof Date?f?.(e):e)),v===null){if(a)return c&&!h?c(t,j.encoder,g,`key`,p):t;v=``}if(vt(v)||pt(v)){if(c){let e=h?t:c(t,j.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,j.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&S(v))h&&c&&(v=mt(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(S(l))te=l;else{let e=Object.keys(v);u&&e.sort(u),te=e}let ne=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&S(v)&&v.length===1?ne+`[]`:ne;if(i&&S(v)&&v.length===0)return re+`[]`;for(let t of te){let y=typeof t==`object`&&t.value!==void 0?t.value:v[t];if(o&&y===null)continue;let x=d&&s?t.replace(/\./g,`%2E`):t,te;te=S(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`),_.set(e,b);let ne=new WeakMap([[yt,_]]);gt(ee,bt(y,te,n,r,i,a,o,s,n===`comma`&&h&&S(v)?null:c,l,u,d,f,p,m,h,g,ne))}return ee}function xt(e=j){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||j.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=ot;if(e.format!==void 0){if(!ut(ct,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=ct[n],i=j.filter;(typeof e.filter==`function`||S(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in ht?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:j.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o;return o=e.allowDots===void 0?e.encodeDotInKeys?!0:j.allowDots:!!e.allowDots,{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:j.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?j.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:j.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:j.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:j.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:j.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:j.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:j.strictNullHandling}}function St(e,t={}){let n=e,r=xt(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):S(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=ht[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e of i)r.skipNulls&&n[e]===null||gt(o,bt(n[e],e,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l));let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(d+=r.charset===`iso-8859-1`?`utf8=%26%2310003%3B&`:`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Ct(e){return St(e,{arrayFormat:`brackets`})}var wt,Tt=class e extends Promise{constructor(e,t,n=qe){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,wt.set(this,void 0),s(this,wt,e,`f`)}_thenUnwrap(t){return new e(c(this,wt,`f`),this.responsePromise,async(e,n)=>Ye(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(c(this,wt,`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)}};wt=new WeakMap;var Et,Dt=class{constructor(e,t,n,r){Et.set(this,void 0),s(this,Et,e,`f`),this.options=r,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 f("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Et,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Et=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ot=class extends Tt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await qe(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},kt=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},M=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...de(this.options.query),after:t}}:null}},N=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...de(this.options.query),after:e}}:null}},At=class extends Dt{constructor(e,t,n,r){super(e,t,n,r),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&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...de(this.options.query),after:e}}:null}},jt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Mt=`urn:ietf:params:oauth:grant-type:token-exchange`,Nt=class e{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??_e()}async getToken(){if(!this.cachedToken||e.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(this.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={grant_type:Mt,subject_token:await this.config.provider.getToken(),subject_token_type:jt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),redirect:`manual`});if(!n.ok){let e=await n.text(),t;try{t=JSON.parse(e)}catch{}throw n.status===400||n.status===401||n.status===403?new oe(n.status,t,n.headers):p.generate(n.status,t,`Token exchange failed with status ${n.status}`,n.headers)}let r=await n.json();if(typeof r!=`object`||!r||!(`access_token`in r)||typeof r.access_token!=`string`||r.access_token.trim().length===0)throw new f(`Token exchange response missing 'access_token' field`);let i=r.access_token,a=r.expires_in??3600;if(typeof a!=`number`||!Number.isFinite(a)||a<=0)throw new f(`Token exchange response has invalid 'expires_in' field`);let o=Date.now(),s=o+a*1e3;if(!Number.isSafeInteger(s)||s<=o)throw new f(`Token exchange response has invalid 'expires_in' field`);return this.tokenGeneration===e&&(this.cachedToken={token:i,expiresAt:s}),i}static isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}},Pt=Symbol(`brand.privateNullableHeaders`),Ft=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*It(e){if(!e)return;if(Pt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ue(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ue(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var P=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of It(r)){if(!Ft.test(i))throw TypeError(`Header name must be a valid HTTP token ["${i}"]`);let r=i.toLowerCase();e.has(r)||(t.delete(r),e.add(r)),a===null?(t.delete(r),n.add(r)):(t.append(r,a),n.delete(r))}}return{[Pt]:!0,values:t,nulls:n}},Lt=Symbol(`brand.privateStreamingFile`);function Rt(e,t,n){if(typeof t!=`string`||!t)throw TypeError(`toStreamingFile requires a non-empty file name`);let r=n?.type;return r&&cn(r),{[Lt]:!0,data:e,name:t,...r?{type:r}:{}}}var zt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&Number.parseInt(e.versions.node.split(`.`),10)<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function Bt(e,t,n){return zt(),new File(e,t??`unknown_file`,n)}function Vt(e,t){if(typeof e!=`object`||!e)return;let n=`name`in e&&e.name&&String(e.name)||`filename`in e&&e.filename&&String(e.filename);if(n)return t?.stripFilename===!1?Ut(n):Ht(n);let r=`url`in e&&e.url&&String(e.url);if(r)try{return Ht(new URL(r).pathname)}catch{return Ht(r)}let i=`path`in e&&e.path&&String(e.path);return i?Ht(i):void 0}function Ht(e){return e.split(/[\\/]/).pop()||void 0}function Ut(e){return e.replace(/\\/g,`/`)}var Wt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Gt=async(e,t,n)=>en(e.body)?$t(e.body)?tn(e,n):{...e,body:await Jt(e.body,t,n)}:e,F=async(e,t,n)=>$t(e.body)?tn(e,n):{...e,body:await Jt(e.body,t,n)},Kt=new WeakMap;function qt(e){let t=typeof e==`function`?e:e.fetch,n=Kt.get(t);if(n)return n;let r=(async()=>{try{let e;if(`Response`in t)e=t.Response;else{let n=await t(`data:,`);await n.arrayBuffer(),e=n.constructor}let n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Kt.set(t,r),r}var Jt=async(e,t,n={})=>{if(!await qt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>fn(r,e,t,n))),r},Yt=e=>e instanceof Blob&&`name`in e,Xt=e=>typeof e==`object`&&!!e&&`getReader`in e&&typeof e.getReader==`function`,Zt=e=>typeof e==`object`&&!!e&&Lt in e,Qt=e=>typeof e==`object`&&!!e&&(e instanceof Response||Wt(e)||Xt(e)||Zt(e)||Yt(e)),$t=e=>{if(Zt(e)||Wt(e)||Xt(e))return!0;if(Array.isArray(e))return e.some($t);if(e&&typeof e==`object`&&!Yt(e)&&!(e instanceof Response)){for(let t in e)if($t(e[t]))return!0}return!1},en=e=>{if(Qt(e))return!0;if(Array.isArray(e))return e.some(en);if(e&&typeof e==`object`){for(let t in e)if(en(e[t]))return!0}return!1},tn=(e,t={})=>{let n=`openai-${Math.random().toString(36).slice(2)}`,r=ye(nn(e.body,n,t));return{...e,body:r,headers:P([{"content-type":`multipart/form-data; boundary=${n}`},e.headers])}};async function*nn(e,t,n){for await(let{key:r,value:i}of rn(e)){if(Qt(i)){let e=on(i,n),a=sn(i);yield w(`--${t}\r\n`),yield w(`Content-Disposition: form-data; name="${dn(r)}"; filename="${dn(e)}"\r\nContent-Type: ${a}\r\n\r\n`),yield*un(ln(i))}else yield w(`--${t}\r\n`),yield w(`Content-Disposition: form-data; name="${dn(r)}"\r\n\r\n${String(i)}`);yield w(`\r
|
|
6
|
-
`)}yield w(`--${t}--\r\n`)}async function*
|
|
7
|
-
`)}\n${a}\n${t}`)}return a})(xn),Cn=class extends I{list(e,t={},n){return this._client.getAPIList(L`/chat/completions/${e}/messages`,M,{query:t,...n,__security:{bearerAuth:!0}})}};function wn(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Tn(e){return e?.$brand===`auto-parseable-response-format`}function En(e){return Tn(e)||e?.type===`json_schema`}function Dn(e,t){return En(e)?typeof e==`object`&&e&&`$parseRaw`in e&&typeof e.$parseRaw==`function`?e.$parseRaw(t):JSON.parse(t):null}function On(e){return e?.$brand===`auto-parseable-tool`}function kn(e,t){return!t||!Pn(t)?{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:An(e,t)}function An(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new re;if(e.finish_reason===`content_filter`)throw new ie;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Mn(t,e))??void 0}:void 0,parsed:e.message.content!==null&&e.message.content!==void 0&&!e.message.refusal&&(e.message.content!==``||!e.message.tool_calls?.length&&!e.message.function_call)?jn(t,e.message.content):null}}});return{...e,choices:n}}function jn(e,t){return Dn(e.response_format,t)}function Mn(e,t){if(t.type===`custom`)return t;if(t.type!==`function`){let e=t.type;throw new f(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${e}\``)}let n=e.tools?.find(e=>wn(e)&&e.function?.name===t.function.name),r=null;return On(n)?r=n.$parseRaw(t.function.arguments):n?.function.strict&&(r=JSON.parse(t.function.arguments)),{...t,function:{...t.function,parsed_arguments:r}}}function Nn(e,t){if(!e||!(`tools`in e)||!e.tools||t.type!==`function`)return!1;let n=e.tools?.find(e=>wn(e)&&e.function?.name===t.function?.name);return wn(n)&&(On(n)||n?.function.strict||!1)}function Pn(e){return En(e.response_format)?!0:e.tools?.some(e=>On(e)||e.type===`function`&&e.function.strict===!0)??!1}function Fn(e){for(let t of e??[])if(t.type!==`custom`){if(t.type!==`function`){let e=t.type;throw new f(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${e}\``)}if(t.function.strict!==!0)throw new f(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var In=e=>e?.role===`assistant`,Ln=e=>e?.role===`tool`,Rn,zn,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn;function $n(){let e=[],t=0;return{get length(){return e.length-t},enqueue(t){e.push(t)},dequeue(){if(t===e.length)return;let n=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&t*2>=e.length&&(e=e.slice(t),t=0),n},clear(){e=[],t=0}}}var er=class{constructor(){Rn.add(this),this.controller=new AbortController,zn.set(this,void 0),Bn.set(this,()=>void 0),Vn.set(this,()=>void 0),Hn.set(this,void 0),Un.set(this,()=>void 0),Wn.set(this,()=>void 0),Gn.set(this,Object.create(null)),Kn.set(this,[]),qn.set(this,!1),Jn.set(this,!1),Yn.set(this,!1),Xn.set(this,!1),s(this,zn,new Promise((e,t)=>{s(this,Bn,e,`f`),s(this,Vn,t,`f`)}),`f`),s(this,Hn,new Promise((e,t)=>{s(this,Un,e,`f`),s(this,Wn,t,`f`)}),`f`),c(this,zn,`f`).catch(()=>void 0),c(this,Hn,`f`).catch(()=>void 0)}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(e=>{t=!0,c(this,Rn,`m`,Qn).call(this,e)}).then(()=>{if(!t){try{this._emitFinal()}catch(e){c(this,Rn,`m`,Qn).call(this,e);return}this._emit(`end`)}})},0)}_connected(){this.ended||(c(this,Bn,`f`).call(this),this._emit(`connect`))}get ended(){return c(this,qn,`f`)}get errored(){return c(this,Jn,`f`)}get aborted(){return c(this,Yn,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),c(this,Kn,`f`).push({signal:e,listener:t})}on(e,t){var n;return((n=c(this,Gn,`f`))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=c(this,Gn,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r!==-1&&n.splice(r,1),this}once(e,t){var n;return((n=c(this,Gn,`f`))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{s(this,Xn,!0,`f`);let r=t=>{this.off(e,i),n(t)},i=(...n)=>{e!==`error`&&this.off(`error`,r),t(n.length>1?n:n[0])};e!==`error`&&this.once(`error`,r),this.once(e,i)})}events(e){return this._createIterator(t=>{let n=(...e)=>t(e);return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!==`error`,rejectOnAbort:e!==`abort`})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:n=!0,onReturn:r}={}){let i=$n(),a=$n(),o=this.ended,s,c=!1,l=()=>void 0,u=()=>({value:void 0,done:!0}),d=()=>{for(;a.length;)a.dequeue().resolve(u())},f=()=>{!s||c||!a.length||(c=!0,a.dequeue().reject(s))},p=()=>{l(),this.off(`end`,g),t&&this.off(`error`,h),n&&this.off(`abort`,h)},m=e=>{if(o)return;let t=a.dequeue();t?t.resolve({value:e,done:!1}):i.enqueue(e)},h=e=>{s=e,i.length||f()},g=()=>{o=!0,p(),i.length||(f(),d())};return o||(l=e(m),this.on(`end`,g),t&&this.on(`error`,h),n&&this.on(`abort`,h)),{next:()=>i.length?Promise.resolve({value:i.dequeue(),done:!1}):s&&!c?(c=!0,Promise.reject(s)):o?Promise.resolve(u()):new Promise((e,t)=>{a.enqueue({resolve:e,reject:t})}),return:()=>(o=!0,i.clear(),p(),d(),r&&(this.done().catch(()=>void 0),r()),Promise.resolve(u())),[Symbol.asyncIterator](){return this}}}async done(){s(this,Xn,!0,`f`),await c(this,Hn,`f`)}_hasListeners(e){return!!c(this,Gn,`f`)[e]?.length}_emit(e,...t){if(c(this,qn,`f`))return;e===`end`&&(c(this,Rn,`m`,Zn).call(this),s(this,qn,!0,`f`),c(this,Un,`f`).call(this));let n=c(this,Gn,`f`)[e];if(n){c(this,Gn,`f`)[e]=n.filter(e=>!e.once);for(let{listener:e}of n)e(...t)}if(e===`abort`){let e=t[0];!c(this,Xn,`f`)&&!n?.length&&Promise.reject(e),c(this,Vn,`f`).call(this,e),c(this,Wn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!c(this,Xn,`f`)&&!n?.length&&Promise.reject(e),c(this,Vn,`f`).call(this,e),c(this,Wn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};zn=new WeakMap,Bn=new WeakMap,Vn=new WeakMap,Hn=new WeakMap,Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Rn=new WeakSet,Zn=function(){for(let{signal:e,listener:t}of c(this,Kn,`f`).splice(0))e.removeEventListener(`abort`,t)},Qn=function(e){if(s(this,Jn,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new m),e instanceof m)return s(this,Yn,!0,`f`),this._emit(`abort`,e);if(e instanceof f)return this._emit(`error`,e);if(e instanceof Error){let t=new f(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new f(String(e)))};function tr(e){return typeof e.parse==`function`}var R,nr,rr,ir,ar,or,sr,cr,lr,ur=10;function dr(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||=`call_${l()}`}function fr(e){if(!In(e))return e;let t={role:`assistant`};return e.audio!=null&&(t.audio={id:e.audio.id}),e.content!==void 0&&(t.content=e.content),e.function_call!=null&&(t.function_call=e.function_call),e.name!==void 0&&(t.name=e.name),e.refusal!=null&&(t.refusal=e.refusal),e.tool_calls!==void 0&&(t.tool_calls=e.tool_calls.map(e=>e.type===`custom`?{id:e.id,type:e.type,custom:{input:e.custom.input,name:e.custom.name}}:{id:e.id,type:e.type,function:{arguments:e.function.arguments,name:e.function.name}})),t}var pr=class extends er{constructor(){super(...arguments),R.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){dr(e),this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Ln(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(In(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new f(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),c(this,R,`m`,rr).call(this)}async finalMessage(){return await this.done(),c(this,R,`m`,ir).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,R,`m`,ar).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,R,`m`,or).call(this)}async totalUsage(){return await this.done(),c(this,R,`m`,sr).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=c(this,R,`m`,ir).call(this);t&&this._emit(`finalMessage`,t);let n=c(this,R,`m`,rr).call(this);n&&this._emit(`finalContent`,n);let r=c(this,R,`m`,ar).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=c(this,R,`m`,or).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,c(this,R,`m`,sr).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),c(nr,nr,`m`,cr).call(nr,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(An(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,toolContext:s,...l}=t,u=s,d=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:p=ur,afterCompletion:m}=r||{},h=t.tools.map(e=>{if(On(e)){if(!e.$callback)throw new f("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),g=Object.create(null);for(let e of h)e.type===`function`&&(g[e.function.name||e.function.function.name]=e.function);let _=`tools`in t?h.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let v=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=g[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(g).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(d&&d!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(d)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let s;if(tr(o)){let e;try{e=await o.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}s=await o.function(e,n,u)}else s=await o.function(a,n,u);let l=c(nr,nr,`m`,lr).call(nr,s);return{message:{role:i,tool_call_id:t,content:l},functionCalled:!0}};for(let i=0;i<p;++i){let i=await this._createChatCompletion(e,{...l,tool_choice:a,tools:_,messages:this.messages.map(fr)},r),o=i.choices[0]?.message;if(!o)throw new f(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await m?.(i,n);return}if(d||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await v(e);if(t.message&&this._addMessage(t.message),d&&t.functionCalled){await m?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(v));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await m?.(i,n)}}};nr=pr,R=new WeakSet,rr=function(){return c(this,R,`m`,ir).call(this).content??null},ir=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(In(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new f(`stream ended without producing a ChatCompletionMessage with role=assistant`)},ar=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(In(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},or=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ln(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},sr=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},cr=function(e){if(e.n!=null&&e.n>1)throw new f(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},lr=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var mr=class e extends pr{static runTools(t,n,r){let i=new e,a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),In(e)&&e.content&&this._emit(`content`,e.content)}},z={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},hr=class extends Error{},gr=class extends Error{};function _r(e,t=z.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return vr(e.trim(),t)}var vr=(e,t)=>{let n=e.length,r=0,i=e=>{throw new hr(`${e} at position ${r}`)},a=e=>{throw new gr(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||z.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||z.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||z.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||z.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||z.MINUS_INFINITY&t&&n-r>1&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||z.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)===`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(z.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&z.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(z.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(z.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(z.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(z.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r===n&&!(z.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
8
|
-
\r `.includes(e[r]);)r++};return o()},yr=e=>_r(e,z.ALL^z.NUM),B,V,br,xr,H,Sr,Cr,wr,Tr,Er,Dr,Or,kr=`chat.completion.chunk.message:`;function Ar(e,t,n){let r={type:`message`,message:t,...n?{tool_call_ids:n}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${kr}${JSON.stringify(r)}`}}function jr(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(kr)}function Mr(e){return`type`in e?e:JSON.parse(e.object.slice(30))}var Nr=128,Pr=128;function Fr(e,t){return Object.prototype.propertyIsEnumerable.call(t,`__proto__`)&&!pe(e,`__proto__`)&&Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(e,t)}var Ir=class e extends pr{constructor(e){super(),B.add(this),V.set(this,void 0),br.set(this,void 0),xr.set(this,void 0),H.set(this,void 0),s(this,V,e,`f`),s(this,br,new Set,`f`),s(this,xr,[],`f`)}get currentChatCompletionSnapshot(){return c(this,H,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),c(this,B,`m`,Sr).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)c(this,B,`m`,wr).call(this,e);if(r.controller.signal?.aborted)throw new m;return this._addChatCompletion(c(this,B,`m`,Dr).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,B,`m`,Sr).call(this),this._connected();let n=Ve.fromReadableStream(e,this.controller),r;for await(let e of n){if(jr(e)){let t=Mr(e);if(c(this,H,`f`)){let e=c(this,H,`f`).choices[0]?.message.tool_calls;for(let[n,r]of t.tool_call_ids?.entries()??[]){let t=e?.[n];t&&r&&(t.id=r)}this._addChatCompletion(c(this,B,`m`,Dr).call(this)),r=void 0}this._addMessage(t.message);continue}let t=e;r&&t.id&&r!==t.id&&this._addChatCompletion(c(this,B,`m`,Dr).call(this)),c(this,B,`m`,wr).call(this,t),t.id&&(r=t.id)}if(n.controller.signal?.aborted)throw new m;if(c(this,H,`f`))return this._addChatCompletion(c(this,B,`m`,Dr).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new f(`request ended without sending any chunks`)}[(V=new WeakMap,br=new WeakMap,xr=new WeakMap,H=new WeakMap,B=new WeakSet,Sr=function(){this.ended||(s(this,br,new Set,`f`),s(this,H,void 0,`f`))},Cr=function(e){let t=c(this,xr,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,xr,`f`)[e.index]=t,t)},wr=function(e){if(this.ended)return;let t=c(this,B,`m`,Or).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index],{delta:r}=n;r?.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.content,e.message.content),this._emit(`content.delta`,{delta:r.content,snapshot:e.message.content,parsed:e.message.parsed})),r?.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=c(this,B,`m`,Cr).call(this,e);e.finish_reason&&(c(this,B,`m`,Er).call(this,e),i.current_tool_call_index!=null&&c(this,B,`m`,Tr).call(this,e,i.current_tool_call_index));for(let t of r?.tool_calls??[])i.current_tool_call_index!==t.index&&(c(this,B,`m`,Er).call(this,e),i.current_tool_call_index!=null&&c(this,B,`m`,Tr).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=t.index;for(let t of r?.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n.type)}}},Tr=function(e,t){if(c(this,B,`m`,Cr).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=c(this,V,`f`)?.tools?.find(e=>wn(e)&&e.function.name===n.function.name),r=null;On(e)?r=e.$parseRaw(n.function.arguments):e?.function.strict&&(r=JSON.parse(n.function.arguments)),this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:r})}else n.type},Er=function(e){let t=c(this,B,`m`,Cr).call(this,e);e.message.content!=null&&(e.message.content!==``||!e.message.refusal&&!e.message.tool_calls?.length&&!e.message.function_call)&&!t.content_done&&(t.content_done=!0,this._emit(`content.done`,{content:e.message.content,parsed:e.message.refusal?null:Dn(c(this,V,`f`)?.response_format,e.message.content)})),e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},Dr=function(){if(this.ended)throw new f(`stream has ended, this shouldn't happen`);let e=c(this,H,`f`);if(!e)throw new f(`request ended without sending any chunks`);let t=c(this,br,`f`);return s(this,br,new Set,`f`),s(this,H,void 0,`f`),s(this,xr,[],`f`),Lr(e,c(this,V,`f`),t)},Or=function(e){var t,n,r,i,a;let o=c(this,H,`f`),{choices:l,...u}=e;if(o)e.id&&Fr(o,u);else{let e={...u,choices:[]};s(this,H,e,`f`),o=e}let d=c(this,V,`f`)?.n,p=typeof d==`number`&&Number.isSafeInteger(d)&&d>0?Math.min(d,Nr):Nr;for(let{delta:s,finish_reason:l,index:u,logprobs:d=null,...m}of e.choices){if(!Number.isSafeInteger(u)||u<0||u>=p)throw new f(`Chat completion stream contains an invalid choice index: ${u}`);let e=o.choices[u];if(!e){let t={finish_reason:l,index:u,message:{},logprobs:d,...m};o.choices[u]=t,e=t}if(d){if(e.logprobs){let{content:r,refusal:i,...a}=d;Fr(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}else e.logprobs={...d}}if(l&&(e.finish_reason=l,c(this,V,`f`)&&Pn(c(this,V,`f`)))){if(l===`length`)throw new re;if(l===`content_filter`)throw new ie}if(Fr(e,m),!s)continue;c(this,br,`f`).delete(u);let{audio:h,content:g,refusal:_,function_call:v,role:y,tool_calls:b,...x}=s;if(Fr(e.message,x),h?.expires_at!=null&&h.id==null&&h.data==null&&h.transcript==null&&g==null&&_==null&&v==null&&y==null&&b==null&&Object.keys(x).length===0&&c(this,br,`f`).add(u),_&&(e.message.refusal=(e.message.refusal||``)+_),y&&(e.message.role=y),h){let t=(r=e.message).audio??(r.audio={});h.id!=null&&(t.id=h.id),h.data!=null&&(t.data=(t.data??``)+h.data),h.transcript!=null&&(t.transcript=(t.transcript??``)+h.transcript),h.expires_at!=null&&(t.expires_at=h.expires_at)}if(v&&(e.message.function_call?(v.name&&(e.message.function_call.name=v.name),v.arguments&&((i=e.message.function_call).arguments??(i.arguments=``),e.message.function_call.arguments+=v.arguments)):e.message.function_call=v),g!=null&&(e.message.content=(e.message.content||``)+g,!e.message.refusal&&En(c(this,V,`f`)?.response_format)&&(e.message.parsed=e.message.content.trim()?yr(e.message.content):null)),b){let t=(a=e.message).tool_calls??(a.tool_calls=[]);for(let{index:e,id:n,type:r,function:i,custom:a,...o}of b){if(!Number.isSafeInteger(e)||e<0||e>=Pr)throw new f(`Chat completion stream contains an invalid tool call index: ${e}`);let s=t[e]??(t[e]={});if(Fr(s,o),n&&(s.id=n),r&&(s.type=r),a){let e=s.custom??={name:a.name??``,input:``};a.name&&(e.name=a.name),a.input&&(e.input+=a.input)}if(i){let e=s.function??={name:i.name??``,arguments:``};i.name&&(e.name=i.name),i.arguments&&(e.arguments+=i.arguments,Nn(c(this,V,`f`),s)&&(e.parsed_arguments=yr(e.arguments)))}}}}return o},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`chunk`,t),()=>this.off(`chunk`,t)},{onReturn:()=>this.abort()})}toReadableStream(){return new Ve(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Lr(e,t,n){let{id:r,choices:i,created:a,model:o,system_fingerprint:s,...c}=e;return kn({...c,id:r,choices:i.map(({message:t,finish_reason:r,index:i,logprobs:a,...o})=>{let{content:s=null,function_call:c,tool_calls:u,audio:d,...p}=t,m=r??(n.has(i)&&Rr(d)?`stop`:null);if(!m)throw new f(`missing finish_reason for choice ${i}`);let h=d?{audio:d}:{},g=t.role;if(!g)throw new f(`missing role for choice ${i}`);if(c){let{arguments:e,name:n}=c;if(e==null)throw new f(`missing function_call.arguments for choice ${i}`);if(!n)throw new f(`missing function_call.name for choice ${i}`);return{...o,message:{...h,content:s,function_call:{arguments:e,name:n},role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}return u?{...o,index:i,finish_reason:m,logprobs:a,message:{...p,...h,role:g,content:s,refusal:t.refusal??null,tool_calls:u.map((t,n)=>{if(t.type==null)throw new f(`missing choices[${i}].tool_calls[${n}].type\n${zr(e)}`);if(t.type===`custom`){let{custom:r,type:a,id:o,...s}=t,{input:c=``,name:u,...d}=r||{};if(u==null)throw new f(`missing choices[${i}].tool_calls[${n}].custom.name\n${zr(e)}`);return{...s,id:o||`call_${l()}`,type:a,custom:{...d,name:u,input:c}}}let{function:r,type:a,id:o,...s}=t,{arguments:c,name:u,...d}=r||{};if(u==null)throw new f(`missing choices[${i}].tool_calls[${n}].function.name\n${zr(e)}`);if(c==null)throw new f(`missing choices[${i}].tool_calls[${n}].function.arguments\n${zr(e)}`);return{...s,id:o||`call_${l()}`,type:a,function:{...d,name:u,arguments:c}}})}}:{...o,message:{...p,...h,content:s,role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}),created:a,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Rr(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function zr(e){return JSON.stringify(e)}var Br=class e extends Ir{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e,t,n=this._createIterator(n=>{let r=t=>{e=t,n(t)},i=r=>{if(In(r)){t=r.tool_calls?.map(e=>e.id);return}if(Ln(r)){if(!e)throw new f(`cannot serialize a tool message before receiving any chunks`);n(Ar(e,r,t))}};return this.on(`chunk`,r),this.on(`message`,i),()=>{this.off(`chunk`,r),this.off(`message`,i)}},{onReturn:()=>this.abort()});return new Ve(()=>n,this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},Vr=class extends I{constructor(){super(...arguments),this.messages=new Cn(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`,M,{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 Fn(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:`chat.completions.parse`}})._thenUnwrap(t=>An(t,e))}runTools(e,t){return e.stream?Br.runTools(this._client,e,t):mr.runTools(this._client,e,t)}stream(e,t){return Ir.createChatCompletion(this._client,e,t)}};Vr.Messages=Cn;var Hr=class extends I{constructor(){super(...arguments),this.completions=new Vr(this._client)}};Hr.Completions=Vr;var Ur=class extends I{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`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Wr=class extends I{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},Gr=class extends I{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`,N,{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`,kt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,kt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},Kr=class extends I{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}})}},qr=class extends I{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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Jr=class extends I{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`,At,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Yr=class extends I{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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Xr=class extends I{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}})}},Zr=class extends I{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}})}},Qr=class extends I{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:r}=t;return this._client.get(L`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/groups/${e}/roles`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(L`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},$r=class extends I{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:r}=t;return this._client.get(L`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/groups/${e}/users`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(L`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ei=class extends I{constructor(){super(...arguments),this.users=new $r(this._client),this.roles=new Qr(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`,At,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};ei.Users=$r,ei.Roles=Qr;var ti=class extends I{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(L`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/api_keys`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ni=class extends I{list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/certificates`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(L`/organization/projects/${e}/certificates/activate`,kt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(L`/organization/projects/${e}/certificates/deactivate`,kt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},ri=class extends I{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}})}},ii=class extends I{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}})}},ai=class extends I{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}})}},oi=class extends I{listRateLimits(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/rate_limits`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},si=class extends I{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:r}=t;return this._client.get(L`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/projects/${e}/roles`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ci=class extends I{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:r}=t;return this._client.get(L`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/spend_alerts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},li=class extends I{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}})}},ui=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(L`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(L`/projects/${r}/groups/${e}/roles`,At,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(L`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},di=class extends I{constructor(){super(...arguments),this.roles=new ui(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:r,...i}=t;return this._client.get(L`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/groups`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};di.Roles=ui;var fi=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/service_accounts/${e}/api_keys`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},pi=class extends I{constructor(){super(...arguments),this.apiKeys=new fi(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:r}=t;return this._client.get(L`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/service_accounts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};pi.APIKeys=fi;var mi=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(L`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(L`/projects/${r}/users/${e}/roles`,At,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(L`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},hi=class extends I{constructor(){super(...arguments),this.roles=new mi(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:r}=t;return this._client.get(L`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/users`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};hi.Roles=mi;var U=class extends I{constructor(){super(...arguments),this.users=new hi(this._client),this.serviceAccounts=new pi(this._client),this.apiKeys=new ti(this._client),this.rateLimits=new oi(this._client),this.modelPermissions=new ai(this._client),this.hostedToolPermissions=new ii(this._client),this.groups=new di(this._client),this.roles=new si(this._client),this.dataRetention=new ri(this._client),this.spendLimit=new li(this._client),this.spendAlerts=new ci(this._client),this.certificates=new ni(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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(L`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};U.Users=hi,U.ServiceAccounts=pi,U.APIKeys=ti,U.RateLimits=oi,U.ModelPermissions=ai,U.HostedToolPermissions=ii,U.Groups=di,U.Roles=si,U.DataRetention=ri,U.SpendLimit=li,U.SpendAlerts=ci,U.Certificates=ni;var gi=class extends I{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:r}=t;return this._client.get(L`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/users/${e}/roles`,At,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(L`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},_i=class extends I{constructor(){super(...arguments),this.roles=new gi(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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};_i.Roles=gi;var W=class extends I{constructor(){super(...arguments),this.auditLogs=new Wr(this._client),this.adminAPIKeys=new Ur(this._client),this.usage=new Zr(this._client),this.invites=new qr(this._client),this.users=new _i(this._client),this.groups=new ei(this._client),this.roles=new Jr(this._client),this.dataRetention=new Kr(this._client),this.spendLimit=new Xr(this._client),this.spendAlerts=new Yr(this._client),this.certificates=new Gr(this._client),this.projects=new U(this._client)}};W.AuditLogs=Wr,W.AdminAPIKeys=Ur,W.Usage=Zr,W.Invites=qr,W.Users=_i,W.Groups=ei,W.Roles=Jr,W.DataRetention=Kr,W.SpendLimit=Xr,W.SpendAlerts=Yr,W.Certificates=Gr,W.Projects=U;var vi=class extends I{constructor(){super(...arguments),this.organization=new W(this._client)}};vi.Organization=W;var yi=class extends I{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:P([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},bi=class extends I{create(e,t){return this._client.post(`/audio/transcriptions`,F({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},xi=class extends I{create(e,t){return this._client.post(`/audio/translations`,F({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Si=class extends I{constructor(){super(...arguments),this.transcriptions=new bi(this._client),this.translations=new xi(this._client),this.speech=new yi(this._client)}};Si.Transcriptions=bi,Si.Translations=xi,Si.Speech=yi;var Ci=class extends I{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`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},wi=class extends I{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/assistants/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Ti=class extends I{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Ei=class extends I{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Di=class extends I{constructor(){super(...arguments),this.sessions=new Ti(this._client),this.transcriptionSessions=new Ei(this._client)}};Di.Sessions=Ti,Di.TranscriptionSessions=Ei;var Oi=class extends I{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/chatkit/sessions/${e}/cancel`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},ki=class extends I{retrieve(e,t){return this._client.get(L`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,N,{query:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(L`/chatkit/threads/${e}/items`,N,{query:t,...n,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Ai=class extends I{constructor(){super(...arguments),this.sessions=new Oi(this._client),this.threads=new ki(this._client)}};Ai.Sessions=Oi,Ai.Threads=ki;var ji=class extends I{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(L`/responses/${e}/input_items?beta=true`,M,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}},Mi=class extends I{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},Ni=class extends I{constructor(){super(...arguments),this.inputItems=new ji(this._client),this.inputTokens=new Mi(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(L`/responses/${e}?beta=true`,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(L`/responses/${e}?beta=true`,{...n,headers:P([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(L`/responses/${e}/cancel?beta=true`,{...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}};Ni.InputItems=ji,Ni.InputTokens=Mi;var Pi=class extends I{create(e,t,n){return this._client.post(L`/threads/${e}/messages`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/messages/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/messages`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(L`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Fi=class extends I{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(L`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(L`/threads/${r}/runs/${e}/steps`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Ii=e=>{if(globalThis.Buffer!==void 0){let t=globalThis.Buffer.from(e,`base64`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof atob<`u`){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}throw new f("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Li=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},G=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},Ri=1024,zi=65536,Bi=new WeakMap,Vi=new WeakSet;function Hi(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function Ui(e){for(let[t,n]of e.arrays)n.cacheable&&!Vi.has(t)?Bi.set(t,{length:n.length,ownEntryCount:n.ownEntryCount}):Bi.delete(t)}function Wi(e){return typeof e==`string`||typeof e==`number`}function Gi(e,t){return t.every(Wi)&&e.every(Wi)}function Ki(e){let t=0;for(let n of Object.keys(e)){let r=Number(n);Number.isSafeInteger(r)&&r>=0&&r<e.length&&String(r)===n&&(t+=1)}return t}function qi(e,t,n){return t?n?.length===e.length?n.ownEntryCount:Ki(e):0}function Ji(e,t,n){let{index:r}=e;if(t===`array`&&r==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(t===`array`&&typeof r!=`number`)throw TypeError(`Expected array delta entry \`index\` property to be a number but got ${r}`);if(!Number.isSafeInteger(r)||r<0||r>=n+Ri||r>=zi)throw new f(`Assistant stream delta contains an invalid ${t} index: ${r}`);return r}function Yi(e,t,n,r,i){let a=r.arrays.get(e);if(!a){let t=r.cacheArrays&&!Vi.has(e),n=t?Bi.get(e):void 0;a={baselineLength:e.length,cacheable:t,enforceSparseHoleBudget:t,entries:new Map,length:e.length,ownEntryCount:qi(e,t,n)},r.arrays.set(e,a)}for(let o of t){if(!C(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let t=Ji(o,n,a.baselineLength),s;a.entries.has(t)?s=a.entries.get(t):pe(e,t)?(s=e[t],s??a.entries.set(t,o)):(a.entries.set(t,o),a.ownEntryCount+=1);let c=Math.max(a.length,t+1);if(a.enforceSparseHoleBudget&&c-a.ownEntryCount>Ri)throw new f(`Assistant stream delta contains an invalid ${n} index: ${t}`);C(s)&&i(s,o,r),a.length=c}}function Xi(e,t,n){let r=n.records.get(e);for(let[i,a]of Object.entries(t)){if(i===`index`||i===`type`)continue;let t;if(r?.has(i)?t=r.get(i):pe(e,i)&&(t=e[i]),t==null){r||(r=new Map,n.records.set(e,r)),r.set(i,a);continue}C(t)&&C(a)?Xi(t,a,n):Array.isArray(t)&&Array.isArray(a)&&!Gi(t,a)&&Yi(t,a,`array`,n,Xi)}}function Zi(e){return(C(e)||Array.isArray(e))&&Vi.has(e)}function K(e){if(!(!C(e)&&!Array.isArray(e)||Vi.has(e))){Vi.add(e),Array.isArray(e)&&Bi.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n&&`value`in n&&K(n.value)}}}function Qi(e,t,n){Vi.has(e)&&K(n),Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function $i(e){let{index:t}=e;if(t==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof t!=`number`)throw TypeError(`Expected array delta entry \`index\` property to be a number but got ${t}`);return t}function ea(e,t,n){if(Gi(e,t)){e.push(...t),Bi.delete(e);return}for(let r of t){if(!C(r))throw Error(`Expected array delta entry to be an object but got: ${r}`);let t=$i(r);if(pe(e,t)){let i=e[t];i==null?(Vi.has(e)&&K(r),e[t]=r):e[t]=n(i,r)}else Qi(e,t,r)}}function ta(e,t){let n=Vi.has(e);for(let[r,i]of Object.entries(t)){if(r===`__proto__`||r===`constructor`||r===`prototype`)throw new f(`Assistant stream delta contains an unsafe property: ${r}`);if(!pe(e,r)){n&&K(i),e[r]=i;continue}let t=e[r];if(t==null){n&&K(i),e[r]=i;continue}if(r===`index`||r===`type`){e[r]=i;continue}if(typeof t==`string`&&typeof i==`string`)t+=i;else if(typeof t==`number`&&typeof i==`number`)t+=i;else if(C(t)&&C(i))t=ta(t,i);else if(Array.isArray(t)&&Array.isArray(i)){ea(t,i,ta);continue}else throw TypeError(`Unhandled record type: ${r}, deltaValue: ${i}, accValue: ${t}`);e[r]=t}return e}function na(e){if(!(!C(e)&&!Array.isArray(e)))for(let[t,n]of Object.entries(e)){if(t===`__proto__`||t===`constructor`||t===`prototype`)throw new f(`Assistant stream delta contains an unsafe property: ${t}`);na(n)}}function ra(e,t,n=!1){na(t);let r=e,i=t,a=Hi(n&&!Zi(e));return Xi(r,i,a),ta(r,i),Ui(a),e}function ia(e,t,n,r=!0){na(t);let i=Hi(r&&!Zi(e));return Yi(e,t,n,i,Xi),()=>Ui(i)}var q,aa,oa,sa,J,ca,la,ua,da,Y,fa,pa,ma,ha,ga,_a,va,X,ya,ba,xa,Sa,Ca,wa=class e extends er{constructor(){super(...arguments),q.add(this),aa.set(this,[]),oa.set(this,Object.create(null)),sa.set(this,Object.create(null)),J.set(this,void 0),ca.set(this,void 0),la.set(this,void 0),ua.set(this,void 0),da.set(this,void 0),Y.set(this,void 0),fa.set(this,void 0),pa.set(this,void 0),ma.set(this,void 0)}[(aa=new WeakMap,oa=new WeakMap,sa=new WeakMap,J=new WeakMap,ca=new WeakMap,la=new WeakMap,ua=new WeakMap,da=new WeakMap,Y=new WeakMap,fa=new WeakMap,pa=new WeakMap,ma=new WeakMap,q=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(structuredClone(t));return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}static fromReadableStream(t){let n=new e;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=Ve.fromReadableStream(e,this.controller);for await(let e of n)c(this,q,`m`,ha).call(this,e);if(n.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}toReadableStream(){return new Ve(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runToolAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)c(this,q,`m`,ha).call(this,e);if(a.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}static createThreadAssistantStream(t,n,r){let i=new e;return i._run(()=>i._threadAssistantStream(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static createAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}currentEvent(){return K(c(this,fa,`f`)),c(this,fa,`f`)}currentRun(){return K(c(this,pa,`f`)),c(this,pa,`f`)}currentMessageSnapshot(){return K(c(this,J,`f`)),c(this,J,`f`)}currentRunStepSnapshot(){return K(c(this,ma,`f`)),c(this,ma,`f`)}async finalRunSteps(){return await this.done(),Object.values(c(this,oa,`f`))}async finalMessages(){return await this.done(),Object.values(c(this,sa,`f`))}async finalRun(){if(await this.done(),!c(this,ca,`f`))throw Error(`Final run was not received.`);return c(this,ca,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)c(this,q,`m`,ha).call(this,e);if(i.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)c(this,q,`m`,ha).call(this,e);if(a.controller.signal?.aborted)throw new m;return this._addRun(c(this,q,`m`,ga).call(this))}static accumulateDelta(e,t){return ra(e,t)}_addRun(e){return c(this,q,`m`,X).call(this,`run`,e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};ha=function(e){if(!this.ended)switch(s(this,fa,e,`f`),c(this,q,`m`,ya).call(this,e),e.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`:c(this,q,`m`,Ca).call(this,e);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`:c(this,q,`m`,va).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:c(this,q,`m`,_a).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`)}},ga=function(){if(this.ended)throw new f(`stream has ended, this shouldn't happen`);if(!c(this,ca,`f`))throw Error(`Final run has not been received`);return c(this,ca,`f`)},_a=function(e){let[t,n]=c(this,q,`m`,xa).call(this,e,c(this,J,`f`));s(this,J,t,`f`),c(this,sa,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type===`text`&&c(this,q,`m`,X).call(this,`textCreated`,n.text)}switch(e.event){case`thread.message.created`:s(this,la,void 0,`f`),s(this,ua,void 0,`f`),c(this,q,`m`,X).call(this,`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(c(this,q,`m`,X).call(this,`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type===`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type===`text`)c(this,q,`m`,X).call(this,`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!==c(this,la,`f`)){if(c(this,ua,`f`))switch(c(this,ua,`f`).type){case`text`:c(this,q,`m`,X).call(this,`textDone`,c(this,ua,`f`).text,c(this,J,`f`));break;case`image_file`:c(this,q,`m`,X).call(this,`imageFileDone`,c(this,ua,`f`).image_file,c(this,J,`f`))}s(this,la,n.index,`f`)}s(this,ua,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(c(this,la,`f`)!==void 0){let t=e.data.content[c(this,la,`f`)];if(t)switch(t.type){case`image_file`:c(this,q,`m`,X).call(this,`imageFileDone`,t.image_file,c(this,J,`f`));break;case`text`:c(this,q,`m`,X).call(this,`textDone`,t.text,c(this,J,`f`))}}c(this,J,`f`)&&c(this,q,`m`,X).call(this,`messageDone`,e.data),s(this,la,void 0,`f`),s(this,ua,void 0,`f`),s(this,J,void 0,`f`)}},va=function(e){let t=c(this,q,`m`,ba).call(this,e);switch(s(this,ma,t,`f`),e.event){case`thread.run.step.created`:s(this,da,void 0,`f`),s(this,Y,void 0,`f`),c(this,q,`m`,X).call(this,`runStepCreated`,e.data);break;case`thread.run.step.delta`:{let n=e.data.delta;if(n.step_details&&n.step_details.type===`tool_calls`&&n.step_details.tool_calls&&t.step_details.type===`tool_calls`)for(let e of n.step_details.tool_calls)e.index===c(this,da,`f`)?c(this,q,`m`,X).call(this,`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallDone`,c(this,Y,`f`)),s(this,da,e.index,`f`),s(this,Y,t.step_details.tool_calls[e.index],`f`),c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallCreated`,c(this,Y,`f`)));c(this,q,`m`,X).call(this,`runStepDelta`,e.data.delta,t);break}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:s(this,ma,void 0,`f`),e.data.step_details.type===`tool_calls`&&c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallDone`,c(this,Y,`f`)),c(this,q,`m`,X).call(this,`runStepDone`,e.data,t),s(this,da,void 0,`f`),s(this,Y,void 0,`f`)}},X=function(e,...t){if(this._hasListeners(e))for(let e of t)K(e);this._emit(e,...t)},ya=function(e){c(this,aa,`f`).push(e),c(this,q,`m`,X).call(this,`event`,e)},ba=function(e){switch(e.event){case`thread.run.step.created`:return c(this,oa,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:{let t=c(this,oa,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=ra(t,n.delta,!0);c(this,oa,`f`)[e.data.id]=r}return c(this,oa,`f`)[e.data.id]}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:c(this,oa,`f`)[e.data.id]=e.data}if(c(this,oa,`f`)[e.data.id])return c(this,oa,`f`)[e.data.id];throw Error(`No snapshot available`)},xa=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:{if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content){na(r.delta);let e=!Zi(t),i=ia(t.content,r.delta.content,`content`,e);for(let i of r.delta.content)if(pe(t.content,i.index)){let n=t.content[i.index];t.content[i.index]=c(this,q,`m`,Sa).call(this,i,n,e)}else Qi(t.content,i.index,i),n.push(i);i()}return[t,n]}case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Sa=function(e,t,n){return ra(t,e,n)},Ca=function(e){switch(s(this,pa,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`:s(this,ca,e.data,`f`),c(this,Y,`f`)&&c(this,q,`m`,X).call(this,`toolCallDone`,c(this,Y,`f`)),s(this,da,void 0,`f`),s(this,Y,void 0,`f`)}};var Ta=class extends I{constructor(){super(...arguments),this.steps=new Fi(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/runs/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/runs`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(L`/threads/${r}/runs/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return wa.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ge(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return wa.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return wa.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Ta.Steps=Fi;var Ea=class extends I{constructor(){super(...arguments),this.runs=new Ta(this._client),this.messages=new Pi(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/threads/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:P([{"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 wa.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ea.Runs=Ta,Ea.Messages=Pi;var Da=class extends I{constructor(){super(...arguments),this.realtime=new Di(this._client),this.responses=new Ni(this._client),this.chatkit=new Ai(this._client),this.assistants=new wi(this._client),this.threads=new Ea(this._client)}};Da.Realtime=Di,Da.Responses=Ni,Da.ChatKit=Ai,Da.Assistants=wi,Da.Threads=Ea;var Oa=class extends I{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},ka=class extends I{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(L`/containers/${r}/files/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Aa=class extends I{constructor(){super(...arguments),this.content=new ka(this._client)}create(e,t,n){return this._client.post(L`/containers/${e}/files`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(L`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/containers/${e}/files`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(L`/containers/${r}/files/${e}`,{...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};Aa.Content=ka;var ja=class extends I{constructor(){super(...arguments),this.files=new Aa(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`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/containers/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};ja.Files=Aa;var Ma=class extends I{create(e,t){return this._client.post(`/content_provenance_checks`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}},Na=class extends I{create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(L`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/conversations/${e}/items`,N,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(L`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},Pa=class extends I{constructor(){super(...arguments),this.items=new Na(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}})}};Pa.Items=Na;var Fa=class extends I{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(k(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=Li(t)}),e)))}},Ia=class extends I{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(L`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(L`/evals/${r}/runs/${e}/output_items`,M,{query:i,...n,__security:{bearerAuth:!0}})}},La=class extends I{constructor(){super(...arguments),this.outputItems=new Ia(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:r}=t;return this._client.get(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/evals/${e}/runs`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};La.OutputItems=Ia;var Ra=class extends I{constructor(){super(...arguments),this.runs=new La(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`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Ra.Runs=La;var za=class extends I{create(e,t){return this._client.post(`/files`,F({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`,M,{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:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await ge(t),a=await this.retrieve(e),Date.now()-i>n)throw new g({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Ba=class extends I{},Va=class extends I{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}})}},Ha=class extends I{constructor(){super(...arguments),this.graders=new Va(this._client)}};Ha.Graders=Va;var Ua=class extends I{create(e,t,n){return this._client.getAPIList(L`/fine_tuning/checkpoints/${e}/permissions`,kt,{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`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(L`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Wa=class extends I{constructor(){super(...arguments),this.permissions=new Ua(this._client)}};Wa.Permissions=Ua;var Ga=class extends I{list(e,t={},n){return this._client.getAPIList(L`/fine_tuning/jobs/${e}/checkpoints`,M,{query:t,...n,__security:{bearerAuth:!0}})}},Ka=class extends I{constructor(){super(...arguments),this.checkpoints=new Ga(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`,M,{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`,M,{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}})}};Ka.Checkpoints=Ga;var qa=class extends I{constructor(){super(...arguments),this.methods=new Ba(this._client),this.jobs=new Ka(this._client),this.checkpoints=new Wa(this._client),this.alpha=new Ha(this._client)}};qa.Methods=Ba,qa.Jobs=Ka,qa.Checkpoints=Wa,qa.Alpha=Ha;var Ja=class extends I{},Ya=class extends I{constructor(){super(...arguments),this.graderModels=new Ja(this._client)}};Ya.GraderModels=Ja;var Xa=class extends I{createVariation(e,t){return this._client.post(`/images/variations`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,F({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}})}},Za=class extends I{retrieve(e,t){return this._client.get(L`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,kt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},Qa=class extends I{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},$a=class extends I{accept(e,t,n){return this._client.post(L`/realtime/calls/${e}/accept`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(L`/realtime/calls/${e}/hangup`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(L`/realtime/calls/${e}/refer`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(L`/realtime/calls/${e}/reject`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},eo=class extends I{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},to=class extends I{constructor(){super(...arguments),this.clientSecrets=new eo(this._client),this.calls=new $a(this._client)}};to.ClientSecrets=eo,to.Calls=$a;function no(e,t){if(!t||!ao(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return lo(e,t)&&uo(t),t}return ro(e,t)}function ro(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?co(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?io(t,e.text):null}:e);return{...e,content:r}}return e}),i={...e,output:r};return lo(e,i)&&uo(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function io(e,t){return Dn(e.text?.format,t)}function ao(e){return En(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>oo(e)||e.type===`function`&&e.strict===!0)}function oo(e){return e?.$brand===`auto-parseable-tool`}function so(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function co(e,t){let n=so(e.tools??[],t.name),r=null;return oo(n)?r=n.$parseRaw(t.arguments):n?.strict&&(r=JSON.parse(t.arguments)),{...t,parsed_arguments:r}}function lo(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function uo(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var fo=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 RangeError(`missing output at index ${e}`);let n=this.capacity+e,r=t-(this.values[n]??0);if(r!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+r,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,r=0;for(;t<n;)t%2==1&&(r+=this.values[t]??0,t+=1),n%2==1&&(--n,r+=this.values[n]??0),t=Math.floor(t/2),n=Math.floor(n/2);return r}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 e=this.capacity-1;e>0;--e)t[e]=(t[e*2]??0)+(t[e*2+1]??0);this.values=t}};function po(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new fo}}function mo(e,t){if(t.type!==`message`)return``;let n=``;for(let e of t.content)e.type===`output_text`&&(n+=e.text);return e.outputTextLengths.set(t,n.length),n}function ho(e,t){if(e.canonicalSnapshot===t)return;let n=new fo,r=``;for(let i of t.output){let t=mo(e,i);r+=t,n.append(t.length)}t.output_text!==r&&(t.output_text=r),e.outputTextIndex=n,e.canonicalSnapshot=t}function go(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new fo;let n=structuredClone(t);return!Object.getOwnPropertyDescriptor(n,`output_text`)||n.output_text===null||n.output_text===void 0?ho(e,n):n.output.length===0&&n.output_text===``&&(e.canonicalSnapshot=n),n}function _o(e,t,n,r,i){let a=e.outputTextLengths.get(t);if(a!==void 0){let o=a-r.length+i.length;e.outputTextLengths.set(t,o),e.outputTextIndex.update(n,o)}}function vo(e,t,n){if(t.length===0){e.output_text+=n;return}e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+n}function yo(e,t,n,r){if(n===void 0||t?.type!==`message`)return 0;if(n<t.content.length-n-1){let e=0;for(let r=0;r<n;r+=1){let n=t.content[r];n?.type===`output_text`&&(e+=n.text.length)}return e}let i=0;for(let e=n+1;e<t.content.length;e+=1){let n=t.content[e];n?.type===`output_text`&&(i+=n.text.length)}return(e.outputTextLengths.get(t)??mo(e,t).length)-i-r.length}function bo(e,t,n,r,i,a){if(r===i)return;let o=t.output[n];if(n===t.output.length-1&&(a===void 0||o?.type===`message`&&a===o.content.length-1)){vo(t,r,i);return}let s=yo(e,o,a,i),c=e.outputTextIndex.prefixSum(n)+s;if(c+r.length===t.output_text.length){vo(t,r,i);return}t.output_text=t.output_text.slice(0,c)+i+t.output_text.slice(c+r.length)}function xo(e,t,n,r=!1){if(!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!r||t in e:!pe(e,t)))throw new f(`missing ${n} at index ${t}`)}function So(e,t,n){if(t!==e.length)throw new f(`missing ${n} at index ${t}`);xo(e,t,n,!0)}function Z(e,t){xo(e.output,t,`output`);let n=e.output[t];if(!n)throw new f(`missing output at index ${t}`);return n}function Q(e,t){xo(e,t,`content`);let n=e[t];if(!n)throw new f(`missing content at index ${t}`);return n}function Co(e,t,n){let r=e.output.find(e=>e.type===`shell_call`&&e.call_id===t.call_id);for(r?xo(r.action.commands,n,`command`):xo(t.output,n,`content`,!0);t.output.length<=n;)t.output.push({stdout:``,stderr:``,outcome:{type:`exit`,exit_code:0}});return Q(t.output,n)}function wo(e){throw new f(`Unhandled response stream event: ${JSON.stringify(e)}`)}function To(e,t,n){switch(e.type){case`response.output_item.added`:{So(t.output,e.output_index,`output`);let r=structuredClone(e.item);r.type===`message`&&ho(n,t),t.output.push(r);let i=mo(n,r);return n.canonicalSnapshot===t&&n.outputTextIndex.append(i.length),i&&(t.output_text+=i),!0}case`response.output_item.done`:{let r=Z(t,e.output_index),i=mo(n,r),a=structuredClone(e.item);(r.type===`message`||a.type===`message`)&&ho(n,t),t.output[e.output_index]=a;let o=mo(n,a);return n.canonicalSnapshot===t&&n.outputTextIndex.update(e.output_index,o.length),bo(n,t,e.output_index,i,o),!0}default:return!1}}function Eo(e,t,n){switch(e.type){case`response.content_part.added`:{let r=Z(t,e.output_index),{type:i}=r,{part:a}=e;if(i===`message`&&a.type!==`reasoning_text`){So(r.content,e.content_index,`content`);let i=structuredClone(a);i.type===`output_text`&&ho(n,t),r.content.push(i),i.type===`output_text`&&(_o(n,r,e.output_index,``,i.text),bo(n,t,e.output_index,``,i.text,e.content_index))}else if(i===`reasoning`&&a.type===`reasoning_text`){let t=r.content??[];So(t,e.content_index,`content`),r.content||=t,t.push(structuredClone(a))}return!0}default:return!1}}function Do(e,t,n){switch(e.type){case`response.content_part.done`:{let r=Z(t,e.output_index),{part:i}=e;if(r.type===`message`&&i.type!==`reasoning_text`){let a=Q(r.content,e.content_index),o=a.type===`output_text`?a.text:``,s=structuredClone(i);(a.type===`output_text`||s.type===`output_text`)&&ho(n,t),r.content[e.content_index]=s;let c=s.type===`output_text`?s.text:``;_o(n,r,e.output_index,o,c),bo(n,t,e.output_index,o,c,e.content_index)}else if(r.type===`reasoning`&&i.type===`reasoning_text`){let{content:t}=r;if(!t)throw new f(`missing content at index ${e.content_index}`);Q(t,e.content_index),t[e.content_index]=structuredClone(i)}return!0}default:return!1}}function Oo(e,t,n){switch(e.type){case`response.output_text.delta`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Q(r.content,e.content_index);if(i.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${i.type}`);let a=i.text;ho(n,t),i.text=a+e.delta,_o(n,r,e.output_index,a,i.text),e.output_index===t.output.length-1&&e.content_index===r.content.length-1?t.output_text+=e.delta:bo(n,t,e.output_index,a,i.text,e.content_index)}return!0}case`response.output_text.done`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Q(r.content,e.content_index);if(i.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${i.type}`);let a=i.text;ho(n,t),i.text=e.text,_o(n,r,e.output_index,a,e.text),bo(n,t,e.output_index,a,e.text,e.content_index)}return!0}case`response.output_text.annotation.added`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${t.type}`);xo(t.annotations,e.annotation_index,`annotation`,!0),t.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function ko(e,t){switch(e.type){case`response.refusal.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new f(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}return!0}case`response.refusal.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new f(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}return!0}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments+=e.delta),!0}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments=e.arguments),!0}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input+=e.delta),!0}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input=e.input),!0}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments+=e.delta),!0}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments=e.arguments),!0}default:return!1}}function Ao(e,t){switch(e.type){case`response.shell_call_command.added`:case`response.shell_call_command.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call`){let t=e.type===`response.shell_call_command.added`;xo(n.action.commands,e.command_index,`command`,t),n.action.commands[e.command_index]=e.command}return!0}case`response.shell_call_command.delta`:{let n=Z(t,e.output_index);return n.type===`shell_call`&&(xo(n.action.commands,e.command_index,`command`),n.action.commands[e.command_index]+=e.delta),!0}case`response.shell_call_output_content.delta`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=Co(t,n,e.command_index);r.stdout+=e.delta.stdout??``,r.stderr+=e.delta.stderr??``}return!0}case`response.shell_call_output_content.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=Q(e.output,0);Co(t,n,e.command_index),n.output[e.command_index]=structuredClone(r)}return!0}default:return!1}}function jo(e,t){switch(e.type){case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new f(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new f(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}return!0}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new f(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new f(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}return!0}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(So(n.summary,e.summary_index,`content`),n.summary.push(structuredClone(e.part))),!0}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(Q(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part)),!0}case`response.reasoning_summary_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text+=e.delta}return!0}case`response.reasoning_summary_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text=e.text}return!0}default:return!1}}function Mo(e,t){switch(e.type){case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta),!0}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=e.code),!0}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`in_progress`),!0}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`interpreting`),!0}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`completed`),!0}default:return!1}}function No(e,t){switch(e.type){case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`in_progress`),!0}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`searching`),!0}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`completed`),!0}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`in_progress`),!0}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`searching`),!0}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`completed`),!0}default:return!1}}function Po(e,t){switch(e.type){case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`in_progress`),!0}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`generating`),!0}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`completed`),!0}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`in_progress`),!0}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`completed`),!0}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`failed`),!0}default:return!1}}function Fo(e){switch(e.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 Io(e){switch(e.type){case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`: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 Lo(){return po()}function Ro(e,t,n){if(!t){if(e.type!==`response.created`)throw new f(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return go(n,e.response)}return To(e,t,n)||Eo(e,t,n)||Do(e,t,n)||Oo(e,t,n)||ko(e,t)||Ao(e,t)||jo(e,t)||Mo(e,t)||No(e,t)||Po(e,t)?t:Fo(e)?go(n,e.response):Io(e)?t:wo(e)}var zo,Bo,Vo,Ho,Uo,Wo,Go,Ko,qo=class e extends er{constructor(e){super(),zo.add(this),Bo.set(this,void 0),Vo.set(this,void 0),Ho.set(this,void 0),Uo.set(this,Lo()),s(this,Bo,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),c(this,zo,`m`,Wo).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)c(this,zo,`m`,Go).call(this,e,i);if(r.controller.signal?.aborted)throw new m;return c(this,zo,`m`,Ko).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,zo,`m`,Wo).call(this),this._connected();let n=Ve.fromReadableStream(e,this.controller);for await(let e of n)c(this,zo,`m`,Go).call(this,e,null);if(n.controller.signal?.aborted)throw new m;return c(this,zo,`m`,Ko).call(this)}[(Bo=new WeakMap,Vo=new WeakMap,Ho=new WeakMap,Uo=new WeakMap,zo=new WeakSet,Wo=function(){this.ended||(s(this,Vo,void 0,`f`),s(this,Uo,Lo(),`f`))},Go=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)};if(e.type===`error`)throw new p(void 0,`error`in e&&typeof e.error==`object`&&e.error!==null?e.error:e,e.message,void 0);let r=Ro(e,c(this,Vo,`f`),c(this,Uo,`f`));switch(s(this,Vo,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new f(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new f(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new f(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new f(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e)}},Ko=function(){if(this.ended)throw new f(`stream has ended, this shouldn't happen`);let e=c(this,Vo,`f`);if(!e)throw new f(`request ended without sending any events`);s(this,Vo,void 0,`f`),s(this,Uo,Lo(),`f`);let t=Jo(e,c(this,Bo,`f`));return s(this,Ho,t,`f`),t},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=c(this,Ho,`f`);if(!e)throw new f(`stream ended without producing a Response`);return e}};function Jo(e,t){return no(e,t)}var Yo=class extends I{list(e,t={},n){return this._client.getAPIList(L`/responses/${e}/input_items`,M,{query:t,...n,__security:{bearerAuth:!0}})}},Xo=class extends I{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},Zo=class extends I{constructor(){super(...arguments),this.inputItems=new Yo(this._client),this.inputTokens=new Xo(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&uo(e),e))}retrieve(e,t={},n){return this._client.get(L`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&uo(e),e))}delete(e,t){return this._client.delete(L`/responses/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>ro(t,e))}stream(e,t){return qo.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}})}};Zo.InputItems=Yo,Zo.InputTokens=Xo;var Qo=class extends I{retrieve(e,t){return this._client.get(L`/skills/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},$o=class extends I{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(L`/skills/${r}/versions/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},es=class extends I{constructor(){super(...arguments),this.content=new $o(this._client)}create(e,t={},n){return this._client.post(L`/skills/${e}/versions`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(L`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/skills/${e}/versions`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(L`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};es.Content=$o;var ts=class extends I{constructor(){super(...arguments),this.content=new Qo(this._client),this.versions=new es(this._client)}create(e={},t){return this._client.post(`/skills`,Gt({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`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};ts.Content=Qo,ts.Versions=es;var ns=class extends I{create(e,t,n){return this._client.post(L`/uploads/${e}/parts`,F({body:t,...n,__security:{bearerAuth:!0}},this._client))}},rs=class extends I{constructor(){super(...arguments),this.parts=new ns(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}})}};rs.Parts=ns;var is=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},as=class extends I{create(e,t,n){return this._client.post(L`/vector_stores/${e}/file_batches`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/file_batches/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(L`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(L`/vector_stores/${r}/file_batches/${e}/files`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ge(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await is(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c},r)}},os=class extends I{create(e,t,n){return this._client.post(L`/vector_stores/${e}/files`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(L`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/vector_stores/${e}/files`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(L`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ge(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(L`/vector_stores/${r}/files/${e}/content`,kt,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ss=class extends I{constructor(){super(...arguments),this.files=new os(this._client),this.fileBatches=new as(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/vector_stores/${e}`,{...t,headers:P([{"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:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(L`/vector_stores/${e}/search`,kt,{body:t,method:`post`,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};ss.Files=os,ss.FileBatches=as;var cs=class extends I{create(e,t){return this._client.post(`/videos`,F({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`,N,{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`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(L`/videos/${e}/content`,{query:t,...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,F({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`,Gt({body:t,...n,__security:{bearerAuth:!0}},this._client))}},ls,us,ds,fs=class extends I{constructor(){super(...arguments),ls.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,ls,`m`,us).call(this,n);let i=P([t]).values,a=c(this,ls,`m`,ds).call(this,i,`webhook-signature`),o=c(this,ls,`m`,ds).call(this,i,`webhook-timestamp`),s=c(this,ls,`m`,ds).call(this,i,`webhook-id`),l=parseInt(o,10);if(isNaN(l))throw new ae(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>r)throw new ae(`Webhook timestamp is too old`);if(l>u+r)throw new ae(`Webhook timestamp is too new`);let d=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=Uint8Array.from(n.startsWith(`whsec_`)?Ii(n.slice(6)):w(n)),p=s?`${s}.${o}.${e}`:`${o}.${e}`,m=Uint8Array.from(w(p)),h=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Uint8Array.from(Ii(e));if(await crypto.subtle.verify(`HMAC`,h,t,m))return}catch{continue}throw new ae(`The given webhook signature does not match the expected signature`)}};ls=new WeakSet,us=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},ds=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var ps=Symbol.for(`openai.node.providerDefinitions.v1`),ms=globalThis,hs=ms[ps],gs=hs??new WeakMap;hs||Object.defineProperty(ms,ps,{value:gs});function _s(e){let t=gs.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var vs,ys,bs,xs,Ss;function Cs(){if(Ze())return!0;let e=globalThis;return typeof e.WorkerGlobalScope==`function`&&e instanceof e.WorkerGlobalScope&&typeof e.WorkerNavigator==`function`&&e.navigator instanceof e.WorkerNavigator&&typeof e.navigator?.userAgent==`string`&&e.navigator.userAgent!==`Cloudflare-Workers`&&e.process?.versions?.node===void 0&&e.Deno===void 0&&e.Bun===void 0&&e.EdgeRuntime===void 0&&e.WebSocketPair===void 0}var ws=`workload-identity-auth`,$=class{constructor(e={}){vs.add(this),bs.set(this,void 0),xs.set(this,new WeakMap),this.completions=new Oa(this),this.chat=new Hr(this),this.embeddings=new Fa(this),this.files=new za(this),this.images=new Xa(this),this.contentProvenanceChecks=new Ma(this),this.audio=new Si(this),this.moderations=new Qa(this),this.models=new Za(this),this.fineTuning=new qa(this),this.graders=new Ya(this),this.vectorStores=new ss(this),this.webhooks=new fs(this),this.beta=new Da(this),this.batches=new Ci(this),this.uploads=new rs(this),this.admin=new vi(this),this.responses=new Zo(this),this.realtime=new to(this),this.conversations=new Pa(this),this.evals=new Ra(this),this.containers=new ja(this),this.skills=new ts(this),this.videos=new cs(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new f(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:G(`OPENAI_BASE_URL`),apiKey:r=t?null:G(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:G(`OPENAI_ADMIN_KEY`)??null,organization:a=t?null:G(`OPENAI_ORG_ID`)??null,project:o=t?null:G(`OPENAI_PROJECT_ID`)??null,webhookSecret:c=G(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:l,...u}=e,d=t?_s(t):void 0,p={apiKey:r,adminAPIKey:i,organization:a,project:o,webhookSecret:c,workloadIdentity:l,provider:t,...u,baseURL:d?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&l)throw new f("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!d&&!r&&!i&&!l)throw new f("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!p.dangerouslyAllowBrowser&&Cs())throw new f(`It looks like you're running in a browser-like environment.
|
|
1
|
+
import{a as e}from"./diagnostics-Cag7MsZI.js";import{t}from"./models-Xc0Gclrk.js";import{a as n}from"./compat-DpI6NrfX.js";import{S as r,v as i}from"./account-store-D2qVGeJK.js";import{r as a,t as o}from"./transform-messages-k2mfzJwY.js";import{n as s,t as c}from"./pi-transcript-context-miZCMig3.js";function l(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function u(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var d=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return d=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function f(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var p=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},m=class extends Error{},h=class e extends m{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new _({message:r,cause:p(n)});let a=n?.error;return t===400?new y(t,a,r,i):t===401?new b(t,a,r,i):t===403?new x(t,a,r,i):t===404?new ee(t,a,r,i):t===409?new te(t,a,r,i):t===422?new ne(t,a,r,i):t===429?new re(t,a,r,i):t>=500?new ie(t,a,r,i):new e(t,a,r,i)}},g=class extends h{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},_=class extends h{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},v=class extends _{constructor({message:e}={}){super({message:e??`Request timed out.`})}},y=class extends h{},b=class extends h{},x=class extends h{},ee=class extends h{},te=class extends h{},ne=class extends h{},re=class extends h{},ie=class extends h{},ae=class extends m{constructor(){super(`Could not parse response content as the length limit was reached`)}},oe=class extends m{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},se=class extends Error{constructor(e){super(e)}},ce=class extends h{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},le=class extends m{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},ue=/^[a-z][a-z0-9+.-]*:/i,de=e=>ue.test(e),S=e=>(S=Array.isArray,S(e)),fe=S;function pe(e){return typeof e==`object`?e??{}:{}}function me(e){if(!e)return!0;for(let t in e)return!1;return!0}function he(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function C(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ge=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t},_e=e=>{try{return JSON.parse(e)}catch{return}},ve=e=>new Promise(t=>setTimeout(t,e));function ye(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function be(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function xe(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return be({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Se(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Ce(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var we;function w(e){let t;return(we??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Te;function Ee(e){let t;return(Te??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var De,T,E,D,O,Oe,ke,Ae=65536,je=class{constructor(){De.add(this),T.set(this,void 0),E.set(this,void 0),D.set(this,void 0),O.set(this,void 0),Oe.set(this,void 0),l(this,T,new Uint8Array,`f`),l(this,E,0,`f`),l(this,D,0,`f`),l(this,O,0,`f`),l(this,Oe,!1,`f`)}decode(e){if(e==null)return[];let t;if(t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?w(e):e,t.length===0||u(this,Oe,`f`)&&(l(this,Oe,!1,`f`),t[0]===10&&(t=t.subarray(1)),t.length===0))return[];u(this,De,`m`,ke).call(this,t);let n=[],r;for(;(r=Me(u(this,T,`f`),u(this,O,`f`),u(this,D,`f`)))!=null;){let e=Ee(u(this,T,`f`).subarray(u(this,E,`f`),r.preceding));n.push(e),l(this,E,r.index,`f`),r.carriage&&(u(this,E,`f`)<u(this,D,`f`)&&u(this,T,`f`)[u(this,E,`f`)]===10?l(this,E,u(this,E,`f`)+1,`f`):u(this,E,`f`)===u(this,D,`f`)&&l(this,Oe,!0,`f`)),l(this,O,u(this,E,`f`),`f`)}if(l(this,O,u(this,D,`f`),`f`),u(this,E,`f`)===u(this,D,`f`))l(this,E,0,`f`),l(this,D,0,`f`),l(this,O,0,`f`),u(this,T,`f`).length>Ae&&l(this,T,new Uint8Array,`f`);else if(n.length>0&&u(this,T,`f`).length>Ae){let e=u(this,D,`f`)-u(this,E,`f`);if(e<=Ae||u(this,T,`f`).length>e*4){let t=e<=Ae?Math.min(Math.max(e*2,256),Ae):e*2,n=new Uint8Array(t);n.set(u(this,T,`f`).subarray(u(this,E,`f`),u(this,D,`f`))),l(this,T,n,`f`),l(this,E,0,`f`),l(this,D,e,`f`),l(this,O,e,`f`)}}return n}flush(){return l(this,Oe,!1,`f`),u(this,E,`f`)===u(this,D,`f`)?[]:this.decode(`
|
|
2
|
+
`)}};T=new WeakMap,E=new WeakMap,D=new WeakMap,O=new WeakMap,Oe=new WeakMap,De=new WeakSet,ke=function(e){if(u(this,D,`f`)+e.length>u(this,T,`f`).length){let t=u(this,D,`f`)-u(this,E,`f`);if(u(this,E,`f`)>=u(this,T,`f`).length/2&&t+e.length<=u(this,T,`f`).length)u(this,T,`f`).copyWithin(0,u(this,E,`f`),u(this,D,`f`));else{let n=Math.max(u(this,T,`f`).length*2,t+e.length,256),r=new Uint8Array(n);r.set(u(this,T,`f`).subarray(u(this,E,`f`),u(this,D,`f`))),l(this,T,r,`f`)}l(this,O,u(this,O,`f`)-u(this,E,`f`),`f`),l(this,D,t,`f`),l(this,E,0,`f`)}u(this,T,`f`).set(e,u(this,D,`f`)),l(this,D,u(this,D,`f`)+e.length,`f`)},je.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,`\r`]),je.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Me(e,t,n){for(let r=t;r<n;r++){if(e[r]===10)return{preceding:r,index:r+1,carriage:!1};if(e[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Ne(e){for(let t=0;t<e.length-1;t++){let n=Pe(e,t);if(n>0){let r=t+n,i=Pe(e,r);if(i>0)return r+i}}return-1}function Pe(e,t){return e[t]===10?1:e[t]===13?e[t+1]===10?2:1:0}var Fe={off:0,error:200,warn:300,info:400,debug:500},Ie=(e,t,n)=>{if(e){if(he(Fe,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Fe))}`)}};function Le(){}function Re(e,t,n){return!t||Fe[e]>Fe[n]?Le:t[e].bind(t)}var ze={error:Le,warn:Le,info:Le,debug:Le},Be=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return ze;let r=Be.get(t);if(r&&r[0]===n)return r[1];let i={error:Re(`error`,t,n),warn:Re(`warn`,t,n),info:Re(`info`,t,n),debug:Re(`debug`,t,n)};return Be.set(t,[n,i]),i}var Ve=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`x-amz-security-token`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),He,Ue=class e{constructor(e,t,n){He.set(this,void 0),this.iterator=e,this.controller=t,l(this,He,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?k(r):console;async function*s(){if(a)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1,r=!1;try{for await(let e of We(t,n)){if(e.data.startsWith(`[DONE]`)){r=!0;break}if(e.event===null||!e.event.startsWith(`thread.`)){let n;try{n=JSON.parse(e.data)}catch(t){throw o.error(`Could not parse message into JSON:`,e.data),o.error(`From chunk:`,e.raw),t}if(n&&n.error)throw new h(void 0,n.error,void 0,t.headers);yield i?{event:e.event,data:n}:n}else{let t;try{t=JSON.parse(e.data)}catch(t){throw console.error(`Could not parse message into JSON:`,e.data),console.error(`From chunk:`,e.raw),t}if(e.event===`error`)throw new h(void 0,t.error,t.message,void 0);yield{event:e.event,data:t}}}e=!0}catch(e){if(r||f(e)||n.signal.aborted&&e===n.signal.reason)return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new je,r=t.getReader(),i=!1,a,o=()=>{a??=r.cancel(),a.catch(()=>void 0)};n.signal.addEventListener(`abort`,o,{once:!0});try{if(n.signal.aborted){o();return}for(;;){let{value:t,done:a}=await r.read();if(a){i=!0;break}if(n.signal.aborted)return;for(let r of e.decode(t)){if(n.signal.aborted)return;yield r}}if(n.signal.aborted)return;for(let t of e.flush()){if(n.signal.aborted)return;yield t}}finally{n.signal.removeEventListener(`abort`,o),i||o(),r.releaseLock()}}async function*o(){if(i)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(n.signal.aborted||f(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(He=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,u(this,He,`f`)),new e(()=>i(n),this.controller,u(this,He,`f`))]}toReadableStream(){let e;return be({start:async()=>{e=this[Symbol.asyncIterator]()},async pull(t){try{let{value:n,done:r}=await e.next();if(r)return t.close();let i=w(JSON.stringify(n)+`
|
|
4
|
+
`);t.enqueue(i)}catch(e){t.error(e)}},async cancel(){await e.return?.()}})}};async function*We(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new m(`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 m(`Attempted to iterate over a response with no body`);let n=new qe,r=new je,i=Se(e.body);for await(let e of Ke(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}var Ge=3;async function*Ke(e){let t=new Uint8Array,n=0,r=0,i=0;for await(let a of e){if(a==null)continue;let e;if(e=a instanceof ArrayBuffer?new Uint8Array(a):typeof a==`string`?w(a):a,r+e.length>t.length){let a=r-n;if(n>=t.length/2&&a+e.length<=t.length)t.copyWithin(0,n,r);else{let i=new Uint8Array(Math.max(t.length*2,a+e.length));i.set(t.subarray(n,r)),t=i}i-=n,n=0,r=a}t.set(e,r),r+=e.length;let o;for(;(o=Ne(t.subarray(i,r)))!==-1;)o+=i,yield t.slice(n,o),n=o,i=n;i=Math.max(n,r-Ge)}r>n&&(yield t.slice(n,r))}var qe=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 e={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,,n]=Je(e,`:`),r=n;return r.startsWith(` `)&&(r=r.slice(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function Je(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.slice(0,n),t,e.slice(n+t.length)]}async function Ye(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return k(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):Ue.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();if(r?.includes(`application/json`)||r?.endsWith(`+json`)){if(n.headers.get(`content-length`)===`0`)return;let e=await n.text();return e?Ze(JSON.parse(e),n):void 0}return await n.text()})().catch(e=>{throw Xe(e,t.controller.signal)});return k(e).debug(`[${r}] response parsed`,Ve({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function Xe(e,t){if(!t.aborted||e!==t.reason||f(e))return e;let n=`This operation was aborted`,r=globalThis.DOMException;return typeof r==`function`?new r(n,`AbortError`):Object.assign(Error(n),{name:`AbortError`})}function Ze(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var Qe=`7.5.0`,$e=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function et(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var tt=()=>{let e=et();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":it(Deno.build.os),"X-Stainless-Arch":rt(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":Qe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":it(globalThis.process.platform??`unknown`),"X-Stainless-Arch":rt(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=nt();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function nt(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var rt=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,it=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),at,ot=()=>at??=tt(),st=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),ct=`RFC3986`,lt=String,ut={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:lt},dt,ft=(e,t)=>{let n=dt??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return dt=n,n(e,t)},A=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),pt=1024,mt=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,e=>`%26%23`+Number.parseInt(e.slice(2),16)+`%3B`);let o=``;for(let e=0;e<a.length;){let t=Math.min((Math.floor(e/pt)+1)*pt,a.length);t<a.length&&a.codePointAt(t-1)>65535&&(t+=1);let n=a.length>=pt?a.slice(e,t):a,r=[];for(let e=0;e<n.length;++e){let t=n.charCodeAt(e);if(t===45||t===46||t===95||t===126||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||i===`RFC1738`&&(t===40||t===41)){r[r.length]=n.charAt(e);continue}if(t<128){r[r.length]=A[t];continue}if(t<2048){r[r.length]=A[192|t>>6]+A[128|t&63];continue}if(t<55296||t>=57344){r[r.length]=A[224|t>>12]+A[128|t>>6&63]+A[128|t&63];continue}e+=1,t=65536+((t&1023)<<10|n.charCodeAt(e)&1023),r[r.length]=A[240|t>>18]+A[128|t>>12&63]+A[128|t>>6&63]+A[128|t&63]}o+=r.join(``),e=t}return o};function ht(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function gt(e,t){if(S(e)){let n=[];for(let r of e)n.push(t(r));return n}return t(e)}var _t={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},vt=function(e,t){Array.prototype.push.apply(e,S(t)?t:[t])},yt,j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:mt,encodeValuesOnly:!1,format:ct,formatter:lt,indices:!1,serializeDate(e){return(yt??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function bt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var xt={};function St(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(xt))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(xt)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&S(v)&&(v=gt(v,e=>e instanceof Date?f?.(e):e)),v===null){if(a)return c&&!h?c(t,j.encoder,g,`key`,p):t;v=``}if(bt(v)||ht(v)){if(c){let e=h?t:c(t,j.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,j.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&S(v))h&&c&&(v=gt(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(S(l))te=l;else{let e=Object.keys(v);u&&e.sort(u),te=e}let ne=s?String(t).replace(/\./g,`%2E`):String(t),re=r&&S(v)&&v.length===1?ne+`[]`:ne;if(i&&S(v)&&v.length===0)return re+`[]`;for(let t of te){let y=typeof t==`object`&&t.value!==void 0?t.value:v[t];if(o&&y===null)continue;let x=d&&s?t.replace(/\./g,`%2E`):t,te;te=S(v)?typeof n==`function`?n(re,x):re:re+(d?`.`+x:`[`+x+`]`),_.set(e,b);let ne=new WeakMap([[xt,_]]);vt(ee,St(y,te,n,r,i,a,o,s,n===`comma`&&h&&S(v)?null:c,l,u,d,f,p,m,h,g,ne))}return ee}function Ct(e=j){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||j.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=ct;if(e.format!==void 0){if(!ft(ut,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=ut[n],i=j.filter;(typeof e.filter==`function`||S(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in _t?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:j.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o;return o=e.allowDots===void 0?e.encodeDotInKeys?!0:j.allowDots:!!e.allowDots,{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:j.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?j.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:j.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:j.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:j.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:j.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:j.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:j.strictNullHandling}}function wt(e,t={}){let n=e,r=Ct(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):S(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=_t[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e of i)r.skipNulls&&n[e]===null||vt(o,St(n[e],e,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l));let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(d+=r.charset===`iso-8859-1`?`utf8=%26%2310003%3B&`:`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Tt(e){return wt(e,{arrayFormat:`brackets`})}var Et,Dt=class e extends Promise{constructor(e,t,n=Ye){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,Et.set(this,void 0),l(this,Et,e,`f`)}_thenUnwrap(t){return new e(u(this,Et,`f`),this.responsePromise,async(e,n)=>Ze(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(u(this,Et,`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)}};Et=new WeakMap;var Ot,kt=class{constructor(e,t,n,r){Ot.set(this,void 0),l(this,Ot,e,`f`),this.options=r,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 m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,Ot,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ot=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},At=class extends Dt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Ye(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},jt=class extends kt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},M=class extends kt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...pe(this.options.query),after:t}}:null}},N=class extends kt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...pe(this.options.query),after:e}}:null}},Mt=class extends kt{constructor(e,t,n,r){super(e,t,n,r),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&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...pe(this.options.query),after:e}}:null}},Nt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Pt=`urn:ietf:params:oauth:grant-type:token-exchange`,Ft=class e{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??ye()}async getToken(){if(!this.cachedToken||e.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(this.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={grant_type:Pt,subject_token:await this.config.provider.getToken(),subject_token_type:Nt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),redirect:`manual`});if(!n.ok){let e=await n.text(),t;try{t=JSON.parse(e)}catch{}throw n.status===400||n.status===401||n.status===403?new ce(n.status,t,n.headers):h.generate(n.status,t,`Token exchange failed with status ${n.status}`,n.headers)}let r=await n.json();if(typeof r!=`object`||!r||!(`access_token`in r)||typeof r.access_token!=`string`||r.access_token.trim().length===0)throw new m(`Token exchange response missing 'access_token' field`);let i=r.access_token,a=r.expires_in??3600;if(typeof a!=`number`||!Number.isFinite(a)||a<=0)throw new m(`Token exchange response has invalid 'expires_in' field`);let o=Date.now(),s=o+a*1e3;if(!Number.isSafeInteger(s)||s<=o)throw new m(`Token exchange response has invalid 'expires_in' field`);return this.tokenGeneration===e&&(this.cachedToken={token:i,expiresAt:s}),i}static isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}},It=Symbol(`brand.privateNullableHeaders`),Lt=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*Rt(e){if(!e)return;if(It in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():fe(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=fe(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var P=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Rt(r)){if(!Lt.test(i))throw TypeError(`Header name must be a valid HTTP token ["${i}"]`);let r=i.toLowerCase();e.has(r)||(t.delete(r),e.add(r)),a===null?(t.delete(r),n.add(r)):(t.append(r,a),n.delete(r))}}return{[It]:!0,values:t,nulls:n}},zt=Symbol(`brand.privateStreamingFile`);function Bt(e,t,n){if(typeof t!=`string`||!t)throw TypeError(`toStreamingFile requires a non-empty file name`);let r=n?.type;return r&&un(r),{[zt]:!0,data:e,name:t,...r?{type:r}:{}}}var Vt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&Number.parseInt(e.versions.node.split(`.`),10)<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function Ht(e,t,n){return Vt(),new File(e,t??`unknown_file`,n)}function Ut(e,t){if(typeof e!=`object`||!e)return;let n=`name`in e&&e.name&&String(e.name)||`filename`in e&&e.filename&&String(e.filename);if(n)return t?.stripFilename===!1?Gt(n):Wt(n);let r=`url`in e&&e.url&&String(e.url);if(r)try{return Wt(new URL(r).pathname)}catch{return Wt(r)}let i=`path`in e&&e.path&&String(e.path);return i?Wt(i):void 0}function Wt(e){return e.split(/[\\/]/).pop()||void 0}function Gt(e){return e.replace(/\\/g,`/`)}var Kt=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,qt=async(e,t,n)=>nn(e.body)?tn(e.body)?rn(e,n):{...e,body:await Xt(e.body,t,n)}:e,F=async(e,t,n)=>tn(e.body)?rn(e,n):{...e,body:await Xt(e.body,t,n)},Jt=new WeakMap;function Yt(e){let t=typeof e==`function`?e:e.fetch,n=Jt.get(t);if(n)return n;let r=(async()=>{try{let e;if(`Response`in t)e=t.Response;else{let n=await t(`data:,`);await n.arrayBuffer(),e=n.constructor}let n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Jt.set(t,r),r}var Xt=async(e,t,n={})=>{if(!await Yt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>mn(r,e,t,n))),r},Zt=e=>e instanceof Blob&&`name`in e,Qt=e=>typeof e==`object`&&!!e&&`getReader`in e&&typeof e.getReader==`function`,$t=e=>typeof e==`object`&&!!e&&zt in e,en=e=>typeof e==`object`&&!!e&&(e instanceof Response||Kt(e)||Qt(e)||$t(e)||Zt(e)),tn=e=>{if($t(e)||Kt(e)||Qt(e))return!0;if(Array.isArray(e))return e.some(tn);if(e&&typeof e==`object`&&!Zt(e)&&!(e instanceof Response)){for(let t in e)if(tn(e[t]))return!0}return!1},nn=e=>{if(en(e))return!0;if(Array.isArray(e))return e.some(nn);if(e&&typeof e==`object`){for(let t in e)if(nn(e[t]))return!0}return!1},rn=(e,t={})=>{let n=`openai-${Math.random().toString(36).slice(2)}`,r=xe(an(e.body,n,t));return{...e,body:r,headers:P([{"content-type":`multipart/form-data; boundary=${n}`},e.headers])}};async function*an(e,t,n){for await(let{key:r,value:i}of on(e)){if(en(i)){let e=cn(i,n),a=ln(i);yield w(`--${t}\r\n`),yield w(`Content-Disposition: form-data; name="${pn(r)}"; filename="${pn(e)}"\r\nContent-Type: ${a}\r\n\r\n`),yield*fn(dn(i))}else yield w(`--${t}\r\n`),yield w(`Content-Disposition: form-data; name="${pn(r)}"\r\n\r\n${String(i)}`);yield w(`\r
|
|
6
|
+
`)}yield w(`--${t}--\r\n`)}async function*on(e){if(!(!e||typeof e!=`object`))for(let[t,n]of Object.entries(e))yield*sn(t,n)}async function*sn(e,t){if(t!==void 0){if(t==null)throw 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`||en(t))yield{key:e,value:t};else if(Array.isArray(t))for(let n of t)yield*sn(e+`[]`,n);else if(typeof t==`object`)for(let[n,r]of Object.entries(t))yield*sn(`${e}[${n}]`,r);else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}}function cn(e,t){if($t(e)){let{name:n}=e;if(typeof n!=`string`||!n)throw TypeError(`Streaming upload file name must be a non-empty string`);return t.stripFilenames===!1?Gt(n):n}return Ut(e,{stripFilename:t.stripFilenames})??`unknown_file`}function ln(e){let t;return $t(e)||Zt(e)?{type:t}=e:e instanceof Response&&(t=e.headers.get(`content-type`)??void 0),un(t||`application/octet-stream`)}function un(e){if(typeof e!=`string`)throw TypeError(`Streaming upload content type must be a string`);for(let t=0;t<e.length;t+=1){let n=e.codePointAt(t)??0;if(n<=31||n===127)throw TypeError(`Streaming upload content type must not contain control characters`)}return e}function dn(e){return $t(e)?e.data:e}async function*fn(e){if(typeof e==`string`)yield w(e);else if(ArrayBuffer.isView(e))yield new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)yield new Uint8Array(e);else if(e instanceof Response)yield*fn(e.body||await e.blob());else if(e instanceof Blob)typeof e.stream==`function`?yield*fn(e.stream()):yield new Uint8Array(await e.arrayBuffer());else if(Qt(e))for await(let t of Se(e))yield*fn(t);else if(Kt(e))for await(let t of e)yield*fn(t);else throw TypeError(`Invalid streaming file chunk: ${String(e)}`)}function pn(e){return Array.from(e,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e===`"`||e===`\\`?encodeURIComponent(e):e}).join(``)}var mn=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,Ht([await n.blob()],Ut(n,{stripFilename:r.stripFilenames})));else if(Kt(n))e.append(t,Ht([await new Response(xe(n)).blob()],Ut(n,{stripFilename:r.stripFilenames})));else if(Zt(n))e.append(t,n,Ut(n,{stripFilename:r.stripFilenames}));else if(Array.isArray(n))await Promise.all(n.map(n=>mn(e,t+`[]`,n,r)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>mn(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},hn=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,gn=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&hn(e),_n=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`,vn=(e,t)=>t?.type!=null&&t.type!==e.type||t?.lastModified!=null&&t.lastModified!==e.lastModified||t?.endings!=null,yn=(e,t,n)=>(t==null||t===e.name)&&!vn(e,n);async function bn(e,t,n){if(Vt(),e=await e,gn(e)){let r={...n,type:n?.type??e.type,lastModified:n?.lastModified??e.lastModified};return e instanceof File?yn(e,t,n)?e:Ht([e],t??e.name,r):Ht([await e.arrayBuffer()],t??e.name,r)}if(_n(e)){let r=await e.blob();t||=Ut(e);let i=n?.type===void 0&&r.type?{...n,type:r.type}:n;return Ht(await xn(r),t,i)}let r=await xn(e);if(t||=Ut(e),n?.type===void 0){let e=r.find(e=>typeof e==`object`&&`type`in e&&!!e.type);e&&(n={...n,type:e.type})}return Ht(r,t,n)}async function xn(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(hn(e))t.push(e instanceof Blob?e:new Blob([await e.arrayBuffer()],{type:e.type}));else if(Kt(e))for await(let n of e)t.push(...await xn(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${Sn(e)}`)}return t}function Sn(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var I=class{constructor(e){this._client=e}};function Cn(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var wn=Object.freeze(Object.create(null)),L=((e=Cn)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=``;for(let o=0;o<t.length;o+=1)if(o in t){let s=t[o];/[?#]/.test(s)&&(r=!0);let c=n[o],l=(r?encodeURIComponent:e)(``+c);o!==n.length&&(c==null||typeof c==`object`&&c.toString===Object.getPrototypeOf(Object.getPrototypeOf(c.hasOwnProperty??wn)??wn)?.toString)&&(l=c+``,i.push({start:a.length+s.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),a+=s+(o===n.length?``:l)}let o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=``;for(let n of i){let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);e=n.start+n.length,t+=r+i}throw new m(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
|
7
|
+
`)}\n${a}\n${t}`)}return a})(Cn),Tn=class extends I{list(e,t={},n){return this._client.getAPIList(L`/chat/completions/${e}/messages`,M,{query:t,...n,__security:{bearerAuth:!0}})}};function En(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Dn(e){return e?.$brand===`auto-parseable-response-format`}function On(e){return Dn(e)||e?.type===`json_schema`}function kn(e,t){return On(e)?typeof e==`object`&&e&&`$parseRaw`in e&&typeof e.$parseRaw==`function`?e.$parseRaw(t):JSON.parse(t):null}function An(e){return e?.$brand===`auto-parseable-tool`}function jn(e,t){return!t||!In(t)?{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Mn(e,t)}function Mn(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new ae;if(e.finish_reason===`content_filter`)throw new oe;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Pn(t,e))??void 0}:void 0,parsed:e.message.content!==null&&e.message.content!==void 0&&!e.message.refusal&&(e.message.content!==``||!e.message.tool_calls?.length&&!e.message.function_call)?Nn(t,e.message.content):null}}});return{...e,choices:n}}function Nn(e,t){return kn(e.response_format,t)}function Pn(e,t){if(t.type===`custom`)return t;if(t.type!==`function`){let e=t.type;throw new m(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${e}\``)}let n=e.tools?.find(e=>En(e)&&e.function?.name===t.function.name),r=null;return An(n)?r=n.$parseRaw(t.function.arguments):n?.function.strict&&(r=JSON.parse(t.function.arguments)),{...t,function:{...t.function,parsed_arguments:r}}}function Fn(e,t){if(!e||!(`tools`in e)||!e.tools||t.type!==`function`)return!1;let n=e.tools?.find(e=>En(e)&&e.function?.name===t.function?.name);return En(n)&&(An(n)||n?.function.strict||!1)}function In(e){return On(e.response_format)?!0:e.tools?.some(e=>An(e)||e.type===`function`&&e.function.strict===!0)??!1}function Ln(e){for(let t of e??[])if(t.type!==`custom`){if(t.type!==`function`){let e=t.type;throw new m(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${e}\``)}if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Rn=e=>e?.role===`assistant`,zn=e=>e?.role===`tool`,Bn,Vn,Hn,Un,Wn,Gn,Kn,qn,Jn,Yn,Xn,Zn,Qn,$n,er;function tr(){let e=[],t=0;return{get length(){return e.length-t},enqueue(t){e.push(t)},dequeue(){if(t===e.length)return;let n=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&t*2>=e.length&&(e=e.slice(t),t=0),n},clear(){e=[],t=0}}}var nr=class{constructor(){Bn.add(this),this.controller=new AbortController,Vn.set(this,void 0),Hn.set(this,()=>void 0),Un.set(this,()=>void 0),Wn.set(this,void 0),Gn.set(this,()=>void 0),Kn.set(this,()=>void 0),qn.set(this,Object.create(null)),Jn.set(this,[]),Yn.set(this,!1),Xn.set(this,!1),Zn.set(this,!1),Qn.set(this,!1),l(this,Vn,new Promise((e,t)=>{l(this,Hn,e,`f`),l(this,Un,t,`f`)}),`f`),l(this,Wn,new Promise((e,t)=>{l(this,Gn,e,`f`),l(this,Kn,t,`f`)}),`f`),u(this,Vn,`f`).catch(()=>void 0),u(this,Wn,`f`).catch(()=>void 0)}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(e=>{t=!0,u(this,Bn,`m`,er).call(this,e)}).then(()=>{if(!t){try{this._emitFinal()}catch(e){u(this,Bn,`m`,er).call(this,e);return}this._emit(`end`)}})},0)}_connected(){this.ended||(u(this,Hn,`f`).call(this),this._emit(`connect`))}get ended(){return u(this,Yn,`f`)}get errored(){return u(this,Xn,`f`)}get aborted(){return u(this,Zn,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),u(this,Jn,`f`).push({signal:e,listener:t})}on(e,t){var n;return((n=u(this,qn,`f`))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=u(this,qn,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r!==-1&&n.splice(r,1),this}once(e,t){var n;return((n=u(this,qn,`f`))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{l(this,Qn,!0,`f`);let r=t=>{this.off(e,i),n(t)},i=(...n)=>{e!==`error`&&this.off(`error`,r),t(n.length>1?n:n[0])};e!==`error`&&this.once(`error`,r),this.once(e,i)})}events(e){return this._createIterator(t=>{let n=(...e)=>t(e);return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!==`error`,rejectOnAbort:e!==`abort`})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:n=!0,onReturn:r}={}){let i=tr(),a=tr(),o=this.ended,s,c=!1,l=()=>void 0,u=()=>({value:void 0,done:!0}),d=()=>{for(;a.length;)a.dequeue().resolve(u())},f=()=>{!s||c||!a.length||(c=!0,a.dequeue().reject(s))},p=()=>{l(),this.off(`end`,g),t&&this.off(`error`,h),n&&this.off(`abort`,h)},m=e=>{if(o)return;let t=a.dequeue();t?t.resolve({value:e,done:!1}):i.enqueue(e)},h=e=>{s=e,i.length||f()},g=()=>{o=!0,p(),i.length||(f(),d())};return o||(l=e(m),this.on(`end`,g),t&&this.on(`error`,h),n&&this.on(`abort`,h)),{next:()=>i.length?Promise.resolve({value:i.dequeue(),done:!1}):s&&!c?(c=!0,Promise.reject(s)):o?Promise.resolve(u()):new Promise((e,t)=>{a.enqueue({resolve:e,reject:t})}),return:()=>(o=!0,i.clear(),p(),d(),r&&(this.done().catch(()=>void 0),r()),Promise.resolve(u())),[Symbol.asyncIterator](){return this}}}async done(){l(this,Qn,!0,`f`),await u(this,Wn,`f`)}_hasListeners(e){return!!u(this,qn,`f`)[e]?.length}_emit(e,...t){if(u(this,Yn,`f`))return;e===`end`&&(u(this,Bn,`m`,$n).call(this),l(this,Yn,!0,`f`),u(this,Gn,`f`).call(this));let n=u(this,qn,`f`)[e];if(n){u(this,qn,`f`)[e]=n.filter(e=>!e.once);for(let{listener:e}of n)e(...t)}if(e===`abort`){let e=t[0];!u(this,Qn,`f`)&&!n?.length&&Promise.reject(e),u(this,Un,`f`).call(this,e),u(this,Kn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!u(this,Qn,`f`)&&!n?.length&&Promise.reject(e),u(this,Un,`f`).call(this,e),u(this,Kn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Vn=new WeakMap,Hn=new WeakMap,Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,Bn=new WeakSet,$n=function(){for(let{signal:e,listener:t}of u(this,Jn,`f`).splice(0))e.removeEventListener(`abort`,t)},er=function(e){if(l(this,Xn,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new g),e instanceof g)return l(this,Zn,!0,`f`),this._emit(`abort`,e);if(e instanceof m)return this._emit(`error`,e);if(e instanceof Error){let t=new m(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new m(String(e)))};function rr(e){return typeof e.parse==`function`}var R,ir,ar,or,sr,cr,lr,ur,dr,fr=10;function pr(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||=`call_${d()}`}function mr(e){if(!Rn(e))return e;let t={role:`assistant`};return e.audio!=null&&(t.audio={id:e.audio.id}),e.content!==void 0&&(t.content=e.content),e.function_call!=null&&(t.function_call=e.function_call),e.name!==void 0&&(t.name=e.name),e.refusal!=null&&(t.refusal=e.refusal),e.tool_calls!==void 0&&(t.tool_calls=e.tool_calls.map(e=>e.type===`custom`?{id:e.id,type:e.type,custom:{input:e.custom.input,name:e.custom.name}}:{id:e.id,type:e.type,function:{arguments:e.function.arguments,name:e.function.name}})),t}var hr=class extends nr{constructor(){super(...arguments),R.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){pr(e),this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),zn(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Rn(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),u(this,R,`m`,ar).call(this)}async finalMessage(){return await this.done(),u(this,R,`m`,or).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,R,`m`,sr).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,R,`m`,cr).call(this)}async totalUsage(){return await this.done(),u(this,R,`m`,lr).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=u(this,R,`m`,or).call(this);t&&this._emit(`finalMessage`,t);let n=u(this,R,`m`,ar).call(this);n&&this._emit(`finalContent`,n);let r=u(this,R,`m`,sr).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=u(this,R,`m`,cr).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,u(this,R,`m`,lr).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),u(ir,ir,`m`,ur).call(ir,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Mn(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,toolContext:s,...c}=t,l=s,d=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:f=fr,afterCompletion:p}=r||{},h=t.tools.map(e=>{if(An(e)){if(!e.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),g=Object.create(null);for(let e of h)e.type===`function`&&(g[e.function.name||e.function.function.name]=e.function);let _=`tools`in t?h.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let v=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=g[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(g).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(d&&d!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(d)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let s;if(rr(o)){let e;try{e=await o.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}s=await o.function(e,n,l)}else s=await o.function(a,n,l);let c=u(ir,ir,`m`,dr).call(ir,s);return{message:{role:i,tool_call_id:t,content:c},functionCalled:!0}};for(let i=0;i<f;++i){let i=await this._createChatCompletion(e,{...c,tool_choice:a,tools:_,messages:this.messages.map(mr)},r),o=i.choices[0]?.message;if(!o)throw new m(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await p?.(i,n);return}if(d||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await v(e);if(t.message&&this._addMessage(t.message),d&&t.functionCalled){await p?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(v));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await p?.(i,n)}}};ir=hr,R=new WeakSet,ar=function(){return u(this,R,`m`,or).call(this).content??null},or=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Rn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new m(`stream ended without producing a ChatCompletionMessage with role=assistant`)},sr=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Rn(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},cr=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(zn(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},lr=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},ur=function(e){if(e.n!=null&&e.n>1)throw new m(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},dr=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var gr=class e extends hr{static runTools(t,n,r){let i=new e,a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Rn(e)&&e.content&&this._emit(`content`,e.content)}},z={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},_r=class extends Error{},vr=class extends Error{};function yr(e,t=z.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return br(e.trim(),t)}var br=(e,t)=>{let n=e.length,r=0,i=e=>{throw new _r(`${e} at position ${r}`)},a=e=>{throw new vr(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||z.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||z.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||z.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||z.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||z.MINUS_INFINITY&t&&n-r>1&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||z.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)===`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(z.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&z.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(z.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(z.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(z.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(z.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r===n&&!(z.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&z.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
|
8
|
+
\r `.includes(e[r]);)r++};return o()},xr=e=>yr(e,z.ALL^z.NUM),B,V,Sr,Cr,H,wr,Tr,Er,Dr,Or,kr,Ar,jr=`chat.completion.chunk.message:`;function Mr(e,t,n){let r={type:`message`,message:t,...n?{tool_call_ids:n}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${jr}${JSON.stringify(r)}`}}function Nr(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(jr)}function Pr(e){return`type`in e?e:JSON.parse(e.object.slice(30))}var Fr=128,Ir=128;function Lr(e,t){return Object.prototype.propertyIsEnumerable.call(t,`__proto__`)&&!he(e,`__proto__`)&&Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(e,t)}var Rr=class e extends hr{constructor(e){super(),B.add(this),V.set(this,void 0),Sr.set(this,void 0),Cr.set(this,void 0),H.set(this,void 0),l(this,V,e,`f`),l(this,Sr,new Set,`f`),l(this,Cr,[],`f`)}get currentChatCompletionSnapshot(){return u(this,H,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),u(this,B,`m`,wr).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)u(this,B,`m`,Er).call(this,e);if(r.controller.signal?.aborted)throw new g;return this._addChatCompletion(u(this,B,`m`,kr).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,B,`m`,wr).call(this),this._connected();let n=Ue.fromReadableStream(e,this.controller),r;for await(let e of n){if(Nr(e)){let t=Pr(e);if(u(this,H,`f`)){let e=u(this,H,`f`).choices[0]?.message.tool_calls;for(let[n,r]of t.tool_call_ids?.entries()??[]){let t=e?.[n];t&&r&&(t.id=r)}this._addChatCompletion(u(this,B,`m`,kr).call(this)),r=void 0}this._addMessage(t.message);continue}let t=e;r&&t.id&&r!==t.id&&this._addChatCompletion(u(this,B,`m`,kr).call(this)),u(this,B,`m`,Er).call(this,t),t.id&&(r=t.id)}if(n.controller.signal?.aborted)throw new g;if(u(this,H,`f`))return this._addChatCompletion(u(this,B,`m`,kr).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new m(`request ended without sending any chunks`)}[(V=new WeakMap,Sr=new WeakMap,Cr=new WeakMap,H=new WeakMap,B=new WeakSet,wr=function(){this.ended||(l(this,Sr,new Set,`f`),l(this,H,void 0,`f`))},Tr=function(e){let t=u(this,Cr,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},u(this,Cr,`f`)[e.index]=t,t)},Er=function(e){if(this.ended)return;let t=u(this,B,`m`,Ar).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index],{delta:r}=n;r?.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.content,e.message.content),this._emit(`content.delta`,{delta:r.content,snapshot:e.message.content,parsed:e.message.parsed})),r?.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=u(this,B,`m`,Tr).call(this,e);e.finish_reason&&(u(this,B,`m`,Or).call(this,e),i.current_tool_call_index!=null&&u(this,B,`m`,Dr).call(this,e,i.current_tool_call_index));for(let t of r?.tool_calls??[])i.current_tool_call_index!==t.index&&(u(this,B,`m`,Or).call(this,e),i.current_tool_call_index!=null&&u(this,B,`m`,Dr).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=t.index;for(let t of r?.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n.type)}}},Dr=function(e,t){if(u(this,B,`m`,Tr).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=u(this,V,`f`)?.tools?.find(e=>En(e)&&e.function.name===n.function.name),r=null;An(e)?r=e.$parseRaw(n.function.arguments):e?.function.strict&&(r=JSON.parse(n.function.arguments)),this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:r})}else n.type},Or=function(e){let t=u(this,B,`m`,Tr).call(this,e);e.message.content!=null&&(e.message.content!==``||!e.message.refusal&&!e.message.tool_calls?.length&&!e.message.function_call)&&!t.content_done&&(t.content_done=!0,this._emit(`content.done`,{content:e.message.content,parsed:e.message.refusal?null:kn(u(this,V,`f`)?.response_format,e.message.content)})),e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},kr=function(){if(this.ended)throw new m(`stream has ended, this shouldn't happen`);let e=u(this,H,`f`);if(!e)throw new m(`request ended without sending any chunks`);let t=u(this,Sr,`f`);return l(this,Sr,new Set,`f`),l(this,H,void 0,`f`),l(this,Cr,[],`f`),zr(e,u(this,V,`f`),t)},Ar=function(e){var t,n,r,i,a;let o=u(this,H,`f`),{choices:s,...c}=e;if(o)e.id&&Lr(o,c);else{let e={...c,choices:[]};l(this,H,e,`f`),o=e}let d=u(this,V,`f`)?.n,f=typeof d==`number`&&Number.isSafeInteger(d)&&d>0?Math.min(d,Fr):Fr;for(let{delta:s,finish_reason:c,index:l,logprobs:d=null,...p}of e.choices){if(!Number.isSafeInteger(l)||l<0||l>=f)throw new m(`Chat completion stream contains an invalid choice index: ${l}`);let e=o.choices[l];if(!e){let t={finish_reason:c,index:l,message:{},logprobs:d,...p};o.choices[l]=t,e=t}if(d){if(e.logprobs){let{content:r,refusal:i,...a}=d;Lr(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}else e.logprobs={...d}}if(c&&(e.finish_reason=c,u(this,V,`f`)&&In(u(this,V,`f`)))){if(c===`length`)throw new ae;if(c===`content_filter`)throw new oe}if(Lr(e,p),!s)continue;u(this,Sr,`f`).delete(l);let{audio:h,content:g,refusal:_,function_call:v,role:y,tool_calls:b,...x}=s;if(Lr(e.message,x),h?.expires_at!=null&&h.id==null&&h.data==null&&h.transcript==null&&g==null&&_==null&&v==null&&y==null&&b==null&&Object.keys(x).length===0&&u(this,Sr,`f`).add(l),_&&(e.message.refusal=(e.message.refusal||``)+_),y&&(e.message.role=y),h){let t=(r=e.message).audio??(r.audio={});h.id!=null&&(t.id=h.id),h.data!=null&&(t.data=(t.data??``)+h.data),h.transcript!=null&&(t.transcript=(t.transcript??``)+h.transcript),h.expires_at!=null&&(t.expires_at=h.expires_at)}if(v&&(e.message.function_call?(v.name&&(e.message.function_call.name=v.name),v.arguments&&((i=e.message.function_call).arguments??(i.arguments=``),e.message.function_call.arguments+=v.arguments)):e.message.function_call=v),g!=null&&(e.message.content=(e.message.content||``)+g,!e.message.refusal&&On(u(this,V,`f`)?.response_format)&&(e.message.parsed=e.message.content.trim()?xr(e.message.content):null)),b){let t=(a=e.message).tool_calls??(a.tool_calls=[]);for(let{index:e,id:n,type:r,function:i,custom:a,...o}of b){if(!Number.isSafeInteger(e)||e<0||e>=Ir)throw new m(`Chat completion stream contains an invalid tool call index: ${e}`);let s=t[e]??(t[e]={});if(Lr(s,o),n&&(s.id=n),r&&(s.type=r),a){let e=s.custom??={name:a.name??``,input:``};a.name&&(e.name=a.name),a.input&&(e.input+=a.input)}if(i){let e=s.function??={name:i.name??``,arguments:``};i.name&&(e.name=i.name),i.arguments&&(e.arguments+=i.arguments,Fn(u(this,V,`f`),s)&&(e.parsed_arguments=xr(e.arguments)))}}}}return o},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`chunk`,t),()=>this.off(`chunk`,t)},{onReturn:()=>this.abort()})}toReadableStream(){return new Ue(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function zr(e,t,n){let{id:r,choices:i,created:a,model:o,system_fingerprint:s,...c}=e;return jn({...c,id:r,choices:i.map(({message:t,finish_reason:r,index:i,logprobs:a,...o})=>{let{content:s=null,function_call:c,tool_calls:l,audio:u,...f}=t,p=r??(n.has(i)&&Br(u)?`stop`:null);if(!p)throw new m(`missing finish_reason for choice ${i}`);let h=u?{audio:u}:{},g=t.role;if(!g)throw new m(`missing role for choice ${i}`);if(c){let{arguments:e,name:n}=c;if(e==null)throw new m(`missing function_call.arguments for choice ${i}`);if(!n)throw new m(`missing function_call.name for choice ${i}`);return{...o,message:{...h,content:s,function_call:{arguments:e,name:n},role:g,refusal:t.refusal??null},finish_reason:p,index:i,logprobs:a}}return l?{...o,index:i,finish_reason:p,logprobs:a,message:{...f,...h,role:g,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{if(t.type==null)throw new m(`missing choices[${i}].tool_calls[${n}].type\n${Vr(e)}`);if(t.type===`custom`){let{custom:r,type:a,id:o,...s}=t,{input:c=``,name:l,...u}=r||{};if(l==null)throw new m(`missing choices[${i}].tool_calls[${n}].custom.name\n${Vr(e)}`);return{...s,id:o||`call_${d()}`,type:a,custom:{...u,name:l,input:c}}}let{function:r,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=r||{};if(l==null)throw new m(`missing choices[${i}].tool_calls[${n}].function.name\n${Vr(e)}`);if(c==null)throw new m(`missing choices[${i}].tool_calls[${n}].function.arguments\n${Vr(e)}`);return{...s,id:o||`call_${d()}`,type:a,function:{...u,name:l,arguments:c}}})}}:{...o,message:{...f,...h,content:s,role:g,refusal:t.refusal??null},finish_reason:p,index:i,logprobs:a}}),created:a,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function Br(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function Vr(e){return JSON.stringify(e)}var Hr=class e extends Rr{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e,t,n=this._createIterator(n=>{let r=t=>{e=t,n(t)},i=r=>{if(Rn(r)){t=r.tool_calls?.map(e=>e.id);return}if(zn(r)){if(!e)throw new m(`cannot serialize a tool message before receiving any chunks`);n(Mr(e,r,t))}};return this.on(`chunk`,r),this.on(`message`,i),()=>{this.off(`chunk`,r),this.off(`message`,i)}},{onReturn:()=>this.abort()});return new Ue(()=>n,this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},Ur=class extends I{constructor(){super(...arguments),this.messages=new Tn(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`,M,{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 Ln(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:`chat.completions.parse`}})._thenUnwrap(t=>Mn(t,e))}runTools(e,t){return e.stream?Hr.runTools(this._client,e,t):gr.runTools(this._client,e,t)}stream(e,t){return Rr.createChatCompletion(this._client,e,t)}};Ur.Messages=Tn;var Wr=class extends I{constructor(){super(...arguments),this.completions=new Ur(this._client)}};Wr.Completions=Ur;var Gr=class extends I{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`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Kr=class extends I{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},qr=class extends I{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`,N,{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`,jt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,jt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},Jr=class extends I{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}})}},Yr=class extends I{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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Xr=class extends I{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`,Mt,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Zr=class extends I{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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Qr=class extends I{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}})}},$r=class extends I{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}})}},ei=class extends I{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:r}=t;return this._client.get(L`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/groups/${e}/roles`,Mt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(L`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ti=class extends I{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:r}=t;return this._client.get(L`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/groups/${e}/users`,Mt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(L`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ni=class extends I{constructor(){super(...arguments),this.users=new ti(this._client),this.roles=new ei(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`,Mt,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};ni.Users=ti,ni.Roles=ei;var ri=class extends I{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(L`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/api_keys`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ii=class extends I{list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/certificates`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(L`/organization/projects/${e}/certificates/activate`,jt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(L`/organization/projects/${e}/certificates/deactivate`,jt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},ai=class extends I{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}})}},oi=class extends I{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}})}},si=class extends I{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}})}},ci=class extends I{listRateLimits(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/rate_limits`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},li=class extends I{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:r}=t;return this._client.get(L`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/projects/${e}/roles`,Mt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ui=class extends I{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:r}=t;return this._client.get(L`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/spend_alerts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},di=class extends I{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}})}},fi=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(L`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(L`/projects/${r}/groups/${e}/roles`,Mt,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(L`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},pi=class extends I{constructor(){super(...arguments),this.roles=new fi(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:r,...i}=t;return this._client.get(L`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/groups`,Mt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};pi.Roles=fi;var mi=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/service_accounts/${e}/api_keys`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},hi=class extends I{constructor(){super(...arguments),this.apiKeys=new mi(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:r}=t;return this._client.get(L`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/service_accounts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};hi.APIKeys=mi;var gi=class extends I{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(L`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(L`/projects/${r}/users/${e}/roles`,Mt,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(L`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},_i=class extends I{constructor(){super(...arguments),this.roles=new gi(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:r}=t;return this._client.get(L`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(L`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/projects/${e}/users`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(L`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};_i.Roles=gi;var U=class extends I{constructor(){super(...arguments),this.users=new _i(this._client),this.serviceAccounts=new hi(this._client),this.apiKeys=new ri(this._client),this.rateLimits=new ci(this._client),this.modelPermissions=new si(this._client),this.hostedToolPermissions=new oi(this._client),this.groups=new pi(this._client),this.roles=new li(this._client),this.dataRetention=new ai(this._client),this.spendLimit=new di(this._client),this.spendAlerts=new ui(this._client),this.certificates=new ii(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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(L`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};U.Users=_i,U.ServiceAccounts=hi,U.APIKeys=ri,U.RateLimits=ci,U.ModelPermissions=si,U.HostedToolPermissions=oi,U.Groups=pi,U.Roles=li,U.DataRetention=ai,U.SpendLimit=di,U.SpendAlerts=ui,U.Certificates=ii;var vi=class extends I{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:r}=t;return this._client.get(L`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/organization/users/${e}/roles`,Mt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(L`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},yi=class extends I{constructor(){super(...arguments),this.roles=new vi(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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(L`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};yi.Roles=vi;var W=class extends I{constructor(){super(...arguments),this.auditLogs=new Kr(this._client),this.adminAPIKeys=new Gr(this._client),this.usage=new $r(this._client),this.invites=new Yr(this._client),this.users=new yi(this._client),this.groups=new ni(this._client),this.roles=new Xr(this._client),this.dataRetention=new Jr(this._client),this.spendLimit=new Qr(this._client),this.spendAlerts=new Zr(this._client),this.certificates=new qr(this._client),this.projects=new U(this._client)}};W.AuditLogs=Kr,W.AdminAPIKeys=Gr,W.Usage=$r,W.Invites=Yr,W.Users=yi,W.Groups=ni,W.Roles=Xr,W.DataRetention=Jr,W.SpendLimit=Qr,W.SpendAlerts=Zr,W.Certificates=qr,W.Projects=U;var bi=class extends I{constructor(){super(...arguments),this.organization=new W(this._client)}};bi.Organization=W;var xi=class extends I{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:P([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Si=class extends I{create(e,t){return this._client.post(`/audio/transcriptions`,F({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Ci=class extends I{create(e,t){return this._client.post(`/audio/translations`,F({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},wi=class extends I{constructor(){super(...arguments),this.transcriptions=new Si(this._client),this.translations=new Ci(this._client),this.speech=new xi(this._client)}};wi.Transcriptions=Si,wi.Translations=Ci,wi.Speech=xi;var Ti=class extends I{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`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},Ei=class extends I{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/assistants/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Di=class extends I{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Oi=class extends I{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ki=class extends I{constructor(){super(...arguments),this.sessions=new Di(this._client),this.transcriptionSessions=new Oi(this._client)}};ki.Sessions=Di,ki.TranscriptionSessions=Oi;var Ai=class extends I{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(L`/chatkit/sessions/${e}/cancel`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},ji=class extends I{retrieve(e,t){return this._client.get(L`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,N,{query:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(L`/chatkit/threads/${e}/items`,N,{query:t,...n,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Mi=class extends I{constructor(){super(...arguments),this.sessions=new Ai(this._client),this.threads=new ji(this._client)}};Mi.Sessions=Ai,Mi.Threads=ji;var Ni=class extends I{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(L`/responses/${e}/input_items?beta=true`,M,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}},Pi=class extends I{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},Fi=class extends I{constructor(){super(...arguments),this.inputItems=new Ni(this._client),this.inputTokens=new Pi(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(L`/responses/${e}?beta=true`,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(L`/responses/${e}?beta=true`,{...n,headers:P([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(L`/responses/${e}/cancel?beta=true`,{...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}};Fi.InputItems=Ni,Fi.InputTokens=Pi;var Ii=class extends I{create(e,t,n){return this._client.post(L`/threads/${e}/messages`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/messages/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/messages`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(L`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Li=class extends I{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(L`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(L`/threads/${r}/runs/${e}/steps`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Ri=e=>{if(globalThis.Buffer!==void 0){let t=globalThis.Buffer.from(e,`base64`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof atob<`u`){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}throw new m("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},zi=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},G=e=>{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0},Bi=1024,Vi=65536,Hi=new WeakMap,Ui=new WeakSet;function Wi(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function Gi(e){for(let[t,n]of e.arrays)n.cacheable&&!Ui.has(t)?Hi.set(t,{length:n.length,ownEntryCount:n.ownEntryCount}):Hi.delete(t)}function Ki(e){return typeof e==`string`||typeof e==`number`}function qi(e,t){return t.every(Ki)&&e.every(Ki)}function Ji(e){let t=0;for(let n of Object.keys(e)){let r=Number(n);Number.isSafeInteger(r)&&r>=0&&r<e.length&&String(r)===n&&(t+=1)}return t}function Yi(e,t,n){return t?n?.length===e.length?n.ownEntryCount:Ji(e):0}function Xi(e,t,n){let{index:r}=e;if(t===`array`&&r==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(t===`array`&&typeof r!=`number`)throw TypeError(`Expected array delta entry \`index\` property to be a number but got ${r}`);if(!Number.isSafeInteger(r)||r<0||r>=n+Bi||r>=Vi)throw new m(`Assistant stream delta contains an invalid ${t} index: ${r}`);return r}function Zi(e,t,n,r,i){let a=r.arrays.get(e);if(!a){let t=r.cacheArrays&&!Ui.has(e),n=t?Hi.get(e):void 0;a={baselineLength:e.length,cacheable:t,enforceSparseHoleBudget:t,entries:new Map,length:e.length,ownEntryCount:Yi(e,t,n)},r.arrays.set(e,a)}for(let o of t){if(!C(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let t=Xi(o,n,a.baselineLength),s;a.entries.has(t)?s=a.entries.get(t):he(e,t)?(s=e[t],s??a.entries.set(t,o)):(a.entries.set(t,o),a.ownEntryCount+=1);let c=Math.max(a.length,t+1);if(a.enforceSparseHoleBudget&&c-a.ownEntryCount>Bi)throw new m(`Assistant stream delta contains an invalid ${n} index: ${t}`);C(s)&&i(s,o,r),a.length=c}}function Qi(e,t,n){let r=n.records.get(e);for(let[i,a]of Object.entries(t)){if(i===`index`||i===`type`)continue;let t;if(r?.has(i)?t=r.get(i):he(e,i)&&(t=e[i]),t==null){r||(r=new Map,n.records.set(e,r)),r.set(i,a);continue}C(t)&&C(a)?Qi(t,a,n):Array.isArray(t)&&Array.isArray(a)&&!qi(t,a)&&Zi(t,a,`array`,n,Qi)}}function $i(e){return(C(e)||Array.isArray(e))&&Ui.has(e)}function K(e){if(!(!C(e)&&!Array.isArray(e)||Ui.has(e))){Ui.add(e),Array.isArray(e)&&Hi.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n&&`value`in n&&K(n.value)}}}function ea(e,t,n){Ui.has(e)&&K(n),Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function ta(e){let{index:t}=e;if(t==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof t!=`number`)throw TypeError(`Expected array delta entry \`index\` property to be a number but got ${t}`);return t}function na(e,t,n){if(qi(e,t)){e.push(...t),Hi.delete(e);return}for(let r of t){if(!C(r))throw Error(`Expected array delta entry to be an object but got: ${r}`);let t=ta(r);if(he(e,t)){let i=e[t];i==null?(Ui.has(e)&&K(r),e[t]=r):e[t]=n(i,r)}else ea(e,t,r)}}function ra(e,t){let n=Ui.has(e);for(let[r,i]of Object.entries(t)){if(r===`__proto__`||r===`constructor`||r===`prototype`)throw new m(`Assistant stream delta contains an unsafe property: ${r}`);if(!he(e,r)){n&&K(i),e[r]=i;continue}let t=e[r];if(t==null){n&&K(i),e[r]=i;continue}if(r===`index`||r===`type`){e[r]=i;continue}if(typeof t==`string`&&typeof i==`string`)t+=i;else if(typeof t==`number`&&typeof i==`number`)t+=i;else if(C(t)&&C(i))t=ra(t,i);else if(Array.isArray(t)&&Array.isArray(i)){na(t,i,ra);continue}else throw TypeError(`Unhandled record type: ${r}, deltaValue: ${i}, accValue: ${t}`);e[r]=t}return e}function ia(e){if(!(!C(e)&&!Array.isArray(e)))for(let[t,n]of Object.entries(e)){if(t===`__proto__`||t===`constructor`||t===`prototype`)throw new m(`Assistant stream delta contains an unsafe property: ${t}`);ia(n)}}function aa(e,t,n=!1){ia(t);let r=e,i=t,a=Wi(n&&!$i(e));return Qi(r,i,a),ra(r,i),Gi(a),e}function oa(e,t,n,r=!0){ia(t);let i=Wi(r&&!$i(e));return Zi(e,t,n,i,Qi),()=>Gi(i)}var q,sa,ca,la,J,ua,da,fa,pa,Y,ma,ha,ga,_a,va,ya,ba,X,xa,Sa,Ca,wa,Ta,Ea=class e extends nr{constructor(){super(...arguments),q.add(this),sa.set(this,[]),ca.set(this,Object.create(null)),la.set(this,Object.create(null)),J.set(this,void 0),ua.set(this,void 0),da.set(this,void 0),fa.set(this,void 0),pa.set(this,void 0),Y.set(this,void 0),ma.set(this,void 0),ha.set(this,void 0),ga.set(this,void 0)}[(sa=new WeakMap,ca=new WeakMap,la=new WeakMap,J=new WeakMap,ua=new WeakMap,da=new WeakMap,fa=new WeakMap,pa=new WeakMap,Y=new WeakMap,ma=new WeakMap,ha=new WeakMap,ga=new WeakMap,q=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(structuredClone(t));return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}static fromReadableStream(t){let n=new e;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=Ue.fromReadableStream(e,this.controller);for await(let e of n)u(this,q,`m`,_a).call(this,e);if(n.controller.signal?.aborted)throw new g;return this._addRun(u(this,q,`m`,va).call(this))}toReadableStream(){return new Ue(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runToolAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)u(this,q,`m`,_a).call(this,e);if(a.controller.signal?.aborted)throw new g;return this._addRun(u(this,q,`m`,va).call(this))}static createThreadAssistantStream(t,n,r){let i=new e;return i._run(()=>i._threadAssistantStream(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static createAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}currentEvent(){return K(u(this,ma,`f`)),u(this,ma,`f`)}currentRun(){return K(u(this,ha,`f`)),u(this,ha,`f`)}currentMessageSnapshot(){return K(u(this,J,`f`)),u(this,J,`f`)}currentRunStepSnapshot(){return K(u(this,ga,`f`)),u(this,ga,`f`)}async finalRunSteps(){return await this.done(),Object.values(u(this,ca,`f`))}async finalMessages(){return await this.done(),Object.values(u(this,la,`f`))}async finalRun(){if(await this.done(),!u(this,ua,`f`))throw Error(`Final run was not received.`);return u(this,ua,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)u(this,q,`m`,_a).call(this,e);if(i.controller.signal?.aborted)throw new g;return this._addRun(u(this,q,`m`,va).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)u(this,q,`m`,_a).call(this,e);if(a.controller.signal?.aborted)throw new g;return this._addRun(u(this,q,`m`,va).call(this))}static accumulateDelta(e,t){return aa(e,t)}_addRun(e){return u(this,q,`m`,X).call(this,`run`,e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};_a=function(e){if(!this.ended)switch(l(this,ma,e,`f`),u(this,q,`m`,xa).call(this,e),e.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`:u(this,q,`m`,Ta).call(this,e);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`:u(this,q,`m`,ba).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:u(this,q,`m`,ya).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`)}},va=function(){if(this.ended)throw new m(`stream has ended, this shouldn't happen`);if(!u(this,ua,`f`))throw Error(`Final run has not been received`);return u(this,ua,`f`)},ya=function(e){let[t,n]=u(this,q,`m`,Ca).call(this,e,u(this,J,`f`));l(this,J,t,`f`),u(this,la,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type===`text`&&u(this,q,`m`,X).call(this,`textCreated`,n.text)}switch(e.event){case`thread.message.created`:l(this,da,void 0,`f`),l(this,fa,void 0,`f`),u(this,q,`m`,X).call(this,`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(u(this,q,`m`,X).call(this,`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type===`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type===`text`)u(this,q,`m`,X).call(this,`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!==u(this,da,`f`)){if(u(this,fa,`f`))switch(u(this,fa,`f`).type){case`text`:u(this,q,`m`,X).call(this,`textDone`,u(this,fa,`f`).text,u(this,J,`f`));break;case`image_file`:u(this,q,`m`,X).call(this,`imageFileDone`,u(this,fa,`f`).image_file,u(this,J,`f`))}l(this,da,n.index,`f`)}l(this,fa,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(u(this,da,`f`)!==void 0){let t=e.data.content[u(this,da,`f`)];if(t)switch(t.type){case`image_file`:u(this,q,`m`,X).call(this,`imageFileDone`,t.image_file,u(this,J,`f`));break;case`text`:u(this,q,`m`,X).call(this,`textDone`,t.text,u(this,J,`f`))}}u(this,J,`f`)&&u(this,q,`m`,X).call(this,`messageDone`,e.data),l(this,da,void 0,`f`),l(this,fa,void 0,`f`),l(this,J,void 0,`f`)}},ba=function(e){let t=u(this,q,`m`,Sa).call(this,e);switch(l(this,ga,t,`f`),e.event){case`thread.run.step.created`:l(this,pa,void 0,`f`),l(this,Y,void 0,`f`),u(this,q,`m`,X).call(this,`runStepCreated`,e.data);break;case`thread.run.step.delta`:{let n=e.data.delta;if(n.step_details&&n.step_details.type===`tool_calls`&&n.step_details.tool_calls&&t.step_details.type===`tool_calls`)for(let e of n.step_details.tool_calls)e.index===u(this,pa,`f`)?u(this,q,`m`,X).call(this,`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(u(this,Y,`f`)&&u(this,q,`m`,X).call(this,`toolCallDone`,u(this,Y,`f`)),l(this,pa,e.index,`f`),l(this,Y,t.step_details.tool_calls[e.index],`f`),u(this,Y,`f`)&&u(this,q,`m`,X).call(this,`toolCallCreated`,u(this,Y,`f`)));u(this,q,`m`,X).call(this,`runStepDelta`,e.data.delta,t);break}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:l(this,ga,void 0,`f`),e.data.step_details.type===`tool_calls`&&u(this,Y,`f`)&&u(this,q,`m`,X).call(this,`toolCallDone`,u(this,Y,`f`)),u(this,q,`m`,X).call(this,`runStepDone`,e.data,t),l(this,pa,void 0,`f`),l(this,Y,void 0,`f`)}},X=function(e,...t){if(this._hasListeners(e))for(let e of t)K(e);this._emit(e,...t)},xa=function(e){u(this,sa,`f`).push(e),u(this,q,`m`,X).call(this,`event`,e)},Sa=function(e){switch(e.event){case`thread.run.step.created`:return u(this,ca,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:{let t=u(this,ca,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=aa(t,n.delta,!0);u(this,ca,`f`)[e.data.id]=r}return u(this,ca,`f`)[e.data.id]}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:u(this,ca,`f`)[e.data.id]=e.data}if(u(this,ca,`f`)[e.data.id])return u(this,ca,`f`)[e.data.id];throw Error(`No snapshot available`)},Ca=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:{if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content){ia(r.delta);let e=!$i(t),i=oa(t.content,r.delta.content,`content`,e);for(let i of r.delta.content)if(he(t.content,i.index)){let n=t.content[i.index];t.content[i.index]=u(this,q,`m`,wa).call(this,i,n,e)}else ea(t.content,i.index,i),n.push(i);i()}return[t,n]}case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},wa=function(e,t,n){return aa(t,e,n)},Ta=function(e){switch(l(this,ha,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`:l(this,ua,e.data,`f`),u(this,Y,`f`)&&u(this,q,`m`,X).call(this,`toolCallDone`,u(this,Y,`f`)),l(this,pa,void 0,`f`),l(this,Y,void 0,`f`)}};var Da=class extends I{constructor(){super(...arguments),this.steps=new Li(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(L`/threads/${r}/runs/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/threads/${e}/runs`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(L`/threads/${r}/runs/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Ea.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ve(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Ea.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(L`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Ea.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Da.Steps=Li;var Oa=class extends I{constructor(){super(...arguments),this.runs=new Da(this._client),this.messages=new Ii(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(L`/threads/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:P([{"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 Ea.createThreadAssistantStream(e,this._client.beta.threads,t)}};Oa.Runs=Da,Oa.Messages=Ii;var ka=class extends I{constructor(){super(...arguments),this.realtime=new ki(this._client),this.responses=new Fi(this._client),this.chatkit=new Mi(this._client),this.assistants=new Ei(this._client),this.threads=new Oa(this._client)}};ka.Realtime=ki,ka.Responses=Fi,ka.ChatKit=Mi,ka.Assistants=Ei,ka.Threads=Oa;var Aa=class extends I{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},ja=class extends I{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(L`/containers/${r}/files/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Ma=class extends I{constructor(){super(...arguments),this.content=new ja(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:r}=t;return this._client.get(L`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/containers/${e}/files`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(L`/containers/${r}/files/${e}`,{...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};Ma.Content=ja;var Na=class extends I{constructor(){super(...arguments),this.files=new Ma(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`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/containers/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};Na.Files=Ma;var Pa=class extends I{create(e,t){return this._client.post(`/content_provenance_checks`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}},Fa=class extends I{create(e,t,n){let{include:r,...i}=t;return this._client.post(L`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(L`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/conversations/${e}/items`,N,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(L`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},Ia=class extends I{constructor(){super(...arguments),this.items=new Fa(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}})}};Ia.Items=Fa;var La=class extends I{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&k(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(k(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=zi(t)}),e)))}},Ra=class extends I{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(L`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(L`/evals/${r}/runs/${e}/output_items`,M,{query:i,...n,__security:{bearerAuth:!0}})}},za=class extends I{constructor(){super(...arguments),this.outputItems=new Ra(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:r}=t;return this._client.get(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/evals/${e}/runs`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(L`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};za.OutputItems=Ra;var Ba=class extends I{constructor(){super(...arguments),this.runs=new za(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`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Ba.Runs=za;var Va=class extends I{create(e,t){return this._client.post(`/files`,F({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`,M,{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:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await ve(t),a=await this.retrieve(e),Date.now()-i>n)throw new v({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Ha=class extends I{},Ua=class extends I{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}})}},Wa=class extends I{constructor(){super(...arguments),this.graders=new Ua(this._client)}};Wa.Graders=Ua;var Ga=class extends I{create(e,t,n){return this._client.getAPIList(L`/fine_tuning/checkpoints/${e}/permissions`,jt,{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`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(L`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Ka=class extends I{constructor(){super(...arguments),this.permissions=new Ga(this._client)}};Ka.Permissions=Ga;var qa=class extends I{list(e,t={},n){return this._client.getAPIList(L`/fine_tuning/jobs/${e}/checkpoints`,M,{query:t,...n,__security:{bearerAuth:!0}})}},Ja=class extends I{constructor(){super(...arguments),this.checkpoints=new qa(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`,M,{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`,M,{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}})}};Ja.Checkpoints=qa;var Ya=class extends I{constructor(){super(...arguments),this.methods=new Ha(this._client),this.jobs=new Ja(this._client),this.checkpoints=new Ka(this._client),this.alpha=new Wa(this._client)}};Ya.Methods=Ha,Ya.Jobs=Ja,Ya.Checkpoints=Ka,Ya.Alpha=Wa;var Xa=class extends I{},Za=class extends I{constructor(){super(...arguments),this.graderModels=new Xa(this._client)}};Za.GraderModels=Xa;var Qa=class extends I{createVariation(e,t){return this._client.post(`/images/variations`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,F({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}})}},$a=class extends I{retrieve(e,t){return this._client.get(L`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,jt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},eo=class extends I{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},to=class extends I{accept(e,t,n){return this._client.post(L`/realtime/calls/${e}/accept`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(L`/realtime/calls/${e}/hangup`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(L`/realtime/calls/${e}/refer`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(L`/realtime/calls/${e}/reject`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},no=class extends I{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},ro=class extends I{constructor(){super(...arguments),this.clientSecrets=new no(this._client),this.calls=new to(this._client)}};ro.ClientSecrets=no,ro.Calls=to;function io(e,t){if(!t||!so(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return fo(e,t)&&po(t),t}return ao(e,t)}function ao(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?uo(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?oo(t,e.text):null}:e);return{...e,content:r}}return e}),i={...e,output:r};return fo(e,i)&&po(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function oo(e,t){return kn(e.text?.format,t)}function so(e){return On(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>co(e)||e.type===`function`&&e.strict===!0)}function co(e){return e?.$brand===`auto-parseable-tool`}function lo(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function uo(e,t){let n=lo(e.tools??[],t.name),r=null;return co(n)?r=n.$parseRaw(t.arguments):n?.strict&&(r=JSON.parse(t.arguments)),{...t,parsed_arguments:r}}function fo(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function po(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var mo=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 RangeError(`missing output at index ${e}`);let n=this.capacity+e,r=t-(this.values[n]??0);if(r!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+r,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,r=0;for(;t<n;)t%2==1&&(r+=this.values[t]??0,t+=1),n%2==1&&(--n,r+=this.values[n]??0),t=Math.floor(t/2),n=Math.floor(n/2);return r}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 e=this.capacity-1;e>0;--e)t[e]=(t[e*2]??0)+(t[e*2+1]??0);this.values=t}};function ho(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new mo}}function go(e,t){if(t.type!==`message`)return``;let n=``;for(let e of t.content)e.type===`output_text`&&(n+=e.text);return e.outputTextLengths.set(t,n.length),n}function _o(e,t){if(e.canonicalSnapshot===t)return;let n=new mo,r=``;for(let i of t.output){let t=go(e,i);r+=t,n.append(t.length)}t.output_text!==r&&(t.output_text=r),e.outputTextIndex=n,e.canonicalSnapshot=t}function vo(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new mo;let n=structuredClone(t);return!Object.getOwnPropertyDescriptor(n,`output_text`)||n.output_text===null||n.output_text===void 0?_o(e,n):n.output.length===0&&n.output_text===``&&(e.canonicalSnapshot=n),n}function yo(e,t,n,r,i){let a=e.outputTextLengths.get(t);if(a!==void 0){let o=a-r.length+i.length;e.outputTextLengths.set(t,o),e.outputTextIndex.update(n,o)}}function bo(e,t,n){if(t.length===0){e.output_text+=n;return}e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+n}function xo(e,t,n,r){if(n===void 0||t?.type!==`message`)return 0;if(n<t.content.length-n-1){let e=0;for(let r=0;r<n;r+=1){let n=t.content[r];n?.type===`output_text`&&(e+=n.text.length)}return e}let i=0;for(let e=n+1;e<t.content.length;e+=1){let n=t.content[e];n?.type===`output_text`&&(i+=n.text.length)}return(e.outputTextLengths.get(t)??go(e,t).length)-i-r.length}function So(e,t,n,r,i,a){if(r===i)return;let o=t.output[n];if(n===t.output.length-1&&(a===void 0||o?.type===`message`&&a===o.content.length-1)){bo(t,r,i);return}let s=xo(e,o,a,i),c=e.outputTextIndex.prefixSum(n)+s;if(c+r.length===t.output_text.length){bo(t,r,i);return}t.output_text=t.output_text.slice(0,c)+i+t.output_text.slice(c+r.length)}function Co(e,t,n,r=!1){if(!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!r||t in e:!he(e,t)))throw new m(`missing ${n} at index ${t}`)}function wo(e,t,n){if(t!==e.length)throw new m(`missing ${n} at index ${t}`);Co(e,t,n,!0)}function Z(e,t){Co(e.output,t,`output`);let n=e.output[t];if(!n)throw new m(`missing output at index ${t}`);return n}function Q(e,t){Co(e,t,`content`);let n=e[t];if(!n)throw new m(`missing content at index ${t}`);return n}function To(e,t,n){let r=e.output.find(e=>e.type===`shell_call`&&e.call_id===t.call_id);for(r?Co(r.action.commands,n,`command`):Co(t.output,n,`content`,!0);t.output.length<=n;)t.output.push({stdout:``,stderr:``,outcome:{type:`exit`,exit_code:0}});return Q(t.output,n)}function Eo(e){throw new m(`Unhandled response stream event: ${JSON.stringify(e)}`)}function Do(e,t,n){switch(e.type){case`response.output_item.added`:{wo(t.output,e.output_index,`output`);let r=structuredClone(e.item);r.type===`message`&&_o(n,t),t.output.push(r);let i=go(n,r);return n.canonicalSnapshot===t&&n.outputTextIndex.append(i.length),i&&(t.output_text+=i),!0}case`response.output_item.done`:{let r=Z(t,e.output_index),i=go(n,r),a=structuredClone(e.item);(r.type===`message`||a.type===`message`)&&_o(n,t),t.output[e.output_index]=a;let o=go(n,a);return n.canonicalSnapshot===t&&n.outputTextIndex.update(e.output_index,o.length),So(n,t,e.output_index,i,o),!0}default:return!1}}function Oo(e,t,n){switch(e.type){case`response.content_part.added`:{let r=Z(t,e.output_index),{type:i}=r,{part:a}=e;if(i===`message`&&a.type!==`reasoning_text`){wo(r.content,e.content_index,`content`);let i=structuredClone(a);i.type===`output_text`&&_o(n,t),r.content.push(i),i.type===`output_text`&&(yo(n,r,e.output_index,``,i.text),So(n,t,e.output_index,``,i.text,e.content_index))}else if(i===`reasoning`&&a.type===`reasoning_text`){let t=r.content??[];wo(t,e.content_index,`content`),r.content||=t,t.push(structuredClone(a))}return!0}default:return!1}}function ko(e,t,n){switch(e.type){case`response.content_part.done`:{let r=Z(t,e.output_index),{part:i}=e;if(r.type===`message`&&i.type!==`reasoning_text`){let a=Q(r.content,e.content_index),o=a.type===`output_text`?a.text:``,s=structuredClone(i);(a.type===`output_text`||s.type===`output_text`)&&_o(n,t),r.content[e.content_index]=s;let c=s.type===`output_text`?s.text:``;yo(n,r,e.output_index,o,c),So(n,t,e.output_index,o,c,e.content_index)}else if(r.type===`reasoning`&&i.type===`reasoning_text`){let{content:t}=r;if(!t)throw new m(`missing content at index ${e.content_index}`);Q(t,e.content_index),t[e.content_index]=structuredClone(i)}return!0}default:return!1}}function Ao(e,t,n){switch(e.type){case`response.output_text.delta`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Q(r.content,e.content_index);if(i.type!==`output_text`)throw new m(`expected content to be 'output_text', got ${i.type}`);let a=i.text;_o(n,t),i.text=a+e.delta,yo(n,r,e.output_index,a,i.text),e.output_index===t.output.length-1&&e.content_index===r.content.length-1?t.output_text+=e.delta:So(n,t,e.output_index,a,i.text,e.content_index)}return!0}case`response.output_text.done`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Q(r.content,e.content_index);if(i.type!==`output_text`)throw new m(`expected content to be 'output_text', got ${i.type}`);let a=i.text;_o(n,t),i.text=e.text,yo(n,r,e.output_index,a,e.text),So(n,t,e.output_index,a,e.text,e.content_index)}return!0}case`response.output_text.annotation.added`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`output_text`)throw new m(`expected content to be 'output_text', got ${t.type}`);Co(t.annotations,e.annotation_index,`annotation`,!0),t.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function jo(e,t){switch(e.type){case`response.refusal.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new m(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}return!0}case`response.refusal.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Q(n.content,e.content_index);if(t.type!==`refusal`)throw new m(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}return!0}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments+=e.delta),!0}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments=e.arguments),!0}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input+=e.delta),!0}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input=e.input),!0}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments+=e.delta),!0}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments=e.arguments),!0}default:return!1}}function Mo(e,t){switch(e.type){case`response.shell_call_command.added`:case`response.shell_call_command.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call`){let t=e.type===`response.shell_call_command.added`;Co(n.action.commands,e.command_index,`command`,t),n.action.commands[e.command_index]=e.command}return!0}case`response.shell_call_command.delta`:{let n=Z(t,e.output_index);return n.type===`shell_call`&&(Co(n.action.commands,e.command_index,`command`),n.action.commands[e.command_index]+=e.delta),!0}case`response.shell_call_output_content.delta`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=To(t,n,e.command_index);r.stdout+=e.delta.stdout??``,r.stderr+=e.delta.stderr??``}return!0}case`response.shell_call_output_content.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=Q(e.output,0);To(t,n,e.command_index),n.output[e.command_index]=structuredClone(r)}return!0}default:return!1}}function No(e,t){switch(e.type){case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new m(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new m(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}return!0}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new m(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new m(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}return!0}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(wo(n.summary,e.summary_index,`content`),n.summary.push(structuredClone(e.part))),!0}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(Q(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part)),!0}case`response.reasoning_summary_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text+=e.delta}return!0}case`response.reasoning_summary_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Q(n.summary,e.summary_index);t.text=e.text}return!0}default:return!1}}function Po(e,t){switch(e.type){case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta),!0}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=e.code),!0}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`in_progress`),!0}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`interpreting`),!0}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`completed`),!0}default:return!1}}function Fo(e,t){switch(e.type){case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`in_progress`),!0}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`searching`),!0}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`completed`),!0}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`in_progress`),!0}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`searching`),!0}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`completed`),!0}default:return!1}}function Io(e,t){switch(e.type){case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`in_progress`),!0}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`generating`),!0}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`completed`),!0}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`in_progress`),!0}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`completed`),!0}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`failed`),!0}default:return!1}}function Lo(e){switch(e.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 Ro(e){switch(e.type){case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`: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 zo(){return ho()}function Bo(e,t,n){if(!t){if(e.type!==`response.created`)throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return vo(n,e.response)}return Do(e,t,n)||Oo(e,t,n)||ko(e,t,n)||Ao(e,t,n)||jo(e,t)||Mo(e,t)||No(e,t)||Po(e,t)||Fo(e,t)||Io(e,t)?t:Lo(e)?vo(n,e.response):Ro(e)?t:Eo(e)}var Vo,Ho,Uo,Wo,Go,Ko,qo,Jo,Yo=class e extends nr{constructor(e){super(),Vo.add(this),Ho.set(this,void 0),Uo.set(this,void 0),Wo.set(this,void 0),Go.set(this,zo()),l(this,Ho,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),u(this,Vo,`m`,Ko).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)u(this,Vo,`m`,qo).call(this,e,i);if(r.controller.signal?.aborted)throw new g;return u(this,Vo,`m`,Jo).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,Vo,`m`,Ko).call(this),this._connected();let n=Ue.fromReadableStream(e,this.controller);for await(let e of n)u(this,Vo,`m`,qo).call(this,e,null);if(n.controller.signal?.aborted)throw new g;return u(this,Vo,`m`,Jo).call(this)}[(Ho=new WeakMap,Uo=new WeakMap,Wo=new WeakMap,Go=new WeakMap,Vo=new WeakSet,Ko=function(){this.ended||(l(this,Uo,void 0,`f`),l(this,Go,zo(),`f`))},qo=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)};if(e.type===`error`)throw new h(void 0,`error`in e&&typeof e.error==`object`&&e.error!==null?e.error:e,e.message,void 0);let r=Bo(e,u(this,Uo,`f`),u(this,Go,`f`));switch(l(this,Uo,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new m(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new m(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new m(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new m(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e)}},Jo=function(){if(this.ended)throw new m(`stream has ended, this shouldn't happen`);let e=u(this,Uo,`f`);if(!e)throw new m(`request ended without sending any events`);l(this,Uo,void 0,`f`),l(this,Go,zo(),`f`);let t=Xo(e,u(this,Ho,`f`));return l(this,Wo,t,`f`),t},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=u(this,Wo,`f`);if(!e)throw new m(`stream ended without producing a Response`);return e}};function Xo(e,t){return io(e,t)}var Zo=class extends I{list(e,t={},n){return this._client.getAPIList(L`/responses/${e}/input_items`,M,{query:t,...n,__security:{bearerAuth:!0}})}},Qo=class extends I{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},$o=class extends I{constructor(){super(...arguments),this.inputItems=new Zo(this._client),this.inputTokens=new Qo(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&po(e),e))}retrieve(e,t={},n){return this._client.get(L`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&po(e),e))}delete(e,t){return this._client.delete(L`/responses/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>ao(t,e))}stream(e,t){return Yo.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}})}};$o.InputItems=Zo,$o.InputTokens=Qo;var es=class extends I{retrieve(e,t){return this._client.get(L`/skills/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},ts=class extends I{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(L`/skills/${r}/versions/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},ns=class extends I{constructor(){super(...arguments),this.content=new ts(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:r}=t;return this._client.get(L`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/skills/${e}/versions`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(L`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};ns.Content=ts;var rs=class extends I{constructor(){super(...arguments),this.content=new es(this._client),this.versions=new ns(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`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};rs.Content=es,rs.Versions=ns;var is=class extends I{create(e,t,n){return this._client.post(L`/uploads/${e}/parts`,F({body:t,...n,__security:{bearerAuth:!0}},this._client))}},as=class extends I{constructor(){super(...arguments),this.parts=new is(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}})}};as.Parts=is;var os=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},ss=class extends I{create(e,t,n){return this._client.post(L`/vector_stores/${e}/file_batches`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/file_batches/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(L`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(L`/vector_stores/${r}/file_batches/${e}/files`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ve(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await os(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c},r)}},cs=class extends I{create(e,t,n){return this._client.post(L`/vector_stores/${e}/files`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(L`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(L`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(L`/vector_stores/${e}/files`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(L`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=P([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await ve(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(L`/vector_stores/${r}/files/${e}/content`,jt,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ls=class extends I{constructor(){super(...arguments),this.files=new cs(this._client),this.fileBatches=new ss(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(L`/vector_stores/${e}`,{...t,headers:P([{"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:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(L`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(L`/vector_stores/${e}/search`,jt,{body:t,method:`post`,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};ls.Files=cs,ls.FileBatches=ss;var us=class extends I{create(e,t){return this._client.post(`/videos`,F({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`,N,{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`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(L`/videos/${e}/content`,{query:t,...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,F({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,F({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))}},ds,fs,ps,ms=class extends I{constructor(){super(...arguments),ds.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");u(this,ds,`m`,fs).call(this,n);let i=P([t]).values,a=u(this,ds,`m`,ps).call(this,i,`webhook-signature`),o=u(this,ds,`m`,ps).call(this,i,`webhook-timestamp`),s=u(this,ds,`m`,ps).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new se(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new se(`Webhook timestamp is too old`);if(c>l+r)throw new se(`Webhook timestamp is too new`);let d=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=Uint8Array.from(n.startsWith(`whsec_`)?Ri(n.slice(6)):w(n)),p=s?`${s}.${o}.${e}`:`${o}.${e}`,m=Uint8Array.from(w(p)),h=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=Uint8Array.from(Ri(e));if(await crypto.subtle.verify(`HMAC`,h,t,m))return}catch{continue}throw new se(`The given webhook signature does not match the expected signature`)}};ds=new WeakSet,fs=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},ps=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var hs=Symbol.for(`openai.node.providerDefinitions.v1`),gs=globalThis,_s=gs[hs],vs=_s??new WeakMap;_s||Object.defineProperty(gs,hs,{value:vs});function ys(e){let t=vs.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var bs,xs,Ss,Cs,ws;function Ts(){if($e())return!0;let e=globalThis;return typeof e.WorkerGlobalScope==`function`&&e instanceof e.WorkerGlobalScope&&typeof e.WorkerNavigator==`function`&&e.navigator instanceof e.WorkerNavigator&&typeof e.navigator?.userAgent==`string`&&e.navigator.userAgent!==`Cloudflare-Workers`&&e.process?.versions?.node===void 0&&e.Deno===void 0&&e.Bun===void 0&&e.EdgeRuntime===void 0&&e.WebSocketPair===void 0}var Es=`workload-identity-auth`,$=class{constructor(e={}){bs.add(this),Ss.set(this,void 0),Cs.set(this,new WeakMap),this.completions=new Aa(this),this.chat=new Wr(this),this.embeddings=new La(this),this.files=new Va(this),this.images=new Qa(this),this.contentProvenanceChecks=new Pa(this),this.audio=new wi(this),this.moderations=new eo(this),this.models=new $a(this),this.fineTuning=new Ya(this),this.graders=new Za(this),this.vectorStores=new ls(this),this.webhooks=new ms(this),this.beta=new ka(this),this.batches=new Ti(this),this.uploads=new as(this),this.admin=new bi(this),this.responses=new $o(this),this.realtime=new ro(this),this.conversations=new Ia(this),this.evals=new Ba(this),this.containers=new Na(this),this.skills=new rs(this),this.videos=new us(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new m(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:G(`OPENAI_BASE_URL`),apiKey:r=t?null:G(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:G(`OPENAI_ADMIN_KEY`)??null,organization:a=t?null:G(`OPENAI_ORG_ID`)??null,project:o=t?null:G(`OPENAI_PROJECT_ID`)??null,webhookSecret:s=G(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:c,...u}=e,d=t?ys(t):void 0,f={apiKey:r,adminAPIKey:i,organization:a,project:o,webhookSecret:s,workloadIdentity:c,provider:t,...u,baseURL:d?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&c)throw new m("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!d&&!r&&!i&&!c)throw new m("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!f.dangerouslyAllowBrowser&&Ts())throw new m(`It looks like you're running in a browser-like environment.
|
|
9
9
|
|
|
10
10
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
11
11
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -14,5 +14,5 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
14
14
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
15
15
|
|
|
16
16
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
17
|
-
`);this.baseURL=
|
|
18
|
-
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}p.defaultHeaders=P([e,p.defaultHeaders])}this._options=p,this._provider=d,l&&(this._workloadIdentityAuth=new Nt(l,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=i,this.organization=a,this.project=o,this.webhookSecret=c}withOptions(e){let t=this._options.provider,n=e.provider??t,r={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.baseURL,n!==t&&(delete r.organization,delete r.project,delete r.defaultHeaders)),new this.constructor({...r,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}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 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 P([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return P([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return P([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return P([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ct(e)}getUserAgent(){return`${this.constructor.name}/JS ${Xe}`}defaultIdempotencyKey(){return`stainless-node-retry-${l()}`}makeStatusError(e,t,n,r){let i=t&&typeof t==`object`&&t.error==null?{error:t}:t;return p.generate(e,i,n,r)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof f?e:new f(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new f(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!c(this,vs,`m`,Ss).call(this)&&n||this.baseURL,i=le(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!fe(a)||!fe(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return this.responsePromise(this.makeRequest(e,t,void 0))}responsePromise(e,t=(e,t)=>this.parseResponseWithTimeout(e,t)){let n=new Tt(this,e,t);return n.withResponse=async()=>{let t=await n,{response:r}=await e;return{data:t,response:r,request_id:r.headers.get(`x-request-id`)}},n._thenUnwrap=n=>this.responsePromise(e,async(e,r)=>Ye(n(await t(e,r),r),r.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 qe(e,t);for(;;){let n=c(this,xs,`f`).get(t.controller),r=n?.timeout??t.options.timeout??this.timeout,i=Math.max(0,t.startTime+r-Date.now()),a=t.options.signal,o,s,l=!1;try{if(a?.aborted&&t.options.__metadata?.helperMethod!==`runTools`)throw new m;let n=new Promise((e,n)=>{o=setTimeout(()=>{l=!0,t.controller.abort(),n(new g)},i),a&&(s=()=>n(new m),a.addEventListener(`abort`,s,{once:!0}))});return await Promise.race([qe(e,t),n])}catch(e){if(a?.aborted)throw new m;if(!l)throw e;let r=n?.retriesRemaining??0;if(!r||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 g;o!==void 0&&clearTimeout(o),s&&a?.removeEventListener(`abort`,s),s=void 0;let i=await this.retryRequest(t.options,r,t.retryOfRequestLogID??t.requestLogID);Object.assign(t,i)}finally{o!==void 0&&clearTimeout(o),s&&a?.removeEventListener(`abort`,s)}}}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t}),l=r.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let f=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),p=n===void 0?``:`, retryOf: ${n}`,m=Date.now();if(k(this).debug(`[${f}] sending request`,ze({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted||a.signal?.aborted)throw this._makeUserAbortError(r.signal?.aborted?r.signal:a.signal);let _=r.__security??{bearerAuth:!0},v=this.fetchWithTimeout===ys.prototype.fetchWithTimeout?Es(a.signal):new AbortController,y=await this.fetchWithAuth(o,a,s,v,_).catch(d),b=Date.now();if(y instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted||a.signal?.aborted)throw this._makeUserAbortError(r.signal?.aborted?r.signal:a.signal);let i=u(y)||/timed? ?out/i.test(String(y)+(`cause`in y?String(y.cause):``));if(t&&!l)return k(this).info(`[${f}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${f}] connection ${i?`timed out`:`failed`} (${e})`,ze({retryOfRequestLogID:n,url:o,durationMs:b-m,message:y.message})),this.retryRequest(r,t,n??f);let s=l?`error; streaming body cannot be retried`:`error; no more retries left`;if(k(this).info(`[${f}] connection ${i?`timed out`:`failed`} - ${s}`),k(this).debug(`[${f}] connection ${i?`timed out`:`failed`} (${s})`,ze({retryOfRequestLogID:n,url:o,durationMs:b-m,message:y.message})),y instanceof oe||y instanceof se)throw y;if(i){let e=`cause`in y?y.cause:void 0,t=typeof e==`object`&&e&&`code`in e&&e.code===`UND_ERR_HEADERS_TIMEOUT`?new g({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 g;throw Object.assign(t,{cause:y})}throw new h({message:Ds(y),cause:y})}let x=`[${f}${p}${[...y.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${y.ok?`succeeded`:`failed`} with status ${y.status} in ${b-m}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await xe(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??f);let e=await this.shouldRetry(y);if(t&&e&&!l){let e=`retrying, ${t} attempts remaining`;return await xe(y.body),k(this).info(`${x} - ${e}`),k(this).debug(`[${f}] response error (${e})`,ze({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-m})),this.retryRequest(r,t,n??f,y.headers)}let i=e?l?`error; streaming body cannot be retried`:`error; no more retries left`:`error; not retryable`;k(this).info(`${x} - ${i}`);let a=await y.text().catch(e=>d(e).message),o=he(a),s=o?void 0:a;throw k(this).debug(`[${f}] response error (${i})`,ze({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:s,durationMs:Date.now()-m})),this.makeStatusError(y.status,o,s,y.headers)}return k(this).info(x),k(this).debug(`[${f}] response start`,ze({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-m})),c(this,xs,`f`).set(v,{timeout:s,retriesRemaining:t}),{response:y,options:r,controller:v,requestLogID:f,retryOfRequestLogID:n,startTime:m}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0),r=new Ot(this,n,e),i=this.responsePromise(n,async(t,n)=>{let r=await this.parseResponseWithTimeout(t,n);return new e(t,n.response,r,n.options)});return r.then=i.then.bind(i),r.catch=i.catch.bind(i),r.finally=i.finally.bind(i),r.withResponse=i.withResponse.bind(i),r._thenUnwrap=i._thenUnwrap.bind(i),r}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${ws}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r),c=!!i&&Ts.get(r)===i;i&&!c&&i.addEventListener(`abort`,s,{once:!0});let l=setTimeout(s,n),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:r.signal,...u?{duplex:`half`}:{},method:`GET`,...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}catch(e){throw i&&!c&&i.removeEventListener(`abort`,s),e}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&i===void 0){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0||!Number.isFinite(i)||i<0||i>6e4){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ge(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&me(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=e.__metadata?.helperMethod,o=P([i,{Accept:`application/json`,...Cs()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...it(),...typeof a==`string`?{"X-Stainless-Helper-Method":a}:{},"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(o,e.__security??{bearerAuth:!0}),o.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new m;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?{...c(this,bs,`f`).call(this,{body:t,headers:P([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=P([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,a=!i&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:ye(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,bs,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};ys=$,bs=new WeakMap,xs=new WeakMap,vs=new WeakSet,Ss=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=ys,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=f,$.APIError=p,$.APIConnectionError=h,$.APIConnectionTimeoutError=g,$.APIUserAbortError=m,$.NotFoundError=b,$.ConflictError=x,$.RateLimitError=te,$.BadRequestError=_,$.AuthenticationError=v,$.InternalServerError=ne,$.PermissionDeniedError=y,$.UnprocessableEntityError=ee,$.InvalidWebhookSignatureError=ae,$.toFile=vn,$.toStreamingFile=Rt,$.Completions=Oa,$.Chat=Hr,$.Embeddings=Fa,$.Files=za,$.Images=Xa,$.ContentProvenanceChecks=Ma,$.Audio=Si,$.Moderations=Qa,$.Models=Za,$.FineTuning=qa,$.Graders=Ya,$.VectorStores=ss,$.Webhooks=fs,$.Beta=Da,$.Batches=Ci,$.Uploads=rs,$.Admin=vi,$.Responses=Zo,$.Realtime=to,$.Conversations=Pa,$.Evals=Ra,$.Containers=ja,$.Skills=ts,$.Videos=cs;var Ts=new WeakMap;function Es(e){let t=new AbortController;if(!e)return t;let n=globalThis.AbortSignal;if(typeof n?.any!=`function`||!(e instanceof n))return t;try{let r=n.any([t.signal,e]);Object.defineProperty(t,"signal",{value:r,configurable:!0}),Ts.set(t,e)}catch{}return t}function Ds(e){if(Os(e))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 Os(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var ks=class extends ${constructor({baseURL:e=G(`OPENAI_BASE_URL`),apiKey:t=G(`AZURE_OPENAI_API_KEY`),apiVersion:n=G(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new f(`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 a==`function`&&(o??=!0),!a&&!t)throw new f("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new f("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(s.defaultQuery={...s.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new f("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let t=r.length;for(;t>0&&r[t-1]===`/`;)t--;e=`${r.slice(0,t)}/openai`}else if(r)throw new f(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...s,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(As.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!C(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=L`/deployments/${t}`+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,r,i){return new Headers(t.headers).has(`api-key`)&&(t.redirect=`manual`),super.fetchWithAuth(e,t,n,r,i)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?P([{"api-key":this.apiKey}]):super.authHeaders(e,n)}},As=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]),js=`azure-openai`,Ms=`2024-12-01-preview`,Ns={id:js,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:Ms,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let e=r(js);if(!e)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:t.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function Ps(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Fs(e,t){let n=o(e.messages,t,Ps),r=[];for(let e of n)if(e.role===`user`){if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function Is(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Ls(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function Rs(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}function zs(e){return{role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:js,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()}}function Bs(e,t){let n=t.apiKey;if(!n)throw Error(`Azure API key is required`);let r=e.baseUrl;if(!r)throw Error(`Azure endpoint is required`);let a={};e.headers&&Object.assign(a,e.headers),t.headers&&Object.assign(a,t.headers);let o=i(js)||Ms,s=e.id;return{client:new ks({endpoint:r.replace(/\/+$/,``),apiKey:n,deployment:s,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:a}),deployment:s}}function Vs(e,t){return[...e.systemPrompt?[{role:`system`,content:e.systemPrompt}]:[],...Fs(e,t)]}function Hs(e,n,r){r&&(e.usage.input=r.prompt_tokens??0,e.usage.output=r.completion_tokens??0,e.usage.totalTokens=r.total_tokens??0,t(n,e.usage))}function Us(e){return e===`tool_calls`?`toolUse`:e===`length`?`length`:`stop`}function Ws(e,t,n){let{block:r,index:i}=Ls(t);r.text===``&&e.push({type:`text_start`,contentIndex:i,partial:t}),r.text+=n,e.push({type:`text_delta`,contentIndex:i,delta:n,partial:t})}function Gs(e,t,n){let r=n.id?Rs(t,n.id):void 0;if(r||!n.id)return r;let i={type:`toolCall`,id:n.id,name:n.function?.name??``,arguments:{},_partialJson:``};return t.content.push(i),e.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}),i}function Ks(e,t,n,r){n._partialJson+=r;try{n.arguments=JSON.parse(n._partialJson)}catch{}e.push({type:`toolcall_delta`,contentIndex:t.content.indexOf(n),delta:r,partial:t})}function qs(e,t,n){for(let r of n){let n=Gs(e,t,r);n&&r.function?.arguments&&Ks(e,t,n,r.function.arguments)}}function Js(e,t,n){let r=n.delta;r&&(r.content&&Ws(e,t,r.content),r.tool_calls&&qs(e,t,r.tool_calls),n.finish_reason&&(t.stopReason=Us(n.finish_reason)))}function Ys(e,t,n,r){try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,e.push({type:`toolcall_end`,contentIndex:r,toolCall:n,partial:t})}function Xs(e,t){for(let n=0;n<t.content.length;n+=1){let r=t.content[n];r.type===`toolCall`?Ys(e,t,r,n):r.type===`text`&&e.push({type:`text_end`,contentIndex:n,content:r.text,partial:t})}}async function Zs(e,t,n,r,i){let{client:a,deployment:o}=Bs(n,i),s=Is(r.tools),c=await a.chat.completions.create({model:o,messages:Vs(r,n),stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...s?{tools:s}:{}});e.push({type:`start`,partial:t});for await(let r of c){Hs(t,n,r.usage);for(let n of r.choices??[])Js(e,t,n)}Xs(e,t),e.push({type:`done`,reason:t.stopReason,message:t}),e.end()}function Qs(e,t,n,r){t.stopReason=r?`aborted`:`error`,t.errorMessage=n instanceof Error?n.message:JSON.stringify(n),e.push({type:`error`,reason:t.stopReason,error:t}),e.end()}var $s=(t,n,r={})=>{let i=e(),a=zs(t);return Zs(i,a,t,n,r).catch(e=>{Qs(i,a,e,!!r.signal?.aborted)}),i},ec=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return $s(e,t,{...a(e,n,r)})};function tc(){n({api:`azure-openai-anthropic`,stream:$s,streamSimple:ec})}export{Ns as config,tc as register};
|
|
17
|
+
`);this.baseURL=f.baseURL,this.timeout=f.timeout??xs.DEFAULT_TIMEOUT,this.logger=f.logger??console;let p=`warn`;this.logLevel=p,this.logLevel=Ie(f.logLevel,`ClientOptions.logLevel`,this)??Ie(G(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??p,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??ye(),l(this,Ss,st,`f`);let h=t?void 0:G(`OPENAI_CUSTOM_HEADERS`);if(h){let e={};for(let t of h.split(`
|
|
18
|
+
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}f.defaultHeaders=P([e,f.defaultHeaders])}this._options=f,this._provider=d,c&&(this._workloadIdentityAuth=new Ft(c,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=i,this.organization=a,this.project=o,this.webhookSecret=s}withOptions(e){let t=this._options.provider,n=e.provider??t,r={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.baseURL,n!==t&&(delete r.organization,delete r.project,delete r.defaultHeaders)),new this.constructor({...r,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}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 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 P([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return P([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return P([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return P([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Tt(e)}getUserAgent(){return`${this.constructor.name}/JS ${Qe}`}defaultIdempotencyKey(){return`stainless-node-retry-${d()}`}makeStatusError(e,t,n,r){let i=t&&typeof t==`object`&&t.error==null?{error:t}:t;return h.generate(e,i,n,r)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof m?e:new m(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!u(this,bs,`m`,ws).call(this)&&n||this.baseURL,i=de(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!me(a)||!me(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return this.responsePromise(this.makeRequest(e,t,void 0))}responsePromise(e,t=(e,t)=>this.parseResponseWithTimeout(e,t)){let n=new Dt(this,e,t);return n.withResponse=async()=>{let t=await n,{response:r}=await e;return{data:t,response:r,request_id:r.headers.get(`x-request-id`)}},n._thenUnwrap=n=>this.responsePromise(e,async(e,r)=>Ze(n(await t(e,r),r),r.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 Ye(e,t);for(;;){let n=u(this,Cs,`f`).get(t.controller),r=n?.timeout??t.options.timeout??this.timeout,i=Math.max(0,t.startTime+r-Date.now()),a=t.options.signal,o,s,c=!1;try{if(a?.aborted&&t.options.__metadata?.helperMethod!==`runTools`)throw new g;let n=new Promise((e,n)=>{o=setTimeout(()=>{c=!0,t.controller.abort(),n(new v)},i),a&&(s=()=>n(new g),a.addEventListener(`abort`,s,{once:!0}))});return await Promise.race([Ye(e,t),n])}catch(e){if(a?.aborted)throw new g;if(!c)throw e;let r=n?.retriesRemaining??0;if(!r||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 v;o!==void 0&&clearTimeout(o),s&&a?.removeEventListener(`abort`,s),s=void 0;let i=await this.retryRequest(t.options,r,t.retryOfRequestLogID??t.requestLogID);Object.assign(t,i)}finally{o!==void 0&&clearTimeout(o),s&&a?.removeEventListener(`abort`,s)}}}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t}),c=r.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let l=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),d=n===void 0?``:`, retryOf: ${n}`,m=Date.now();if(k(this).debug(`[${l}] sending request`,Ve({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted||a.signal?.aborted)throw this._makeUserAbortError(r.signal?.aborted?r.signal:a.signal);let h=r.__security??{bearerAuth:!0},g=this.fetchWithTimeout===xs.prototype.fetchWithTimeout?Os(a.signal):new AbortController,y=await this.fetchWithAuth(o,a,s,g,h).catch(p),b=Date.now();if(y instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted||a.signal?.aborted)throw this._makeUserAbortError(r.signal?.aborted?r.signal:a.signal);let i=f(y)||/timed? ?out/i.test(String(y)+(`cause`in y?String(y.cause):``));if(t&&!c)return k(this).info(`[${l}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${l}] connection ${i?`timed out`:`failed`} (${e})`,Ve({retryOfRequestLogID:n,url:o,durationMs:b-m,message:y.message})),this.retryRequest(r,t,n??l);let s=c?`error; streaming body cannot be retried`:`error; no more retries left`;if(k(this).info(`[${l}] connection ${i?`timed out`:`failed`} - ${s}`),k(this).debug(`[${l}] connection ${i?`timed out`:`failed`} (${s})`,Ve({retryOfRequestLogID:n,url:o,durationMs:b-m,message:y.message})),y instanceof ce||y instanceof le)throw y;if(i){let e=`cause`in y?y.cause:void 0,t=typeof e==`object`&&e&&`code`in e&&e.code===`UND_ERR_HEADERS_TIMEOUT`?new v({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 v;throw Object.assign(t,{cause:y})}throw new _({message:ks(y),cause:y})}let x=`[${l}${d}${[...y.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${y.ok?`succeeded`:`failed`} with status ${y.status} in ${b-m}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&h.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await Ce(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??l);let e=await this.shouldRetry(y);if(t&&e&&!c){let e=`retrying, ${t} attempts remaining`;return await Ce(y.body),k(this).info(`${x} - ${e}`),k(this).debug(`[${l}] response error (${e})`,Ve({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-m})),this.retryRequest(r,t,n??l,y.headers)}let i=e?c?`error; streaming body cannot be retried`:`error; no more retries left`:`error; not retryable`;k(this).info(`${x} - ${i}`);let a=await y.text().catch(e=>p(e).message),o=_e(a),s=o?void 0:a;throw k(this).debug(`[${l}] response error (${i})`,Ve({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:s,durationMs:Date.now()-m})),this.makeStatusError(y.status,o,s,y.headers)}return k(this).info(x),k(this).debug(`[${l}] response start`,Ve({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-m})),u(this,Cs,`f`).set(g,{timeout:s,retriesRemaining:t}),{response:y,options:r,controller:g,requestLogID:l,retryOfRequestLogID:n,startTime:m}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0),r=new At(this,n,e),i=this.responsePromise(n,async(t,n)=>{let r=await this.parseResponseWithTimeout(t,n);return new e(t,n.response,r,n.options)});return r.then=i.then.bind(i),r.catch=i.catch.bind(i),r.finally=i.finally.bind(i),r.withResponse=i.withResponse.bind(i),r._thenUnwrap=i._thenUnwrap.bind(i),r}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${Es}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r),c=!!i&&Ds.get(r)===i;i&&!c&&i.addEventListener(`abort`,s,{once:!0});let l=setTimeout(s,n),u=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:r.signal,...u?{duplex:`half`}:{},method:`GET`,...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}catch(e){throw i&&!c&&i.removeEventListener(`abort`,s),e}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&i===void 0){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0||!Number.isFinite(i)||i<0||i>6e4){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await ve(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&ge(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=e.__metadata?.helperMethod,o=P([i,{Accept:`application/json`,...Ts()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ot(),...typeof a==`string`?{"X-Stainless-Helper-Method":a}:{},"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(o,e.__security??{bearerAuth:!0}),o.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new g;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?{...u(this,Ss,`f`).call(this,{body:t,headers:P([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=P([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,a=!i&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:xe(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...u(this,Ss,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};xs=$,Ss=new WeakMap,Cs=new WeakMap,bs=new WeakSet,ws=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=xs,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=m,$.APIError=h,$.APIConnectionError=_,$.APIConnectionTimeoutError=v,$.APIUserAbortError=g,$.NotFoundError=ee,$.ConflictError=te,$.RateLimitError=re,$.BadRequestError=y,$.AuthenticationError=b,$.InternalServerError=ie,$.PermissionDeniedError=x,$.UnprocessableEntityError=ne,$.InvalidWebhookSignatureError=se,$.toFile=bn,$.toStreamingFile=Bt,$.Completions=Aa,$.Chat=Wr,$.Embeddings=La,$.Files=Va,$.Images=Qa,$.ContentProvenanceChecks=Pa,$.Audio=wi,$.Moderations=eo,$.Models=$a,$.FineTuning=Ya,$.Graders=Za,$.VectorStores=ls,$.Webhooks=ms,$.Beta=ka,$.Batches=Ti,$.Uploads=as,$.Admin=bi,$.Responses=$o,$.Realtime=ro,$.Conversations=Ia,$.Evals=Ba,$.Containers=Na,$.Skills=rs,$.Videos=us;var Ds=new WeakMap;function Os(e){let t=new AbortController;if(!e)return t;let n=globalThis.AbortSignal;if(typeof n?.any!=`function`||!(e instanceof n))return t;try{let r=n.any([t.signal,e]);Object.defineProperty(t,"signal",{value:r,configurable:!0}),Ds.set(t,e)}catch{}return t}function ks(e){if(As(e))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 As(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var js=class extends ${constructor({baseURL:e=G(`OPENAI_BASE_URL`),apiKey:t=G(`AZURE_OPENAI_API_KEY`),apiVersion:n=G(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new m(`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 a==`function`&&(o??=!0),!a&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(s.defaultQuery={...s.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let t=r.length;for(;t>0&&r[t-1]===`/`;)t--;e=`${r.slice(0,t)}/openai`}else if(r)throw new m(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...s,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(Ms.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!C(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=L`/deployments/${t}`+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,r,i){return new Headers(t.headers).has(`api-key`)&&(t.redirect=`manual`),super.fetchWithAuth(e,t,n,r,i)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?P([{"api-key":this.apiKey}]):super.authHeaders(e,n)}},Ms=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]),Ns=`azure-openai`,Ps=`2024-12-01-preview`,Fs={id:Ns,name:`Azure OpenAI`,description:`GPT models via Azure AI Foundry`,requiresApiKey:!0,apiKeyPlaceholder:`Azure API key`,apiKeyEnvVar:`AZURE_OPENAI_API_KEY`,requiresBaseUrl:!0,baseUrlPlaceholder:`https://your-resource.cognitiveservices.azure.com/`,baseUrlDescription:`Azure resource endpoint`,requiresDeployment:!0,deploymentPlaceholder:`gpt-4.1-mini, gpt-4o, o4-mini`,deploymentDescription:`Comma-separated deployment names (from Azure Portal → Deployments)`,requiresApiVersion:!0,apiVersionDefault:Ps,apiVersionDescription:`Azure OpenAI API version`,getModelIds:()=>{let e=r(Ns);if(!e)return[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}];let t=e.split(`,`).map(e=>e.trim()).filter(Boolean);return t.length===0?[{id:`azure-unconfigured`,name:`Azure OpenAI (set deployments in Settings)`}]:t.map(e=>{let t=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4`);return{id:e,name:`${e} (Azure)`,reasoning:t,input:[`text`,`image`]}})}};function Is(e){return e.replace(/[^a-zA-Z0-9_-]/g,`_`).slice(0,64)}function Ls(e,t){let n=o(e.messages,t,Is),r=[];for(let e of n)if(e.role===`user`){if(typeof e.content==`string`)r.push({role:`user`,content:e.content});else{let t=e.content.map(e=>e.type===`text`?{type:`text`,text:e.text??``}:e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:{type:`text`,text:JSON.stringify(e)});r.push({role:`user`,content:t})}}else if(e.role===`assistant`){let t=e.content,n=t.filter(e=>e.type===`text`).map(e=>e.text??``).join(``),i=t.filter(e=>e.type===`toolCall`).map(e=>({id:e.id??``,type:`function`,function:{name:e.name??``,arguments:JSON.stringify(e.arguments??{})}}));i.length?r.push({role:`assistant`,content:n||null,tool_calls:i}):r.push({role:`assistant`,content:n})}else if(e.role===`toolResult`){let t=e.content;r.push({role:`tool`,tool_call_id:e.toolCallId??``,content:t?.map(e=>e.type===`text`?e.text??``:JSON.stringify(e)).join(``)||``})}return r}function Rs(e){if(e?.length)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function zs(e){let t=e.content.find(e=>e.type===`text`);if(t)return{block:t,index:e.content.indexOf(t)};let n={type:`text`,text:``};return e.content.push(n),{block:n,index:e.content.length-1}}function Bs(e,t){return e.content.find(e=>e.type===`toolCall`&&e.id===t)}function Vs(e){return{role:`assistant`,content:[],api:`azure-openai-anthropic`,provider:Ns,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`stop`,timestamp:Date.now()}}function Hs(e,t){let n=t.apiKey;if(!n)throw Error(`Azure API key is required`);let r=e.baseUrl;if(!r)throw Error(`Azure endpoint is required`);let a={};e.headers&&Object.assign(a,e.headers),t.headers&&Object.assign(a,t.headers);let o=i(Ns)||Ps,s=e.id;return{client:new js({endpoint:r.replace(/\/+$/,``),apiKey:n,deployment:s,apiVersion:o,dangerouslyAllowBrowser:!0,defaultHeaders:a}),deployment:s}}function Us(e,t){return[...e.systemPrompt?[{role:`system`,content:e.systemPrompt}]:[],...Ls(e,t)]}function Ws(e,n,r){r&&(e.usage.input=r.prompt_tokens??0,e.usage.output=r.completion_tokens??0,e.usage.totalTokens=r.total_tokens??0,t(n,e.usage))}function Gs(e){return e===`tool_calls`?`toolUse`:e===`length`?`length`:`stop`}function Ks(e,t,n){let{block:r,index:i}=zs(t);r.text===``&&e.push({type:`text_start`,contentIndex:i,partial:t}),r.text+=n,e.push({type:`text_delta`,contentIndex:i,delta:n,partial:t})}function qs(e,t,n){let r=n.id?Bs(t,n.id):void 0;if(r||!n.id)return r;let i={type:`toolCall`,id:n.id,name:n.function?.name??``,arguments:{},_partialJson:``};return t.content.push(i),e.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}),i}function Js(e,t,n,r){n._partialJson+=r;try{n.arguments=JSON.parse(n._partialJson)}catch{}e.push({type:`toolcall_delta`,contentIndex:t.content.indexOf(n),delta:r,partial:t})}function Ys(e,t,n){for(let r of n){let n=qs(e,t,r);n&&r.function?.arguments&&Js(e,t,n,r.function.arguments)}}function Xs(e,t,n){let r=n.delta;r&&(r.content&&Ks(e,t,r.content),r.tool_calls&&Ys(e,t,r.tool_calls),n.finish_reason&&(t.stopReason=Gs(n.finish_reason)))}function Zs(e,t,n,r){try{n.arguments=JSON.parse(n._partialJson||`{}`)}catch{}delete n._partialJson,e.push({type:`toolcall_end`,contentIndex:r,toolCall:n,partial:t})}function Qs(e,t){for(let n=0;n<t.content.length;n+=1){let r=t.content[n];r.type===`toolCall`?Zs(e,t,r,n):r.type===`text`&&e.push({type:`text_end`,contentIndex:n,content:r.text,partial:t})}}async function $s(e,t,n,r,i){let{client:a,deployment:o}=Hs(n,i),s=Rs(r.tools),c=await a.chat.completions.create({model:o,messages:Us(r,n),stream:!0,stream_options:{include_usage:!0},...i.maxTokens?{max_completion_tokens:i.maxTokens}:{},...i.temperature===void 0?{}:{temperature:i.temperature},...s?{tools:s}:{}});e.push({type:`start`,partial:t});for await(let r of c){Ws(t,n,r.usage);for(let n of r.choices??[])Xs(e,t,n)}Qs(e,t),e.push({type:`done`,reason:t.stopReason,message:t}),e.end()}function ec(e,t,n,r){t.stopReason=r?`aborted`:`error`,t.errorMessage=n instanceof Error?n.message:JSON.stringify(n),e.push({type:`error`,reason:t.stopReason,error:t}),e.end()}var tc=(t,n,r={})=>{let i=e(),a=Vs(t);return $s(i,a,t,c(n),r).catch(e=>{ec(i,a,e,!!r.signal?.aborted)}),i},nc=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`Azure API key is required`);return tc(e,t,{...a(e,s(t),n,r)})};function rc(){n({api:`azure-openai-anthropic`,stream:tc,streamSimple:nc})}export{Fs as config,rc as register};
|