shadow-claw 1.28.0 → 1.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (194) hide show
  1. package/.well-known/mcp/server-card.json +1 -1
  2. package/.well-known/mcp.json +1 -1
  3. package/README.md +96 -278
  4. package/bin/cli.mjs +4 -0
  5. package/bin/commands/mcp.mjs +409 -125
  6. package/bin/commands/mcp.test.mjs +151 -18
  7. package/bin/utils/control-client.mjs +338 -103
  8. package/bin/utils/control-client.test.mjs +14 -0
  9. package/dist/electron/main.cjs +179 -179
  10. package/dist/lib/components/index.js +21 -21
  11. package/dist/lib/components/settings/shadow-claw-channel-config.js +1 -1
  12. package/dist/lib/components/settings/shadow-claw-control-plane.js +1 -1
  13. package/dist/lib/components/settings/shadow-claw-git.js +1 -1
  14. package/dist/lib/components/settings/shadow-claw-llm.js +1 -1
  15. package/dist/lib/components/settings/shadow-claw-networking.js +1 -1
  16. package/dist/lib/components/settings/shadow-claw-notifications.js +1 -1
  17. package/dist/lib/components/settings/shadow-claw-peerjs.js +1 -1
  18. package/dist/lib/components/settings/shadow-claw-storage.js +1 -1
  19. package/dist/lib/components/settings/shadow-claw-task-server.js +1 -1
  20. package/dist/lib/components/settings/shadow-claw-webvm.js +1 -1
  21. package/dist/lib/components/shadow-claw-channel-config.js +1 -1
  22. package/dist/lib/components/shadow-claw-channels.js +1 -1
  23. package/dist/lib/components/shadow-claw-chat.js +1 -1
  24. package/dist/lib/components/shadow-claw-control-plane.js +1 -1
  25. package/dist/lib/components/shadow-claw-conversations.js +1 -1
  26. package/dist/lib/components/shadow-claw-file-viewer.js +1 -1
  27. package/dist/lib/components/shadow-claw-files.js +1 -1
  28. package/dist/lib/components/shadow-claw-git.js +1 -1
  29. package/dist/lib/components/shadow-claw-llm.js +1 -1
  30. package/dist/lib/components/shadow-claw-networking.js +1 -1
  31. package/dist/lib/components/shadow-claw-notifications.js +1 -1
  32. package/dist/lib/components/shadow-claw-pages.js +1 -1
  33. package/dist/lib/components/shadow-claw-peerjs.js +1 -1
  34. package/dist/lib/components/shadow-claw-settings.js +1 -1
  35. package/dist/lib/components/shadow-claw-storage.js +1 -1
  36. package/dist/lib/components/shadow-claw-task-server.js +1 -1
  37. package/dist/lib/components/shadow-claw-tasks.js +1 -1
  38. package/dist/lib/components/shadow-claw-terminal.js +1 -1
  39. package/dist/lib/components/shadow-claw-tools.js +1 -1
  40. package/dist/lib/components/shadow-claw-webvm.js +1 -1
  41. package/dist/lib/components/shadow-claw.js +1 -1
  42. package/dist/lib/{configurePeerJs-D8Ph0-A9.js → configurePeerJs-DG4hliKp.js} +2 -2
  43. package/dist/lib/{configurePeerJs-D8Ph0-A9.js.map → configurePeerJs-DG4hliKp.js.map} +1 -1
  44. package/dist/lib/index.js +21 -21
  45. package/dist/lib/{initControlPlane-BIrWmpzc.js → initControlPlane-DnpAzphg.js} +8 -8
  46. package/dist/lib/{initControlPlane-BIrWmpzc.js.map → initControlPlane-DnpAzphg.js.map} +1 -1
  47. package/dist/lib/{markdown-DEUoM1c6.js → markdown-DgdSt2GD.js} +2 -2
  48. package/dist/lib/{markdown-DEUoM1c6.js.map → markdown-DgdSt2GD.js.map} +1 -1
  49. package/dist/lib/{orchestrator-CFCW-l1O.js → orchestrator-CjEau_RG.js} +5 -5
  50. package/dist/lib/{orchestrator-CFCW-l1O.js.map → orchestrator-CjEau_RG.js.map} +1 -1
  51. package/dist/lib/{orchestrator-BtVj9bBB.js → orchestrator-ClXbJ4Mb.js} +2 -2
  52. package/dist/lib/{orchestrator-BtVj9bBB.js.map → orchestrator-ClXbJ4Mb.js.map} +1 -1
  53. package/dist/lib/{peerjs-BoBkx9DJ.js → peerjs-BdfpltIe.js} +3 -3
  54. package/dist/lib/{peerjs-BoBkx9DJ.js.map → peerjs-BdfpltIe.js.map} +1 -1
  55. package/dist/lib/{push-client-D6hbzDNV.js → push-client-DjwKknNg.js} +9 -3
  56. package/dist/lib/push-client-DjwKknNg.js.map +1 -0
  57. package/dist/lib/{shadow-claw-Cuf2O5bZ.js → shadow-claw-DcPGKenn.js} +4 -4
  58. package/dist/lib/{shadow-claw-Cuf2O5bZ.js.map → shadow-claw-DcPGKenn.js.map} +1 -1
  59. package/dist/lib/{shadow-claw-channel-config-BDPKt6Bd.js → shadow-claw-channel-config-DEL-aZ7N.js} +3 -3
  60. package/dist/lib/{shadow-claw-channel-config-BDPKt6Bd.js.map → shadow-claw-channel-config-DEL-aZ7N.js.map} +1 -1
  61. package/dist/lib/{shadow-claw-channels-BsP5JABM.js → shadow-claw-channels-BgaJiPdE.js} +2 -2
  62. package/dist/lib/{shadow-claw-channels-BsP5JABM.js.map → shadow-claw-channels-BgaJiPdE.js.map} +1 -1
  63. package/dist/lib/{shadow-claw-chat-Cam2lX4k.js → shadow-claw-chat-mXPQZbwT.js} +4 -4
  64. package/dist/lib/{shadow-claw-chat-Cam2lX4k.js.map → shadow-claw-chat-mXPQZbwT.js.map} +1 -1
  65. package/dist/lib/{shadow-claw-control-plane-DB2qcCFs.js → shadow-claw-control-plane-DO6foOLV.js} +6 -6
  66. package/dist/lib/{shadow-claw-control-plane-DB2qcCFs.js.map → shadow-claw-control-plane-DO6foOLV.js.map} +1 -1
  67. package/dist/lib/{shadow-claw-conversations-C9Vf4XGx.js → shadow-claw-conversations-BLwHTwdW.js} +2 -2
  68. package/dist/lib/{shadow-claw-conversations-C9Vf4XGx.js.map → shadow-claw-conversations-BLwHTwdW.js.map} +1 -1
  69. package/dist/lib/{shadow-claw-file-viewer-B4HYiI0v.js → shadow-claw-file-viewer-BSbZvSl-.js} +3 -3
  70. package/dist/lib/{shadow-claw-file-viewer-B4HYiI0v.js.map → shadow-claw-file-viewer-BSbZvSl-.js.map} +1 -1
  71. package/dist/lib/{shadow-claw-files-DVROUESO.js → shadow-claw-files-BLVr9Pua.js} +2 -2
  72. package/dist/lib/{shadow-claw-files-DVROUESO.js.map → shadow-claw-files-BLVr9Pua.js.map} +1 -1
  73. package/dist/lib/{shadow-claw-git-BqrO7cHJ.js → shadow-claw-git-CHC1H86J.js} +3 -3
  74. package/dist/lib/{shadow-claw-git-BqrO7cHJ.js.map → shadow-claw-git-CHC1H86J.js.map} +1 -1
  75. package/dist/lib/{shadow-claw-llm-BexUQdYo.js → shadow-claw-llm-CKXfxd3D.js} +2 -2
  76. package/dist/lib/{shadow-claw-llm-BexUQdYo.js.map → shadow-claw-llm-CKXfxd3D.js.map} +1 -1
  77. package/dist/lib/{shadow-claw-networking-CfXRGpUD.js → shadow-claw-networking-dpYvfchh.js} +2 -2
  78. package/dist/lib/{shadow-claw-networking-CfXRGpUD.js.map → shadow-claw-networking-dpYvfchh.js.map} +1 -1
  79. package/dist/lib/{shadow-claw-notifications-C9KPMgx_.js → shadow-claw-notifications-_YeAVPga.js} +2 -2
  80. package/dist/lib/{shadow-claw-notifications-C9KPMgx_.js.map → shadow-claw-notifications-_YeAVPga.js.map} +1 -1
  81. package/dist/lib/{shadow-claw-pages-CGzGXmrI.js → shadow-claw-pages-DVzZriZ7.js} +3 -3
  82. package/dist/lib/{shadow-claw-pages-CGzGXmrI.js.map → shadow-claw-pages-DVzZriZ7.js.map} +1 -1
  83. package/dist/lib/{shadow-claw-peerjs-B0ZB7yhB.js → shadow-claw-peerjs-BvixjeBz.js} +3 -3
  84. package/dist/lib/{shadow-claw-peerjs-B0ZB7yhB.js.map → shadow-claw-peerjs-BvixjeBz.js.map} +1 -1
  85. package/dist/lib/{shadow-claw-settings-DBfMZdDS.js → shadow-claw-settings-DV9-gD4Q.js} +2 -2
  86. package/dist/lib/{shadow-claw-settings-DBfMZdDS.js.map → shadow-claw-settings-DV9-gD4Q.js.map} +1 -1
  87. package/dist/lib/{shadow-claw-storage-CM-w6mgG.js → shadow-claw-storage-Bv__kXG6.js} +2 -2
  88. package/dist/lib/{shadow-claw-storage-CM-w6mgG.js.map → shadow-claw-storage-Bv__kXG6.js.map} +1 -1
  89. package/dist/lib/{shadow-claw-task-server-DV4b1g2-.js → shadow-claw-task-server-DNOe8PWK.js} +2 -2
  90. package/dist/lib/{shadow-claw-task-server-DV4b1g2-.js.map → shadow-claw-task-server-DNOe8PWK.js.map} +1 -1
  91. package/dist/lib/{shadow-claw-tasks-K-foOHSE.js → shadow-claw-tasks-qmcDT4PU.js} +3 -3
  92. package/dist/lib/{shadow-claw-tasks-K-foOHSE.js.map → shadow-claw-tasks-qmcDT4PU.js.map} +1 -1
  93. package/dist/lib/{shadow-claw-terminal-CpAknKyA.js → shadow-claw-terminal-0QUWP8of.js} +2 -2
  94. package/dist/lib/{shadow-claw-terminal-CpAknKyA.js.map → shadow-claw-terminal-0QUWP8of.js.map} +1 -1
  95. package/dist/lib/{shadow-claw-tools-D98XZ0Ep.js → shadow-claw-tools-Bs_bmI6-.js} +3 -3
  96. package/dist/lib/{shadow-claw-tools-D98XZ0Ep.js.map → shadow-claw-tools-Bs_bmI6-.js.map} +1 -1
  97. package/dist/lib/{shadow-claw-webvm-DLOb8dMI.js → shadow-claw-webvm-DYaoL7QY.js} +2 -2
  98. package/dist/lib/{shadow-claw-webvm-DLOb8dMI.js.map → shadow-claw-webvm-DYaoL7QY.js.map} +1 -1
  99. package/dist/lib/{syncWebMcpRegistration-NspKefOI.js → syncWebMcpRegistration-BhbqI6R2.js} +2 -2
  100. package/dist/lib/{syncWebMcpRegistration-NspKefOI.js.map → syncWebMcpRegistration-BhbqI6R2.js.map} +1 -1
  101. package/dist/public/.well-known/mcp/server-card.json +1 -1
  102. package/dist/public/.well-known/mcp.json +1 -1
  103. package/dist/public/AGENTS.md +22 -3
  104. package/dist/public/README.md +96 -278
  105. package/dist/public/agent.worker.js +50 -50
  106. package/dist/public/{base-task-model-CYkpwnvU-DDfHUUIS.js → base-task-model-CYkpwnvU-DrXr4G1R.js} +1 -1
  107. package/dist/public/{configurePeerJs-BhBokQlC.js → configurePeerJs-B470pdeU.js} +1 -1
  108. package/dist/public/docs/README.md +31 -31
  109. package/dist/public/docs/architecture/context-management.md +7 -0
  110. package/dist/public/docs/architecture/storage.md +10 -1
  111. package/dist/public/docs/decisions/bundled-typescript-architecture.md +0 -1
  112. package/dist/public/docs/decisions/native-web-components-and-signals.md +0 -1
  113. package/dist/public/docs/example/article/index.html +1 -1
  114. package/dist/public/docs/guides/publishing-to-github-pages.md +334 -0
  115. package/dist/public/docs/guides/server-development-configuration.md +15 -0
  116. package/dist/public/docs/publishing/index.html +1 -1
  117. package/dist/public/docs/skill-creator/index.html +1 -1
  118. package/dist/public/docs/subsystems/cli.md +10 -2
  119. package/dist/public/docs/subsystems/control-plane.md +9 -8
  120. package/dist/public/docs/subsystems/crypto.md +9 -0
  121. package/dist/public/docs/subsystems/custom-element-security.md +2 -0
  122. package/dist/public/docs/subsystems/mcp-server.md +31 -16
  123. package/dist/public/docs/subsystems/notifications.md +8 -5
  124. package/dist/public/docs/subsystems/providers.md +9 -0
  125. package/dist/public/docs/subsystems/share-target.md +107 -0
  126. package/dist/public/docs/subsystems/webmcp.md +43 -0
  127. package/dist/public/e2e/README.md +4 -2
  128. package/dist/public/{e2e-bridge-DcBoeFvd.js → e2e-bridge-CSW0S5Yz.js} +1 -1
  129. package/dist/public/{file-viewer-CKtVC9Ix.js → file-viewer-Cs-riNvy.js} +1 -1
  130. package/dist/public/{firebase-OSDX3viP.js → firebase-cwAl_ABm.js} +1 -1
  131. package/dist/public/{git-CkhCJonj.js → git-GD09WATp.js} +25 -25
  132. package/dist/public/index.html +1 -1
  133. package/dist/public/index.js +1 -1
  134. package/dist/public/{initControlPlane-Bi8ouFEb.js → initControlPlane-BqCY0NQy.js} +1 -1
  135. package/dist/public/initControlPlane-C-IXaKYX.js +1 -0
  136. package/dist/public/{language-detector-BRKrlra0.js → language-detector-CIeEuQFk.js} +1 -1
  137. package/dist/public/llms.txt +4 -2
  138. package/dist/public/main/index.html +1 -1
  139. package/dist/public/main/memory/index.html +1 -1
  140. package/dist/public/{markdown-C-hCVJtc.js → markdown-Cw7vCtTg.js} +1 -1
  141. package/dist/public/{openai-Bpd71Oja.js → openai-BJIb2c5j.js} +3 -3
  142. package/dist/public/{orchestrator-8qNGfw8r.js → orchestrator-BWkHHO9Y.js} +1 -1
  143. package/dist/public/{orchestrator-BT3Ks5ip.js → orchestrator-DpkkeD6T.js} +1 -1
  144. package/dist/public/{peerjs-DfhwEiiq.js → peerjs-tf2EmWjB.js} +1 -1
  145. package/dist/public/{prompt-api-polyfill-Dl1kbJhR.js → prompt-api-polyfill-CXd75leW.js} +1 -1
  146. package/dist/public/{push-client-BVLrE9pK.js → push-client-CHjSbrWs.js} +1 -1
  147. package/dist/public/{rewriter-j6D9LDER.js → rewriter-BEHn9gll.js} +1 -1
  148. package/dist/public/service-worker.js +1 -1
  149. package/dist/public/{shadow-claw-DCjxNDCX.js → shadow-claw-BBPV_9X8.js} +2 -2
  150. package/dist/public/{shadow-claw-channels-CITDrqMl.js → shadow-claw-channels-BJvrKQjg.js} +1 -1
  151. package/dist/public/{shadow-claw-chat-BQrSgSKF.js → shadow-claw-chat-BG2EaRaw.js} +1 -1
  152. package/dist/public/{shadow-claw-control-plane-Cp001OY0.js → shadow-claw-control-plane-BBa7WbTg.js} +2 -2
  153. package/dist/public/{shadow-claw-conversations-EhX4RvIj.js → shadow-claw-conversations-CFaWFmkm.js} +1 -1
  154. package/dist/public/{shadow-claw-file-viewer-DiQXIjZD.js → shadow-claw-file-viewer-Z-GIKaE9.js} +1 -1
  155. package/dist/public/{shadow-claw-files-lkTnSJsn.js → shadow-claw-files-BBx4iMsk.js} +1 -1
  156. package/dist/public/{shadow-claw-git-BlcA_z8x.js → shadow-claw-git-vTOKatwd.js} +2 -2
  157. package/dist/public/{shadow-claw-llm-CW16X9Rg.js → shadow-claw-llm-Ce1Ax6-x.js} +1 -1
  158. package/dist/public/{shadow-claw-networking-ySsMBY_i.js → shadow-claw-networking-q4XIzdB5.js} +1 -1
  159. package/dist/public/{shadow-claw-notifications-CyV2zCQ8.js → shadow-claw-notifications-D2cz0gmm.js} +1 -1
  160. package/dist/public/{shadow-claw-pages-Cx7cF9ah.js → shadow-claw-pages-3335lmSC.js} +1 -1
  161. package/dist/public/{shadow-claw-settings-zm4PHHGi.js → shadow-claw-settings-4ptYuJwO.js} +2 -2
  162. package/dist/public/{shadow-claw-storage-dy9JAEGd.js → shadow-claw-storage-bIrPKFhF.js} +1 -1
  163. package/dist/public/{shadow-claw-task-server-Bleww48s.js → shadow-claw-task-server-5yqVBxy1.js} +1 -1
  164. package/dist/public/{shadow-claw-tasks-CTI5oaLN.js → shadow-claw-tasks-DcqYHPLZ.js} +1 -1
  165. package/dist/public/{shadow-claw-terminal-mZ3i4HaQ.js → shadow-claw-terminal-fARaDONr.js} +1 -1
  166. package/dist/public/{shadow-claw-tools-B_nuk8Zl.js → shadow-claw-tools-paEAhcJr.js} +1 -1
  167. package/dist/public/{shadow-claw-webvm-Vl_jH5YL.js → shadow-claw-webvm-CbzH_vyX.js} +1 -1
  168. package/dist/public/{summarizer-VJNr-7xG.js → summarizer-BT3AuFed.js} +1 -1
  169. package/dist/public/{syncWebMcpRegistration-n2vAMJ4w.js → syncWebMcpRegistration-CWSYaHex.js} +1 -1
  170. package/dist/public/{transformers-BhQMWQG5.js → transformers-1VTxqKjT.js} +1 -1
  171. package/dist/public/{translator-DEQXb7ZL.js → translator-B50RYlFt.js} +1 -1
  172. package/dist/public/{webllm-CHN5H-Sy.js → webllm-FmyJWWpt.js} +1 -1
  173. package/dist/public/{writer-CD9oN2pq.js → writer-Bhb4YYRE.js} +1 -1
  174. package/dist/server.js +205 -203
  175. package/package.json +1 -1
  176. package/src/components/settings/shadow-claw-llm/shadow-claw-llm.test.ts +2 -0
  177. package/src/core/orchestrator/utils/configurePeerJs.test.ts +2 -0
  178. package/src/server/client-registry.test.ts +9 -0
  179. package/src/server/client-registry.ts +14 -0
  180. package/src/server/mcp/mcp-integration.test.ts +68 -16
  181. package/src/server/mcp/tools/built-in-tools.ts +125 -34
  182. package/src/server/mcp/tools/client-tool-relay.ts +81 -44
  183. package/src/server/mcp/tools/mcp-tools.test.ts +103 -13
  184. package/src/server/mcp/types.ts +3 -0
  185. package/src/server/openapi/paths/push.ts +48 -0
  186. package/src/server/server.ts +30 -0
  187. package/src/subsystems/notifications/push-client.test.ts +17 -0
  188. package/src/subsystems/notifications/push-client.ts +22 -2
  189. package/src/subsystems/notifications/push-routes.test.ts +31 -0
  190. package/src/subsystems/notifications/push-routes.ts +10 -0
  191. package/src/subsystems/notifications/push-store.test.ts +49 -0
  192. package/src/subsystems/notifications/push-store.ts +45 -0
  193. package/src/worker/worker.test.ts +2 -0
  194. package/dist/lib/push-client-D6hbzDNV.js.map +0 -1
@@ -1,11 +1,11 @@
1
- import"./rolldown-runtime-aKtaBQYM.js";import{_ as e,g as t}from"./agent.worker.js";import{n,t as r}from"./defaults-DwNb0lWM-Drx4e34U.js";function i(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 a(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let o=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return o=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 s(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const c=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var l=class extends Error{},u=class e extends l{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 f({message:r,cause:c(n)});let a=n?.error;return t===400?new m(t,a,r,i):t===401?new h(t,a,r,i):t===403?new g(t,a,r,i):t===404?new _(t,a,r,i):t===409?new v(t,a,r,i):t===422?new y(t,a,r,i):t===429?new b(t,a,r,i):t>=500?new x(t,a,r,i):new e(t,a,r,i)}},d=class extends u{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},f=class extends u{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},p=class extends f{constructor({message:e}={}){super({message:e??`Request timed out.`})}},m=class extends u{},h=class extends u{},g=class extends u{},_=class extends u{},v=class extends u{},y=class extends u{},b=class extends u{},x=class extends u{},ee=class extends l{constructor(){super(`Could not parse response content as the length limit was reached`)}},te=class extends l{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},S=class extends Error{constructor(e){super(e)}},ne=class extends u{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}},re=class extends l{constructor(e,t,n){super(e),this.provider=t,this.cause=n}};const ie=/^[a-z][a-z0-9+.-]*:/i,ae=e=>ie.test(e);let C=e=>(C=Array.isArray,C(e)),oe=C;function se(e){return typeof e==`object`?e??{}:{}}function ce(e){if(!e)return!0;for(let t in e)return!1;return!0}function le(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ue(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const de=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new l(`${e} must be an integer`);if(t<0)throw new l(`${e} must be a positive integer`);return t},fe=e=>{try{return JSON.parse(e)}catch{return}},pe=e=>new Promise(t=>setTimeout(t,e)),me=`7.4.0`,he=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function ge(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const _e=()=>{let e=ge();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":me,"X-Stainless-OS":be(Deno.build.os),"X-Stainless-Arch":ye(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":me,"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":me,"X-Stainless-OS":be(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ye(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=ve();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":me,"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":me,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function ve(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const ye=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,be=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let xe;const Se=()=>xe??=_e();function Ce(){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 we(...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 Te(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return we({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ee(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 De(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Oe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),ke=`RFC3986`,Ae=e=>String(e),je={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Ae};let Me=(e,t)=>(Me=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Me(e,t));const w=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Ne=1024,Pe=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Ne){let t=a.length>=Ne?a.slice(e,e+Ne):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=w[r];continue}if(r<2048){n[n.length]=w[192|r>>6]+w[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=w[224|r>>12]+w[128|r>>6&63]+w[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=w[240|r>>18]+w[128|r>>12&63]+w[128|r>>6&63]+w[128|r&63]}o+=n.join(``)}return o};function Fe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Ie(e,t){if(C(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Le={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Re=function(e,t){Array.prototype.push.apply(e,C(t)?t:[t])};let ze;const T={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Pe,encodeValuesOnly:!1,format:ke,formatter:Ae,indices:!1,serializeDate(e){return(ze??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Be(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const Ve={};function He(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(Ve))!==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(Ve)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&C(v)&&(v=Ie(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,T.encoder,g,`key`,p):t;v=``}if(Be(v)||Fe(v)){if(c){let e=h?t:c(t,T.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,T.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&C(v))h&&c&&(v=Ie(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(C(l))te=l;else{let e=Object.keys(v);te=u?e.sort(u):e}let S=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&C(v)&&v.length===1?S+`[]`:S;if(i&&C(v)&&v.length===0)return ne+`[]`;for(let t=0;t<te.length;++t){let y=te[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let S=d&&s?y.replace(/\./g,`%2E`):y,re=C(v)?typeof n==`function`?n(ne,S):ne:ne+(d?`.`+S:`[`+S+`]`);_.set(e,b);let ie=new WeakMap;ie.set(Ve,_),Re(ee,He(x,re,n,r,i,a,o,s,n===`comma`&&h&&C(v)?null:c,l,u,d,f,p,m,h,g,ie))}return ee}function Ue(e=T){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||T.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=ke;if(e.format!==void 0){if(!Me(je,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=je[n],i=T.filter;(typeof e.filter==`function`||C(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Le?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:T.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:T.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:T.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:T.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:T.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?T.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:T.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:T.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:T.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:T.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:T.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:T.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:T.strictNullHandling}}function We(e,t={}){let n=e,r=Ue(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):C(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Le[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||Re(o,He(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Ge(e){return We(e,{arrayFormat:`brackets`})}function Ke(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let qe;function E(e){let t;return(qe??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let Je;function Ye(e){let t;return(Je??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var D,O,Xe=class{constructor(){D.set(this,void 0),O.set(this,void 0),i(this,D,new Uint8Array,`f`),i(this,O,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?E(e):e;i(this,D,Ke([a(this,D,`f`),t]),`f`);let n=[],r;for(;(r=Ze(a(this,D,`f`),a(this,O,`f`)))!=null;){if(r.carriage&&a(this,O,`f`)==null){i(this,O,r.index,`f`);continue}if(a(this,O,`f`)!=null&&(r.index!==a(this,O,`f`)+1||r.carriage)){n.push(Ye(a(this,D,`f`).subarray(0,a(this,O,`f`)-1))),i(this,D,a(this,D,`f`).subarray(a(this,O,`f`)),`f`),i(this,O,null,`f`);continue}let e=a(this,O,`f`)===null?r.preceding:r.preceding-1,t=Ye(a(this,D,`f`).subarray(0,e));n.push(t),i(this,D,a(this,D,`f`).subarray(r.index),`f`),i(this,O,null,`f`)}return n}flush(){return a(this,D,`f`).length?this.decode(`
1
+ import"./rolldown-runtime-aKtaBQYM.js";import{_ as e,v as t}from"./agent.worker.js";import{n,t as r}from"./defaults-DwNb0lWM-Drx4e34U.js";function i(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 a(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let o=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return o=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 s(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const c=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var l=class extends Error{},u=class e extends l{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 f({message:r,cause:c(n)});let a=n?.error;return t===400?new m(t,a,r,i):t===401?new h(t,a,r,i):t===403?new g(t,a,r,i):t===404?new _(t,a,r,i):t===409?new v(t,a,r,i):t===422?new y(t,a,r,i):t===429?new b(t,a,r,i):t>=500?new x(t,a,r,i):new e(t,a,r,i)}},d=class extends u{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},f=class extends u{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},p=class extends f{constructor({message:e}={}){super({message:e??`Request timed out.`})}},m=class extends u{},h=class extends u{},g=class extends u{},_=class extends u{},v=class extends u{},y=class extends u{},b=class extends u{},x=class extends u{},ee=class extends l{constructor(){super(`Could not parse response content as the length limit was reached`)}},te=class extends l{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},S=class extends Error{constructor(e){super(e)}},ne=class extends u{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}},re=class extends l{constructor(e,t,n){super(e),this.provider=t,this.cause=n}};const ie=/^[a-z][a-z0-9+.-]*:/i,ae=e=>ie.test(e);let C=e=>(C=Array.isArray,C(e)),oe=C;function se(e){return typeof e==`object`?e??{}:{}}function ce(e){if(!e)return!0;for(let t in e)return!1;return!0}function le(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function ue(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const de=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new l(`${e} must be an integer`);if(t<0)throw new l(`${e} must be a positive integer`);return t},fe=e=>{try{return JSON.parse(e)}catch{return}},pe=e=>new Promise(t=>setTimeout(t,e)),me=`7.4.0`,he=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function ge(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const _e=()=>{let e=ge();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":me,"X-Stainless-OS":be(Deno.build.os),"X-Stainless-Arch":ye(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":me,"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":me,"X-Stainless-OS":be(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ye(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=ve();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":me,"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":me,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function ve(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const ye=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,be=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let xe;const Se=()=>xe??=_e();function Ce(){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 we(...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 Te(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return we({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function Ee(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 De(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Oe=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),ke=`RFC3986`,Ae=e=>String(e),je={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Ae};let Me=(e,t)=>(Me=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Me(e,t));const w=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Ne=1024,Pe=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=Ne){let t=a.length>=Ne?a.slice(e,e+Ne):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=w[r];continue}if(r<2048){n[n.length]=w[192|r>>6]+w[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=w[224|r>>12]+w[128|r>>6&63]+w[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=w[240|r>>18]+w[128|r>>12&63]+w[128|r>>6&63]+w[128|r&63]}o+=n.join(``)}return o};function Fe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Ie(e,t){if(C(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Le={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Re=function(e,t){Array.prototype.push.apply(e,C(t)?t:[t])};let ze;const T={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Pe,encodeValuesOnly:!1,format:ke,formatter:Ae,indices:!1,serializeDate(e){return(ze??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Be(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const Ve={};function He(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(Ve))!==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(Ve)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&C(v)&&(v=Ie(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,T.encoder,g,`key`,p):t;v=``}if(Be(v)||Fe(v)){if(c){let e=h?t:c(t,T.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,T.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let te;if(n===`comma`&&C(v))h&&c&&(v=Ie(v,c)),te=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(C(l))te=l;else{let e=Object.keys(v);te=u?e.sort(u):e}let S=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&C(v)&&v.length===1?S+`[]`:S;if(i&&C(v)&&v.length===0)return ne+`[]`;for(let t=0;t<te.length;++t){let y=te[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let S=d&&s?y.replace(/\./g,`%2E`):y,re=C(v)?typeof n==`function`?n(ne,S):ne:ne+(d?`.`+S:`[`+S+`]`);_.set(e,b);let ie=new WeakMap;ie.set(Ve,_),Re(ee,He(x,re,n,r,i,a,o,s,n===`comma`&&h&&C(v)?null:c,l,u,d,f,p,m,h,g,ie))}return ee}function Ue(e=T){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||T.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=ke;if(e.format!==void 0){if(!Me(je,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=je[n],i=T.filter;(typeof e.filter==`function`||C(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Le?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:T.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:T.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:T.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:T.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:T.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?T.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:T.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:T.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:T.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:T.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:T.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:T.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:T.strictNullHandling}}function We(e,t={}){let n=e,r=Ue(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):C(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Le[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||Re(o,He(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Ge(e){return We(e,{arrayFormat:`brackets`})}function Ke(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}let qe;function E(e){let t;return(qe??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}let Je;function Ye(e){let t;return(Je??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var D,O,Xe=class{constructor(){D.set(this,void 0),O.set(this,void 0),i(this,D,new Uint8Array,`f`),i(this,O,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?E(e):e;i(this,D,Ke([a(this,D,`f`),t]),`f`);let n=[],r;for(;(r=Ze(a(this,D,`f`),a(this,O,`f`)))!=null;){if(r.carriage&&a(this,O,`f`)==null){i(this,O,r.index,`f`);continue}if(a(this,O,`f`)!=null&&(r.index!==a(this,O,`f`)+1||r.carriage)){n.push(Ye(a(this,D,`f`).subarray(0,a(this,O,`f`)-1))),i(this,D,a(this,D,`f`).subarray(a(this,O,`f`)),`f`),i(this,O,null,`f`);continue}let e=a(this,O,`f`)===null?r.preceding:r.preceding-1,t=Ye(a(this,D,`f`).subarray(0,e));n.push(t),i(this,D,a(this,D,`f`).subarray(r.index),`f`),i(this,O,null,`f`)}return n}flush(){return a(this,D,`f`).length?this.decode(`
2
2
  `):[]}};D=new WeakMap,O=new WeakMap,Xe.NEWLINE_CHARS=new Set([`
3
3
  `,`\r`]),Xe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ze(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Qe(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}const $e={off:0,error:200,warn:300,info:400,debug:500},et=(e,t,n)=>{if(e){if(le($e,e))return e;k(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys($e))}`)}};function tt(){}function nt(e,t,n){return!t||$e[e]>$e[n]?tt:t[e].bind(t)}const rt={error:tt,warn:tt,info:tt,debug:tt};let it=new WeakMap;function k(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return rt;let r=it.get(t);if(r&&r[0]===n)return r[1];let i={error:nt(`error`,t,n),warn:nt(`warn`,t,n),info:nt(`info`,t,n),debug:nt(`debug`,t,n)};return it.set(t,[n,i]),i}const at=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);var ot,st=class e{constructor(e,t,n){this.iterator=e,ot.set(this,void 0),this.controller=t,i(this,ot,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?k(r):console;async function*c(){if(a)throw new l("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of ct(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new u(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new u(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(s(e))return;throw e}finally{e||n.abort()}}return new e(c,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new Xe,r=t.getReader(),i=!1,a,o=()=>{a??=r.cancel(),a.catch(()=>{})};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 l("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||s(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(ot=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,a(this,ot,`f`)),new e(()=>i(n),this.controller,a(this,ot,`f`))]}toReadableStream(){let e=this,t;return we({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=E(JSON.stringify(n)+`
4
4
  `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*ct(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new l(`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 l(`Attempted to iterate over a response with no body`);let n=new ut,r=new Xe,i=Ee(e.body);for await(let e of lt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*lt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?E(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Qe(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var ut=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
5
  `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=dt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function dt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function ft(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):st.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:pt(await n.json(),n):await n.text()})();return k(e).debug(`[${r}] response parsed`,at({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function pt(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 mt,ht=class e extends Promise{constructor(e,t,n=ft){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,mt.set(this,void 0),i(this,mt,e,`f`)}_thenUnwrap(t){return new e(a(this,mt,`f`),this.responsePromise,async(e,n)=>pt(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(a(this,mt,`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)}};mt=new WeakMap;var gt,_t=class{constructor(e,t,n,r){gt.set(this,void 0),i(this,gt,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 l("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,gt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},vt=class extends ht{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await ft(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},yt=class extends _t{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}},A=class extends _t{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:{...se(this.options.query),after:t}}:null}},j=class extends _t{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:{...se(this.options.query),after:e}}:null}},M=class extends _t{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:{...se(this.options.query),after:e}}:null}};const bt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`};var xt=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??Ce()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e={grant_type:`urn:ietf:params:oauth:grant-type:token-exchange`,subject_token:await this.config.provider.getToken(),subject_token_type:bt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(e.client_id=this.config.clientId);let t=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)});if(!t.ok){let e=await t.text(),n;try{n=JSON.parse(e)}catch{}throw t.status===400||t.status===401||t.status===403?new ne(t.status,n,t.headers):u.generate(t.status,n,`Token exchange failed with status ${t.status}`,t.headers)}let n=await t.json();if(typeof n!=`object`||!n||!(`access_token`in n)||typeof n.access_token!=`string`||n.access_token.trim().length===0)throw new l(`Token exchange response missing 'access_token' field`);let r=n.access_token,i=n.expires_in??3600,a=Date.now()+i*1e3;return this.cachedToken={token:r,expiresAt:a},r}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};const St=Symbol(`brand.privateNullableHeaders`),Ct=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*wt(e){if(!e)return;if(St 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():oe(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=oe(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const N=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of wt(r)){if(!Ct.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{[St]:!0,values:t,nulls:n}},Tt=Symbol(`brand.privateStreamingFile`);function Et(e,t,n){if(!t)throw TypeError(`toStreamingFile requires a non-empty file name`);return{[Tt]:!0,data:e,name:t,...n?.type?{type:n.type}:{}}}const Dt=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function Ot(e,t,n){return Dt(),new File(e,t??`unknown_file`,n)}function kt(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const At=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,jt=async(e,t)=>Bt(e.body)?zt(e.body)?Vt(e):{...e,body:await Pt(e.body,t)}:e,P=async(e,t)=>zt(e.body)?Vt(e):{...e,body:await Pt(e.body,t)},Mt=new WeakMap;function Nt(e){let t=typeof e==`function`?e:e.fetch,n=Mt.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 Mt.set(t,r),r}const Pt=async(e,t)=>{if(!await Nt(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>Xt(n,e,t))),n},Ft=e=>e instanceof Blob&&`name`in e,It=e=>typeof e==`object`&&!!e&&`getReader`in e&&typeof e.getReader==`function`,Lt=e=>typeof e==`object`&&!!e&&Tt in e,Rt=e=>typeof e==`object`&&!!e&&(e instanceof Response||At(e)||It(e)||Lt(e)||Ft(e)),zt=e=>{if(Lt(e)||At(e)||It(e))return!0;if(Array.isArray(e))return e.some(zt);if(e&&typeof e==`object`&&!Ft(e)&&!(e instanceof Response)){for(let t in e)if(zt(e[t]))return!0}return!1},Bt=e=>{if(Rt(e))return!0;if(Array.isArray(e))return e.some(Bt);if(e&&typeof e==`object`){for(let t in e)if(Bt(e[t]))return!0}return!1},Vt=e=>{let t=`openai-${Math.random().toString(36).slice(2)}`,n=Te(Ht(e.body,t));return{...e,body:n,headers:N([{"content-type":`multipart/form-data; boundary=${t}`},e.headers])}};async function*Ht(e,t){for await(let{key:n,value:r}of Ut(e)){if(yield E(`--${t}\r\n`),Rt(r)){let e=Gt(r),t=Kt(r);yield E(`Content-Disposition: form-data; name="${Yt(n)}"; filename="${Yt(e)}"\r\nContent-Type: ${t}\r\n\r\n`),yield*Jt(qt(r))}else yield E(`Content-Disposition: form-data; name="${Yt(n)}"\r\n\r\n${String(r)}`);yield E(`\r
6
6
  `)}yield E(`--${t}--\r\n`)}async function*Ut(e){if(!(!e||typeof e!=`object`))for(let[t,n]of Object.entries(e))yield*Wt(t,n)}async function*Wt(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`||Rt(t))yield{key:e,value:t};else if(Array.isArray(t))for(let n of t)yield*Wt(e+`[]`,n);else if(typeof t==`object`)for(let[n,r]of Object.entries(t))yield*Wt(`${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 Gt(e){return Lt(e)?e.name:kt(e)??`unknown_file`}function Kt(e){return Lt(e)?e.type||`application/octet-stream`:Ft(e)&&e.type?e.type:e instanceof Response&&e.headers.get(`content-type`)||`application/octet-stream`}function qt(e){return Lt(e)?e.data:e}async function*Jt(e){if(typeof e==`string`)yield E(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)e.body?yield*Jt(e.body):yield*Jt(await e.blob());else if(e instanceof Blob)typeof e.stream==`function`?yield*Jt(e.stream()):yield new Uint8Array(await e.arrayBuffer());else if(It(e))for await(let t of Ee(e))yield*Jt(t);else if(At(e))for await(let t of e)yield*Jt(t);else throw TypeError(`Invalid streaming file chunk: ${String(e)}`)}function Yt(e){return e.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}const Xt=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,Ot([await n.blob()],kt(n)));else if(At(n))e.append(t,Ot([await new Response(Te(n)).blob()],kt(n)));else if(Ft(n))e.append(t,n,kt(n));else if(Array.isArray(n))await Promise.all(n.map(n=>Xt(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>Xt(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Zt=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`,Qt=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Zt(e),$t=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function en(e,t,n){if(Dt(),e=await e,Qt(e))return e instanceof File?e:Ot([await e.arrayBuffer()],e.name);if($t(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),Ot(await tn(r),t,n)}let r=await tn(e);if(t||=kt(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return Ot(r,t,n)}async function tn(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Zt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(At(e))for await(let n of e)t.push(...await tn(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${nn(e)}`)}return t}function nn(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var F=class{constructor(e){this._client=e}};function rn(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const an=Object.freeze(Object.create(null)),I=((e=rn)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??an)??an)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),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=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new l(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
7
7
  `)}\n${a}\n${t}`)}return a})(rn);var on=class extends F{list(e,t={},n){return this._client.getAPIList(I`/chat/completions/${e}/messages`,A,{query:t,...n,__security:{bearerAuth:!0}})}};function sn(e){return e!==void 0&&`function`in e&&e.function!==void 0}function cn(e){return e?.$brand===`auto-parseable-response-format`}function ln(e){return e?.$brand===`auto-parseable-tool`}function un(e,t){return!t||!hn(t)?{...e,choices:e.choices.map(e=>(gn(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:dn(e,t)}function dn(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new ee;if(e.finish_reason===`content_filter`)throw new te;return gn(e.message.tool_calls),{...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&&!e.message.refusal?fn(t,e.message.content):null}}});return{...e,choices:n}}function fn(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function pn(e,t){let n=e.tools?.find(e=>sn(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:ln(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function mn(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>sn(e)&&e.function?.name===t.function.name);return sn(n)&&(ln(n)||n?.function.strict||!1)}function hn(e){return cn(e.response_format)?!0:e.tools?.some(e=>ln(e)||e.type===`function`&&e.function.strict===!0)??!1}function gn(e){for(let t of e||[])if(t.type!==`function`)throw new l(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function _n(e){for(let t of e??[]){if(t.type!==`function`)throw new l(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new l(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const vn=e=>e?.role===`assistant`,yn=e=>e?.role===`tool`;var bn,xn,Sn,Cn,wn,Tn,En,L,Dn,On,kn,An,jn,Mn,Nn,Pn=class{constructor(){bn.add(this),this.controller=new AbortController,xn.set(this,void 0),Sn.set(this,()=>{}),Cn.set(this,()=>{}),wn.set(this,void 0),Tn.set(this,()=>{}),En.set(this,()=>{}),L.set(this,{}),Dn.set(this,[]),On.set(this,!1),kn.set(this,!1),An.set(this,!1),jn.set(this,!1),i(this,xn,new Promise((e,t)=>{i(this,Sn,e,`f`),i(this,Cn,t,`f`)}),`f`),i(this,wn,new Promise((e,t)=>{i(this,Tn,e,`f`),i(this,En,t,`f`)}),`f`),a(this,xn,`f`).catch(()=>{}),a(this,wn,`f`).catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(e){a(this,bn,`m`,Nn).call(this,e);return}this._emit(`end`)},a(this,bn,`m`,Nn).bind(this))},0)}_connected(){this.ended||(a(this,Sn,`f`).call(this),this._emit(`connect`))}get ended(){return a(this,On,`f`)}get errored(){return a(this,kn,`f`)}get aborted(){return a(this,An,`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}),a(this,Dn,`f`).push({signal:e,listener:t})}on(e,t){return(a(this,L,`f`)[e]||(a(this,L,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=a(this,L,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(a(this,L,`f`)[e]||(a(this,L,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{i(this,jn,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}events(e){let t=[],n=[],r=this.ended,i,a=!1,o=()=>({value:void 0,done:!0}),s=()=>{for(;n.length;)n.shift().resolve(o())},c=()=>{!i||a||!n.length||(a=!0,n.shift().reject(i))},l=()=>{this.off(e,u),this.off(`end`,f),e!==`error`&&this.off(`error`,d),e!==`abort`&&this.off(`abort`,d)},u=(...e)=>{if(r)return;let i=n.shift();i?i.resolve({value:e,done:!1}):t.push(e)},d=e=>{i=e,t.length||c()},f=()=>{r=!0,l(),t.length||(c(),s())};return r||(this.on(e,u),this.on(`end`,f),e!==`error`&&this.on(`error`,d),e!==`abort`&&this.on(`abort`,d)),{next:()=>{let e=t.shift();return e?Promise.resolve({value:e,done:!1}):i&&!a?(a=!0,Promise.reject(i)):r?Promise.resolve(o()):new Promise((e,t)=>{n.push({resolve:e,reject:t})})},return:()=>(r=!0,t.length=0,l(),s(),Promise.resolve(o())),[Symbol.asyncIterator](){return this}}}async done(){i(this,jn,!0,`f`),await a(this,wn,`f`)}_emit(e,...t){if(a(this,On,`f`))return;e===`end`&&(a(this,bn,`m`,Mn).call(this),i(this,On,!0,`f`),a(this,Tn,`f`).call(this));let n=a(this,L,`f`)[e];if(n&&(a(this,L,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!a(this,jn,`f`)&&!n?.length&&Promise.reject(e),a(this,Cn,`f`).call(this,e),a(this,En,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!a(this,jn,`f`)&&!n?.length&&Promise.reject(e),a(this,Cn,`f`).call(this,e),a(this,En,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};xn=new WeakMap,Sn=new WeakMap,Cn=new WeakMap,wn=new WeakMap,Tn=new WeakMap,En=new WeakMap,L=new WeakMap,Dn=new WeakMap,On=new WeakMap,kn=new WeakMap,An=new WeakMap,jn=new WeakMap,bn=new WeakSet,Mn=function(){for(let{signal:e,listener:t}of a(this,Dn,`f`).splice(0))e.removeEventListener(`abort`,t)},Nn=function(e){if(i(this,kn,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new d),e instanceof d)return i(this,An,!0,`f`),this._emit(`abort`,e);if(e instanceof l)return this._emit(`error`,e);if(e instanceof Error){let t=new l(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new l(String(e)))};function Fn(e){return typeof e.parse==`function`}var R,In,Ln,Rn,zn,Bn,Vn,Hn;function Un(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||=`call_${o()}`}function Wn(e){if(!vn(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 Gn=class extends Pn{constructor(){super(...arguments),R.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Un(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),yn(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(vn(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 l(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),a(this,R,`m`,In).call(this)}async finalMessage(){return await this.done(),a(this,R,`m`,Ln).call(this)}async finalFunctionToolCall(){return await this.done(),a(this,R,`m`,Rn).call(this)}async finalFunctionToolCallResult(){return await this.done(),a(this,R,`m`,zn).call(this)}async totalUsage(){return await this.done(),a(this,R,`m`,Bn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=a(this,R,`m`,Ln).call(this);t&&this._emit(`finalMessage`,t);let n=a(this,R,`m`,In).call(this);n&&this._emit(`finalContent`,n);let r=a(this,R,`m`,Rn).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=a(this,R,`m`,zn).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,a(this,R,`m`,Bn).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),a(this,R,`m`,Vn).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(dn(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:o=`auto`,stream:s,toolContext:c,...u}=t,d=c,f=typeof o!=`string`&&o.type===`function`&&o?.function?.name,{maxChatCompletions:p=10,afterCompletion:m}=r||{},h=t.tools.map(e=>{if(ln(e)){if(!e.$callback)throw new l("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={};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:o}=e.function,s=g[r];if(!s){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(f&&f!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(f)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let c;if(Fn(s)){let e;try{e=await s.parse(o)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}c=await s.function(e,n,d)}else c=await s.function(o,n,d);let l=a(this,R,`m`,Hn).call(this,c);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,{...u,tool_choice:o,tools:_,messages:this.messages.map(Wn)},r),a=i.choices[0]?.message;if(!a)throw new l(`missing message in ChatCompletion response`);if(!a.tool_calls?.length){await m?.(i,n);return}if(f||t.parallel_tool_calls===!1)for(let e of a.tool_calls){let t=await v(e);if(t.message&&this._addMessage(t.message),f&&t.functionCalled){await m?.(i,n);return}}else{let e=await Promise.allSettled(a.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)}}};R=new WeakSet,In=function(){return a(this,R,`m`,Ln).call(this).content??null},Ln=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(vn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new l(`stream ended without producing a ChatCompletionMessage with role=assistant`)},Rn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(vn(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}}},zn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(yn(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}},Bn=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},Vn=function(e){if(e.n!=null&&e.n>1)throw new l(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},Hn=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var Kn=class e extends Gn{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),vn(e)&&e.content&&this._emit(`content`,e.content)}};const 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};var qn=class extends Error{},Jn=class extends Error{};function Yn(e,t=z.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Xn(e.trim(),t)}const Xn=(e,t)=>{let n=e.length,r=0,i=e=>{throw new qn(`${e} at position ${r}`)},a=e=>{throw new Jn(`${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&&1<n-r&&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()},Zn=e=>Yn(e,z.ALL^z.NUM);var B,V,H,Qn,U,$n,er,tr,nr,rr,ir,ar,or;const sr=`chat.completion.chunk.message:`;function cr(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:`${sr}${JSON.stringify(r)}`}}function lr(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(sr)}function ur(e){return`type`in e?e:JSON.parse(e.object.slice(30))}var dr=class e extends Gn{constructor(e){super(),B.add(this),V.set(this,void 0),H.set(this,void 0),Qn.set(this,void 0),U.set(this,void 0),i(this,V,e,`f`),i(this,H,new Set,`f`),i(this,Qn,[],`f`)}get currentChatCompletionSnapshot(){return a(this,U,`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,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion,this._listenForAbort(n?.signal),a(this,B,`m`,$n).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)a(this,B,`m`,tr).call(this,e);if(r.controller.signal?.aborted)throw new d;return this._addChatCompletion(a(this,B,`m`,ir).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,B,`m`,$n).call(this),this._connected();let n=st.fromReadableStream(e,this.controller),r;for await(let e of n){if(lr(e)){let t=ur(e);if(a(this,U,`f`)){let e=a(this,U,`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(a(this,B,`m`,ir).call(this)),r=void 0}this._addMessage(t.message);continue}let t=e;r&&t.id&&r!==t.id&&this._addChatCompletion(a(this,B,`m`,ir).call(this)),a(this,B,`m`,tr).call(this,t),t.id&&(r=t.id)}if(n.controller.signal?.aborted)throw new d;if(a(this,U,`f`))return this._addChatCompletion(a(this,B,`m`,ir).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new l(`request ended without sending any chunks`)}[(V=new WeakMap,H=new WeakMap,Qn=new WeakMap,U=new WeakMap,B=new WeakSet,$n=function(){this.ended||(i(this,H,new Set,`f`),i(this,U,void 0,`f`))},er=function(e){let t=a(this,Qn,`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},a(this,Qn,`f`)[e.index]=t,t)},tr=function(e){if(this.ended)return;let t=a(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=a(this,B,`m`,er).call(this,e);e.finish_reason&&(a(this,B,`m`,rr).call(this,e),i.current_tool_call_index!=null&&a(this,B,`m`,nr).call(this,e,i.current_tool_call_index));for(let t of r?.tool_calls??[])i.current_tool_call_index!==t.index&&(a(this,B,`m`,rr).call(this,e),i.current_tool_call_index!=null&&a(this,B,`m`,nr).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)}}},nr=function(e,t){if(a(this,B,`m`,er).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=a(this,V,`f`)?.tools?.find(e=>sn(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:ln(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},rr=function(e){let t=a(this,B,`m`,er).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=a(this,B,`m`,ar).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}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}))},ir=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=a(this,U,`f`);if(!e)throw new l(`request ended without sending any chunks`);let t=a(this,H,`f`);return i(this,H,new Set,`f`),i(this,U,void 0,`f`),i(this,Qn,[],`f`),fr(e,a(this,V,`f`),t)},ar=function(){let e=a(this,V,`f`)?.response_format;return cn(e)?e:null},or=function(e){var t,n,r,o,s;let c=a(this,U,`f`),{choices:l,...u}=e;c?e.id&&Object.assign(c,u):c=i(this,U,{...u,choices:[]},`f`);for(let{delta:i,finish_reason:l,index:u,logprobs:d=null,...f}of e.choices){let e=c.choices[u];if(e||=c.choices[u]={finish_reason:l,index:u,message:{},logprobs:d,...f},d)if(!e.logprobs)e.logprobs=Object.assign({},d);else{let{content:r,refusal:i,...a}=d;Object.assign(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))}if(l&&(e.finish_reason=l,a(this,V,`f`)&&hn(a(this,V,`f`)))){if(l===`length`)throw new ee;if(l===`content_filter`)throw new te}if(Object.assign(e,f),!i)continue;a(this,H,`f`).delete(u);let{audio:p,content:m,refusal:h,function_call:g,role:_,tool_calls:v,...y}=i;if(Object.assign(e.message,y),p?.expires_at!=null&&p.id==null&&p.data==null&&p.transcript==null&&m==null&&h==null&&g==null&&_==null&&v==null&&Object.keys(y).length===0&&a(this,H,`f`).add(u),h&&(e.message.refusal=(e.message.refusal||``)+h),_&&(e.message.role=_),p){let t=(r=e.message).audio??(r.audio={});p.id!=null&&(t.id=p.id),p.data!=null&&(t.data=(t.data??``)+p.data),p.transcript!=null&&(t.transcript=(t.transcript??``)+p.transcript),p.expires_at!=null&&(t.expires_at=p.expires_at)}if(g&&(e.message.function_call?(g.name&&(e.message.function_call.name=g.name),g.arguments&&((o=e.message.function_call).arguments??(o.arguments=``),e.message.function_call.arguments+=g.arguments)):e.message.function_call=g),m&&(e.message.content=(e.message.content||``)+m,!e.message.refusal&&a(this,B,`m`,ar).call(this)&&(e.message.parsed=e.message.content.trim()?Zn(e.message.content):null)),v){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:i,...o}of v){let c=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(c,o),n&&(c.id=n),r&&(c.type=r),i&&(c.function??={name:i.name??``,arguments:``}),i?.name&&(c.function.name=i.name),i?.arguments&&(c.function.arguments+=i.arguments,mn(a(this,V,`f`),c)&&(c.function.parsed_arguments=Zn(c.function.arguments)))}}}return c},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new st(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function fr(e,t,n){let{id:r,choices:i,created:a,model:s,system_fingerprint:c,...u}=e;return un({...u,id:r,choices:i.map(({message:t,finish_reason:r,index:i,logprobs:a,...s})=>{let{content:c=null,function_call:u,tool_calls:d,audio:f,...p}=t,m=r??(n.has(i)&&pr(f)?`stop`:null);if(!m)throw new l(`missing finish_reason for choice ${i}`);let h=f?{audio:f}:{},g=t.role;if(!g)throw new l(`missing role for choice ${i}`);if(u){let{arguments:e,name:n}=u;if(e==null)throw new l(`missing function_call.arguments for choice ${i}`);if(!n)throw new l(`missing function_call.name for choice ${i}`);return{...s,message:{...h,content:c,function_call:{arguments:e,name:n},role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}return d?{...s,index:i,finish_reason:m,logprobs:a,message:{...p,...h,role:g,content:c,refusal:t.refusal??null,tool_calls:d.map((t,n)=>{let{function:r,type:a,id:s,...c}=t,{arguments:u,name:d,...f}=r||{};if(a==null)throw new l(`missing choices[${i}].tool_calls[${n}].type\n${mr(e)}`);if(d==null)throw new l(`missing choices[${i}].tool_calls[${n}].function.name\n${mr(e)}`);if(u==null)throw new l(`missing choices[${i}].tool_calls[${n}].function.arguments\n${mr(e)}`);return{...c,id:s||`call_${o()}`,type:a,function:{...f,name:d,arguments:u}}})}}:{...s,message:{...p,...h,content:c,role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}),created:a,model:s,object:`chat.completion`,...c?{system_fingerprint:c}:{}},t)}function pr(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function mr(e){return JSON.stringify(e)}var hr=class e extends dr{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e=[],t=[],n=!1,r,i,a=n=>{let r=t.shift();r?r.resolve(n):e.push(n)};return this.on(`chunk`,e=>{r=e,a(e)}),this.on(`message`,e=>{if(vn(e)){i=e.tool_calls?.map(e=>e.id);return}if(yn(e)){if(!r)throw new l(`cannot serialize a tool message before receiving any chunks`);a(cr(r,e,i))}}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),new st(()=>({next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});let r=e.shift();return r?{value:r,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})}),this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},gr=class extends F{constructor(){super(...arguments),this.messages=new on(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(I`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return _n(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>dn(t,e))}runTools(e,t){return e.stream?hr.runTools(this._client,e,t):Kn.runTools(this._client,e,t)}stream(e,t){return dr.createChatCompletion(this._client,e,t)}};gr.Messages=on;var _r=class extends F{constructor(){super(...arguments),this.completions=new gr(this._client)}};_r.Completions=gr;var vr=class extends F{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},yr=class extends F{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},br=class extends F{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(I`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,yt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,yt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},xr=class extends F{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},Sr=class extends F{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Cr=class extends F{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},wr=class extends F{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Tr=class extends F{retrieve(e){return this._client.get(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/spend_limit`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}},Er=class extends F{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},Dr=class extends F{create(e,t,n){return this._client.post(I`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(I`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/groups/${e}/roles`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(I`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Or=class extends F{create(e,t,n){return this._client.post(I`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(I`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/groups/${e}/users`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(I`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},kr=class extends F{constructor(){super(...arguments),this.users=new Or(this._client),this.roles=new Dr(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};kr.Users=Or,kr.Roles=Dr;var Ar=class extends F{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/api_keys`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},jr=class extends F{list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/certificates`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(I`/organization/projects/${e}/certificates/activate`,yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(I`/organization/projects/${e}/certificates/deactivate`,yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},Mr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},Nr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},Pr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},Fr=class extends F{listRateLimits(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/rate_limits`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},Ir=class extends F{create(e,t,n){return this._client.post(I`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/projects/${e}/roles`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Lr=class extends F{create(e,t,n){return this._client.post(I`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/spend_alerts`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Rr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}},zr=class extends F{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/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(I`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(I`/projects/${r}/groups/${e}/roles`,M,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(I`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Br=class extends F{constructor(){super(...arguments),this.roles=new zr(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(I`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/groups`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Br.Roles=zr;var Vr=class extends F{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/service_accounts/${e}/api_keys`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},Hr=class extends F{constructor(){super(...arguments),this.apiKeys=new Vr(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/service_accounts`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Hr.APIKeys=Vr;var Ur=class extends F{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/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(I`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(I`/projects/${r}/users/${e}/roles`,M,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(I`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Wr=class extends F{constructor(){super(...arguments),this.roles=new Ur(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/users`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Wr.Roles=Ur;var W=class extends F{constructor(){super(...arguments),this.users=new Wr(this._client),this.serviceAccounts=new Hr(this._client),this.apiKeys=new Ar(this._client),this.rateLimits=new Fr(this._client),this.modelPermissions=new Pr(this._client),this.hostedToolPermissions=new Nr(this._client),this.groups=new Br(this._client),this.roles=new Ir(this._client),this.dataRetention=new Mr(this._client),this.spendLimit=new Rr(this._client),this.spendAlerts=new Lr(this._client),this.certificates=new jr(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(I`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};W.Users=Wr,W.ServiceAccounts=Hr,W.APIKeys=Ar,W.RateLimits=Fr,W.ModelPermissions=Pr,W.HostedToolPermissions=Nr,W.Groups=Br,W.Roles=Ir,W.DataRetention=Mr,W.SpendLimit=Rr,W.SpendAlerts=Lr,W.Certificates=jr;var Gr=class extends F{create(e,t,n){return this._client.post(I`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(I`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/users/${e}/roles`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(I`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Kr=class extends F{constructor(){super(...arguments),this.roles=new Gr(this._client)}retrieve(e,t){return this._client.get(I`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Kr.Roles=Gr;var G=class extends F{constructor(){super(...arguments),this.auditLogs=new yr(this._client),this.adminAPIKeys=new vr(this._client),this.usage=new Er(this._client),this.invites=new Sr(this._client),this.users=new Kr(this._client),this.groups=new kr(this._client),this.roles=new Cr(this._client),this.dataRetention=new xr(this._client),this.spendLimit=new Tr(this._client),this.spendAlerts=new wr(this._client),this.certificates=new br(this._client),this.projects=new W(this._client)}};G.AuditLogs=yr,G.AdminAPIKeys=vr,G.Usage=Er,G.Invites=Sr,G.Users=Kr,G.Groups=kr,G.Roles=Cr,G.DataRetention=xr,G.SpendLimit=Tr,G.SpendAlerts=wr,G.Certificates=br,G.Projects=W;var qr=class extends F{constructor(){super(...arguments),this.organization=new G(this._client)}};qr.Organization=G;var Jr=class extends F{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:N([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Yr=class extends F{create(e,t){return this._client.post(`/audio/transcriptions`,P({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Xr=class extends F{create(e,t){return this._client.post(`/audio/translations`,P({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Zr=class extends F{constructor(){super(...arguments),this.transcriptions=new Yr(this._client),this.translations=new Xr(this._client),this.speech=new Jr(this._client)}};Zr.Transcriptions=Yr,Zr.Translations=Xr,Zr.Speech=Jr;var Qr=class extends F{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,A,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},$r=class extends F{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/assistants/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/assistants/${e}`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,A,{query:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/assistants/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ei=class extends F{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ti=class extends F{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ni=class extends F{constructor(){super(...arguments),this.sessions=new ei(this._client),this.transcriptionSessions=new ti(this._client)}};ni.Sessions=ei,ni.TranscriptionSessions=ti;var ri=class extends F{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/chatkit/sessions/${e}/cancel`,{...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},ii=class extends F{retrieve(e,t){return this._client.get(I`/chatkit/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,j,{query:e,...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/chatkit/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(I`/chatkit/threads/${e}/items`,j,{query:t,...n,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},ai=class extends F{constructor(){super(...arguments),this.sessions=new ri(this._client),this.threads=new ii(this._client)}};ai.Sessions=ri,ai.Threads=ii;var oi=class extends F{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(I`/responses/${e}/input_items?beta=true`,A,{query:i,...n,headers:N([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}},si=class extends F{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:N([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},ci=class extends F{constructor(){super(...arguments),this.inputItems=new oi(this._client),this.inputTokens=new si(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:N([{...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(I`/responses/${e}?beta=true`,{query:i,...n,headers:N([{...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(I`/responses/${e}?beta=true`,{...n,headers:N([{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(I`/responses/${e}/cancel?beta=true`,{...n,headers:N([{...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:N([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}};ci.InputItems=oi,ci.InputTokens=si;var li=class extends F{create(e,t,n){return this._client.post(I`/threads/${e}/messages`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(I`/threads/${r}/messages/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(I`/threads/${r}/messages/${e}`,{body:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/threads/${e}/messages`,A,{query:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(I`/threads/${r}/messages/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ui=class extends F{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(I`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(I`/threads/${r}/runs/${e}/steps`,A,{query:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},di=t();const fi=e=>{if(di.Buffer!==void 0){let t=di.Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},pi=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var K,mi,hi,q,gi,J,_i,vi,yi,bi,Y,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni=class extends Pn{constructor(){super(...arguments),K.add(this),hi.set(this,[]),q.set(this,{}),gi.set(this,{}),J.set(this,void 0),_i.set(this,void 0),vi.set(this,void 0),yi.set(this,void 0),bi.set(this,void 0),Y.set(this,void 0),xi.set(this,void 0),Si.set(this,void 0),Ci.set(this,void 0)}[(hi=new WeakMap,q=new WeakMap,gi=new WeakMap,J=new WeakMap,_i=new WeakMap,vi=new WeakMap,yi=new WeakMap,bi=new WeakMap,Y=new WeakMap,xi=new WeakMap,Si=new WeakMap,Ci=new WeakMap,K=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=structuredClone(n),i=t.shift();i?i.resolve(r):e.push(r)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new mi;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=st.fromReadableStream(e,this.controller);for await(let e of n)a(this,K,`m`,wi).call(this,e);if(n.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}toReadableStream(){return new st(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new mi;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},o=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of o)a(this,K,`m`,wi).call(this,e);if(o.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}static createThreadAssistantStream(e,t,n){let r=new mi;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new mi;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return a(this,xi,`f`)}currentRun(){return a(this,Si,`f`)}currentMessageSnapshot(){return a(this,J,`f`)}currentRunStepSnapshot(){return a(this,Ci,`f`)}async finalRunSteps(){return await this.done(),Object.values(a(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(a(this,gi,`f`))}async finalRun(){if(await this.done(),!a(this,_i,`f`))throw Error(`Final run was not received.`);return a(this,_i,`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)a(this,K,`m`,wi).call(this,e);if(i.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},o=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of o)a(this,K,`m`,wi).call(this,e);if(o.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ue(t)&&ue(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ue(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t[n]=e:t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};mi=Ni,wi=function(e){if(!this.ended)switch(i(this,xi,e,`f`),a(this,K,`m`,Oi).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`:a(this,K,`m`,Mi).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`:a(this,K,`m`,Di).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`:a(this,K,`m`,Ei).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},Ti=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);if(!a(this,_i,`f`))throw Error(`Final run has not been received`);return a(this,_i,`f`)},Ei=function(e){let[t,n]=a(this,K,`m`,Ai).call(this,e,a(this,J,`f`));i(this,J,t,`f`),a(this,gi,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`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`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=a(this,vi,`f`)){if(a(this,yi,`f`))switch(a(this,yi,`f`).type){case`text`:this._emit(`textDone`,a(this,yi,`f`).text,a(this,J,`f`));break;case`image_file`:this._emit(`imageFileDone`,a(this,yi,`f`).image_file,a(this,J,`f`));break}i(this,vi,n.index,`f`)}i(this,yi,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(a(this,vi,`f`)!==void 0){let t=e.data.content[a(this,vi,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,a(this,J,`f`));break;case`text`:this._emit(`textDone`,t.text,a(this,J,`f`));break}}a(this,J,`f`)&&this._emit(`messageDone`,e.data),i(this,J,void 0,`f`)}},Di=function(e){let t=a(this,K,`m`,ki).call(this,e);switch(i(this,Ci,t,`f`),e.event){case`thread.run.step.created`:this._emit(`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==a(this,bi,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(a(this,Y,`f`)&&this._emit(`toolCallDone`,a(this,Y,`f`)),i(this,bi,e.index,`f`),i(this,Y,t.step_details.tool_calls[e.index],`f`),a(this,Y,`f`)&&this._emit(`toolCallCreated`,a(this,Y,`f`)));this._emit(`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`:i(this,Ci,void 0,`f`),e.data.step_details.type==`tool_calls`&&a(this,Y,`f`)&&(this._emit(`toolCallDone`,a(this,Y,`f`)),i(this,Y,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},Oi=function(e){a(this,hi,`f`).push(e),this._emit(`event`,e)},ki=function(e){switch(e.event){case`thread.run.step.created`:return a(this,q,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=a(this,q,`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=mi.accumulateDelta(t,n.delta);a(this,q,`f`)[e.data.id]=r}return a(this,q,`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`:a(this,q,`f`)[e.data.id]=e.data;break}if(a(this,q,`f`)[e.data.id])return a(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},Ai=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)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=a(this,K,`m`,ji).call(this,e,n)}else t.content[e.index]=e,n.push(e);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`)},ji=function(e,t){return mi.accumulateDelta(t,e)},Mi=function(e){switch(i(this,Si,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`:i(this,_i,e.data,`f`),a(this,Y,`f`)&&(this._emit(`toolCallDone`,a(this,Y,`f`)),i(this,Y,void 0,`f`));break;case`thread.run.cancelling`:break}};var Pi=class extends F{constructor(){super(...arguments),this.steps=new ui(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(I`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:N([{"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(I`/threads/${r}/runs/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(I`/threads/${r}/runs/${e}`,{body:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/threads/${e}/runs`,A,{query:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(I`/threads/${r}/runs/${e}/cancel`,{...n,headers:N([{"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 Ni.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=N([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 pe(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Ni.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(I`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:N([{"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 Ni.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Pi.Steps=ui;var Fi=class extends F{constructor(){super(...arguments),this.runs=new Pi(this._client),this.messages=new li(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/threads/${e}`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:N([{"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 Ni.createThreadAssistantStream(e,this._client.beta.threads,t)}};Fi.Runs=Pi,Fi.Messages=li;var Ii=class extends F{constructor(){super(...arguments),this.realtime=new ni(this._client),this.responses=new ci(this._client),this.chatkit=new ai(this._client),this.assistants=new $r(this._client),this.threads=new Fi(this._client)}};Ii.Realtime=ni,Ii.Responses=ci,Ii.ChatKit=ai,Ii.Assistants=$r,Ii.Threads=Fi;var Li=class extends F{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Ri=class extends F{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(I`/containers/${r}/files/${e}/content`,{...n,headers:N([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},zi=class extends F{constructor(){super(...arguments),this.content=new Ri(this._client)}create(e,t,n){return this._client.post(I`/containers/${e}/files`,jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(I`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/containers/${e}/files`,A,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(I`/containers/${r}/files/${e}`,{...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};zi.Content=Ri;var Bi=class extends F{constructor(){super(...arguments),this.files=new zi(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/containers/${e}`,{...t,headers:N([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};Bi.Files=zi;var Vi=class extends F{create(e,t){return this._client.post(`/content_provenance_checks`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}},Hi=class extends F{create(e,t,n){let{include:r,...i}=t;return this._client.post(I`/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(I`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/conversations/${e}/items`,j,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(I`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},Ui=class extends F{constructor(){super(...arguments),this.items=new Hi(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Ui.Items=Hi;var Wi=class extends F{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=fi(t)}),e)))}},Gi=class extends F{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(I`/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(I`/evals/${r}/runs/${e}/output_items`,A,{query:i,...n,__security:{bearerAuth:!0}})}},Ki=class extends F{constructor(){super(...arguments),this.outputItems=new Gi(this._client)}create(e,t,n){return this._client.post(I`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/evals/${e}/runs`,A,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Ki.OutputItems=Gi;var qi=class extends F{constructor(){super(...arguments),this.runs=new Ki(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};qi.Runs=Ki;var Ji=class extends F{create(e,t){return this._client.post(`/files`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(I`/files/${e}/content`,{...t,headers:N([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await pe(t),a=await this.retrieve(e),Date.now()-i>n)throw new p({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Yi=class extends F{},Xi=class extends F{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},Zi=class extends F{constructor(){super(...arguments),this.graders=new Xi(this._client)}};Zi.Graders=Xi;var Qi=class extends F{create(e,t,n){return this._client.getAPIList(I`/fine_tuning/checkpoints/${e}/permissions`,yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(I`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/fine_tuning/checkpoints/${e}/permissions`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(I`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},$i=class extends F{constructor(){super(...arguments),this.permissions=new Qi(this._client)}};$i.Permissions=Qi;var ea=class extends F{list(e,t={},n){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/checkpoints`,A,{query:t,...n,__security:{bearerAuth:!0}})}},ta=class extends F{constructor(){super(...arguments),this.checkpoints=new ea(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(I`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,A,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/events`,A,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};ta.Checkpoints=ea;var na=class extends F{constructor(){super(...arguments),this.methods=new Yi(this._client),this.jobs=new ta(this._client),this.checkpoints=new $i(this._client),this.alpha=new Zi(this._client)}};na.Methods=Yi,na.Jobs=ta,na.Checkpoints=$i,na.Alpha=Zi;var ra=class extends F{},ia=class extends F{constructor(){super(...arguments),this.graderModels=new ra(this._client)}};ia.GraderModels=ra;var aa=class extends F{createVariation(e,t){return this._client.post(`/images/variations`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,P({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},oa=class extends F{retrieve(e,t){return this._client.get(I`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,yt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},sa=class extends F{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},ca=class extends F{accept(e,t,n){return this._client.post(I`/realtime/calls/${e}/accept`,{body:t,...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(I`/realtime/calls/${e}/hangup`,{...t,headers:N([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(I`/realtime/calls/${e}/refer`,{body:t,...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(I`/realtime/calls/${e}/reject`,{body:t,...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},la=class extends F{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},ua=class extends F{constructor(){super(...arguments),this.clientSecrets=new la(this._client),this.calls=new ca(this._client)}};ua.ClientSecrets=la,ua.Calls=ca;function da(e,t){if(!t||!ma(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 va(e,t)&&X(t),t}return fa(e,t)}function fa(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?_a(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?pa(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return va(e,i)&&X(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 pa(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function ma(e){return cn(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>ha(e)||e.type===`function`&&e.strict===!0)}function ha(e){return e?.$brand===`auto-parseable-tool`}function ga(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function _a(e,t){let n=ga(e.tools??[],t.name);return{...t,...t,parsed_arguments:ha(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function va(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function X(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(``)}function ya(e,t){if(!t){if(e.type!==`response.created`)throw new l(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return ba(e.response)}switch(e.type){case`response.output_item.added`:t.output.push(structuredClone(e.item)),e.item.type===`message`&&X(t);break;case`response.output_item.done`:Z(t,e.output_index),t.output[e.output_index]=structuredClone(e.item),e.item.type===`message`&&X(t);break;case`response.content_part.added`:{let n=Z(t,e.output_index),r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?(n.content.push(structuredClone(i)),i.type===`output_text`&&X(t)):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(structuredClone(i)));break}case`response.content_part.done`:{let n=Z(t,e.output_index),r=e.part;if(n.type===`message`&&r.type!==`reasoning_text`)Q(n.content,e.content_index),n.content[e.content_index]=structuredClone(r),r.type===`output_text`&&X(t);else if(n.type===`reasoning`&&r.type===`reasoning_text`){let t=n.content;if(!t)throw new l(`missing content at index ${e.content_index}`);Q(t,e.content_index),t[e.content_index]=structuredClone(r)}break}case`response.output_text.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let r=Q(n.content,e.content_index);if(r.type!==`output_text`)throw new l(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta,t.output_text+=e.delta}break}case`response.output_text.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let r=Q(n.content,e.content_index);if(r.type!==`output_text`)throw new l(`expected content to be 'output_text', got ${r.type}`);r.text=e.text,X(t)}break}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 l(`expected content to be 'output_text', got ${t.type}`);t.annotations[e.annotation_index]=structuredClone(e.annotation)}break}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 l(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}break}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 l(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}break}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);n.type===`function_call`&&(n.arguments=e.arguments);break}case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new l(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new l(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new l(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new l(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}break}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);n.type===`reasoning`&&n.summary.push(structuredClone(e.part));break}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);n.type===`reasoning`&&(Q(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part));break}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}break}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}break}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);n.type===`custom_tool_call`&&(n.input+=e.delta);break}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);n.type===`custom_tool_call`&&(n.input=e.input);break}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.arguments+=e.delta);break}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.arguments=e.arguments);break}case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta);break}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=e.code);break}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`in_progress`);break}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`interpreting`);break}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`completed`);break}case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`in_progress`);break}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`searching`);break}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`completed`);break}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`in_progress`);break}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`searching`);break}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`completed`);break}case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`in_progress`);break}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`generating`);break}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`completed`);break}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`in_progress`);break}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`completed`);break}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`failed`);break}case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:t=ba(e.response);break;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`:break;default:xa(e)}return t}function ba(e){let t=structuredClone(e);return(!Object.getOwnPropertyDescriptor(t,`output_text`)||t.output_text==null)&&X(t),t}function Z(e,t){let n=e.output[t];if(!n)throw new l(`missing output at index ${t}`);return n}function Q(e,t){let n=e[t];if(!n)throw new l(`missing content at index ${t}`);return n}function xa(e){throw new l(`Unhandled response stream event: ${JSON.stringify(e)}`)}var Sa,Ca,wa,Ta,Ea,Da,Oa,ka=class e extends Pn{constructor(e){super(),Sa.add(this),Ca.set(this,void 0),wa.set(this,void 0),Ta.set(this,void 0),i(this,Ca,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`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),a(this,Sa,`m`,Ea).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)a(this,Sa,`m`,Da).call(this,e,i);if(r.controller.signal?.aborted)throw new d;return a(this,Sa,`m`,Oa).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,Sa,`m`,Ea).call(this),this._connected();let n=st.fromReadableStream(e,this.controller);for await(let e of n)a(this,Sa,`m`,Da).call(this,e,null);if(n.controller.signal?.aborted)throw new d;return a(this,Sa,`m`,Oa).call(this)}[(Ca=new WeakMap,wa=new WeakMap,Ta=new WeakMap,Sa=new WeakSet,Ea=function(){this.ended||i(this,wa,void 0,`f`)},Da=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=ya(e,a(this,wa,`f`));switch(i(this,wa,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new l(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new l(`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 l(`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);break}},Oa=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=a(this,wa,`f`);if(!e)throw new l(`request ended without sending any events`);i(this,wa,void 0,`f`);let t=Aa(e,a(this,Ca,`f`));return i(this,Ta,t,`f`),t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=a(this,Ta,`f`);if(!e)throw new l(`stream ended without producing a ChatCompletion`);return e}};function Aa(e,t){return da(e,t)}var ja=class extends F{list(e,t={},n){return this._client.getAPIList(I`/responses/${e}/input_items`,A,{query:t,...n,__security:{bearerAuth:!0}})}},Ma=class extends F{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},Na=class extends F{constructor(){super(...arguments),this.inputItems=new ja(this._client),this.inputTokens=new Ma(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`&&X(e),e))}retrieve(e,t={},n){return this._client.get(I`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&X(e),e))}delete(e,t){return this._client.delete(I`/responses/${e}`,{...t,headers:N([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>fa(t,e))}stream(e,t){return ka.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(I`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};Na.InputItems=ja,Na.InputTokens=Ma;var Pa=class extends F{retrieve(e,t){return this._client.get(I`/skills/${e}/content`,{...t,headers:N([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Fa=class extends F{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(I`/skills/${r}/versions/${e}/content`,{...n,headers:N([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Ia=class extends F{constructor(){super(...arguments),this.content=new Fa(this._client)}create(e,t={},n){return this._client.post(I`/skills/${e}/versions`,jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(I`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/skills/${e}/versions`,A,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(I`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};Ia.Content=Fa;var La=class extends F{constructor(){super(...arguments),this.content=new Pa(this._client),this.versions=new Ia(this._client)}create(e={},t){return this._client.post(`/skills`,jt({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};La.Content=Pa,La.Versions=Ia;var Ra=class extends F{create(e,t,n){return this._client.post(I`/uploads/${e}/parts`,P({body:t,...n,__security:{bearerAuth:!0}},this._client))}},za=class extends F{constructor(){super(...arguments),this.parts=new Ra(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(I`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};za.Parts=Ra;const Ba=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r};var Va=class extends F{create(e,t,n){return this._client.post(I`/vector_stores/${e}/file_batches`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(I`/vector_stores/${r}/file_batches/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(I`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(I`/vector_stores/${r}/file_batches/${e}/files`,A,{query:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=N([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 pe(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 Ba(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},Ha=class extends F{create(e,t,n){return this._client.post(I`/vector_stores/${e}/files`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(I`/vector_stores/${r}/files/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(I`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/vector_stores/${e}/files`,A,{query:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(I`/vector_stores/${r}/files/${e}`,{...n,headers:N([{"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=N([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 pe(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(I`/vector_stores/${r}/files/${e}/content`,yt,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Ua=class extends F{constructor(){super(...arguments),this.files=new Ha(this._client),this.fileBatches=new Va(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/vector_stores/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/vector_stores/${e}`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,A,{query:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/vector_stores/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(I`/vector_stores/${e}/search`,yt,{body:t,method:`post`,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};Ua.Files=Ha,Ua.FileBatches=Va;var Wa=class extends F{create(e,t){return this._client.post(`/videos`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,j,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(I`/videos/${e}/content`,{query:t,...n,headers:N([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(I`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(I`/videos/${e}/remix`,jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}},Ga,Ka,qa,Ja=class extends F{constructor(){super(...arguments),Ga.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");a(this,Ga,`m`,Ka).call(this,n);let i=N([t]).values,o=a(this,Ga,`m`,qa).call(this,i,`webhook-signature`),s=a(this,Ga,`m`,qa).call(this,i,`webhook-timestamp`),c=a(this,Ga,`m`,qa).call(this,i,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new S(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>r)throw new S(`Webhook timestamp is too old`);if(l>u+r)throw new S(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=n.startsWith(`whsec_`)?di.Buffer.from(n.replace(`whsec_`,``),`base64`):di.Buffer.from(n,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=di.Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new S(`The given webhook signature does not match the expected signature`)}};Ga=new WeakSet,Ka=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`)},qa=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};const Ya=Symbol.for(`openai.node.providerDefinitions.v1`),Xa=globalThis,Za=Xa[Ya],Qa=Za??new WeakMap;Za||Object.defineProperty(Xa,Ya,{value:Qa});function $a(e){let t=Qa.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var eo,to,no,ro,$=class{constructor(e={}){eo.add(this),no.set(this,void 0),this.completions=new Li(this),this.chat=new _r(this),this.embeddings=new Wi(this),this.files=new Ji(this),this.images=new aa(this),this.contentProvenanceChecks=new Vi(this),this.audio=new Zr(this),this.moderations=new sa(this),this.models=new oa(this),this.fineTuning=new na(this),this.graders=new ia(this),this.vectorStores=new Ua(this),this.webhooks=new Ja(this),this.beta=new Ii(this),this.batches=new Qr(this),this.uploads=new za(this),this.admin=new qr(this),this.responses=new Na(this),this.realtime=new ua(this),this.conversations=new Ui(this),this.evals=new qi(this),this.containers=new Bi(this),this.skills=new La(this),this.videos=new Wa(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new l(`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:pi(`OPENAI_BASE_URL`),apiKey:r=t?null:pi(`OPENAI_API_KEY`)??null,adminAPIKey:a=t?null:pi(`OPENAI_ADMIN_KEY`)??null,organization:o=t?null:pi(`OPENAI_ORG_ID`)??null,project:s=t?null:pi(`OPENAI_PROJECT_ID`)??null,webhookSecret:c=pi(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:u,...d}=e,f=t?$a(t):void 0,p={apiKey:r,adminAPIKey:a,organization:o,project:s,webhookSecret:c,workloadIdentity:u,provider:t,...d,baseURL:f?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&u)throw new l("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!f&&!r&&!a&&!u)throw new l("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!p.dangerouslyAllowBrowser&&he())throw new l(`It looks like you're running in a browser-like environment.
8
+ \r `.includes(e[r]);)r++};return o()},Zn=e=>Yn(e,z.ALL^z.NUM);var B,V,H,Qn,U,$n,er,tr,nr,rr,ir,ar,or;const sr=`chat.completion.chunk.message:`;function cr(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:`${sr}${JSON.stringify(r)}`}}function lr(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(sr)}function ur(e){return`type`in e?e:JSON.parse(e.object.slice(30))}var dr=class e extends Gn{constructor(e){super(),B.add(this),V.set(this,void 0),H.set(this,void 0),Qn.set(this,void 0),U.set(this,void 0),i(this,V,e,`f`),i(this,H,new Set,`f`),i(this,Qn,[],`f`)}get currentChatCompletionSnapshot(){return a(this,U,`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,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion,this._listenForAbort(n?.signal),a(this,B,`m`,$n).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)a(this,B,`m`,tr).call(this,e);if(r.controller.signal?.aborted)throw new d;return this._addChatCompletion(a(this,B,`m`,ir).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,B,`m`,$n).call(this),this._connected();let n=st.fromReadableStream(e,this.controller),r;for await(let e of n){if(lr(e)){let t=ur(e);if(a(this,U,`f`)){let e=a(this,U,`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(a(this,B,`m`,ir).call(this)),r=void 0}this._addMessage(t.message);continue}let t=e;r&&t.id&&r!==t.id&&this._addChatCompletion(a(this,B,`m`,ir).call(this)),a(this,B,`m`,tr).call(this,t),t.id&&(r=t.id)}if(n.controller.signal?.aborted)throw new d;if(a(this,U,`f`))return this._addChatCompletion(a(this,B,`m`,ir).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new l(`request ended without sending any chunks`)}[(V=new WeakMap,H=new WeakMap,Qn=new WeakMap,U=new WeakMap,B=new WeakSet,$n=function(){this.ended||(i(this,H,new Set,`f`),i(this,U,void 0,`f`))},er=function(e){let t=a(this,Qn,`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},a(this,Qn,`f`)[e.index]=t,t)},tr=function(e){if(this.ended)return;let t=a(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=a(this,B,`m`,er).call(this,e);e.finish_reason&&(a(this,B,`m`,rr).call(this,e),i.current_tool_call_index!=null&&a(this,B,`m`,nr).call(this,e,i.current_tool_call_index));for(let t of r?.tool_calls??[])i.current_tool_call_index!==t.index&&(a(this,B,`m`,rr).call(this,e),i.current_tool_call_index!=null&&a(this,B,`m`,nr).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)}}},nr=function(e,t){if(a(this,B,`m`,er).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=a(this,V,`f`)?.tools?.find(e=>sn(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:ln(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},rr=function(e){let t=a(this,B,`m`,er).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=a(this,B,`m`,ar).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}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}))},ir=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=a(this,U,`f`);if(!e)throw new l(`request ended without sending any chunks`);let t=a(this,H,`f`);return i(this,H,new Set,`f`),i(this,U,void 0,`f`),i(this,Qn,[],`f`),fr(e,a(this,V,`f`),t)},ar=function(){let e=a(this,V,`f`)?.response_format;return cn(e)?e:null},or=function(e){var t,n,r,o,s;let c=a(this,U,`f`),{choices:l,...u}=e;c?e.id&&Object.assign(c,u):c=i(this,U,{...u,choices:[]},`f`);for(let{delta:i,finish_reason:l,index:u,logprobs:d=null,...f}of e.choices){let e=c.choices[u];if(e||=c.choices[u]={finish_reason:l,index:u,message:{},logprobs:d,...f},d)if(!e.logprobs)e.logprobs=Object.assign({},d);else{let{content:r,refusal:i,...a}=d;Object.assign(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))}if(l&&(e.finish_reason=l,a(this,V,`f`)&&hn(a(this,V,`f`)))){if(l===`length`)throw new ee;if(l===`content_filter`)throw new te}if(Object.assign(e,f),!i)continue;a(this,H,`f`).delete(u);let{audio:p,content:m,refusal:h,function_call:g,role:_,tool_calls:v,...y}=i;if(Object.assign(e.message,y),p?.expires_at!=null&&p.id==null&&p.data==null&&p.transcript==null&&m==null&&h==null&&g==null&&_==null&&v==null&&Object.keys(y).length===0&&a(this,H,`f`).add(u),h&&(e.message.refusal=(e.message.refusal||``)+h),_&&(e.message.role=_),p){let t=(r=e.message).audio??(r.audio={});p.id!=null&&(t.id=p.id),p.data!=null&&(t.data=(t.data??``)+p.data),p.transcript!=null&&(t.transcript=(t.transcript??``)+p.transcript),p.expires_at!=null&&(t.expires_at=p.expires_at)}if(g&&(e.message.function_call?(g.name&&(e.message.function_call.name=g.name),g.arguments&&((o=e.message.function_call).arguments??(o.arguments=``),e.message.function_call.arguments+=g.arguments)):e.message.function_call=g),m&&(e.message.content=(e.message.content||``)+m,!e.message.refusal&&a(this,B,`m`,ar).call(this)&&(e.message.parsed=e.message.content.trim()?Zn(e.message.content):null)),v){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:i,...o}of v){let c=(s=e.message.tool_calls)[t]??(s[t]={});Object.assign(c,o),n&&(c.id=n),r&&(c.type=r),i&&(c.function??={name:i.name??``,arguments:``}),i?.name&&(c.function.name=i.name),i?.arguments&&(c.function.arguments+=i.arguments,mn(a(this,V,`f`),c)&&(c.function.parsed_arguments=Zn(c.function.arguments)))}}}return c},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new st(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function fr(e,t,n){let{id:r,choices:i,created:a,model:s,system_fingerprint:c,...u}=e;return un({...u,id:r,choices:i.map(({message:t,finish_reason:r,index:i,logprobs:a,...s})=>{let{content:c=null,function_call:u,tool_calls:d,audio:f,...p}=t,m=r??(n.has(i)&&pr(f)?`stop`:null);if(!m)throw new l(`missing finish_reason for choice ${i}`);let h=f?{audio:f}:{},g=t.role;if(!g)throw new l(`missing role for choice ${i}`);if(u){let{arguments:e,name:n}=u;if(e==null)throw new l(`missing function_call.arguments for choice ${i}`);if(!n)throw new l(`missing function_call.name for choice ${i}`);return{...s,message:{...h,content:c,function_call:{arguments:e,name:n},role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}return d?{...s,index:i,finish_reason:m,logprobs:a,message:{...p,...h,role:g,content:c,refusal:t.refusal??null,tool_calls:d.map((t,n)=>{let{function:r,type:a,id:s,...c}=t,{arguments:u,name:d,...f}=r||{};if(a==null)throw new l(`missing choices[${i}].tool_calls[${n}].type\n${mr(e)}`);if(d==null)throw new l(`missing choices[${i}].tool_calls[${n}].function.name\n${mr(e)}`);if(u==null)throw new l(`missing choices[${i}].tool_calls[${n}].function.arguments\n${mr(e)}`);return{...c,id:s||`call_${o()}`,type:a,function:{...f,name:d,arguments:u}}})}}:{...s,message:{...p,...h,content:c,role:g,refusal:t.refusal??null},finish_reason:m,index:i,logprobs:a}}),created:a,model:s,object:`chat.completion`,...c?{system_fingerprint:c}:{}},t)}function pr(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function mr(e){return JSON.stringify(e)}var hr=class e extends dr{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e=[],t=[],n=!1,r,i,a=n=>{let r=t.shift();r?r.resolve(n):e.push(n)};return this.on(`chunk`,e=>{r=e,a(e)}),this.on(`message`,e=>{if(vn(e)){i=e.tool_calls?.map(e=>e.id);return}if(yn(e)){if(!r)throw new l(`cannot serialize a tool message before receiving any chunks`);a(cr(r,e,i))}}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),new st(()=>({next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});let r=e.shift();return r?{value:r,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})}),this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},gr=class extends F{constructor(){super(...arguments),this.messages=new on(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(I`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return _n(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>dn(t,e))}runTools(e,t){return e.stream?hr.runTools(this._client,e,t):Kn.runTools(this._client,e,t)}stream(e,t){return dr.createChatCompletion(this._client,e,t)}};gr.Messages=on;var _r=class extends F{constructor(){super(...arguments),this.completions=new gr(this._client)}};_r.Completions=gr;var vr=class extends F{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,A,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},yr=class extends F{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},br=class extends F{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(I`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,yt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,yt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},xr=class extends F{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},Sr=class extends F{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Cr=class extends F{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},wr=class extends F{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Tr=class extends F{retrieve(e){return this._client.get(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/spend_limit`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}},Er=class extends F{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},Dr=class extends F{create(e,t,n){return this._client.post(I`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(I`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/groups/${e}/roles`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(I`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Or=class extends F{create(e,t,n){return this._client.post(I`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(I`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/groups/${e}/users`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(I`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},kr=class extends F{constructor(){super(...arguments),this.users=new Or(this._client),this.roles=new Dr(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};kr.Users=Or,kr.Roles=Dr;var Ar=class extends F{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/api_keys`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},jr=class extends F{list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/certificates`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(I`/organization/projects/${e}/certificates/activate`,yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(I`/organization/projects/${e}/certificates/deactivate`,yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},Mr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},Nr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},Pr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},Fr=class extends F{listRateLimits(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/rate_limits`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},Ir=class extends F{create(e,t,n){return this._client.post(I`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/projects/${e}/roles`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Lr=class extends F{create(e,t,n){return this._client.post(I`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/spend_alerts`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Rr=class extends F{retrieve(e,t){return this._client.get(I`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}},zr=class extends F{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/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(I`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(I`/projects/${r}/groups/${e}/roles`,M,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(I`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Br=class extends F{constructor(){super(...arguments),this.roles=new zr(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(I`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/groups`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Br.Roles=zr;var Vr=class extends F{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/service_accounts/${e}/api_keys`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},Hr=class extends F{constructor(){super(...arguments),this.apiKeys=new Vr(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/service_accounts`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Hr.APIKeys=Vr;var Ur=class extends F{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/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(I`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(I`/projects/${r}/users/${e}/roles`,M,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(I`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Wr=class extends F{constructor(){super(...arguments),this.roles=new Ur(this._client)}create(e,t,n){return this._client.post(I`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(I`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(I`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/projects/${e}/users`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(I`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};Wr.Roles=Ur;var W=class extends F{constructor(){super(...arguments),this.users=new Wr(this._client),this.serviceAccounts=new Hr(this._client),this.apiKeys=new Ar(this._client),this.rateLimits=new Fr(this._client),this.modelPermissions=new Pr(this._client),this.hostedToolPermissions=new Nr(this._client),this.groups=new Br(this._client),this.roles=new Ir(this._client),this.dataRetention=new Mr(this._client),this.spendLimit=new Rr(this._client),this.spendAlerts=new Lr(this._client),this.certificates=new jr(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(I`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(I`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};W.Users=Wr,W.ServiceAccounts=Hr,W.APIKeys=Ar,W.RateLimits=Fr,W.ModelPermissions=Pr,W.HostedToolPermissions=Nr,W.Groups=Br,W.Roles=Ir,W.DataRetention=Mr,W.SpendLimit=Rr,W.SpendAlerts=Lr,W.Certificates=jr;var Gr=class extends F{create(e,t,n){return this._client.post(I`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(I`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/organization/users/${e}/roles`,M,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(I`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Kr=class extends F{constructor(){super(...arguments),this.roles=new Gr(this._client)}retrieve(e,t){return this._client.get(I`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(I`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,j,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(I`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Kr.Roles=Gr;var G=class extends F{constructor(){super(...arguments),this.auditLogs=new yr(this._client),this.adminAPIKeys=new vr(this._client),this.usage=new Er(this._client),this.invites=new Sr(this._client),this.users=new Kr(this._client),this.groups=new kr(this._client),this.roles=new Cr(this._client),this.dataRetention=new xr(this._client),this.spendLimit=new Tr(this._client),this.spendAlerts=new wr(this._client),this.certificates=new br(this._client),this.projects=new W(this._client)}};G.AuditLogs=yr,G.AdminAPIKeys=vr,G.Usage=Er,G.Invites=Sr,G.Users=Kr,G.Groups=kr,G.Roles=Cr,G.DataRetention=xr,G.SpendLimit=Tr,G.SpendAlerts=wr,G.Certificates=br,G.Projects=W;var qr=class extends F{constructor(){super(...arguments),this.organization=new G(this._client)}};qr.Organization=G;var Jr=class extends F{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:N([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Yr=class extends F{create(e,t){return this._client.post(`/audio/transcriptions`,P({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Xr=class extends F{create(e,t){return this._client.post(`/audio/translations`,P({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Zr=class extends F{constructor(){super(...arguments),this.transcriptions=new Yr(this._client),this.translations=new Xr(this._client),this.speech=new Jr(this._client)}};Zr.Transcriptions=Yr,Zr.Translations=Xr,Zr.Speech=Jr;var Qr=class extends F{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,A,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},$r=class extends F{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/assistants/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/assistants/${e}`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,A,{query:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/assistants/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ei=class extends F{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ti=class extends F{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},ni=class extends F{constructor(){super(...arguments),this.sessions=new ei(this._client),this.transcriptionSessions=new ti(this._client)}};ni.Sessions=ei,ni.TranscriptionSessions=ti;var ri=class extends F{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/chatkit/sessions/${e}/cancel`,{...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},ii=class extends F{retrieve(e,t){return this._client.get(I`/chatkit/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,j,{query:e,...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/chatkit/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(I`/chatkit/threads/${e}/items`,j,{query:t,...n,headers:N([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},ai=class extends F{constructor(){super(...arguments),this.sessions=new ri(this._client),this.threads=new ii(this._client)}};ai.Sessions=ri,ai.Threads=ii;var oi=class extends F{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(I`/responses/${e}/input_items?beta=true`,A,{query:i,...n,headers:N([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}},si=class extends F{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:N([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},ci=class extends F{constructor(){super(...arguments),this.inputItems=new oi(this._client),this.inputTokens=new si(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:N([{...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(I`/responses/${e}?beta=true`,{query:i,...n,headers:N([{...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(I`/responses/${e}?beta=true`,{...n,headers:N([{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(I`/responses/${e}/cancel?beta=true`,{...n,headers:N([{...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:N([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}};ci.InputItems=oi,ci.InputTokens=si;var li=class extends F{create(e,t,n){return this._client.post(I`/threads/${e}/messages`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(I`/threads/${r}/messages/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(I`/threads/${r}/messages/${e}`,{body:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/threads/${e}/messages`,A,{query:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(I`/threads/${r}/messages/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},ui=class extends F{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(I`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(I`/threads/${r}/runs/${e}/steps`,A,{query:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},di=e();const fi=e=>{if(di.Buffer!==void 0){let t=di.Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},pi=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var K,mi,hi,q,gi,J,_i,vi,yi,bi,Y,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni=class extends Pn{constructor(){super(...arguments),K.add(this),hi.set(this,[]),q.set(this,{}),gi.set(this,{}),J.set(this,void 0),_i.set(this,void 0),vi.set(this,void 0),yi.set(this,void 0),bi.set(this,void 0),Y.set(this,void 0),xi.set(this,void 0),Si.set(this,void 0),Ci.set(this,void 0)}[(hi=new WeakMap,q=new WeakMap,gi=new WeakMap,J=new WeakMap,_i=new WeakMap,vi=new WeakMap,yi=new WeakMap,bi=new WeakMap,Y=new WeakMap,xi=new WeakMap,Si=new WeakMap,Ci=new WeakMap,K=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=structuredClone(n),i=t.shift();i?i.resolve(r):e.push(r)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new mi;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=st.fromReadableStream(e,this.controller);for await(let e of n)a(this,K,`m`,wi).call(this,e);if(n.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}toReadableStream(){return new st(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new mi;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},o=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of o)a(this,K,`m`,wi).call(this,e);if(o.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}static createThreadAssistantStream(e,t,n){let r=new mi;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new mi;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return a(this,xi,`f`)}currentRun(){return a(this,Si,`f`)}currentMessageSnapshot(){return a(this,J,`f`)}currentRunStepSnapshot(){return a(this,Ci,`f`)}async finalRunSteps(){return await this.done(),Object.values(a(this,q,`f`))}async finalMessages(){return await this.done(),Object.values(a(this,gi,`f`))}async finalRun(){if(await this.done(),!a(this,_i,`f`))throw Error(`Final run was not received.`);return a(this,_i,`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)a(this,K,`m`,wi).call(this,e);if(i.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},o=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of o)a(this,K,`m`,wi).call(this,e);if(o.controller.signal?.aborted)throw new d;return this._addRun(a(this,K,`m`,Ti).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(ue(t)&&ue(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!ue(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t[n]=e:t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};mi=Ni,wi=function(e){if(!this.ended)switch(i(this,xi,e,`f`),a(this,K,`m`,Oi).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`:a(this,K,`m`,Mi).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`:a(this,K,`m`,Di).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`:a(this,K,`m`,Ei).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},Ti=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);if(!a(this,_i,`f`))throw Error(`Final run has not been received`);return a(this,_i,`f`)},Ei=function(e){let[t,n]=a(this,K,`m`,Ai).call(this,e,a(this,J,`f`));i(this,J,t,`f`),a(this,gi,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`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`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=a(this,vi,`f`)){if(a(this,yi,`f`))switch(a(this,yi,`f`).type){case`text`:this._emit(`textDone`,a(this,yi,`f`).text,a(this,J,`f`));break;case`image_file`:this._emit(`imageFileDone`,a(this,yi,`f`).image_file,a(this,J,`f`));break}i(this,vi,n.index,`f`)}i(this,yi,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(a(this,vi,`f`)!==void 0){let t=e.data.content[a(this,vi,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,a(this,J,`f`));break;case`text`:this._emit(`textDone`,t.text,a(this,J,`f`));break}}a(this,J,`f`)&&this._emit(`messageDone`,e.data),i(this,J,void 0,`f`)}},Di=function(e){let t=a(this,K,`m`,ki).call(this,e);switch(i(this,Ci,t,`f`),e.event){case`thread.run.step.created`:this._emit(`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==a(this,bi,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(a(this,Y,`f`)&&this._emit(`toolCallDone`,a(this,Y,`f`)),i(this,bi,e.index,`f`),i(this,Y,t.step_details.tool_calls[e.index],`f`),a(this,Y,`f`)&&this._emit(`toolCallCreated`,a(this,Y,`f`)));this._emit(`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`:i(this,Ci,void 0,`f`),e.data.step_details.type==`tool_calls`&&a(this,Y,`f`)&&(this._emit(`toolCallDone`,a(this,Y,`f`)),i(this,Y,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},Oi=function(e){a(this,hi,`f`).push(e),this._emit(`event`,e)},ki=function(e){switch(e.event){case`thread.run.step.created`:return a(this,q,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=a(this,q,`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=mi.accumulateDelta(t,n.delta);a(this,q,`f`)[e.data.id]=r}return a(this,q,`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`:a(this,q,`f`)[e.data.id]=e.data;break}if(a(this,q,`f`)[e.data.id])return a(this,q,`f`)[e.data.id];throw Error(`No snapshot available`)},Ai=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)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=a(this,K,`m`,ji).call(this,e,n)}else t.content[e.index]=e,n.push(e);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`)},ji=function(e,t){return mi.accumulateDelta(t,e)},Mi=function(e){switch(i(this,Si,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`:i(this,_i,e.data,`f`),a(this,Y,`f`)&&(this._emit(`toolCallDone`,a(this,Y,`f`)),i(this,Y,void 0,`f`));break;case`thread.run.cancelling`:break}};var Pi=class extends F{constructor(){super(...arguments),this.steps=new ui(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(I`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:N([{"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(I`/threads/${r}/runs/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(I`/threads/${r}/runs/${e}`,{body:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/threads/${e}/runs`,A,{query:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(I`/threads/${r}/runs/${e}/cancel`,{...n,headers:N([{"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 Ni.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=N([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 pe(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Ni.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(I`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:N([{"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 Ni.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Pi.Steps=ui;var Fi=class extends F{constructor(){super(...arguments),this.runs=new Pi(this._client),this.messages=new li(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/threads/${e}`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:N([{"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 Ni.createThreadAssistantStream(e,this._client.beta.threads,t)}};Fi.Runs=Pi,Fi.Messages=li;var Ii=class extends F{constructor(){super(...arguments),this.realtime=new ni(this._client),this.responses=new ci(this._client),this.chatkit=new ai(this._client),this.assistants=new $r(this._client),this.threads=new Fi(this._client)}};Ii.Realtime=ni,Ii.Responses=ci,Ii.ChatKit=ai,Ii.Assistants=$r,Ii.Threads=Fi;var Li=class extends F{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Ri=class extends F{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(I`/containers/${r}/files/${e}/content`,{...n,headers:N([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},zi=class extends F{constructor(){super(...arguments),this.content=new Ri(this._client)}create(e,t,n){return this._client.post(I`/containers/${e}/files`,jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(I`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/containers/${e}/files`,A,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(I`/containers/${r}/files/${e}`,{...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};zi.Content=Ri;var Bi=class extends F{constructor(){super(...arguments),this.files=new zi(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/containers/${e}`,{...t,headers:N([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};Bi.Files=zi;var Vi=class extends F{create(e,t){return this._client.post(`/content_provenance_checks`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}},Hi=class extends F{create(e,t,n){let{include:r,...i}=t;return this._client.post(I`/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(I`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/conversations/${e}/items`,j,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(I`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},Ui=class extends F{constructor(){super(...arguments),this.items=new Hi(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Ui.Items=Hi;var Wi=class extends F{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=fi(t)}),e)))}},Gi=class extends F{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(I`/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(I`/evals/${r}/runs/${e}/output_items`,A,{query:i,...n,__security:{bearerAuth:!0}})}},Ki=class extends F{constructor(){super(...arguments),this.outputItems=new Gi(this._client)}create(e,t,n){return this._client.post(I`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/evals/${e}/runs`,A,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(I`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Ki.OutputItems=Gi;var qi=class extends F{constructor(){super(...arguments),this.runs=new Ki(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};qi.Runs=Ki;var Ji=class extends F{create(e,t){return this._client.post(`/files`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(I`/files/${e}/content`,{...t,headers:N([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await pe(t),a=await this.retrieve(e),Date.now()-i>n)throw new p({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Yi=class extends F{},Xi=class extends F{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},Zi=class extends F{constructor(){super(...arguments),this.graders=new Xi(this._client)}};Zi.Graders=Xi;var Qi=class extends F{create(e,t,n){return this._client.getAPIList(I`/fine_tuning/checkpoints/${e}/permissions`,yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(I`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/fine_tuning/checkpoints/${e}/permissions`,j,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(I`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},$i=class extends F{constructor(){super(...arguments),this.permissions=new Qi(this._client)}};$i.Permissions=Qi;var ea=class extends F{list(e,t={},n){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/checkpoints`,A,{query:t,...n,__security:{bearerAuth:!0}})}},ta=class extends F{constructor(){super(...arguments),this.checkpoints=new ea(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(I`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,A,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/events`,A,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(I`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};ta.Checkpoints=ea;var na=class extends F{constructor(){super(...arguments),this.methods=new Yi(this._client),this.jobs=new ta(this._client),this.checkpoints=new $i(this._client),this.alpha=new Zi(this._client)}};na.Methods=Yi,na.Jobs=ta,na.Checkpoints=$i,na.Alpha=Zi;var ra=class extends F{},ia=class extends F{constructor(){super(...arguments),this.graderModels=new ra(this._client)}};ia.GraderModels=ra;var aa=class extends F{createVariation(e,t){return this._client.post(`/images/variations`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,P({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},oa=class extends F{retrieve(e,t){return this._client.get(I`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,yt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},sa=class extends F{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}},ca=class extends F{accept(e,t,n){return this._client.post(I`/realtime/calls/${e}/accept`,{body:t,...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(I`/realtime/calls/${e}/hangup`,{...t,headers:N([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(I`/realtime/calls/${e}/refer`,{body:t,...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(I`/realtime/calls/${e}/reject`,{body:t,...n,headers:N([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},la=class extends F{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},ua=class extends F{constructor(){super(...arguments),this.clientSecrets=new la(this._client),this.calls=new ca(this._client)}};ua.ClientSecrets=la,ua.Calls=ca;function da(e,t){if(!t||!ma(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 va(e,t)&&X(t),t}return fa(e,t)}function fa(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?_a(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?pa(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return va(e,i)&&X(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 pa(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function ma(e){return cn(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>ha(e)||e.type===`function`&&e.strict===!0)}function ha(e){return e?.$brand===`auto-parseable-tool`}function ga(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function _a(e,t){let n=ga(e.tools??[],t.name);return{...t,...t,parsed_arguments:ha(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function va(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function X(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(``)}function ya(e,t){if(!t){if(e.type!==`response.created`)throw new l(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return ba(e.response)}switch(e.type){case`response.output_item.added`:t.output.push(structuredClone(e.item)),e.item.type===`message`&&X(t);break;case`response.output_item.done`:Z(t,e.output_index),t.output[e.output_index]=structuredClone(e.item),e.item.type===`message`&&X(t);break;case`response.content_part.added`:{let n=Z(t,e.output_index),r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?(n.content.push(structuredClone(i)),i.type===`output_text`&&X(t)):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(structuredClone(i)));break}case`response.content_part.done`:{let n=Z(t,e.output_index),r=e.part;if(n.type===`message`&&r.type!==`reasoning_text`)Q(n.content,e.content_index),n.content[e.content_index]=structuredClone(r),r.type===`output_text`&&X(t);else if(n.type===`reasoning`&&r.type===`reasoning_text`){let t=n.content;if(!t)throw new l(`missing content at index ${e.content_index}`);Q(t,e.content_index),t[e.content_index]=structuredClone(r)}break}case`response.output_text.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let r=Q(n.content,e.content_index);if(r.type!==`output_text`)throw new l(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta,t.output_text+=e.delta}break}case`response.output_text.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let r=Q(n.content,e.content_index);if(r.type!==`output_text`)throw new l(`expected content to be 'output_text', got ${r.type}`);r.text=e.text,X(t)}break}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 l(`expected content to be 'output_text', got ${t.type}`);t.annotations[e.annotation_index]=structuredClone(e.annotation)}break}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 l(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}break}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 l(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}break}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);n.type===`function_call`&&(n.arguments=e.arguments);break}case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new l(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new l(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new l(`missing content at index ${e.content_index}`);let t=Q(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new l(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}break}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);n.type===`reasoning`&&n.summary.push(structuredClone(e.part));break}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);n.type===`reasoning`&&(Q(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part));break}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}break}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}break}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);n.type===`custom_tool_call`&&(n.input+=e.delta);break}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);n.type===`custom_tool_call`&&(n.input=e.input);break}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.arguments+=e.delta);break}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.arguments=e.arguments);break}case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta);break}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=e.code);break}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`in_progress`);break}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`interpreting`);break}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`completed`);break}case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`in_progress`);break}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`searching`);break}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);n.type===`file_search_call`&&(n.status=`completed`);break}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`in_progress`);break}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`searching`);break}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);n.type===`web_search_call`&&(n.status=`completed`);break}case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`in_progress`);break}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`generating`);break}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);n.type===`image_generation_call`&&(n.status=`completed`);break}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`in_progress`);break}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`completed`);break}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);n.type===`mcp_call`&&(n.status=`failed`);break}case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:t=ba(e.response);break;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`:break;default:xa(e)}return t}function ba(e){let t=structuredClone(e);return(!Object.getOwnPropertyDescriptor(t,`output_text`)||t.output_text==null)&&X(t),t}function Z(e,t){let n=e.output[t];if(!n)throw new l(`missing output at index ${t}`);return n}function Q(e,t){let n=e[t];if(!n)throw new l(`missing content at index ${t}`);return n}function xa(e){throw new l(`Unhandled response stream event: ${JSON.stringify(e)}`)}var Sa,Ca,wa,Ta,Ea,Da,Oa,ka=class e extends Pn{constructor(e){super(),Sa.add(this),Ca.set(this,void 0),wa.set(this,void 0),Ta.set(this,void 0),i(this,Ca,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`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),a(this,Sa,`m`,Ea).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)a(this,Sa,`m`,Da).call(this,e,i);if(r.controller.signal?.aborted)throw new d;return a(this,Sa,`m`,Oa).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),a(this,Sa,`m`,Ea).call(this),this._connected();let n=st.fromReadableStream(e,this.controller);for await(let e of n)a(this,Sa,`m`,Da).call(this,e,null);if(n.controller.signal?.aborted)throw new d;return a(this,Sa,`m`,Oa).call(this)}[(Ca=new WeakMap,wa=new WeakMap,Ta=new WeakMap,Sa=new WeakSet,Ea=function(){this.ended||i(this,wa,void 0,`f`)},Da=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=ya(e,a(this,wa,`f`));switch(i(this,wa,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new l(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new l(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new l(`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 l(`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);break}},Oa=function(){if(this.ended)throw new l(`stream has ended, this shouldn't happen`);let e=a(this,wa,`f`);if(!e)throw new l(`request ended without sending any events`);i(this,wa,void 0,`f`);let t=Aa(e,a(this,Ca,`f`));return i(this,Ta,t,`f`),t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=a(this,Ta,`f`);if(!e)throw new l(`stream ended without producing a ChatCompletion`);return e}};function Aa(e,t){return da(e,t)}var ja=class extends F{list(e,t={},n){return this._client.getAPIList(I`/responses/${e}/input_items`,A,{query:t,...n,__security:{bearerAuth:!0}})}},Ma=class extends F{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},Na=class extends F{constructor(){super(...arguments),this.inputItems=new ja(this._client),this.inputTokens=new Ma(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`&&X(e),e))}retrieve(e,t={},n){return this._client.get(I`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&X(e),e))}delete(e,t){return this._client.delete(I`/responses/${e}`,{...t,headers:N([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>fa(t,e))}stream(e,t){return ka.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(I`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};Na.InputItems=ja,Na.InputTokens=Ma;var Pa=class extends F{retrieve(e,t){return this._client.get(I`/skills/${e}/content`,{...t,headers:N([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Fa=class extends F{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(I`/skills/${r}/versions/${e}/content`,{...n,headers:N([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Ia=class extends F{constructor(){super(...arguments),this.content=new Fa(this._client)}create(e,t={},n){return this._client.post(I`/skills/${e}/versions`,jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(I`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/skills/${e}/versions`,A,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(I`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};Ia.Content=Fa;var La=class extends F{constructor(){super(...arguments),this.content=new Pa(this._client),this.versions=new Ia(this._client)}create(e={},t){return this._client.post(`/skills`,jt({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,A,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};La.Content=Pa,La.Versions=Ia;var Ra=class extends F{create(e,t,n){return this._client.post(I`/uploads/${e}/parts`,P({body:t,...n,__security:{bearerAuth:!0}},this._client))}},za=class extends F{constructor(){super(...arguments),this.parts=new Ra(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(I`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(I`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};za.Parts=Ra;const Ba=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r};var Va=class extends F{create(e,t,n){return this._client.post(I`/vector_stores/${e}/file_batches`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(I`/vector_stores/${r}/file_batches/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(I`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(I`/vector_stores/${r}/file_batches/${e}/files`,A,{query:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=N([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 pe(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 Ba(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},Ha=class extends F{create(e,t,n){return this._client.post(I`/vector_stores/${e}/files`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(I`/vector_stores/${r}/files/${e}`,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(I`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(I`/vector_stores/${e}/files`,A,{query:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(I`/vector_stores/${r}/files/${e}`,{...n,headers:N([{"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=N([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 pe(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(I`/vector_stores/${r}/files/${e}/content`,yt,{...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Ua=class extends F{constructor(){super(...arguments),this.files=new Ha(this._client),this.fileBatches=new Va(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(I`/vector_stores/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(I`/vector_stores/${e}`,{body:t,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,A,{query:e,...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/vector_stores/${e}`,{...t,headers:N([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(I`/vector_stores/${e}/search`,yt,{body:t,method:`post`,...n,headers:N([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};Ua.Files=Ha,Ua.FileBatches=Va;var Wa=class extends F{create(e,t){return this._client.post(`/videos`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(I`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,j,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(I`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(I`/videos/${e}/content`,{query:t,...n,headers:N([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,P({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(I`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(I`/videos/${e}/remix`,jt({body:t,...n,__security:{bearerAuth:!0}},this._client))}},Ga,Ka,qa,Ja=class extends F{constructor(){super(...arguments),Ga.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");a(this,Ga,`m`,Ka).call(this,n);let i=N([t]).values,o=a(this,Ga,`m`,qa).call(this,i,`webhook-signature`),s=a(this,Ga,`m`,qa).call(this,i,`webhook-timestamp`),c=a(this,Ga,`m`,qa).call(this,i,`webhook-id`),l=parseInt(s,10);if(isNaN(l))throw new S(`Invalid webhook timestamp format`);let u=Math.floor(Date.now()/1e3);if(u-l>r)throw new S(`Webhook timestamp is too old`);if(l>u+r)throw new S(`Webhook timestamp is too new`);let d=o.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),f=n.startsWith(`whsec_`)?di.Buffer.from(n.replace(`whsec_`,``),`base64`):di.Buffer.from(n,`utf-8`),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey(`raw`,f,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of d)try{let t=di.Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,m,t,new TextEncoder().encode(p)))return}catch{continue}throw new S(`The given webhook signature does not match the expected signature`)}};Ga=new WeakSet,Ka=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`)},qa=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};const Ya=Symbol.for(`openai.node.providerDefinitions.v1`),Xa=globalThis,Za=Xa[Ya],Qa=Za??new WeakMap;Za||Object.defineProperty(Xa,Ya,{value:Qa});function $a(e){let t=Qa.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var eo,to,no,ro,$=class{constructor(e={}){eo.add(this),no.set(this,void 0),this.completions=new Li(this),this.chat=new _r(this),this.embeddings=new Wi(this),this.files=new Ji(this),this.images=new aa(this),this.contentProvenanceChecks=new Vi(this),this.audio=new Zr(this),this.moderations=new sa(this),this.models=new oa(this),this.fineTuning=new na(this),this.graders=new ia(this),this.vectorStores=new Ua(this),this.webhooks=new Ja(this),this.beta=new Ii(this),this.batches=new Qr(this),this.uploads=new za(this),this.admin=new qr(this),this.responses=new Na(this),this.realtime=new ua(this),this.conversations=new Ui(this),this.evals=new qi(this),this.containers=new Bi(this),this.skills=new La(this),this.videos=new Wa(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new l(`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:pi(`OPENAI_BASE_URL`),apiKey:r=t?null:pi(`OPENAI_API_KEY`)??null,adminAPIKey:a=t?null:pi(`OPENAI_ADMIN_KEY`)??null,organization:o=t?null:pi(`OPENAI_ORG_ID`)??null,project:s=t?null:pi(`OPENAI_PROJECT_ID`)??null,webhookSecret:c=pi(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:u,...d}=e,f=t?$a(t):void 0,p={apiKey:r,adminAPIKey:a,organization:o,project:s,webhookSecret:c,workloadIdentity:u,provider:t,...d,baseURL:f?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&u)throw new l("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!f&&!r&&!a&&!u)throw new l("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!p.dangerouslyAllowBrowser&&he())throw new l(`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,
@@ -15,4 +15,4 @@ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
15
15
 
16
16
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
17
17
  `);this.baseURL=p.baseURL,this.timeout=p.timeout??to.DEFAULT_TIMEOUT,this.logger=p.logger??console;let m=`warn`;this.logLevel=m,this.logLevel=et(p.logLevel,`ClientOptions.logLevel`,this)??et(pi(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??m,this.fetchOptions=p.fetchOptions,this.maxRetries=p.maxRetries??2,this.fetch=p.fetch??Ce(),i(this,no,Oe,`f`);let h=t?void 0:pi(`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())}p.defaultHeaders=N([e,p.defaultHeaders])}this._options=p,this._provider=f,u&&(this._workloadIdentityAuth=new xt(u,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=a,this.organization=o,this.project=s,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 N([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return N([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return N([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return N([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ge(e)}getUserAgent(){return`${this.constructor.name}/JS ${me}`}defaultIdempotencyKey(){return`stainless-node-retry-${o()}`}makeStatusError(e,t,n,r){return u.generate(e,t,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 l?e:new l(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new l(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!a(this,eo,`m`,ro).call(this)&&n||this.baseURL,i=ae(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(i.searchParams);return(!ce(o)||!ce(s))&&(t={...s,...o,...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 new ht(this,this.makeRequest(e,t,void 0))}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:l}=await this.buildRequest(r,{retryCount:i-t}),u=r.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let m=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),h=n===void 0?``:`, retryOf: ${n}`,g=Date.now();if(k(this).debug(`[${m}] sending request`,at({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new d;let _=r.__security??{bearerAuth:!0},v=new AbortController,y=await this.fetchWithAuth(o,a,l,v,_).catch(c),b=Date.now();if(y instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new d;let i=s(y)||/timed? ?out/i.test(String(y)+(`cause`in y?String(y.cause):``));if(t&&!u)return k(this).info(`[${m}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${m}] connection ${i?`timed out`:`failed`} (${e})`,at({retryOfRequestLogID:n,url:o,durationMs:b-g,message:y.message})),this.retryRequest(r,t,n??m);let a=u?`error; streaming body cannot be retried`:`error; no more retries left`;throw k(this).info(`[${m}] connection ${i?`timed out`:`failed`} - ${a}`),k(this).debug(`[${m}] connection ${i?`timed out`:`failed`} (${a})`,at({retryOfRequestLogID:n,url:o,durationMs:b-g,message:y.message})),y instanceof ne||y instanceof re?y:i?new p:new f({message:io(y),cause:y})}let x=`[${m}${h}${[...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-g}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await De(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??m);let e=await this.shouldRetry(y);if(t&&e&&!u){let e=`retrying, ${t} attempts remaining`;return await De(y.body),k(this).info(`${x} - ${e}`),k(this).debug(`[${m}] response error (${e})`,at({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-g})),this.retryRequest(r,t,n??m,y.headers)}let i=e?u?`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=>c(e).message),o=fe(a),s=o?void 0:a;throw k(this).debug(`[${m}] response error (${i})`,at({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:s,durationMs:Date.now()-g})),this.makeStatusError(y.status,o,s,y.headers)}return k(this).info(x),k(this).debug(`[${m}] response start`,at({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-g})),{response:y,options:r,controller:v,requestLogID:m,retryOfRequestLogID:n,startTime:g}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new vt(this,n,e)}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 workload-identity-auth`){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);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await pe(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&&de(`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=N([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Se(),"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(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...a(this,no,`f`).call(this,{body:t,headers:N([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=N([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,o=!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:!o}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:Te(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}:{...a(this,no,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};to=$,no=new WeakMap,eo=new WeakSet,ro=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=to,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=l,$.APIError=u,$.APIConnectionError=f,$.APIConnectionTimeoutError=p,$.APIUserAbortError=d,$.NotFoundError=_,$.ConflictError=v,$.RateLimitError=b,$.BadRequestError=m,$.AuthenticationError=h,$.InternalServerError=x,$.PermissionDeniedError=g,$.UnprocessableEntityError=y,$.InvalidWebhookSignatureError=S,$.toFile=en,$.toStreamingFile=Et,$.Completions=Li,$.Chat=_r,$.Embeddings=Wi,$.Files=Ji,$.Images=aa,$.ContentProvenanceChecks=Vi,$.Audio=Zr,$.Moderations=sa,$.Models=oa,$.FineTuning=na,$.Graders=ia,$.VectorStores=Ua,$.Webhooks=Ja,$.Beta=Ii,$.Batches=Qr,$.Uploads=za,$.Admin=qr,$.Responses=Na,$.Realtime=ua,$.Conversations=Ui,$.Evals=qi,$.Containers=Bi,$.Skills=La,$.Videos=Wa;function io(e){if(ao(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 ao(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}e();var oo=class extends r{#e;constructor(e){super(e.modelName||n.openai.modelName),this.config=e,this.openai=new $({apiKey:e.apiKey,dangerouslyAllowBrowser:!0})}static availability(e={}){if(e.expectedInputs){let t=e.expectedInputs.some(e=>e.type===`audio`),n=e.expectedInputs.some(e=>e.type===`image`);if(t&&n)return`unavailable`}return`available`}convertSchema(e){if(typeof e!=`object`||!e)return{schema:e,wrapped:!1};let t=e=>{if(e.type===`object`)if(e.properties){e.additionalProperties=!1,e.required=Object.keys(e.properties);for(let n in e.properties)t(e.properties[n])}else e.additionalProperties=!1,e.required=[];else e.type===`array`&&e.items&&t(e.items);return e},n=JSON.parse(JSON.stringify(e));return n.type===`object`?{wrapped:!1,schema:t(n)}:{wrapped:!0,schema:{type:`object`,properties:{value:n},required:[`value`],additionalProperties:!1}}}createSession(e,t){this.#e={model:e.modelName||this.modelName,systemInstruction:t.systemInstruction};let n=t.generationConfig||{};if(n.responseSchema){let{schema:e,wrapped:t}=n.responseSchema;this.#e.response_format={type:`json_schema`,json_schema:{name:`response`,strict:!0,schema:e}},this.#e.response_wrapped=t}else n.responseMimeType===`application/json`&&(this.#e.response_format={type:`json_object`});return this.#e}#t(e){let t=!1,n=!1;for(let r of e)if(Array.isArray(r.content))for(let e of r.content)e.type===`image_url`&&(t=!0),e.type===`input_audio`&&(n=!0);if(t&&n)throw Error(`OpenAI backend does not support mixing images and audio in the same session. Please start a new session.`);return{hasImage:t,hasAudio:n}}#n(e){return this.#e.model===this.modelName?e?`${this.modelName}-audio-preview`:this.modelName:this.#e.model}async generateContent(e){let{messages:t}=this.#r(e,this.#e.systemInstruction),{hasAudio:n}=this.#t(t),r=this.#n(n);if(r===`${this.modelName}-audio-preview`&&this.#e.response_format)throw new DOMException(`OpenAI audio model ('${r}') does not support structured outputs (responseConstraint).`,`NotSupportedError`);let i={model:r,messages:t};this.#e.temperature>0&&(i.temperature=this.#e.temperature),this.#e.response_format&&(i.response_format=this.#e.response_format);try{let e=await this.openai.chat.completions.create(i),t=e.choices[0].message.content;if(this.#e.response_wrapped&&t)try{let e=JSON.parse(t);e&&typeof e==`object`&&`value`in e&&(t=JSON.stringify(e.value))}catch{}let n=e.usage?.prompt_tokens||0;return{text:t,usage:n}}catch(e){throw console.error(`OpenAI Generate Content Error:`,e),e}}async generateContentStream(e){let{messages:t}=this.#r(e,this.#e.systemInstruction),{hasAudio:n}=this.#t(t),r=this.#n(n);if(r===`${this.modelName}-audio-preview`&&this.#e.response_format)throw new DOMException(`OpenAI audio model ('${r}') does not support structured outputs (responseConstraint).`,`NotSupportedError`);let i={model:r,messages:t,stream:!0};this.#e.temperature>0&&(i.temperature=this.#e.temperature),this.#e.response_format&&(i.response_format=this.#e.response_format);try{let e=await this.openai.chat.completions.create(i);return(async function*(){for await(let t of e){let e=t.choices[0]?.delta?.content;e&&(yield{text:()=>e,usageMetadata:{totalTokenCount:0}})}})()}catch(e){throw console.error(`OpenAI Generate Content Stream Error:`,e),e}}async countTokens(e){let t=``;if(Array.isArray(e)){for(let n of e)if(n.parts)for(let e of n.parts)e.text?t+=e.text:e.inlineData&&(t+=` `.repeat(1e3))}return Math.ceil(t.length/4)}#r(e,t){let n=[];t&&n.push({role:`system`,content:t});for(let t of e){let e=t.role===`model`?`assistant`:`user`,r=[];for(let e of t.parts)if(e.text)r.push({type:`text`,text:e.text});else if(e.inlineData){let{data:t,mimeType:n}=e.inlineData;n.startsWith(`image/`)?r.push({type:`image_url`,image_url:{url:`data:${n};base64,${t}`}}):n.startsWith(`audio/`)&&r.push({type:`input_audio`,input_audio:{data:t,format:n.split(`/`)[1]===`mpeg`?`mp3`:`wav`}})}n.push({role:e,content:r})}return{messages:n}}};export{oo as default};
18
+ `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}p.defaultHeaders=N([e,p.defaultHeaders])}this._options=p,this._provider=f,u&&(this._workloadIdentityAuth=new xt(u,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=a,this.organization=o,this.project=s,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 N([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return N([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return N([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return N([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ge(e)}getUserAgent(){return`${this.constructor.name}/JS ${me}`}defaultIdempotencyKey(){return`stainless-node-retry-${o()}`}makeStatusError(e,t,n,r){return u.generate(e,t,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 l?e:new l(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new l(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!a(this,eo,`m`,ro).call(this)&&n||this.baseURL,i=ae(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(i.searchParams);return(!ce(o)||!ce(s))&&(t={...s,...o,...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 new ht(this,this.makeRequest(e,t,void 0))}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:l}=await this.buildRequest(r,{retryCount:i-t}),u=r.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let m=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),h=n===void 0?``:`, retryOf: ${n}`,g=Date.now();if(k(this).debug(`[${m}] sending request`,at({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new d;let _=r.__security??{bearerAuth:!0},v=new AbortController,y=await this.fetchWithAuth(o,a,l,v,_).catch(c),b=Date.now();if(y instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new d;let i=s(y)||/timed? ?out/i.test(String(y)+(`cause`in y?String(y.cause):``));if(t&&!u)return k(this).info(`[${m}] connection ${i?`timed out`:`failed`} - ${e}`),k(this).debug(`[${m}] connection ${i?`timed out`:`failed`} (${e})`,at({retryOfRequestLogID:n,url:o,durationMs:b-g,message:y.message})),this.retryRequest(r,t,n??m);let a=u?`error; streaming body cannot be retried`:`error; no more retries left`;throw k(this).info(`[${m}] connection ${i?`timed out`:`failed`} - ${a}`),k(this).debug(`[${m}] connection ${i?`timed out`:`failed`} (${a})`,at({retryOfRequestLogID:n,url:o,durationMs:b-g,message:y.message})),y instanceof ne||y instanceof re?y:i?new p:new f({message:io(y),cause:y})}let x=`[${m}${h}${[...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-g}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&_.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await De(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??m);let e=await this.shouldRetry(y);if(t&&e&&!u){let e=`retrying, ${t} attempts remaining`;return await De(y.body),k(this).info(`${x} - ${e}`),k(this).debug(`[${m}] response error (${e})`,at({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-g})),this.retryRequest(r,t,n??m,y.headers)}let i=e?u?`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=>c(e).message),o=fe(a),s=o?void 0:a;throw k(this).debug(`[${m}] response error (${i})`,at({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,message:s,durationMs:Date.now()-g})),this.makeStatusError(y.status,o,s,y.headers)}return k(this).info(x),k(this).debug(`[${m}] response start`,at({retryOfRequestLogID:n,url:y.url,status:y.status,headers:y.headers,durationMs:b-g})),{response:y,options:r,controller:v,requestLogID:m,retryOfRequestLogID:n,startTime:g}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new vt(this,n,e)}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 workload-identity-auth`){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);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await pe(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&&de(`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=N([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Se(),"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(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...a(this,no,`f`).call(this,{body:t,headers:N([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=N([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,o=!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:!o}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:Te(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}:{...a(this,no,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};to=$,no=new WeakMap,eo=new WeakSet,ro=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=to,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=l,$.APIError=u,$.APIConnectionError=f,$.APIConnectionTimeoutError=p,$.APIUserAbortError=d,$.NotFoundError=_,$.ConflictError=v,$.RateLimitError=b,$.BadRequestError=m,$.AuthenticationError=h,$.InternalServerError=x,$.PermissionDeniedError=g,$.UnprocessableEntityError=y,$.InvalidWebhookSignatureError=S,$.toFile=en,$.toStreamingFile=Et,$.Completions=Li,$.Chat=_r,$.Embeddings=Wi,$.Files=Ji,$.Images=aa,$.ContentProvenanceChecks=Vi,$.Audio=Zr,$.Moderations=sa,$.Models=oa,$.FineTuning=na,$.Graders=ia,$.VectorStores=Ua,$.Webhooks=Ja,$.Beta=Ii,$.Batches=Qr,$.Uploads=za,$.Admin=qr,$.Responses=Na,$.Realtime=ua,$.Conversations=Ui,$.Evals=qi,$.Containers=Bi,$.Skills=La,$.Videos=Wa;function io(e){if(ao(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 ao(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}t();var oo=class extends r{#e;constructor(e){super(e.modelName||n.openai.modelName),this.config=e,this.openai=new $({apiKey:e.apiKey,dangerouslyAllowBrowser:!0})}static availability(e={}){if(e.expectedInputs){let t=e.expectedInputs.some(e=>e.type===`audio`),n=e.expectedInputs.some(e=>e.type===`image`);if(t&&n)return`unavailable`}return`available`}convertSchema(e){if(typeof e!=`object`||!e)return{schema:e,wrapped:!1};let t=e=>{if(e.type===`object`)if(e.properties){e.additionalProperties=!1,e.required=Object.keys(e.properties);for(let n in e.properties)t(e.properties[n])}else e.additionalProperties=!1,e.required=[];else e.type===`array`&&e.items&&t(e.items);return e},n=JSON.parse(JSON.stringify(e));return n.type===`object`?{wrapped:!1,schema:t(n)}:{wrapped:!0,schema:{type:`object`,properties:{value:n},required:[`value`],additionalProperties:!1}}}createSession(e,t){this.#e={model:e.modelName||this.modelName,systemInstruction:t.systemInstruction};let n=t.generationConfig||{};if(n.responseSchema){let{schema:e,wrapped:t}=n.responseSchema;this.#e.response_format={type:`json_schema`,json_schema:{name:`response`,strict:!0,schema:e}},this.#e.response_wrapped=t}else n.responseMimeType===`application/json`&&(this.#e.response_format={type:`json_object`});return this.#e}#t(e){let t=!1,n=!1;for(let r of e)if(Array.isArray(r.content))for(let e of r.content)e.type===`image_url`&&(t=!0),e.type===`input_audio`&&(n=!0);if(t&&n)throw Error(`OpenAI backend does not support mixing images and audio in the same session. Please start a new session.`);return{hasImage:t,hasAudio:n}}#n(e){return this.#e.model===this.modelName?e?`${this.modelName}-audio-preview`:this.modelName:this.#e.model}async generateContent(e){let{messages:t}=this.#r(e,this.#e.systemInstruction),{hasAudio:n}=this.#t(t),r=this.#n(n);if(r===`${this.modelName}-audio-preview`&&this.#e.response_format)throw new DOMException(`OpenAI audio model ('${r}') does not support structured outputs (responseConstraint).`,`NotSupportedError`);let i={model:r,messages:t};this.#e.temperature>0&&(i.temperature=this.#e.temperature),this.#e.response_format&&(i.response_format=this.#e.response_format);try{let e=await this.openai.chat.completions.create(i),t=e.choices[0].message.content;if(this.#e.response_wrapped&&t)try{let e=JSON.parse(t);e&&typeof e==`object`&&`value`in e&&(t=JSON.stringify(e.value))}catch{}let n=e.usage?.prompt_tokens||0;return{text:t,usage:n}}catch(e){throw console.error(`OpenAI Generate Content Error:`,e),e}}async generateContentStream(e){let{messages:t}=this.#r(e,this.#e.systemInstruction),{hasAudio:n}=this.#t(t),r=this.#n(n);if(r===`${this.modelName}-audio-preview`&&this.#e.response_format)throw new DOMException(`OpenAI audio model ('${r}') does not support structured outputs (responseConstraint).`,`NotSupportedError`);let i={model:r,messages:t,stream:!0};this.#e.temperature>0&&(i.temperature=this.#e.temperature),this.#e.response_format&&(i.response_format=this.#e.response_format);try{let e=await this.openai.chat.completions.create(i);return(async function*(){for await(let t of e){let e=t.choices[0]?.delta?.content;e&&(yield{text:()=>e,usageMetadata:{totalTokenCount:0}})}})()}catch(e){throw console.error(`OpenAI Generate Content Stream Error:`,e),e}}async countTokens(e){let t=``;if(Array.isArray(e)){for(let n of e)if(n.parts)for(let e of n.parts)e.text?t+=e.text:e.inlineData&&(t+=` `.repeat(1e3))}return Math.ceil(t.length/4)}#r(e,t){let n=[];t&&n.push({role:`system`,content:t});for(let t of e){let e=t.role===`model`?`assistant`:`user`,r=[];for(let e of t.parts)if(e.text)r.push({type:`text`,text:e.text});else if(e.inlineData){let{data:t,mimeType:n}=e.inlineData;n.startsWith(`image/`)?r.push({type:`image_url`,image_url:{url:`data:${n};base64,${t}`}}):n.startsWith(`audio/`)&&r.push({type:`input_audio`,input_audio:{data:t,format:n.split(`/`)[1]===`mpeg`?`mp3`:`wav`}})}n.push({role:e,content:r})}return{messages:n}}};export{oo as default};