@cortex-agent/server 2026.10.28 → 2026.12.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (401) hide show
  1. package/LICENSE +255 -21
  2. package/README.md +36 -7
  3. package/THIRD_PARTY_NOTICES.txt +1990 -593
  4. package/defaults/hooks/cortex-hook-api.mjs +2 -1
  5. package/defaults/hooks/quota-stop.mjs +37 -0
  6. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +23 -15
  7. package/defaults/prompts/clean-workspace.md +5 -0
  8. package/dist/agent-adapter/claude/remote-mcp-proxy.js +1 -1
  9. package/dist/chunks/agent-runner-LVZVKBZX.js +4 -0
  10. package/dist/chunks/anthropic-messages-TT6454AA.js +8 -0
  11. package/dist/chunks/azure-openai-responses-52LR2XZD.js +4 -0
  12. package/dist/chunks/bedrock-converse-stream-EOZGYUNY.js +60 -0
  13. package/dist/chunks/bowser-MLGGLXTZ.js +20 -0
  14. package/dist/chunks/child-runner-SMG2VOU5.js +4 -0
  15. package/dist/chunks/chunk-24DH4IR5.js +4 -0
  16. package/dist/chunks/chunk-25XKBRDT.js +70 -0
  17. package/dist/chunks/chunk-2ABET62E.js +23 -0
  18. package/dist/chunks/chunk-2BVUA256.js +4 -0
  19. package/dist/chunks/{chunk-LEUENXI2.js → chunk-2WFL62UO.js} +1 -1
  20. package/dist/chunks/{chunk-OZGBWAT2.js → chunk-2YTYYG4K.js} +1 -1
  21. package/dist/chunks/chunk-335SSANX.js +4 -0
  22. package/dist/chunks/chunk-377OPTXX.js +17 -0
  23. package/dist/chunks/chunk-3EZNVLBF.js +129 -0
  24. package/dist/chunks/chunk-3O6ZG5HA.js +7 -0
  25. package/dist/chunks/{chunk-6AKUD3CF.js → chunk-3XLHL5YT.js} +1 -1
  26. package/dist/chunks/chunk-4HRI75GU.js +4 -0
  27. package/dist/chunks/chunk-4JBYLRPM.js +57 -0
  28. package/dist/chunks/chunk-4KKV7VKE.js +4 -0
  29. package/dist/chunks/chunk-4KQHDDC5.js +4 -0
  30. package/dist/chunks/chunk-4SWD4JMP.js +33 -0
  31. package/dist/chunks/chunk-52VCLZS5.js +4 -0
  32. package/dist/chunks/chunk-54P7TSY3.js +10 -0
  33. package/dist/chunks/chunk-5DVSAXOI.js +7 -0
  34. package/dist/chunks/chunk-5F3A62YS.js +4 -0
  35. package/dist/chunks/{chunk-XNSSUVT6.js → chunk-5FHETFZM.js} +1 -1
  36. package/dist/chunks/{chunk-A34TDMIC.js → chunk-5LBLRAHS.js} +1 -1
  37. package/dist/chunks/chunk-5UYVNA3W.js +4 -0
  38. package/dist/chunks/chunk-6G3OYMCV.js +21 -0
  39. package/dist/chunks/chunk-7GGPYU5E.js +30 -0
  40. package/dist/chunks/chunk-7TYSMLUV.js +4 -0
  41. package/dist/chunks/chunk-7W7VYUTK.js +5 -0
  42. package/dist/chunks/chunk-AXYAZTTN.js +6 -0
  43. package/dist/chunks/{chunk-BGVHA2D4.js → chunk-B3NB243Z.js} +1 -1
  44. package/dist/chunks/chunk-BKYP6AGM.js +8 -0
  45. package/dist/chunks/chunk-BVEDNESB.js +4 -0
  46. package/dist/chunks/chunk-BWDJS6A4.js +12 -0
  47. package/dist/chunks/chunk-C6YVF7EI.js +4 -0
  48. package/dist/chunks/chunk-CEJIYYVE.js +15 -0
  49. package/dist/chunks/chunk-CI2RHH74.js +50 -0
  50. package/dist/chunks/chunk-CMSOOLJB.js +4 -0
  51. package/dist/chunks/chunk-CSVTYYLP.js +4 -0
  52. package/dist/chunks/chunk-DE5EGVKG.js +6 -0
  53. package/dist/chunks/{chunk-E6BYRULL.js → chunk-DK3RPZOQ.js} +1 -1
  54. package/dist/chunks/{chunk-YPK2CAIZ.js → chunk-DK4UCK7L.js} +1 -1
  55. package/dist/chunks/chunk-DYLBVUAU.js +4 -0
  56. package/dist/chunks/chunk-FDC2GRBK.js +27 -0
  57. package/dist/chunks/chunk-FE7HH5JS.js +18 -0
  58. package/dist/chunks/chunk-FYD57YRO.js +436 -0
  59. package/dist/chunks/chunk-G264APQN.js +5 -0
  60. package/dist/chunks/chunk-G4JYZFEO.js +11 -0
  61. package/dist/chunks/chunk-GFFM56U2.js +4 -0
  62. package/dist/chunks/chunk-GOS3P7KS.js +132 -0
  63. package/dist/chunks/chunk-HVN37UXD.js +4 -0
  64. package/dist/chunks/chunk-IA6IODY3.js +4 -0
  65. package/dist/chunks/{chunk-HU6UIDEJ.js → chunk-IGZWZP7Z.js} +1 -1
  66. package/dist/chunks/{chunk-NR6U3WIZ.js → chunk-IJ7XFQMI.js} +1 -1
  67. package/dist/chunks/chunk-IMMGYDAB.js +6 -0
  68. package/dist/chunks/chunk-IOWBF7UK.js +10 -0
  69. package/dist/chunks/{chunk-HALUQ7ZF.js → chunk-ITGCWQFK.js} +1 -1
  70. package/dist/chunks/chunk-IVZ7QUEG.js +4 -0
  71. package/dist/chunks/{chunk-YAEVYJAR.js → chunk-IWY2HIFK.js} +1 -1
  72. package/dist/chunks/{chunk-KGJZAYQD.js → chunk-J7OBATRN.js} +1 -1
  73. package/dist/chunks/{chunk-QWAQHHRS.js → chunk-JGUEIW2W.js} +1 -1
  74. package/dist/chunks/chunk-JKL3AK5D.js +106 -0
  75. package/dist/chunks/chunk-JZ7U7RUK.js +351 -0
  76. package/dist/chunks/chunk-KJUQCCB5.js +4 -0
  77. package/dist/chunks/chunk-KST6OY76.js +10 -0
  78. package/dist/chunks/chunk-KZSAFVSY.js +129 -0
  79. package/dist/chunks/chunk-LD2ZSH3M.js +903 -0
  80. package/dist/chunks/chunk-LE6QPXN6.js +7 -0
  81. package/dist/chunks/chunk-LEAV3FFG.js +4 -0
  82. package/dist/chunks/chunk-LIIZI3HY.js +5 -0
  83. package/dist/chunks/chunk-LP72AF56.js +45 -0
  84. package/dist/chunks/{chunk-FXDIR3SQ.js → chunk-MJQ2D2OP.js} +1 -1
  85. package/dist/chunks/{chunk-6LZK4DDH.js → chunk-NHHR4DCF.js} +1 -1
  86. package/dist/chunks/chunk-NW4GW47L.js +4 -0
  87. package/dist/chunks/chunk-OALEJ6FG.js +60 -0
  88. package/dist/chunks/chunk-OIV4DIMB.js +4 -0
  89. package/dist/chunks/chunk-OJ37ZWBG.js +4 -0
  90. package/dist/chunks/chunk-OZXMPBUX.js +4 -0
  91. package/dist/chunks/{chunk-3THJYAEF.js → chunk-PG7452XE.js} +1 -1
  92. package/dist/chunks/chunk-PJCUB7YJ.js +4 -0
  93. package/dist/chunks/chunk-PTS3J4DQ.js +6 -0
  94. package/dist/chunks/{chunk-PXS5SHOV.js → chunk-PVVEEBUU.js} +1 -1
  95. package/dist/chunks/chunk-Q7BZLPBU.js +8 -0
  96. package/dist/chunks/{chunk-FOJQXLL2.js → chunk-QC66ZXPP.js} +1 -1
  97. package/dist/chunks/chunk-QXFWIL4C.js +4 -0
  98. package/dist/chunks/{chunk-PFMEUFJ7.js → chunk-R2CCD4OF.js} +1 -1
  99. package/dist/chunks/chunk-R6CGBSTC.js +22 -0
  100. package/dist/chunks/chunk-RG5GP4RB.js +5 -0
  101. package/dist/chunks/{chunk-D3NXKK2L.js → chunk-RW2F2QNP.js} +1 -1
  102. package/dist/chunks/{models-L5VF4I5O-XXNJYQMQ.js → chunk-RWPO3NZ3.js} +1 -1
  103. package/dist/chunks/chunk-SAJD4EKE.js +10 -0
  104. package/dist/chunks/chunk-SDUS2H3E.js +4 -0
  105. package/dist/chunks/chunk-SIHGKM4E.js +4 -0
  106. package/dist/chunks/chunk-SKHFU5DI.js +4 -0
  107. package/dist/chunks/{chunk-STUHNKQS.js → chunk-SM45TH22.js} +1 -1
  108. package/dist/chunks/chunk-T54CZKNJ.js +6 -0
  109. package/dist/chunks/chunk-TKFFQNAP.js +19 -0
  110. package/dist/chunks/chunk-TMV2ZDOI.js +18 -0
  111. package/dist/chunks/chunk-TRXLIL7V.js +4 -0
  112. package/dist/chunks/{chunk-SUFW24P4.js → chunk-UEEW2R4E.js} +1 -1
  113. package/dist/chunks/chunk-UHXPRU6G.js +10 -0
  114. package/dist/chunks/chunk-UPQVWHZ3.js +4 -0
  115. package/dist/chunks/{chunk-JERCOLY3.js → chunk-V35MFAUQ.js} +4 -6
  116. package/dist/chunks/chunk-V7K3KNDM.js +4 -0
  117. package/dist/chunks/chunk-VHX2GHBF.js +4 -0
  118. package/dist/chunks/chunk-VOAKRJ4R.js +4 -0
  119. package/dist/chunks/{chunk-X2GYYRVM.js → chunk-VW7TLY3P.js} +1 -1
  120. package/dist/chunks/chunk-W34AK4SK.js +65 -0
  121. package/dist/chunks/{chunk-REBNWCKI.js → chunk-WU7RNAZD.js} +1 -1
  122. package/dist/chunks/chunk-WZC4TDDM.js +6 -0
  123. package/dist/chunks/chunk-WZYS2HAK.js +4 -0
  124. package/dist/chunks/chunk-X2TKJ7KR.js +11 -0
  125. package/dist/chunks/{chunk-H2FP6DG4.js → chunk-X5ND4H4P.js} +1 -1
  126. package/dist/chunks/{chunk-4U7XXM4W.js → chunk-Y3AOGNDT.js} +1 -1
  127. package/dist/chunks/chunk-Y6DGVTKM.js +6 -0
  128. package/dist/chunks/{chunk-KENCMLRE.js → chunk-YAEHSSR4.js} +1 -1
  129. package/dist/chunks/chunk-YWPBE5LP.js +4 -0
  130. package/dist/chunks/chunk-ZAVX7G2M.js +15 -0
  131. package/dist/chunks/chunk-ZD2M73XA.js +19 -0
  132. package/dist/chunks/chunk-ZD4O6NPV.js +4 -0
  133. package/dist/chunks/chunk-ZNAMETPQ.js +4 -0
  134. package/dist/chunks/chunk-ZY6N5LVQ.js +4 -0
  135. package/dist/chunks/chunk-ZYQ4TDTT.js +81 -0
  136. package/dist/chunks/cli-VB2N7HEK.js +55 -0
  137. package/dist/chunks/cloudflare-workers-ai-system-one-YKU742EC.js +4 -0
  138. package/dist/chunks/context-CI2FKEQE.js +4 -0
  139. package/dist/chunks/cost-CZRRSIUF.js +5 -0
  140. package/dist/chunks/dist-QCNQN6DY.js +4 -0
  141. package/dist/chunks/easter-egg-3d-XR5S2O3T.js +4 -0
  142. package/dist/chunks/{event-streams-3JSFPOTZ.js → event-streams-AVE4MSS6.js} +1 -1
  143. package/dist/chunks/{execution-repo-ZLJTBWFC.js → execution-repo-5TLV2NM4.js} +1 -1
  144. package/dist/chunks/{executions-6ARGR3IO.js → executions-I3UUIGSL.js} +1 -1
  145. package/dist/chunks/file-Y5G56IUT.js +4 -0
  146. package/dist/chunks/github-copilot-BRU2SRRZ.js +4 -0
  147. package/dist/chunks/google-generative-ai-ZF5QEUZV.js +4 -0
  148. package/dist/chunks/google-vertex-4PJZZI3Y.js +4 -0
  149. package/dist/chunks/init-A6GY656J.js +4 -0
  150. package/dist/chunks/{install-cli-4IZCSDFZ.js → install-cli-FALWKQYO.js} +1 -1
  151. package/dist/chunks/{interaction-ask-G5T3H3CG.js → interaction-ask-O5HGF6CH.js} +1 -1
  152. package/dist/chunks/{interaction-plan-E5V42MUP.js → interaction-plan-JTVDN3BC.js} +1 -1
  153. package/dist/chunks/kimi-coding-ZCIBMDZ6.js +4 -0
  154. package/dist/chunks/{llama-cpp-classify-OTXZWCMW.js → llama-cpp-classify-NRUXAIGQ.js} +3 -3
  155. package/dist/chunks/local-client-stop-RS4AHNF4.js +4 -0
  156. package/dist/chunks/{memory-cli-PYOILNN5.js → memory-cli-DIT4DQF3.js} +1 -1
  157. package/dist/chunks/meta-JQH66YU7.js +4 -0
  158. package/dist/chunks/mistral-conversations-CXHOECUV.js +7 -0
  159. package/dist/chunks/model-resolver-GIBPYRKP.js +4 -0
  160. package/dist/chunks/monitor-Z2HKNY5E.js +4 -0
  161. package/dist/chunks/{node-PTK2HCDV.js → node-DAO3SX7O.js} +1 -1
  162. package/dist/chunks/{openai-codex-2REL6UQU.js → openai-codex-JULCKICT.js} +1 -1
  163. package/dist/chunks/openai-codex-responses-U6DGMGDK.js +12 -0
  164. package/dist/chunks/openai-completions-PP4XLLOM.js +9 -0
  165. package/dist/chunks/{openai-decisions-2N6ZRPZC.js → openai-decisions-JU6QQKEM.js} +1 -1
  166. package/dist/chunks/openai-responses-2SG757TL.js +6 -0
  167. package/dist/chunks/openrouter-images-32M7YZWC.js +4 -0
  168. package/dist/chunks/pi-messages-VSINMXN4.js +10 -0
  169. package/dist/chunks/radius-THYKWV4E.js +4 -0
  170. package/dist/chunks/remote-ops-2WBEFQ3E.js +14 -0
  171. package/dist/chunks/runner-5MKMRTIN.js +4 -0
  172. package/dist/chunks/runtime-DST3H5JP.js +4 -0
  173. package/dist/chunks/schedule-cli-V7Y2BBVY.js +4 -0
  174. package/dist/chunks/slack-R7SEJYMY.js +4 -0
  175. package/dist/chunks/start-ui-http-7K5JOLPU.js +43 -0
  176. package/dist/chunks/subagent-Z5IQ4L54.js +4 -0
  177. package/dist/chunks/{time-KEHDQT6K.js → time-P6PE52WL.js} +1 -1
  178. package/dist/chunks/tool-shims-YCXZWTST.js +4 -0
  179. package/dist/chunks/typesafe-system-one-M2DABJSZ.js +4 -0
  180. package/dist/chunks/ui-board-HQIE4RZG.js +5 -0
  181. package/dist/chunks/ui-decision-YBZDS4YW.js +4 -0
  182. package/dist/chunks/{ui-file-GVH53O3X.js → ui-file-SRD4ILBS.js} +1 -1
  183. package/dist/chunks/ui-view-Z25MTZT7.js +4 -0
  184. package/dist/chunks/virtual-modules-H4DXPJZB.js +4 -0
  185. package/dist/chunks/waitpoint-M6JZBSLT.js +5 -0
  186. package/dist/chunks/workers-SQ2R32TK.js +4 -0
  187. package/dist/client-bundle/client.mjs +273 -93
  188. package/dist/client-bundle/manifest.json +2 -2
  189. package/dist/core/pi-sdk.js +1 -1
  190. package/dist/domain/auth/cc-auth-cli.js +1 -1
  191. package/dist/domain/mcp/bundled-server.js +1 -1
  192. package/dist/domain/mcp/feishu/client.js +4 -0
  193. package/dist/entry/app.js +151 -559
  194. package/dist/entry/browser-cli.js +10 -10
  195. package/dist/entry/cli.js +1 -1
  196. package/dist/entry/cortex-cli.js +1 -1
  197. package/dist/entry/daemon.js +4 -4
  198. package/dist/entry/hook-cli.js +2 -2
  199. package/dist/entry/production-app-bootstrap.js +1 -1
  200. package/dist/entry/production-evidence-export-cli.js +1 -1
  201. package/dist/entry/signal-cli.js +2 -2
  202. package/dist/tui/index.js +41 -41
  203. package/package.json +3 -3
  204. package/vendor/pi/CHANGELOG.md +330 -0
  205. package/vendor/pi/dist/codemode-worker.js +2 -0
  206. package/vendor/pi/dist/core/export-html/ansi-to-html.js +57 -20
  207. package/vendor/pi/dist/core/export-html/template.css +9 -0
  208. package/vendor/pi/dist/core/export-html/template.js +166 -46
  209. package/vendor/pi/dist/core/export-html/tool-renderer.js +5 -3
  210. package/vendor/pi/dist/core/extensions/loader.js +1 -1
  211. package/vendor/pi/dist/extensions/codemode/execute.js +15 -13
  212. package/vendor/pi/dist/modes/interactive/theme/theme.js +36 -23
  213. package/vendor/pi/dist/utils/image-resize-worker.js +1 -1
  214. package/vendor/pi/dist/utils/image-resize.js +1 -1
  215. package/vendor/pi/docs/cli.md +35 -12
  216. package/vendor/pi/docs/custom-provider.md +2 -0
  217. package/vendor/pi/docs/environment-variables.md +2 -0
  218. package/vendor/pi/docs/extensions.md +3192 -225
  219. package/vendor/pi/docs/keybindings.md +2 -2
  220. package/vendor/pi/docs/llama-cpp.md +27 -19
  221. package/vendor/pi/docs/mcp.md +6 -4
  222. package/vendor/pi/docs/message-types.md +1 -1
  223. package/vendor/pi/docs/models-configuration.md +9 -3
  224. package/vendor/pi/docs/models.md +2 -1
  225. package/vendor/pi/docs/nvidia-rtx-llama-cpp.md +5 -5
  226. package/vendor/pi/docs/packages.md +24 -0
  227. package/vendor/pi/docs/prompt-templates.md +1 -1
  228. package/vendor/pi/docs/providers.md +4 -2
  229. package/vendor/pi/docs/quickstart.md +7 -3
  230. package/vendor/pi/docs/rpc-commands.md +1 -1
  231. package/vendor/pi/docs/rpc.md +4 -2
  232. package/vendor/pi/docs/sessions.md +17 -3
  233. package/vendor/pi/docs/settings.md +6 -5
  234. package/vendor/pi/docs/slash-commands.md +3 -2
  235. package/vendor/pi/docs/terminal-setup.md +3 -1
  236. package/vendor/pi/docs/tmux.md +6 -0
  237. package/vendor/pi/docs/tui.md +4 -0
  238. package/vendor/pi/docs/windows.md +27 -0
  239. package/vendor/pi/examples/extensions/README.md +2 -1
  240. package/vendor/pi/examples/extensions/custom-provider-anthropic/index.ts +27 -31
  241. package/vendor/pi/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  242. package/vendor/pi/examples/extensions/custom-provider-anthropic/package.json +1 -1
  243. package/vendor/pi/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  244. package/vendor/pi/examples/extensions/debug-provider.ts +2 -2
  245. package/vendor/pi/examples/extensions/gondolin/index.ts +4 -7
  246. package/vendor/pi/examples/extensions/gondolin/package-lock.json +19 -29
  247. package/vendor/pi/examples/extensions/gondolin/package.json +2 -2
  248. package/vendor/pi/examples/extensions/plan-mode/index.ts +23 -13
  249. package/vendor/pi/examples/extensions/plan-mode/utils.ts +42 -16
  250. package/vendor/pi/examples/extensions/preset.ts +2 -0
  251. package/vendor/pi/examples/extensions/reload-runtime.ts +17 -5
  252. package/vendor/pi/examples/extensions/subagent/README.md +14 -11
  253. package/vendor/pi/examples/extensions/subagent/index.ts +392 -171
  254. package/vendor/pi/examples/extensions/todo.ts +7 -0
  255. package/vendor/pi/examples/extensions/tools.ts +2 -0
  256. package/vendor/pi/examples/extensions/with-deps/package-lock.json +2 -2
  257. package/vendor/pi/examples/extensions/with-deps/package.json +1 -1
  258. package/vendor/pi/examples/tsconfig.json +208 -0
  259. package/vendor/pi/package.json +15 -16
  260. package/vendor/pi/schemas/models.schema.json +66 -37
  261. package/vendor/pi/schemas/settings.schema.json +18 -1
  262. package/vendor/pi-ai/bedrock.js +1 -1
  263. package/vendor/pi-ai/oauth-load.js +1 -1
  264. package/web/dist/assets/{board-math-css-BPXakv_3.js → board-math-css-DKX6FcUS.js} +1 -1
  265. package/web/dist/assets/index-D11wi0uG.js +540 -0
  266. package/web/dist/assets/index-JedYumhY.css +1 -0
  267. package/web/dist/assets/{index-WCm6wwmM.js → index-jl30Gy8P.js} +1 -1
  268. package/web/dist/assets/pdf-worker-DdZgk2mV.js +57 -0
  269. package/web/dist/assets/pdf.worker.min-Bz_KHX45.js +55 -0
  270. package/web/dist/index.html +2 -2
  271. package/web/dist/theme.css +22 -0
  272. package/dist/chunks/anthropic-messages-M3SMXACA.js +0 -8
  273. package/dist/chunks/api-GM53PHIL-GFHEXXE6.js +0 -4
  274. package/dist/chunks/azure-openai-responses-76YWXHSB.js +0 -4
  275. package/dist/chunks/bedrock-converse-stream-5UPX4NTQ.js +0 -58
  276. package/dist/chunks/child-runner-3GHOWGZP.js +0 -4
  277. package/dist/chunks/chunk-2ZNLUY2U.js +0 -128
  278. package/dist/chunks/chunk-3F6WW7HR.js +0 -13
  279. package/dist/chunks/chunk-3OKHUVEM.js +0 -7
  280. package/dist/chunks/chunk-3YHOCPQU.js +0 -10
  281. package/dist/chunks/chunk-4EX2JJWB.js +0 -4
  282. package/dist/chunks/chunk-4LLH5OWM.js +0 -10
  283. package/dist/chunks/chunk-52T37Y47.js +0 -8
  284. package/dist/chunks/chunk-7MU2AKNM.js +0 -4
  285. package/dist/chunks/chunk-AAA3UBIS.js +0 -4
  286. package/dist/chunks/chunk-ASYQHJVQ.js +0 -9
  287. package/dist/chunks/chunk-BKHDWCRT.js +0 -79
  288. package/dist/chunks/chunk-CQLH4UVX.js +0 -4
  289. package/dist/chunks/chunk-CVC66CFV.js +0 -33
  290. package/dist/chunks/chunk-D6UA4BZC.js +0 -19
  291. package/dist/chunks/chunk-DGMNI4AO.js +0 -4
  292. package/dist/chunks/chunk-DHSA5ACV.js +0 -125
  293. package/dist/chunks/chunk-DPQPXBTP.js +0 -68
  294. package/dist/chunks/chunk-DXBSQXJL.js +0 -18
  295. package/dist/chunks/chunk-E7ZMYIY6.js +0 -30
  296. package/dist/chunks/chunk-EQITBTJC.js +0 -10
  297. package/dist/chunks/chunk-EXJA5RIX.js +0 -357
  298. package/dist/chunks/chunk-FF7UELTU.js +0 -4
  299. package/dist/chunks/chunk-FH74NME3.js +0 -115
  300. package/dist/chunks/chunk-FOQ7VLIL.js +0 -17
  301. package/dist/chunks/chunk-FX6MOGLR.js +0 -11
  302. package/dist/chunks/chunk-G2V65UBA.js +0 -4
  303. package/dist/chunks/chunk-HGPBHTVD.js +0 -6
  304. package/dist/chunks/chunk-J5DVLUKY.js +0 -6
  305. package/dist/chunks/chunk-JW2HFMTF.js +0 -4
  306. package/dist/chunks/chunk-KDYEGGMW.js +0 -4
  307. package/dist/chunks/chunk-KIGMAATV.js +0 -23
  308. package/dist/chunks/chunk-KIU5FAPY.js +0 -5
  309. package/dist/chunks/chunk-KIWMQPH7.js +0 -739
  310. package/dist/chunks/chunk-L6VCIGWS.js +0 -11
  311. package/dist/chunks/chunk-LACGULCN.js +0 -10
  312. package/dist/chunks/chunk-LMSQZ6TQ.js +0 -4
  313. package/dist/chunks/chunk-MEPASGPP.js +0 -6
  314. package/dist/chunks/chunk-MFAEUHMV.js +0 -28
  315. package/dist/chunks/chunk-NAA7GF6Q.js +0 -5
  316. package/dist/chunks/chunk-NKDMKRSB.js +0 -68
  317. package/dist/chunks/chunk-NKXV32S6.js +0 -4
  318. package/dist/chunks/chunk-NVX5IPRN.js +0 -4
  319. package/dist/chunks/chunk-O3JW2F7D.js +0 -8
  320. package/dist/chunks/chunk-OE4KH3NJ.js +0 -4
  321. package/dist/chunks/chunk-OISO5JXB.js +0 -4
  322. package/dist/chunks/chunk-OPYXNSMY.js +0 -4
  323. package/dist/chunks/chunk-OSEIQ7SS.js +0 -4
  324. package/dist/chunks/chunk-P52RMIYX.js +0 -6
  325. package/dist/chunks/chunk-PBJ5MPPX.js +0 -60
  326. package/dist/chunks/chunk-PZMGBKUR.js +0 -13
  327. package/dist/chunks/chunk-PZMXHA6X.js +0 -9
  328. package/dist/chunks/chunk-Q7CE3UIE.js +0 -133
  329. package/dist/chunks/chunk-QBKCAIJG.js +0 -4
  330. package/dist/chunks/chunk-QEOFEETJ.js +0 -4
  331. package/dist/chunks/chunk-QUUEQRIT.js +0 -4
  332. package/dist/chunks/chunk-RA6HKFBV.js +0 -4
  333. package/dist/chunks/chunk-REPYBMQS.js +0 -4
  334. package/dist/chunks/chunk-SKHLZ6XY.js +0 -9
  335. package/dist/chunks/chunk-TAWLERZA.js +0 -4
  336. package/dist/chunks/chunk-TWAEABGG.js +0 -52
  337. package/dist/chunks/chunk-TZFLHVOQ.js +0 -7
  338. package/dist/chunks/chunk-UD3NMUHR.js +0 -12
  339. package/dist/chunks/chunk-UNVEZI57.js +0 -4
  340. package/dist/chunks/chunk-VQUPKMDR.js +0 -4
  341. package/dist/chunks/chunk-W25TB3PU.js +0 -4
  342. package/dist/chunks/chunk-W5LGYSPZ.js +0 -4
  343. package/dist/chunks/chunk-WEZWKMYU.js +0 -4
  344. package/dist/chunks/chunk-XAJLZR7C.js +0 -28
  345. package/dist/chunks/chunk-XH6FMP3N.js +0 -71
  346. package/dist/chunks/chunk-XSRZHN63.js +0 -4
  347. package/dist/chunks/chunk-Y3GFB5XM.js +0 -8
  348. package/dist/chunks/chunk-YG7OEPR2.js +0 -6
  349. package/dist/chunks/chunk-YHIWOGVL.js +0 -4
  350. package/dist/chunks/chunk-YKKEI5GI.js +0 -4
  351. package/dist/chunks/chunk-YZSHTWNM.js +0 -92
  352. package/dist/chunks/chunk-Z4H3VDHI.js +0 -4
  353. package/dist/chunks/cli-5DBTRMHU.js +0 -53
  354. package/dist/chunks/client-XOGYH5UR.js +0 -4
  355. package/dist/chunks/cloudflare-workers-ai-system-one-32JCFHI3.js +0 -4
  356. package/dist/chunks/config-DJSQI77S-335IXHSM.js +0 -4
  357. package/dist/chunks/context-VCQH5OB6.js +0 -4
  358. package/dist/chunks/cost-PGGFI7QJ.js +0 -5
  359. package/dist/chunks/dist-PUKMZ7GW.js +0 -4
  360. package/dist/chunks/easter-egg-3d-MO4MOEVF.js +0 -4
  361. package/dist/chunks/es5-VNTQPCKX.js +0 -4
  362. package/dist/chunks/file-7BN7RCAY.js +0 -4
  363. package/dist/chunks/gateway-UCRPMR75.js +0 -36
  364. package/dist/chunks/github-copilot-HAI2DA62.js +0 -4
  365. package/dist/chunks/google-generative-ai-2VXWLHWI.js +0 -4
  366. package/dist/chunks/google-vertex-UA36QP2U.js +0 -4
  367. package/dist/chunks/init-HA7FAQ73.js +0 -4
  368. package/dist/chunks/kimi-coding-HMJRKCPA.js +0 -4
  369. package/dist/chunks/local-client-stop-SQRU7ZZM.js +0 -4
  370. package/dist/chunks/meta-KY3LNFV2.js +0 -4
  371. package/dist/chunks/mistral-conversations-34F66L3O.js +0 -7
  372. package/dist/chunks/model-resolver-N3DTAQ2S.js +0 -4
  373. package/dist/chunks/openai-codex-responses-ZBVHREB3.js +0 -12
  374. package/dist/chunks/openai-completions-VVIB26SH.js +0 -9
  375. package/dist/chunks/openai-responses-735XA2ZX.js +0 -6
  376. package/dist/chunks/openrouter-images-3IKETHAC.js +0 -4
  377. package/dist/chunks/pi-messages-I3E4ZFHA.js +0 -10
  378. package/dist/chunks/radius-HXRZVBDB.js +0 -4
  379. package/dist/chunks/remote-ops-BALZYKH6.js +0 -14
  380. package/dist/chunks/runner-PLVZDGHB.js +0 -4
  381. package/dist/chunks/runtime-6YLTA2ZD.js +0 -4
  382. package/dist/chunks/schedule-cli-OLASBBYJ.js +0 -4
  383. package/dist/chunks/slack-WAGSPZUX.js +0 -4
  384. package/dist/chunks/start-ui-http-QALT7C3P.js +0 -43
  385. package/dist/chunks/subagent-E3UC7ZHC.js +0 -4
  386. package/dist/chunks/tool-shims-Q6P6UXVC.js +0 -4
  387. package/dist/chunks/typesafe-system-one-6ULACYD4.js +0 -4
  388. package/dist/chunks/ui-board-4GYW6KKW.js +0 -5
  389. package/dist/chunks/ui-decision-U2FXSEC2.js +0 -4
  390. package/dist/chunks/ui-view-O7PLANT7.js +0 -4
  391. package/dist/chunks/virtual-modules-IDC5YKZJ.js +0 -4
  392. package/dist/chunks/waitpoint-2FGQBIAC.js +0 -5
  393. package/dist/chunks/workers-XN4PSTH6.js +0 -4
  394. package/vendor/aistatus/gateway-cli.js +0 -21
  395. package/vendor/pi/examples/extensions/sandbox/index.ts +0 -321
  396. package/vendor/pi/examples/extensions/sandbox/package-lock.json +0 -92
  397. package/vendor/pi/examples/extensions/sandbox/package.json +0 -19
  398. package/web/dist/assets/index-BHZpFXhc.js +0 -525
  399. package/web/dist/assets/index-DqWMdMkh.css +0 -1
  400. package/web/dist/assets/pdf-worker-Hp15W1QJ.js +0 -57
  401. package/web/dist/assets/pdf.worker.min-DnhTvCwe.js +0 -55
@@ -0,0 +1,33 @@
1
+ import { createRequire as __cortexCreateRequire } from 'node:module';
2
+ const require = __cortexCreateRequire(import.meta.url);
3
+ const __cortexPackageRoot = new URL("../../", import.meta.url);
4
+ import{c as A_,d as R_,e as O_}from"./chunk-WHC7AYZD.js";var df=A_((J,Ja)=>{"use strict";if(typeof Ja<"u"&&Ja!==globalThis.module&&typeof J<"u"&&Ja.exports===J){Object.defineProperty(J,"__esModule",{value:!0}),J.findX509Credential=J.rememberX509Credential=J.findX509OAuthError=J.rememberX509OAuthError=J.isApprovedX509Client=J.markApprovedX509Client=J.isRetryableX509IssuerError=J.markRetryableX509IssuerError=J.isTransientX509ConnectionError=J.markTransientX509ConnectionError=J.rememberRegisteredX509Transport=J.findRegisteredX509Transport=void 0;let n=new WeakMap,e=new WeakSet,t=new WeakSet,r=new WeakSet,o=new WeakMap,i=new WeakMap;J.findRegisteredX509Transport=WeakMap.prototype.get.bind(n),J.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(n),J.markTransientX509ConnectionError=WeakSet.prototype.add.bind(e),J.isTransientX509ConnectionError=WeakSet.prototype.has.bind(e),J.markRetryableX509IssuerError=WeakSet.prototype.add.bind(t),J.isRetryableX509IssuerError=WeakSet.prototype.has.bind(t),J.markApprovedX509Client=WeakSet.prototype.add.bind(r),J.isApprovedX509Client=WeakSet.prototype.has.bind(r),J.rememberX509OAuthError=WeakMap.prototype.set.bind(o),J.findX509OAuthError=WeakMap.prototype.get.bind(o),J.rememberX509Credential=WeakMap.prototype.set.bind(i),J.findX509Credential=WeakMap.prototype.get.bind(i)}});function w(n,e,t,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!o:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(n,t):o?o.value=t:e.set(n,t),t}function u(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}var Me=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Me=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Ct(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var ri=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e="cause"in n,t=new Error(n.message,e?{cause:n.cause}:{});return n.stack&&(t.stack=n.stack),e&&!Object.prototype.hasOwnProperty.call(t,"cause")&&(t.cause=n.cause),n.name&&(t.name=n.name),t}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var f=class extends Error{},H=class n extends f{constructor(e,t,r,o){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=o,this.requestID=o?.get("x-request-id"),this.error=t;let i=t;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,r){let o=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&o?`${e} ${o}`:e?`${e} status code (no body)`:o||"(no status code or body)"}static generate(e,t,r,o){if(!e||!o)return new Xe({message:r,cause:ri(t)});let i=t?.error;return e===400?new mt(e,i,r,o):e===401?new Jt(e,i,r,o):e===403?new Vt(e,i,r,o):e===404?new Gt(e,i,r,o):e===409?new Yt(e,i,r,o):e===422?new Zt(e,i,r,o):e===429?new er(e,i,r,o):e>=500?new tr(e,i,r,o):new n(e,i,r,o)}},V=class extends H{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Xe=class extends H{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},re=class extends Xe{constructor({message:e}={}){super({message:e??"Request timed out."})}},mt=class extends H{},Jt=class extends H{},Vt=class extends H{},Gt=class extends H{},Yt=class extends H{},Zt=class extends H{},er=class extends H{},tr=class extends H{},rr=class extends f{constructor(){super("Could not parse response content as the length limit was reached")}},nr=class extends f{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},qe=class extends Error{constructor(e){super(e)}},Je=class extends H{constructor(e,t,r){let o="OAuth2 authentication error",i;if(t&&typeof t=="object"){let s=t;i=s.error;let a=s.error_description;a&&typeof a=="string"?o=a:i&&(o=i)}super(e,t,o,r),this.error_code=i}},qr=class extends f{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var x_=/^[a-z][a-z0-9+.-]*:/i,Od=n=>x_.test(n),we=n=>(we=Array.isArray,we(n)),Pd=we;function ni(n){return typeof n!="object"?{}:n??{}}function Da(n){if(!n)return!0;for(let e in n)return!1;return!0}function k(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function U(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var Tc=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new f(`${n} must be an integer`);if(e<0)throw new f(`${n} must be a positive integer`);return e};var xd=n=>{try{return JSON.parse(n)}catch{return}};var Bn=(n,...e)=>new Promise((t,r)=>{let o=[...new Set(e.filter(h=>h!=null))],i,s=!1,a=()=>{for(let h of o)try{h.removeEventListener("abort",d)}catch{}},c=h=>{s||(s=!0,i!==void 0&&(clearTimeout(i),i=void 0),a(),h())},d=()=>{c(()=>r())};if(o.some(h=>h.aborted)){d();return}i=setTimeout(()=>{c(t)},n);for(let h of o){if(s)break;try{h.addEventListener("abort",d,{once:!0})}catch(_){c(()=>r(_))}}o.some(h=>h.aborted)&&d()});var Kn=globalThis,Fa=typeof Kn.FinalizationRegistry=="function"?new Kn.FinalizationRegistry(n=>{try{n()}catch{}}):void 0,vd=new WeakMap,si=new WeakMap;function v_(n,e,t){let r=si.get(n);if(!r){let i=new Set,s=()=>{si.delete(n);for(let a of i)t.unregister(a),a.deref()?.();i.clear()};r={callbacks:i,abort:s},n.addEventListener("abort",s,{once:!0}),si.set(n,r)}let o=r;return o.callbacks.add(e),()=>{o.callbacks.delete(e),t.unregister(e),o.callbacks.size===0&&(si.get(n)===o&&si.delete(n),n.removeEventListener("abort",o.abort))}}function I_(n,e,t){n.addEventListener("abort",()=>e.deref()?.delete(t),{once:!0})}function kc(n,e,t){if(typeof Kn.WeakRef=="function"&&Fa&&!t.aborted){let r=vd.get(n);r||(r=new Set,vd.set(n,r)),r.add(e),I_(t,new Kn.WeakRef(r),e)}}function Id(n,e,t){if(n.aborted)return e(),()=>{};if(typeof Kn.WeakRef!="function"||!Fa)return n.addEventListener("abort",e,{once:!0}),()=>n.removeEventListener("abort",e);let r=new Kn.WeakRef(e),o=v_(n,r,Fa);return Fa.register(e,o,r),kc(t,e,t),o}function oi(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function jc(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function ii(n,e){let t=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return jc({start(){},async pull(r){let{done:o,value:i}=await t.next();o?r.close():r.enqueue(i)},async cancel(){await t.return?.()}},e)}function za(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ut(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}var Ed;function me(n){let e;return(Ed??(e=new globalThis.TextEncoder,Ed=e.encode.bind(e)))(n)}var Cd;function Td(n){let e;return(Cd??(e=new globalThis.TextDecoder,Cd=e.decode.bind(e)))(n)}var qc,ue,ne,oe,_t,$r,jd,ai=64*1024,Dr=class{constructor(){qc.add(this),ue.set(this,void 0),ne.set(this,void 0),oe.set(this,void 0),_t.set(this,void 0),$r.set(this,void 0),w(this,ue,new Uint8Array,"f"),w(this,ne,0,"f"),w(this,oe,0,"f"),w(this,_t,0,"f"),w(this,$r,!1,"f")}decode(e){if(e==null)return[];let t;if(e instanceof ArrayBuffer?t=new Uint8Array(e):typeof e=="string"?t=me(e):t=e,t.length===0)return[];if(u(this,$r,"f")&&(w(this,$r,!1,"f"),t[0]===10&&(t=t.subarray(1)),t.length===0))return[];u(this,qc,"m",jd).call(this,t);let r=[],o;for(;(o=S_(u(this,ue,"f"),u(this,_t,"f"),u(this,oe,"f")))!=null;){let i=Td(u(this,ue,"f").subarray(u(this,ne,"f"),o.preceding));r.push(i),w(this,ne,o.index,"f"),o.carriage&&(u(this,ne,"f")<u(this,oe,"f")&&u(this,ue,"f")[u(this,ne,"f")]===10?w(this,ne,u(this,ne,"f")+1,"f"):u(this,ne,"f")===u(this,oe,"f")&&w(this,$r,!0,"f")),w(this,_t,u(this,ne,"f"),"f")}if(w(this,_t,u(this,oe,"f"),"f"),u(this,ne,"f")===u(this,oe,"f"))w(this,ne,0,"f"),w(this,oe,0,"f"),w(this,_t,0,"f"),u(this,ue,"f").length>ai&&w(this,ue,new Uint8Array,"f");else if(r.length>0&&u(this,ue,"f").length>ai){let i=u(this,oe,"f")-u(this,ne,"f");if(i<=ai||u(this,ue,"f").length>i*4){let s=i<=ai?Math.min(Math.max(i*2,256),ai):i*2,a=new Uint8Array(s);a.set(u(this,ue,"f").subarray(u(this,ne,"f"),u(this,oe,"f"))),w(this,ue,a,"f"),w(this,ne,0,"f"),w(this,oe,i,"f"),w(this,_t,i,"f")}}return r}flush(){return w(this,$r,!1,"f"),u(this,ne,"f")===u(this,oe,"f")?[]:this.decode(`
5
+ `)}};ue=new WeakMap,ne=new WeakMap,oe=new WeakMap,_t=new WeakMap,$r=new WeakMap,qc=new WeakSet,jd=function(e){if(u(this,oe,"f")+e.length>u(this,ue,"f").length){let t=u(this,oe,"f")-u(this,ne,"f");if(u(this,ne,"f")>=u(this,ue,"f").length/2&&t+e.length<=u(this,ue,"f").length)u(this,ue,"f").copyWithin(0,u(this,ne,"f"),u(this,oe,"f"));else{let r=Math.max(u(this,ue,"f").length*2,t+e.length,256),o=new Uint8Array(r);o.set(u(this,ue,"f").subarray(u(this,ne,"f"),u(this,oe,"f"))),w(this,ue,o,"f")}w(this,_t,u(this,_t,"f")-u(this,ne,"f"),"f"),w(this,oe,t,"f"),w(this,ne,0,"f")}u(this,ue,"f").set(e,u(this,oe,"f")),w(this,oe,u(this,oe,"f")+e.length,"f")};Dr.NEWLINE_CHARS=new Set([`
6
+ `,"\r"]);Dr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function S_(n,e,t){for(let i=e;i<t;i++){if(n[i]===10)return{preceding:i,index:i+1,carriage:!1};if(n[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function qd(n){for(let e=0;e<n.length-1;e++){let t=kd(n,e);if(t>0){let r=e+t,o=kd(n,r);if(o>0)return r+o}}return-1}function kd(n,e){return n[e]===10?1:n[e]===13?n[e+1]===10?2:1:0}var La={off:0,error:200,warn:300,info:400,debug:500},$c=(n,e,t)=>{if(n){if(k(La,n))return n;ie(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(La))}`)}};function ui(){}function Ma(n,e,t){return!e||La[n]>La[t]?ui:e[n].bind(e)}var E_={error:ui,warn:ui,info:ui,debug:ui},$d=new WeakMap;function ie(n){let e=n.logger,t=n.logLevel??"off";if(!e)return E_;let r=$d.get(e);if(r&&r[0]===t)return r[1];let o={error:Ma("error",e,t),warn:Ma("warn",e,t),info:Ma("info",e,t),debug:Ma("debug",e,t)};return $d.set(e,[t,o]),o}var Dd=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","signingsecret","sig","signature","xgoogsignature","xgoogcredential","xamzsecuritytoken","xamzsignature","xamzcredential"]);function ci(n){let e=n.toLowerCase().replace(/[-_]/gu,"");return Dd.has(e)||Dd.has(e.replace(/^x/u,""))}var C_=new Set(["authorization","proxy-authorization","api-key","x-api-key","x-amz-security-token","cookie","set-cookie","x-session-token","x-session-id","x-auth-token","x-id-token"]);function Ka(n){return C_.has(n.toLowerCase().replace(/_/gu,"-"))||ci(n)}function Ba(n){let e=new URL(n);e.username="",e.password="",e.hash="";for(let t of e.searchParams.keys())ci(t)&&e.searchParams.set(t,"***");return e.href}var Tt=n=>{if(n.options){if(n.options={...n.options},delete n.options.headers,n.options.path){let e=n.options.path,t=new URL(Ba(new URL(e,"https://redacted.invalid").href));n.options.path=t.origin==="https://redacted.invalid"?`${e.startsWith("/")?"/":""}${t.pathname.slice(1)}${t.search}`:t.href}n.options.query&&(n.options.query=Object.fromEntries(Object.entries(n.options.query).map(([e,t])=>[e,ci(e)?"***":t])))}return n.url&&(n.url=Ba(n.url)),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,Ka(e)?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n};var Na,Wa,Ua,Dc;function T_(n){return!(n instanceof H)&&Ct(n)}function Fd(){let n=[],e=0,t=!1;return{get length(){return n.length-e},get canceled(){return t},enqueue(r){t||n.push(r)},dequeue(){if(e===n.length)return;let r=n[e];return n[e]=void 0,e+=1,e===n.length?(n=[],e=0):e>=1024&&e*2>=n.length&&(n=n.slice(e),e=0),r},cancel(){t=!0,n.length=0,e=0}}}var $e=class n{constructor(e,t,r){Na.add(this),Wa.set(this,void 0),Ua.set(this,!1),this.iterator=e,this.controller=t,w(this,Wa,r,"f")}static fromSSEResponse(e,t,r,o,i="legacy"){let s=!1,a=r?ie(r):console;async function*c(){if(s)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let d=!1,h=!1,_=j_(e,t),m=_.return.bind(_);_.return=b=>(h||t.abort(),m(b));try{for await(let b of _){if(b.data==="[DONE]"){h=!0;break}let y;try{y=JSON.parse(b.data)}catch{throw a.error("Could not parse message into JSON:"),a.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if(i==="legacy"){if(b.event?.startsWith("thread.")){yield{event:b.event,data:y};continue}if(b.event==="error")throw new H(void 0,y?.error??y,void 0,e.headers);if(y&&y.error)throw new H(void 0,y.error,void 0,e.headers)}yield o?{event:b.event,data:y}:y}d=!0}catch(b){if(h||T_(b)||t.signal.aborted&&b===t.signal.reason)return;throw b}finally{d||t.abort()}}return new n(c,t,r)}static fromReadableStream(e,t,r){let o=!1;async function*i(){let a=new Dr,c=e.getReader(),d=!1,h,_=()=>{h??(h=c.cancel()),h.catch(()=>{})};t.signal.addEventListener("abort",_,{once:!0});try{if(t.signal.aborted){_();return}for(;;){let{value:m,done:b}=await c.read();if(b){d=!0;break}if(t.signal.aborted)return;for(let y of a.decode(m)){if(t.signal.aborted)return;yield y}}if(t.signal.aborted)return;for(let m of a.flush()){if(t.signal.aborted)return;yield m}}finally{t.signal.removeEventListener("abort",_),d||_(),c.releaseLock()}}async function*s(){if(o)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let a=!1;try{for await(let c of i())if(c){let d;try{d=JSON.parse(c)}catch(h){throw h instanceof SyntaxError?new SyntaxError("Error reading response: malformed newline-delimited JSON."):h}yield d}a=!0}catch(c){if(t.signal.aborted||Ct(c))return;throw c}finally{a||t.abort()}}return new n(s,t,r)}[(Wa=new WeakMap,Ua=new WeakMap,Na=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}__betaTransformIterator(e){this.iterator=e(this.iterator.bind(this))}tee(){let{controller:e}=this,t=Fd(),r=Fd(),o=this.iterator(),i=a=>({next:()=>{if(a.canceled)return Promise.resolve({value:void 0,done:!0});if(a.length===0){let c=o.next();t.enqueue(c),r.enqueue(c)}return a.dequeue()},return:async()=>(a.canceled||(a.cancel(),t.canceled&&r.canceled&&await u(this,Na,"m",Dc).call(this,o,e)),{value:void 0,done:!0})}),s=a=>{let c=new n(()=>i(a),e,u(this,Wa,"f"));return w(c,Ua,!0,"f"),c};return[s(t),s(r)]}toReadableStream(){let{controller:e}=this,t,r,o=()=>r??(r=u(this,Na,"m",Dc).call(this,t,e));return jc({start:async()=>{t=this[Symbol.asyncIterator]()},async pull(i){try{let{value:s,done:a}=await t.next();if(a)return i.close();let c=me(JSON.stringify(s)+`
7
+ `);i.enqueue(c)}catch(s){i.error(s),o().catch(()=>{})}},cancel:o})}};Dc=async function(e,t){let r=e.return;r&&(u(this,Ua,"f")||t.abort(),await Reflect.apply(r,e,[]))};function k_(n,e){let t=typeof n.getReader=="function"?n.getReader():void 0,r=t?{next:()=>t.read(),return:()=>t.cancel()}:za(n)[Symbol.asyncIterator](),o={value:void 0,done:!0},i=!1,s=!1,a,c,d=()=>new Promise(b=>{c=b}),h=()=>{if(s||i)return a;s=!0;try{a=Promise.resolve(r.return?.())}catch(b){a=Promise.reject(b)}return a.catch(()=>{}),a},_=()=>{queueMicrotask(()=>{c?.(),h()})};return{iterator:{async next(){if(e.aborted)return o;let b=d().then(()=>o);try{let y=await Promise.race([r.next(),b]);return e.aborted?o:y.done?(i=!0,o):{value:y.value,done:!1}}catch(y){if(e.aborted&&(Ct(y)||y===e.reason))return o;throw y}finally{c=void 0}},async return(){let b=h();if(b&&!e.aborted){let y=d();try{e.aborted||await Promise.race([b,y])}finally{c=void 0}}return o},[Symbol.asyncIterator](){return this}},start(){e.addEventListener("abort",_,{once:!0}),e.aborted&&_()},async cleanup(b){let y;try{e.removeEventListener("abort",_)}catch(A){y=A}if(!i){let A=h();if(A&&!b&&!e.aborted)try{await A}catch(O){y??(y=O)}}if(t)try{t.releaseLock()}catch(A){y??(y=A)}if(y!==void 0&&!b&&!e.aborted)throw y}}}async function*j_(n,e){if(!n.body)throw e.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative"?new f("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 f("Attempted to iterate over a response with no body");let t=new Fc,r=new Dr,{signal:o}=e,i=k_(n.body,o),s=!1;try{i.start();for await(let c of $_(i.iterator)){if(o.aborted)return;for(let d of r.decode(c)){if(o.aborted)return;let h=t.decode(d);h&&(yield h)}}if(o.aborted)return;for(let c of r.flush()){if(o.aborted)return;let d=t.decode(c);d&&(yield d)}if(o.aborted)return;let a=t.flush();a&&(yield a)}catch(a){if(s=!0,!o.aborted||!Ct(a)&&a!==o.reason)throw a}finally{await i.cleanup(s)}}var q_=3;async function*$_(n){let e=new Uint8Array,t=0,r=0,o=0;for await(let i of n){if(i==null)continue;let s;if(i instanceof ArrayBuffer?s=new Uint8Array(i):typeof i=="string"?s=me(i):s=i,r+s.length>e.length){let c=r-t;if(t>=e.length/2&&c+s.length<=e.length)e.copyWithin(0,t,r);else{let d=new Uint8Array(Math.max(e.length*2,c+s.length));d.set(e.subarray(t,r)),e=d}o-=t,t=0,r=c}e.set(s,r),r+=s.length;let a;for(;(a=qd(e.subarray(o,r)))!==-1;)a+=o,yield e.slice(t,a),t=a,o=t;o=Math.max(t,r-q_)}r>t&&(yield e.slice(t,r))}var Fc=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.slice(0,-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
8
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,,r]=D_(e,":"),o=r;return o.startsWith(" ")&&(o=o.slice(1)),t==="event"?this.event=o:t==="data"&&this.data.push(o),null}flush(){return this.decode("")}};function D_(n,e){let t=n.indexOf(e);return t!==-1?[n.slice(0,t),e,n.slice(t+e.length)]:[n,"",""]}async function Fr(n,e){let{response:t,requestLogID:r,retryOfRequestLogID:o,startTime:i}=e,s,a=await(async()=>{if(e.options.stream)return ie(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData,e.options.__streamMode):$e.fromSSEResponse(t,e.controller,n,e.options.__synthesizeEventData,e.options.__streamMode);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let d=t.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(d?.includes("application/json")||d?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let b=await t.text();if(!b)return;let y=JSON.parse(b);return s=b.length,li(y,t)}return await t.text()})().catch(c=>{throw F_(c,e.controller.signal)});return n.logLevel==="debug"&&ie(n).debug(`[${r}] response parsed`,Tt({retryOfRequestLogID:o,url:t.url,status:t.status,body:s===void 0?a:{type:"json",length:s},durationMs:Date.now()-i})),a}function F_(n,e){if(!e.aborted||n!==e.reason||Ct(n))return n;let t="This operation was aborted",r=globalThis.DOMException;return typeof r=="function"?new r(t,"AbortError"):Object.assign(new Error(t),{name:"AbortError"})}function li(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var sr="7.59.0";var Bd=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function z_(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var M_=()=>{let n=z_();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":sr,"X-Stainless-OS":Md(Deno.build.os),"X-Stainless-Arch":zd(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":sr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":sr,"X-Stainless-OS":Md(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zd(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=L_();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":sr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":sr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function L_(){if(typeof navigator>"u"||!navigator)return null;let n=[{key:"edge",pattern:/\bEdg(?:e|A|iOS)?\b(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let r=t.exec(navigator.userAgent);if(r){let o=r[1]||0,i=r[2]||0,s=r[3]||0;return{browser:e,version:`${o}.${i}.${s}`}}}return null}var zd=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Md=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),Ld,Kd=()=>Ld??(Ld=M_());var di=new WeakMap;function Qa(n,e){let t=di.get(n);return t||(t=new Set,di.set(n,t)),t.add(e),()=>{let r=di.get(n);r&&(r.delete(e),r.size===0&&di.delete(n))}}var Nd=({headers:n,body:e})=>{let t=typeof e=="object"&&e!==null?di.get(e):void 0,r;if(!t||t.size===0)r=JSON.stringify(e);else{let o=[...t];r=JSON.stringify(e,function(i,s){let a=s;for(let c of o){let d=c.value(this,i,a);d!==void 0&&(a=d)}return a});for(let i of o)i.complete()}return{bodyHeaders:{"content-type":"application/json"},body:r}};var zc="RFC3986",Mc=String,Lc={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:Mc},Wd="RFC1738";var Ud,Qd=(n,e)=>{let t=Ud??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return Ud=t,t(n,e)};var yt=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var Bc=1024,Hd=(n,e,t,r,o)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,a=>"%26%23"+Number.parseInt(a.slice(2),16)+"%3B");let s="";for(let a=0;a<i.length;){let c=Math.min((Math.floor(a/Bc)+1)*Bc,i.length);c<i.length&&i.codePointAt(c-1)>65535&&(c+=1);let d=i.length>=Bc?i.slice(a,c):i,h=[];for(let _=0;_<d.length;++_){let m=d.charCodeAt(_);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||o===Wd&&(m===40||m===41)){h[h.length]=d.charAt(_);continue}if(m<128){h[h.length]=yt[m];continue}if(m<2048){h[h.length]=yt[192|m>>6]+yt[128|m&63];continue}if(m<55296||m>=57344){h[h.length]=yt[224|m>>12]+yt[128|m>>6&63]+yt[128|m&63];continue}_+=1,m=65536+((m&1023)<<10|d.charCodeAt(_)&1023),h[h.length]=yt[240|m>>18]+yt[128|m>>12&63]+yt[128|m>>6&63]+yt[128|m&63]}s+=h.join(""),a=c}return s};function Xd(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Kc(n,e){if(we(n)){let t=[];for(let r of n)t.push(e(r));return t}return e(n)}var Vd={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat:String},Gd=function(e,t){Array.prototype.push.apply(e,we(t)?t:[t])},Jd,fe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Hd,encodeValuesOnly:!1,format:zc,formatter:Mc,indices:!1,serializeDate(n){return(Jd??(Jd=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function K_(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var Nc={};function Yd(n,e,t,r,o,i,s,a,c,d,h,_,m,b,y,A,O,S){let P=n,q=S,E=0,z=!1;for(;(q=q.get(Nc))!==void 0&&!z;){let C=q.get(n);if(E+=1,C!==void 0){if(C===E)throw new RangeError("Cyclic object value");z=!0}q.get(Nc)===void 0&&(E=0)}if(typeof d=="function"?P=d(e,P):P instanceof Date?P=m?.(P):t==="comma"&&we(P)&&(P=Kc(P,C=>C instanceof Date?m?.(C):C)),P===null){if(i)return c&&!A?c(e,fe.encoder,O,"key",b):e;P=""}if(K_(P)||Xd(P)){if(c){let C=A?e:c(e,fe.encoder,O,"key",b);return[y?.(C)+"="+y?.(c(P,fe.encoder,O,"value",b))]}return[y?.(e)+"="+y?.(String(P))]}let R=[];if(P===void 0)return R;let v;if(t==="comma"&&we(P))A&&c&&(P=Kc(P,c)),v=[{value:P.length>0?P.join(",")||null:void 0}];else if(we(d))v=d;else{let C=Object.keys(P);h&&C.sort(h),v=C}let I=a?String(e).replace(/\./g,"%2E"):String(e),j=r&&we(P)&&P.length===1?I+"[]":I;if(o&&we(P)&&P.length===0)return j+"[]";for(let C of v){let $=typeof C=="object"&&C.value!==void 0?C.value:P[C];if(s&&$===null)continue;let T=_&&a?C.replace(/\./g,"%2E"):C,F;we(P)?F=typeof t=="function"?t(j,T):j:F=j+(_?"."+T:"["+T+"]"),S.set(n,E);let K=new WeakMap([[Nc,S]]);Gd(R,Yd($,F,t,r,o,i,s,a,t==="comma"&&A&&we(P)?null:c,d,h,_,m,b,y,A,O,K))}return R}function N_(n=fe){if(n.allowEmptyArrays!==void 0&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(n.encodeDotInKeys!==void 0&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&n.encoder!==void 0&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||fe.charset;if(n.charset!==void 0&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=zc;if(n.format!==void 0){if(!Qd(Lc,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=Lc[t],o=fe.filter;(typeof n.filter=="function"||we(n.filter))&&(o=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in Vd?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=fe.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let s;return n.allowDots===void 0?s=n.encodeDotInKeys?!0:fe.allowDots:s=!!n.allowDots,{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:fe.addQueryPrefix,allowDots:s,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:fe.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:fe.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:n.delimiter===void 0?fe.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:fe.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:fe.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:fe.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:fe.encodeValuesOnly,filter:o,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:fe.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:fe.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:fe.strictNullHandling}}function Zd(n,e={}){let t=n,r=N_(e),o,i;typeof r.filter=="function"?(i=r.filter,t=i("",t)):we(r.filter)&&(i=r.filter,o=i);let s=[];if(typeof t!="object"||t===null)return"";let a=Vd[r.arrayFormat],c=a==="comma"&&r.commaRoundTrip;o||(o=Object.keys(t)),r.sort&&o.sort(r.sort);let d=new WeakMap;for(let m of o)r.skipNulls&&t[m]===null||Gd(s,Yd(t[m],m,a,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,d));let h=s.join(r.delimiter),_=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(_+=r.charset==="iso-8859-1"?"utf8=%26%2310003%3B&":"utf8=%E2%9C%93&"),h.length>0?_+h:""}function ef(n){return Zd(n,{arrayFormat:"brackets"})}var U_=new Map([["global","https://api.openai.com/v1"],["us","https://us.api.openai.com/v1"],["eu","https://eu.api.openai.com/v1"],["ae","https://ae.api.openai.com/v1"],["au","https://au.api.openai.com/v1"],["in","https://in.api.openai.com/v1"],["jp","https://jp.api.openai.com/v1"]]);function Wc(n){if(n.dataResidency===null||n.dataResidency===void 0)return;if(k(n,"baseURL"))throw new f("The `dataResidency` and `baseURL` options are mutually exclusive.");let e=U_.get(n.dataResidency);if(e===void 0)throw new f("Invalid `dataResidency`; expected one of: global, us, eu, ae, au, in, jp.");return e}function Uc(n,e){if(n!=null)throw new f(`${e} does not support \`dataResidency\`.`)}var fi,kt=class n extends Promise{constructor(e,t,r=Fr){super(o=>{o(null)}),this.responsePromise=t,this.parseResponse=r,fi.set(this,void 0),w(this,fi,e,"f")}_thenUnwrap(e){return new n(u(this,fi,"f"),this.responsePromise,async(t,r)=>li(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(u(this,fi,"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)}};fi=new WeakMap;var Ha,zr=class{constructor(e,t,r,o){Ha.set(this,void 0),w(this,Ha,e,"f"),this.options=o,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new f("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,Ha,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ha=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},pi=class extends kt{constructor(e,t,r){super(e,t,async(o,i)=>new r(o,i.response,await Fr(o,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},_e=class extends zr{constructor(e,t,r,o){super(e,t,r,o),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},x=class extends zr{constructor(e,t,r,o){super(e,t,r,o),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...ni(this.options.query),after:t}}:null}},N=class extends zr{constructor(e,t,r,o){super(e,t,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ni(this.options.query),after:e}}:null}},se=class extends zr{constructor(e,t,r,o){super(e,t,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ni(this.options.query),after:e}}:null}},Nn=class extends zr{constructor(e,t,r,o){super(e,t,r,o),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ni(this.options.query),page:e}}:null}};var H_={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},X_="urn:ietf:params:oauth:grant-type:token-exchange",J_=.5;function V_(n,e){if(typeof n!="number"||!Number.isFinite(n)||n<=0)throw new f("Token exchange response has invalid 'expires_in' field");let t=Date.now(),r=t+n*1e3;if(!Number.isSafeInteger(r)||r<=t)throw new f("Token exchange response has invalid 'expires_in' field");let o=r-(performance.now()-e);if(o<=t)throw new f("Workload identity token expired before its exchange completed.");return o}function G_(n,e,t){let r=(t??1200)*1e3,o=Math.min(r,e*1e3*J_);return n-o}var tf=Response.prototype,Y_=tf.arrayBuffer;function Z_(n,e){let t=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(e===n||typeof t!="function"||Object.getOwnPropertyDescriptor(t,"name")?.value!=="Response"||Object.getOwnPropertyDescriptor(t,"prototype")?.value!==e)return!1;let r=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);return(r?.value==="Response"||typeof r?.get=="function")&&typeof Object.getOwnPropertyDescriptor(e,"headers")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"ok")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"status")?.get=="function"}function ey(n,e){if(n===e)return!0;let t=Object.getOwnPropertyDescriptor(n,"constructor")?.value;return e!==null&&Object.getPrototypeOf(e)===n&&typeof t=="function"&&Object.getOwnPropertyDescriptor(t,"name")?.value==="Body"&&Object.getOwnPropertyDescriptor(t,"prototype")?.value===n}function ty(n){let e=globalThis;return new TextDecoder("utf-8",{ignoreBOM:typeof e.Bun?.version=="string"}).decode(n)}async function ry(n){let e,t=null;for(let o=0,i=n;i!==null&&o<16&&i!==tf;i=Object.getPrototypeOf(i),o+=1){Z_(n,i)&&(t=i);let s=Object.getOwnPropertyDescriptor(i,"json");if(!s)continue;if(typeof s.value!="function")break;let a=Object.getOwnPropertyDescriptor(i,"text")?.value;if(typeof a=="function"&&ey(i,t)){e=a;break}return s.value.call(n)}let r=e===void 0?ty(await Y_.call(n)):await e.call(n);try{return JSON.parse(r)}catch{throw new SyntaxError("Token exchange response contains invalid JSON")}}function ny(n){return typeof globalThis.Bun?.version=="string"?/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(n):/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(n)}var Xa=class n{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl="https://auth.openai.com/oauth/token";let{identityProviderId:r,serviceAccountId:o,clientId:i,refreshBufferSeconds:s,provider:a}=e;this.config={identityProviderId:r,serviceAccountId:o,...i===void 0?{}:{clientId:i},...s===void 0?{}:{refreshBufferSeconds:s},provider:{tokenType:a.tokenType,getToken:a.getToken.bind(a)}},this.fetch=t??oi()}async getToken(){if(!this.cachedToken||n.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;let e=this.refreshToken(this.tokenGeneration);this.refreshPromise=e;try{return await e}finally{this.refreshPromise===e&&(this.refreshPromise=null)}}if(n.needsRefresh(this.cachedToken)&&!this.refreshPromise){let e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){let t=await this.config.provider.getToken(),r={grant_type:X_,subject_token:t,subject_token_type:H_[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(r.client_id=this.config.clientId);let o=performance.now(),i=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r),redirect:"manual"});if(!i.ok){let h=await i.text(),_;try{_=JSON.parse(h)}catch{}throw i.status===400||i.status===401||i.status===403?new Je(i.status,_,i.headers):H.generate(i.status,_,`Token exchange failed with status ${i.status}`,i.headers)}let s=await ry(i),a=typeof s=="object"&&s!==null&&"access_token"in s?s.access_token:void 0;if(typeof a!="string"||a.trim().length===0||ny(a))throw new f("Token exchange response missing 'access_token' field");let c=s.expires_in??3600,d=V_(c,o);return this.tokenGeneration===e&&(this.cachedToken={token:a,expiresAt:d,refreshAt:G_(d,c,this.config.refreshBufferSeconds)}),a}static isTokenExpired(e){return Date.now()>=e.expiresAt}static needsRefresh(e){return Date.now()>=e.refreshAt}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}};var rf="https://mtls.api.openai.com/v1";function Wn(n){let e;try{e=new URL(n)}catch{throw new f("X.509 workload identity requires the approved global mTLS API origin.")}if(e.origin!=="https://mtls.api.openai.com"||e.username||e.password)throw new f("X.509 workload identity requires the approved global mTLS API origin.");for(let t of e.searchParams.keys())if(ci(t))throw new f("X.509 workload identity cannot send conflicting query authentication credentials.");return e}var nf=Symbol("brand.privateNullableHeaders"),sy=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*oy(n){if(!n)return;if(nf in n){let{values:o,nulls:i}=n;yield*o.entries();for(let s of i)yield[s,null];return}let e=!1,t,r=Symbol.iterator in n?n[Symbol.iterator]:void 0;typeof r=="function"?t={[Symbol.iterator]:()=>r.call(n)}:(e=!0,t=Object.entries(n??{}));for(let o of t){let i=o[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=Pd(o[1])?o[1]:[o[1]],a=!1;for(let c of s)c!==void 0&&(e&&!a&&(a=!0,yield[i,null]),yield[i,c])}}var g=n=>{let e=new Headers,t=new Set;for(let r of n){let o=new Set;for(let[i,s]of oy(r)){if(!sy.test(i))throw new TypeError(`Header name must be a valid HTTP token ["${i}"]`);let a=i.toLowerCase();o.has(a)||(e.delete(a),o.add(a)),s===null?(e.delete(a),t.add(a)):(e.append(a,s),t.delete(a))}}return{[nf]:!0,values:e,nulls:t}};var Qc={};R_(Qc,{findRegisteredX509Transport:()=>iy,findX509Credential:()=>yy,findX509OAuthError:()=>my,isApprovedX509Client:()=>py,isRetryableX509IssuerError:()=>dy,isTransientX509ConnectionError:()=>cy,markApprovedX509Client:()=>fy,markRetryableX509IssuerError:()=>ly,markTransientX509ConnectionError:()=>uy,rememberRegisteredX509Transport:()=>ay,rememberX509Credential:()=>_y,rememberX509OAuthError:()=>hy});var sf=new WeakMap,of=new WeakSet,af=new WeakSet,uf=new WeakSet,cf=new WeakMap,lf=new WeakMap,iy=WeakMap.prototype.get.bind(sf),ay=WeakMap.prototype.set.bind(sf),uy=WeakSet.prototype.add.bind(of),cy=WeakSet.prototype.has.bind(of),ly=WeakSet.prototype.add.bind(af),dy=WeakSet.prototype.has.bind(af),fy=WeakSet.prototype.add.bind(uf),py=WeakSet.prototype.has.bind(uf),hy=WeakMap.prototype.set.bind(cf),my=WeakMap.prototype.get.bind(cf),_y=WeakMap.prototype.set.bind(lf),yy=WeakMap.prototype.get.bind(lf);var Hc=O_(df(),1),gy=typeof Hc.findRegisteredX509Transport=="function"?Hc:Qc,{findRegisteredX509Transport:ff,rememberRegisteredX509Transport:$P,markTransientX509ConnectionError:DP,isTransientX509ConnectionError:Va,markRetryableX509IssuerError:FP,isRetryableX509IssuerError:Xc,markApprovedX509Client:pf,isApprovedX509Client:by,rememberX509OAuthError:zP,findX509OAuthError:hf,rememberX509Credential:MP,findX509Credential:mf}=gy;function _f(n){if(!n||typeof n!="object")throw new f("X.509 workload identity requires an approved X.509 transport capability.");let e=ff(n);if(!e)throw new f("X.509 workload identity requires an approved X.509 transport capability.");return e}var Q,ve,Mr,Lr,gt,Ve,qt,$t,ye,Br,jt,Ye,Ge,wf,Ya,Af,yf,Rf,Of,gf,Pf,G,Vc,wy=["dispatcher","agent","client","tls","proxy"],Un=(n,e)=>Headers.prototype.get.call(n,e),Ay=1200*1e3,bf=1e3,Ga=n=>{let e=new V;return Object.defineProperty(e,"cause",{value:n.reason,writable:!0,configurable:!0}),e};function Jc(n){for(let e of Headers.prototype.keys.call(n)){let t=e.toLowerCase().split("_").join("-");if(t!=="authorization"&&Ka(t)||t==="host")throw new f("X.509 workload identity cannot send conflicting authentication credentials.")}}function Ry(n,e){let t=new AbortController,r=n===void 0?void 0:setTimeout(()=>t.abort(new re),n),o=r;typeof o=="object"&&o!==null&&"unref"in o&&typeof o.unref=="function"&&o.unref();let i=()=>t.abort(e?.reason);return e?.addEventListener("abort",i,{once:!0}),e?.aborted&&i(),{signal:t.signal,dispose:()=>{e?.removeEventListener("abort",i),r&&clearTimeout(r)}}}function Oy(n,e){let t,r=new Promise((o,i)=>{t=()=>i(e.reason),e.addEventListener("abort",t,{once:!0}),e.aborted&&t()});return{result:Promise.race([n.promise,r]),dispose:()=>{t&&e.removeEventListener("abort",t)}}}function Za(n){if(!n||typeof n!="object")return!1;let e=n;for(;e!==null&&e!==Object.prototype;){let r=Object.getOwnPropertyDescriptor(e,"provider");if(r){if(!("value"in r)||r.value!==void 0)return!1;break}e=Object.getPrototypeOf(e)}let t=n;for(;t!==null&&t!==Object.prototype;){let r=Object.getOwnPropertyDescriptor(t,"type");if(r){if(!("value"in r))throw new f("X.509 workload identity type must be a plain data property.");return r.value==="x509"}t=Object.getPrototypeOf(t)}return!1}function Gc(n){if(!n)return;for(let t of wy)if(k(n,t))throw new f("X.509 workload identity cannot override its approved transport capability.");let e=Object.getOwnPropertyDescriptor(n,"redirect")?.value;if(e!==void 0&&e!=="manual")throw new f("X.509 workload identity requests require manual redirects.")}function hi(n){if(Gc(n),n&&["body","headers","method","signal"].some(e=>k(n,e)))throw new f("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.")}function Yc(n){hi(n);let e={...n};return hi(e),e}var Ae=class{constructor(e,t,r,o){if(Q.add(this),Mr.set(this,void 0),Lr.set(this,void 0),gt.set(this,void 0),Ve.set(this,void 0),qt.set(this,void 0),$t.set(this,void 0),ye.set(this,void 0),Br.set(this,void 0),jt.set(this,void 0),Ye.set(this,void 0),Ge.set(this,0),w(this,ye,_f(t),"f"),w(this,Mr,e.identityProviderId,"f"),w(this,Lr,e.serviceAccountId,"f"),w(this,gt,e.refreshBufferMs,"f"),w(this,Ve,e.refreshBufferSeconds,"f"),w(this,qt,r,"f"),w(this,$t,o,"f"),u(this,gt,"f")!==void 0&&u(this,Ve,"f")!==void 0)throw new f("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");if(u(this,gt,"f")!==void 0&&(!Number.isSafeInteger(u(this,gt,"f"))||u(this,gt,"f")<0))throw new f("X.509 workload identity requires a nonnegative integer refreshBufferMs.");if(u(this,Ve,"f")!==void 0&&(!Number.isSafeInteger(u(this,Ve,"f"))||u(this,Ve,"f")<0||!Number.isSafeInteger(u(this,Ve,"f")*1e3)))throw new f("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");w(this,Br,u(this,Ve,"f")===void 0?u(this,gt,"f")??Ay:u(this,Ve,"f")*1e3,"f")}identitySnapshot(){return{type:"x509",identityProviderId:u(this,Mr,"f"),serviceAccountId:u(this,Lr,"f"),...u(this,gt,"f")===void 0?{}:{refreshBufferMs:u(this,gt,"f")},...u(this,Ve,"f")===void 0?{}:{refreshBufferSeconds:u(this,Ve,"f")}}}static shouldAuthenticate(e,t,r=e.headers){return!g([t,r]).nulls.has("authorization")}snapshotHeaders(e,t){let r=u(this,Q,"m",G).call(this);return r.defaultHeaders??(r.defaultHeaders=g([e])),r.requestHeaders??(r.requestHeaders=g([t])),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:t}=u(this,Q,"m",G).call(this);if(!e||!t)throw new f("X.509 workload identity requires snapshotted request headers.");return{defaultHeaders:e,requestHeaders:t}}snapshotTenant(e,t){if(e!==u(this,qt,"f")||t!==u(this,$t,"f"))throw new f("X.509 workload identity cannot override its enrolled organization or project.");let r=u(this,Q,"m",G).call(this);return r.tenant={organization:e,project:t},r.tenant}tenantSnapshot(){let{tenant:e}=u(this,Q,"m",G).call(this);if(!e)throw new f("X.509 workload identity requires snapshotted tenant selectors.");return e}snapshotAPIURL(e){Wn(e),u(this,Q,"m",G).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=u(this,Q,"m",G).call(this);if(e===void 0)throw new f("X.509 workload identity requires a snapshotted API destination.");return e}snapshotRequest(e,t,r){var o;(o=u(this,Q,"m",G).call(this)).request??(o.request={signal:e,timeout:t,fetchOptions:r})}requestSnapshot(){let{request:e}=u(this,Q,"m",G).call(this);if(!e)throw new f("X.509 workload identity requires snapshotted request settings.");return e}beginRequestPreparation(){let e=u(this,Q,"m",G).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){u(this,Q,"m",G).call(this).phase="planning"}beginRequestNetwork(){let e=u(this,Q,"m",G).call(this);e.deadlineArmed?e.preparationStartedAt!==void 0&&(e.monotonicStartedAt+=performance.now()-e.preparationStartedAt,e.wallStartedAt+=Date.now()-(e.preparationWallStartedAt??Date.now()),delete e.preparationStartedAt,delete e.preparationWallStartedAt):(e.wallStartedAt=Date.now(),e.monotonicStartedAt=performance.now(),e.deadlineArmed=!0)}isPlanningRequest(){return u(this,Q,"m",G).call(this).phase==="planning"}authorizePlannedRequest(e,t,r,o=!1){let i=u(this,Q,"m",G).call(this),s=Object.getOwnPropertyDescriptor(t,"headers"),a=Object.getOwnPropertyDescriptor(t,"body"),c=Object.getOwnPropertyDescriptor(t,"signal"),d=Object.getOwnPropertyDescriptor(t,"redirect");if(i.phase!=="planning"||!s||!(s.value instanceof Headers)||!a&&"body"in t||[a,c,d].some(_=>_&&!("value"in _)))throw new f("X.509 workload identity requires an approved final request.");this.snapshotAPIURL(e),Gc(t);try{Jc(s.value)}catch{throw new f("X.509 workload identity cannot use caller-supplied authentication credentials.")}if(Un(s.value,"Authorization")!==null)throw new f("X.509 workload identity cannot use caller-supplied authorization credentials.");if(u(this,Q,"m",Vc).call(this,s.value),!o&&(c?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new f("X.509 workload identity must preserve its approved request signal.");let h=this.requestSnapshot();i.request={...h,timeout:Math.min(h.timeout,r)},i.phase="authorizing"}ownRequestBody(e,t){e instanceof ReadableStream&&e!==t&&(u(this,Q,"m",G).call(this).materializedBody=e)}static isStreamingRequestBody(e){return globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream||typeof e=="object"&&e!==null&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")}retireRequestBody(){let e=u(this,Q,"m",G).call(this),t=e.materializedBody;delete e.materializedBody,t&&u(ve,ve,"m",wf).call(ve,t)}releaseRequestBody(e){let t=u(this,Q,"m",G).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?u(this,Q,"m",G).call(this).effectiveSignal=e:delete u(this,Q,"m",G).call(this).effectiveSignal}effectiveSignal(){let e=u(this,Q,"m",G).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,t){return u(this,ye,"f").run(async()=>{let r=u(this,ye,"f").current();if(!r)throw new f("X.509 workload identity requires an active certificate request scope.");r.owner=this,r.requestOwner=t;try{return await e()}finally{this.retireRequestBody(),this.releaseRequestCredentials(),delete r.requestOwner,delete r.owner}})}inRequest(e){let t=u(this,ye,"f").current();return t?.owner===this&&t.requestOwner===e&&t.phase!=="authorizing"}matches(e){return u(this,ye,"f")===u(e,ye,"f")&&u(this,Mr,"f")===u(e,Mr,"f")&&u(this,Lr,"f")===u(e,Lr,"f")&&u(this,qt,"f")===u(e,qt,"f")&&u(this,$t,"f")===u(e,$t,"f")&&u(this,Br,"f")===u(e,Br,"f")}continuation(){let{wallStartedAt:e,monotonicStartedAt:t,deadlineArmed:r,request:o,requestOwner:i,effectiveSignal:s}=u(this,Q,"m",G).call(this),a={wallStartedAt:e,monotonicStartedAt:t,owner:this,...r?{deadlineArmed:r}:{},...o?{request:o}:{},...s?{effectiveSignal:s}:{},...i?{requestOwner:i}:{}};return c=>u(this,ye,"f").resume(a,async()=>{try{return await c()}finally{this.releaseRequestCredentials(),delete a.requestOwner,delete a.owner}})}releaseRequestCredentials(){let e=u(this,Q,"m",G).call(this);delete e.request,delete e.phase,delete e.deadlineArmed,delete e.preparationStartedAt,delete e.preparationWallStartedAt,delete e.effectiveSignal,delete e.materializedBody,delete e.apiURL,delete e.tenant,delete e.token,delete e.defaultHeaders,delete e.requestHeaders,delete e.tokenGeneration,delete e.headers,delete e.authorization}requestStartedAt(e){return u(this,ye,"f").current()?.wallStartedAt}usedWorkloadToken(e){return u(this,ye,"f").current()?.token!==void 0}remainingTimeout(e,t){let r=u(this,ye,"f").current();if(r===void 0)return t;let o=t-(performance.now()-r.monotonicStartedAt);if(o<=0)throw new re;return o}async waitForRetry(e,t){try{await u(this,ye,"f").sleep(e,t)}catch(r){throw t?.aborted?Ga(t):r}}static isRetryableFailure(e){return typeof e=="object"&&e!==null&&(Va(e)||Xc(e))}static retryHeaders(e){if(!e||typeof e!="object"||!Xc(e))return;let t=Object.getOwnPropertyDescriptor(e,"headers")?.value;return t instanceof Headers?t:void 0}async getToken(e,t){let r=t?t.signal:e?.signal;if(r?.aborted)throw Ga(r);e&&hi(t?t.fetchOptions:e.fetchOptions),u(this,Q,"m",Pf).call(this,t);let o=e?u(this,Q,"m",G).call(this):void 0,i=u(this,jt,"f");if(i&&performance.now()<i.refreshAt&&Date.now()<i.wallRefreshAt)return u(ve,ve,"m",Ya).call(ve,o,i);let s=t&&e?this.remainingTimeout(e,t.timeout):t?.timeout,{signal:a,dispose:c}=Ry(s,r);if(r?.aborted)throw c(),Ga(r);let d=u(this,Ye,"f")??u(this,Q,"m",Of).call(this);d.waiters+=1;let h=Oy(d,a);try{let _=await h.result,m=u(this,jt,"f");if(!m||m.accessToken!==_.accessToken)throw new V;return u(ve,ve,"m",Ya).call(ve,o,m)}catch(_){return await u(this,Q,"m",Af).call(this,_,d,i,o,e,t)}finally{h.dispose(),c(),d.waiters-=1,u(this,Q,"m",Rf).call(this,d)}}invalidateToken(){let e=u(this,ye,"f").current();if(!e?.token||u(this,jt,"f")?.accessToken!==e.token||u(this,jt,"f").generation!==e.tokenGeneration)return;w(this,Ge,u(this,Ge,"f")+1,"f"),w(this,jt,void 0,"f");let t=u(this,Ye,"f");w(this,Ye,void 0,"f"),t?.controller.abort(new V)}bindRequest(e,t,r){if(!(t.headers instanceof Headers))throw new f("X.509 workload identity requires the original workload authorization headers.");let o=u(this,Q,"m",G).call(this),{token:i}=o,s=e.__security??{bearerAuth:!0},a=i?`Bearer ${i}`:null;!i&&s.adminAPIKeyAuth&&r!==null&&Un(t.headers,"Authorization")!==null&&(a=new Headers({Authorization:`Bearer ${r}`}).get("Authorization")),o.headers=t.headers,o.authorization=a,this.assertRequest(t)}adoptRequestHeaders(e){let t=u(this,Q,"m",G).call(this),r=t.headers;if(!(r instanceof Headers)||!(e.headers instanceof Headers))throw new f("X.509 workload identity must preserve its issued workload authorization.");t.headers=e.headers;try{this.assertRequest(e)}catch(o){throw t.headers=r,o}}assertRequest(e){let{headers:t}=e;if(!(t instanceof Headers))throw new f("X.509 workload identity must preserve its issued workload authorization.");let r=u(this,ye,"f").current();if(!r||r.headers!==t||r.authorization===void 0||Un(t,"Authorization")!==r.authorization)throw new f("X.509 workload identity must preserve its issued workload authorization.");u(this,Q,"m",Vc).call(this,t),Jc(t)}fetch(){return async(e,t={})=>{let r=Wn(typeof e=="string"||e instanceof URL?e:e.url);Gc(t),this.assertRequest(t);let o=t.headers;if(!(o instanceof Headers))throw new f("X.509 workload identity must preserve its issued workload authorization.");let i=new Headers([...Headers.prototype.entries.call(o)]);return Jc(i),t.headers=i,t.redirect="manual",await u(this,ye,"f").dispatch(r,t)}}};ve=Ae,Mr=new WeakMap,Lr=new WeakMap,gt=new WeakMap,Ve=new WeakMap,qt=new WeakMap,$t=new WeakMap,ye=new WeakMap,Br=new WeakMap,jt=new WeakMap,Ye=new WeakMap,Ge=new WeakMap,Q=new WeakSet,wf=async function(e){try{await ut(e)}catch{}},Ya=function(e,t){return e&&(e.token=t.accessToken,e.tokenGeneration=t.generation),t.accessToken},Af=async function(e,t,r,o,i,s){let a=s?s.signal:i?.signal;if(a?.aborted)throw Ga(a);if(t.controller.signal.aborted&&t.generation!==u(this,Ge,"f"))return await this.getToken(i,s);let c=u(this,Q,"m",yf).call(this,e,r,o);if(c!==void 0)return c;if(e&&typeof e=="object"&&!(e instanceof Je)){let d=hf(e);if(d)throw new Je(d.status,d.error,d.headers)}throw e},yf=function(e,t,r){if(!t||t!==u(this,jt,"f")||performance.now()>=t.expiresAt||Date.now()>=t.wallExpiresAt||!ve.isRetryableFailure(e))return;let o=ve.retryHeaders(e),i=o?.get("retry-after-ms"),s=i?Number(i):void 0,a=o?.get("retry-after");if(a&&(s===void 0||Number.isNaN(s))){let d=Number(a);s=Number.isNaN(d)?Date.parse(a)-Date.now():d*1e3}let c=s!==void 0&&Number.isFinite(s)&&s>=0&&s<=6e4?Math.max(bf,s):bf;return t.refreshAt=Math.min(t.expiresAt,performance.now()+c),t.wallRefreshAt=Math.min(t.wallExpiresAt,Date.now()+c),u(ve,ve,"m",Ya).call(ve,r,t)},Rf=function(e){e.waiters!==0||u(this,Ye,"f")!==e||queueMicrotask(()=>{e.waiters===0&&u(this,Ye,"f")===e&&(w(this,Ye,void 0,"f"),w(this,Ge,u(this,Ge,"f")+1,"f"),e.controller.abort(new V))})},Of=function(){let e=new AbortController,t=u(this,Ge,"f"),r={controller:e,generation:t,waiters:0,promise:u(this,Q,"m",gf).call(this,e,t)};return w(this,Ye,r,"f"),r},gf=async function(e,t){let r=performance.now(),o=Date.now();try{let i=await u(this,ye,"f").exchange(u(this,Mr,"f"),u(this,Lr,"f"),e.signal),s=i.expiresIn*1e3,a=r+s,c=o+s;if(performance.now()>=a||Date.now()>=c)throw new f("X.509 workload identity token expired before its exchange completed.");if(u(this,Ge,"f")!==t||e.signal.aborted||u(this,Ye,"f")?.controller!==e)throw new V;return w(this,Ge,u(this,Ge,"f")+1,"f"),w(this,jt,{accessToken:i.accessToken,generation:u(this,Ge,"f"),expiresAt:a,refreshAt:a-Math.min(u(this,Br,"f"),s/2),wallExpiresAt:c,wallRefreshAt:c-Math.min(u(this,Br,"f"),s/2)},"f"),i}finally{u(this,Ye,"f")?.controller===e&&w(this,Ye,void 0,"f")}},Pf=function(e){if(!e)return;if(e.organization!==u(this,qt,"f")||e.project!==u(this,$t,"f"))throw new f("X.509 workload identity cannot override its enrolled organization or project.");Wn(e.apiURL);let t=g([e.defaultHeaders,e.requestHeaders]);if(u(this,qt,"f")!==null&&t.nulls.has("openai-organization")||u(this,$t,"f")!==null&&t.nulls.has("openai-project"))throw new f("X.509 workload identity cannot omit its enrolled organization or project.");for(let r of t.values.keys()){let o=r.toLowerCase().split("_").join("-");if((o==="openai-organization"||o==="openai-project")&&(r!==o||Un(t.values,r)!==(o==="openai-organization"?e.organization:e.project)))throw new f("X.509 workload identity cannot override its enrolled organization or project.");if(Ka(o)||o==="host")throw new f("X.509 workload identity cannot use caller-supplied authentication credentials.")}},G=function(){let e=u(this,ye,"f").current();if(!e||e.owner!==this)throw new f("X.509 workload identity requires an active certificate request scope.");return e},Vc=function(e){if(Un(e,"OpenAI-Organization")!==u(this,qt,"f")||Un(e,"OpenAI-Project")!==u(this,$t,"f"))throw new f("X.509 workload identity cannot override its enrolled organization or project.");for(let t of Headers.prototype.keys.call(e)){let r=t.toLowerCase().split("_").join("-");if((r==="openai-organization"||r==="openai-project")&&t!==r)throw new f("X.509 workload identity cannot override its enrolled organization or project.")}};function xf(n){let{credential:e}=n;if(e===void 0)return{credential:e,options:n};let t=mf(e);if(!t)throw new f("An X.509 credential must be created by the SDK authentication helper.");let r=["apiKey","adminAPIKey","workloadIdentity","x509Transport"].filter(o=>{let i=n[o];return i!=null});if(r.length>0)throw new f(`The \`credential\` option cannot be combined with ${r.map(o=>`\`${o}\``).join(", ")}.`);return{credential:e,options:{...n,apiKey:null,adminAPIKey:null,baseURL:n.baseURL??null,organization:n.organization??null,project:n.project??null,workloadIdentity:t.identity,x509Transport:t.transport}}}function Py({apiKey:n,adminAPIKey:e}){return n!=null||e!=null}function xy(n,e){let t=n.provider,r=e.credential??e.workloadIdentity,o=e.provider??(r?void 0:t);return o!==t&&(delete n.baseURL,delete n.organization,delete n.project,delete n.defaultHeaders,delete n.defaultQuery,delete n.fetchOptions,delete n.fetch),o&&(delete n.apiKey,delete n.adminAPIKey,delete n.credential,delete n.workloadIdentity,delete n.x509Transport,delete n.baseURL),o}function vf(n,e,t,r){let o=k(e,"workloadIdentity")?e.workloadIdentity:n.workloadIdentity,i=t!==void 0&&(Py(e)&&e.workloadIdentity===void 0||e.provider!==void 0);t!==void 0&&k(e,"workloadIdentity")&&delete n.x509Transport;let s=t!==void 0&&!i&&e.credential===void 0&&!k(e,"workloadIdentity")&&!k(e,"x509Transport")?t:void 0,a=e.credential===void 0?s:e.credential,c=a!==void 0||!i&&Za(o);return r!==c&&(delete n.fetch,delete n.baseURL,delete n.organization,delete n.project,delete n.defaultHeaders,delete n.defaultQuery,delete n.fetchOptions,c?n.apiKey=null:(delete n.x509Transport,i&&delete n.workloadIdentity)),a!==void 0&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.x509Transport,n.credential=a,e.credential!==void 0&&(delete n.organization,delete n.project,delete n.defaultHeaders,delete n.defaultQuery,delete n.fetchOptions)),{credential:a,provider:xy(n,e)}}var Cf=Symbol("brand.privateStreamingFile");function tu(n,e,t){if(typeof e!="string"||!e)throw new TypeError("toStreamingFile requires a non-empty file name");let r=t?.type;return r&&Df(r),{[Cf]:!0,data:n,name:e,...r?{type:r}:{}}}var nl=()=>{if(typeof File>"u"){let{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&Number.parseInt(n.versions.node.split("."),10)<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Dt(n,e,t){return nl(),new File(n,e??"unknown_file",t)}function Kr(n,e){if(typeof n!="object"||n===null)return;let t="name"in n?n.name:void 0,r=t&&String(t)||"filename"in n&&n.filename&&String(n.filename);if(r)return e?.stripFilename===!1?Tf(r):Qn(r);let o="url"in n&&n.url&&String(n.url);if(o)try{let s=Qn(new URL(o).pathname);return s===void 0?void 0:Qn(vy(s))}catch{return Qn(o)}let i="path"in n&&n.path&&String(n.path);return i?Qn(i):void 0}function Qn(n){return n.split(/[\\/]/).pop()||void 0}function vy(n){try{let e=decodeURIComponent(n);return/%(?:0[AD]|22)/i.test(e)?n:e.replace(/[\u0000-\u001F\u007F]/gu,encodeURIComponent)}catch{return n}}function Tf(n){let e=n.replace(/\\/g,"/");if(e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.split("/").includes(".."))throw new TypeError("Upload file name must be a safe relative path without parent directory segments");return e}var Iy=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get;function sl(n){try{return Iy?.call(n)!==void 0}catch{return!1}}var Hn=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",bt=async(n,e,t)=>{if(!_i(n.body))return n.__metadata?.finalizeMultipart===!0&&t?.stripFilenames===!1?{...n,__metadata:{...n.__metadata,preserveMultipartFilenames:!0}}:n;let r=n.__metadata?.finalizeMultipart===!0?{...n,__metadata:{...n.__metadata,finalizeMultipart:!1}}:n;return eu(n.body)?qf(r,t):{...r,body:await kf(r.body,e,t)}},ee=async(n,e,t)=>eu(n.body)?qf(n,t):{...n,body:await kf(n.body,e,t)},If=new WeakMap;function Sy(n){let e=typeof n=="function"?n:n.fetch,t=If.get(e);if(t)return t;let r=(async()=>{try{let o;if("Response"in e)o=e.Response;else{let s=await e("data:,");await s.arrayBuffer(),o=s.constructor}let i=new FormData;return i.toString()!==await new o(i).text()}catch{return!0}})();return If.set(e,r),r}var kf=async(n,e,t={})=>{if(!await Sy(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(n||{}).map(([o,i])=>rl(r,o,i,t))),r},ru=n=>n instanceof Blob,ol=n=>typeof n=="object"&&n!==null&&"getReader"in n&&typeof n.getReader=="function",yi=n=>typeof n=="object"&&n!==null&&Cf in n,nu=n=>typeof n=="object"&&n!==null&&(n instanceof Response||Hn(n)||ol(n)||yi(n)||ru(n)),eu=n=>{if(yi(n)||Hn(n)||ol(n))return!0;if(Array.isArray(n))return n.some(eu);if(n&&typeof n=="object"&&!ru(n)&&!(n instanceof Response)){for(let e of Object.keys(n))if(eu(n[e]))return!0}return!1},_i=n=>{if(nu(n))return!0;if(Array.isArray(n))return n.some(_i);if(n&&typeof n=="object"){for(let e of Object.keys(n))if(_i(n[e]))return!0}return!1},Sf=(n,e)=>{let t=[];for(let r of n)nu(r.value)&&!e.has(r.value)&&e.set(r.value,$f(r.value,{stripFilenames:!1})),t.push(r);return t},el=new WeakMap,jf=n=>{if(typeof n.body!="object"||n.body===null)return;let e=el.get(n.body);e&&(n.stream=e(),el.delete(n.body))},qf=(n,e={})=>{let t=Ef(n.body),r=e.stripFilenames===!1?new WeakMap:void 0,o=r?Sf(t,r):t,i=`openai-${Math.random().toString(36).slice(2)}`;async function*s(){yield*Ey(o,i,e,r)}let a=ii(s(),n.__metadata?.streamFromBody===!0?{highWaterMark:0}:void 0),c=n.body;return n.__metadata?.streamFromBody===!0&&typeof c=="object"&&c!==null&&el.set(a,()=>{let d={...c},h=Ef(d);o=r?Sf(h,r):h;let _=Object.getOwnPropertyDescriptor(d,"stream")?.value;return _===!0||_==="true"}),{...n,body:a,headers:g([{"content-type":`multipart/form-data; boundary=${i}`},n.headers])}};async function*Ey(n,e,t,r){for await(let{key:o,value:i}of n){if(nu(i)){let s=r?.get(i)??$f(i,t),a=Cy(i);yield me(`--${e}\r
9
+ `),yield me(`Content-Disposition: form-data; name="${Zc(o)}"; filename="${Zc(s)}"\r
10
+ Content-Type: ${a}\r
11
+ \r
12
+ `),yield*mi(Ty(i))}else yield me(`--${e}\r
13
+ `),yield me(`Content-Disposition: form-data; name="${Zc(o)}"\r
14
+ \r
15
+ ${String(i)}`);yield me(`\r
16
+ `)}yield me(`--${e}--\r
17
+ `)}function*Ef(n){if(!(!n||typeof n!="object"))for(let[e,t]of Object.entries(n))yield*tl(e,t)}function*tl(n,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${n}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||nu(e))yield{key:n,value:e};else if(Array.isArray(e))for(let t of e)yield*tl(n+"[]",t);else if(typeof e=="object")for(let[t,r]of Object.entries(e))yield*tl(`${n}[${t}]`,r);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function $f(n,e){if(yi(n)){let{name:t}=n;if(typeof t!="string"||!t)throw new TypeError("Streaming upload file name must be a non-empty string");return e.stripFilenames===!1?Tf(t):Qn(t)??"unknown_file"}return Kr(n,{stripFilename:e.stripFilenames})??"unknown_file"}function Cy(n){let e;return yi(n)||ru(n)?{type:e}=n:n instanceof Response&&(e=n.headers.get("content-type")??void 0),Df(e||"application/octet-stream")}function Df(n){if(typeof n!="string")throw new TypeError("Streaming upload content type must be a string");for(let e=0;e<n.length;e+=1){let t=n.codePointAt(e)??0;if(t<=31||t===127)throw new TypeError("Streaming upload content type must not contain control characters")}return n}function Ty(n){return yi(n)?n.data:n}async function*mi(n){if(typeof n=="string")yield me(n);else if(ArrayBuffer.isView(n))yield new Uint8Array(n.buffer,n.byteOffset,n.byteLength);else if(sl(n))yield new Uint8Array(n);else if(n instanceof Response)yield*mi(n.body||await n.blob());else if(n instanceof Blob)typeof n.stream=="function"?yield*mi(n.stream()):yield new Uint8Array(await n.arrayBuffer());else if(ol(n))for await(let e of za(n))yield*mi(e);else if(Hn(n))for await(let e of n)yield*mi(e);else throw new TypeError(`Invalid streaming file chunk: ${String(n)}`)}function Zc(n){return Array.from(n,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e==='"'||e==="\\"?encodeURIComponent(e):e}).join("")}var rl=async(n,e,t,r)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response){let o=await t.blob();n.append(e,Dt([o],Kr(t,{stripFilename:r.stripFilenames}),{type:o.type}))}else if(Hn(t))n.append(e,Dt([await new Response(ii(t)).blob()],Kr(t,{stripFilename:r.stripFilenames})));else if(ru(t)){let o=Kr(t,{stripFilename:r.stripFilenames});o===void 0?n.append(e,t):n.append(e,t,o)}else if(Array.isArray(t)){let o=await Promise.all(t.map(async i=>{let s=new FormData;return await rl(s,e+"[]",i,r),s}));for(let i of o)if(i)for(let[s,a]of i.entries())n.append(s,a)}else if(typeof t=="object")await Promise.all(Object.entries(t).map(([o,i])=>rl(n,`${e}[${o}]`,i,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Ff=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",ky=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Ff(n),jy=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function",qy=(n,e)=>e?.type!=null&&e.type!==n.type||e?.lastModified!=null&&e.lastModified!==n.lastModified||e?.endings!=null,$y=(n,e,t)=>(e==null||e===n.name)&&!qy(n,t);async function su(n,e,t){if(nl(),n=await n,ky(n)){let o={...t,type:t?.type??n.type,lastModified:t?.lastModified??n.lastModified};return n instanceof File?$y(n,e,t)?n:Dt([n],e??n.name,o):Dt([await n.arrayBuffer()],e??n.name,o)}if(jy(n)){let o=await n.blob();e??(e=Kr(n));let i=t?.type===void 0&&o.type?{...t,type:o.type}:t;return Dt(await il(o),e,i)}let r=await il(n);if(e??(e=Kr(n)),t?.type===void 0){let o=r.find(i=>typeof i=="object"&&"type"in i&&!!i.type);o&&(t={...t,type:o.type})}return Dt(r,e,t)}async function il(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||sl(n))e.push(n);else if(Ff(n))e.push(n instanceof Blob?n:new Blob([await n.arrayBuffer()],{type:n.type}));else if(Hn(n))for await(let t of n)e.push(...await il(t));else{let t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Dy(n)}`)}return e}function Dy(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}var p=class{constructor(e){this._client=e}};function Mf(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var zf=Object.freeze(Object.create(null)),zy=(n=Mf)=>function(t,...r){if(t.length===1)return t[0];let o=!1,i=[],s="";for(let h=0;h<t.length;h+=1)if(h in t){let _=t[h];/[?#]/.test(_)&&(o=!0);let m=r[h],b=(o?encodeURIComponent:n)(""+m);h!==r.length&&(m==null||typeof m=="object"&&m.toString===Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??zf)??zf)?.toString)&&(b=m+"",i.push({start:s.length+_.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),s+=_+(h===r.length?"":b)}let a=s.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=c.exec(a))!==null;)i.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(i.sort((h,_)=>h.start-_.start),i.length>0){let h=0,_="";for(let m of i){let b=" ".repeat(m.start-h),y="^".repeat(m.length);h=m.start+m.length,_+=b+y}throw new f(`Path parameters result in path with invalid segments:
18
+ ${i.map(m=>m.error).join(`
19
+ `)}
20
+ ${s}
21
+ ${_}`)}return s},l=zy(Mf);function My(n,e){return Promise.resolve(n).then(e)}var Lf=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Ly(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Lf.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Lf.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Nr=class extends p{list(e,t={},r){let o=Ly(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/chat/completions/${e}/messages`,x,My(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}};function wt(n){return n!==void 0&&"function"in n&&n.function!==void 0}function Ky(n){return n?.$brand==="auto-parseable-response-format"}function At(n){return Ky(n)||n?.type==="json_schema"}function Ft(n,e){if(!At(n))return null;if(typeof n=="object"&&n!==null&&"$parseRaw"in n&&typeof n.$parseRaw=="function")return n.$parseRaw(e);try{return JSON.parse(e)}catch(t){throw t instanceof SyntaxError?new SyntaxError("Error reading response: invalid structured output JSON."):t}}function ct(n){return n?.$brand==="auto-parseable-tool"}function Bf(n,e){return!e||!ul(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:gi(n,e)}function gi(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new rr;if(r.finish_reason==="content_filter")throw new nr;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(o=>Wy(e,o))??void 0}:void 0,parsed:r.message.content!==null&&r.message.content!==void 0&&!r.message.refusal&&(r.message.content!==""||!r.message.tool_calls?.length&&!r.message.function_call)?Ny(e,r.message.content):null}}});return{...n,choices:t}}function Ny(n,e){return Ft(n.response_format,e)}function Wy(n,e){if(e.type==="custom")return e;if(e.type!=="function"){let o=e.type;throw new f(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${o}\``)}let t=n.tools?.find(o=>wt(o)&&o.function?.name===e.function.name),r=null;return ct(t)?r=t.$parseRaw(e.function.arguments):t?.function.strict&&(r=Ft({type:"json_schema",$parseRaw:void 0},e.function.arguments)),{...e,function:{...e.function,parsed_arguments:r}}}function ou(n,e){if(!n||!("tools"in n)||!n.tools||e.type!=="function")return!1;let t=n.tools?.find(r=>wt(r)&&r.function?.name===e.function?.name);return wt(t)&&(ct(t)||t?.function.strict||!1)}function ul(n){return At(n.response_format)?!0:n.tools?.some(e=>ct(e)||e.type==="function"&&e.function.strict===!0)??!1}function Kf(n){for(let e of n??[])if(e.type!=="custom"){if(e.type!=="function"){let t=e.type;throw new f(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${t}\``)}if(e.function.strict!==!0)throw new f(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var zt=n=>n?.role==="assistant",bi=n=>n?.role==="tool";var De,uu,cu,Pi,Ai,lu,xi,Ze,vi,Ii,Ri,Xn,or,Wr,fu,pu,Jn,Ur,hl,Jf,ml,Vf,_l,du,Gf,Nf=4096,Oi=8*1024*1024,Uy=4096,Si=256,Qy=JSON.stringify,Hy=JSON.parse,cl=new WeakSet,Xy=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,Jy=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,Vy=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,Wf=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,Gy=Date.prototype.getTime,Yy=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,Zy=typeof SharedArrayBuffer=="function"?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,wi=Object.getOwnPropertyDescriptor(new Error("native stack descriptor"),"stack"),Rt=Function.prototype.toString,eg=Object.prototype.toString,iu=Object.getOwnPropertyDescriptor(Error,"isError"),Uf=iu&&"value"in iu&&typeof iu.value=="function"?iu.value:void 0,tg=Rt.call(Error),rg=Rt.call(Date),ng=Rt.call(Function),hu=new Set([Xe.prototype,re.prototype,H.prototype,f.prototype,V.prototype,Jt.prototype,mt.prototype,Yt.prototype,nr.prototype,tr.prototype,qe.prototype,rr.prototype,Gt.prototype,Je.prototype,Vt.prototype,er.prototype,qr.prototype,Zt.prototype]),Yf=new Set,Zf=new Map,Qf=new WeakMap;function sg(){if(!(typeof process>"u"))try{let n=Object.getOwnPropertyDescriptor(process,"getBuiltinModule");if(!n||!("value"in n)||typeof n.value!="function")return;let e=Reflect.apply(n.value,process,["node:util"]);if(typeof e!="object"||e===null)return;let t=Object.getOwnPropertyDescriptor(e,"types");if(!t||!("value"in t)||typeof t.value!="object"||t.value===null)return;let r=Object.getOwnPropertyDescriptor(t.value,"isProxy");return!r||!("value"in r)||typeof r.value!="function"?void 0:r.value}catch{return}}var og=sg();function mu(n){if(typeof n!="function")return;let e=Object.getOwnPropertyDescriptor(n,"prototype");if(!e||!("value"in e)||typeof e.value!="object"&&typeof e.value!="function")return;hu.add(e.value);let t=Rt.call(n);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(t)&&e.configurable===!1&&e.writable===!1){Yf.add(t);let r=new Map;for(let o of Reflect.ownKeys(e.value)){let i=Object.getOwnPropertyDescriptor(e.value,o);i&&r.set(o,i)}Zf.set(t,r)}}for(let n of[Object,Function,Array,Date,Map,Set,ArrayBuffer,DataView,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array])mu(n);for(let n of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){let e=Object.getOwnPropertyDescriptor(globalThis,n);e&&"value"in e&&mu(e.value)}var ll=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");ll&&"value"in ll&&mu(ll.value);typeof Buffer=="function"&&mu(Buffer);var ig=(()=>{if(typeof Blob=="function")try{let n=new Blob([]);for(let e of Object.getOwnPropertySymbols(n)){let t=Object.getOwnPropertyDescriptor(n,e);if(t&&"value"in t&&typeof t.value=="object"&&t.value)return Object.getPrototypeOf(t.value)}}catch{return}})(),ag=Map.prototype.entries,ug=Set.prototype.values,au=typeof Headers=="function"?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,Hf=au&&"value"in au&&typeof au.value=="function"?au.value:void 0,cg=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);function _u(n){let e=Object.getOwnPropertyDescriptor(n,"constructor");if(!e||!("value"in e)||typeof e.value!="function")return;let t=e.value,r=Rt.call(t),o=Zf.get(r);if(!Yf.has(r)||!o)return;let i=Object.getOwnPropertyDescriptor(t,"prototype");if(!(!i||!("value"in i)||i.value!==n||i.configurable!==!1||i.writable!==!1))return{constructor:t,descriptors:o,functionPrototype:Object.getPrototypeOf(t)}}function lg(n){return hu.has(n)||_u(n)!==void 0}function dl(n,e,t){if(e===void 0)return n===void 0;if(typeof n!="function"||typeof e!="function")return!1;let r=Rt.call(e);if(Rt.call(n)!==r)return!1;let o=Object.getPrototypeOf(n);if(o===t)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(r))return!1;let i=_u(o);return i!==void 0&&Rt.call(i.constructor)===ng}function dg(n,e,t){return!e||n.configurable!==e.configurable||n.enumerable!==e.enumerable||"value"in n!="value"in e?!1:"value"in n&&"value"in e?n.writable!==e.writable?!1:typeof e.value=="function"?dl(n.value,e.value,t):e.value!==null&&typeof e.value=="object"?!1:Object.is(n.value,e.value):dl(n.get,e.get,t)&&dl(n.set,e.set,t)}function Xf(n){if(Uf)return Uf.call(Error,n);let e=n;for(let t=0;e!==null&&t<Si;t+=1){if(Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))return!1;e=Object.getPrototypeOf(e)}return e===null&&eg.call(n)==="[object Error]"}function fg(n,e){if(typeof e.get!="function"||typeof e.set!="function")return;let t=Object.getPrototypeOf(n);for(let r=0;t!==null&&r<Si;r+=1){let o=Object.getOwnPropertyDescriptor(t,"constructor");if(o&&"value"in o&&typeof o.value=="function"){let i=o.value;if(Rt.call(i)===tg&&lg(t)){let s=Object.getPrototypeOf(i);return Object.getPrototypeOf(e.get)===s&&Object.getPrototypeOf(e.set)===s?{constructor:i,prototype:t}:void 0}}t=Object.getPrototypeOf(t)}}function pg(n,e){if(!Xf(n))return!1;if(wi&&!("value"in wi)&&typeof wi.get=="function"&&Object.prototype.isPrototypeOf.call(Error.prototype,n)&&e.get===wi.get&&e.set===wi.set)return!0;let t=fg(n,e);if(!t)return!1;let r=Qf.get(t.prototype);if(!r){let o=Reflect.construct(t.constructor,[]);if(typeof o!="object"||o===null||!Xf(o)||Object.getPrototypeOf(o)!==t.prototype||(r=Object.getOwnPropertyDescriptor(o,"stack"),!r||"value"in r||typeof r.get!="function"||typeof r.set!="function"))return!1;Qf.set(t.prototype,r)}return e.get===r.get&&e.set===r.set}function fl(){let n=[],e=0;return{get length(){return n.length-e},enqueue(t){n.push(t)},dequeue(){if(e===n.length)return;let t=n[e];return n[e]=void 0,e+=1,e===n.length?(n=[],e=0):e>=1024&&e*2>=n.length&&(n=n.slice(e),e=0),t},clear(){n=[],e=0}}}function hg(n){let e=Object.getPrototypeOf(n);for(let t=0;e!==null&&t<Si;t+=1){if(e===Date.prototype)return"Date";if(!hu.has(e)){let o=Object.getOwnPropertyDescriptor(e,"constructor");if(o&&"value"in o&&typeof o.value=="function"&&Rt.call(o.value)===rg&&_u(e))return"Date"}let r=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);if(r&&"value"in r&&typeof r.value=="string"&&cg.has(r.value))return r.value;e=Object.getPrototypeOf(e)}}function mg(n,e,t){if(ArrayBuffer.isView(n)){let a,c="typed-array";try{a=Xy?.call(n)}catch{c="data-view",a=Vy?.call(n)}return typeof a!="object"||a===null?{bytes:Number.POSITIVE_INFINITY,kind:c}:(e(a,t+1),{bytes:0,kind:c})}let r=hg(n);if(!r)return;let o,i="buffer";switch(r){case"ArrayBuffer":{o=Yy;break}case"SharedArrayBuffer":{o=Zy;break}case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(Gy,n,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}let s=o?.call(n);return{bytes:typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?s:Number.POSITIVE_INFINITY,kind:i}}function _g(n,e,t){if(e==="map"){for(let[r,o]of ag.call(n))if(!t(r,8)||!t(o,8))return!1}if(e==="set"){for(let r of ug.call(n))if(!t(r,8))return!1}if(e==="headers"){if(!Hf)return!1;for(let[r,o]of Hf.call(n))if(!t(r,8)||!t(o,8))return!1}return!0}function yg(n,e,t){if(Array.isArray(n)){let o=Object.getOwnPropertyDescriptor(n,"length"),i=o&&"value"in o?o.value:void 0;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>Math.floor(t/16))return}if(e!=="typed-array")return Reflect.ownKeys(n);let r=Jy?.call(n);if(!(typeof r!="number"||!Number.isSafeInteger(r)||r<0||r>Uy))return Reflect.ownKeys(n).filter(o=>{if(typeof o!="string")return!0;let i=Number(o);return!Number.isInteger(i)||i<0||i>=r||String(i)!==o})}function ep(n,e,t,r,o,i){let s=yg(n,e,r());if(s===void 0)return!1;for(let a of s){if(!o(typeof a=="string"?a.length*2+8:8))return!1;typeof a=="symbol"&&i(a,t+1);let c=Object.getOwnPropertyDescriptor(n,a);if(!c)return!1;if(!("value"in c)){if(a==="stack"&&pg(n,c))continue;return!1}i(c.value,t+1,e==="blob")}return!0}function gg(n,e,t,r,o,i,s,a){let c=Object.getPrototypeOf(n);for(let d=e+1;c!==null;d+=1){if(d>=Si)return!1;if(hu.has(c)||t&&c===ig)return!0;if(r.has(c))return s(c,d),o()>=0;r.add(c);let h=c;if(!a(h,()=>{if(!i(16))return!1;let m=_u(h);if(!m)return ep(h,void 0,d,o,i,s);for(let b of Reflect.ownKeys(h)){let y=Object.getOwnPropertyDescriptor(h,b);if(!y)return!1;if(!dg(y,m.descriptors.get(b),m.functionPrototype)){if(!i(typeof b=="string"?b.length*2+8:8)||!("value"in y))return!1;typeof b=="symbol"&&s(b,d+1),s(y.value,d+1)}}return o()>=0}))return!1;c=Object.getPrototypeOf(h)}return!0}var bg=32,wg=32,tp=8,rp=16,Ag=128*1024;function pl(n,e){let t=0,r=0,o=new WeakSet,i=new Set,s=new Set,a=new Map,c,d=()=>e-t,h=A=>!Number.isSafeInteger(A)||A<0?(t=e+1,!1):(t+=A,c?c.bytes+=A:r+=A,t<=e),_=A=>{c?c.edges.add(A):s.add(A)},m=(A,O)=>{_(A);let S={bytes:0,edges:new Set};a.set(A,S);let P=c;c=S;try{return O()}finally{c=P}},b=A=>{if(i.has(A)){_(A),h(8);return}i.add(A),m(A,()=>{if(!Wf)return!1;let O=Reflect.apply(Wf,A,[]);return h(8+(O?.length??0)*2)})||(t=e+1)},y=(A,O,S=!1)=>{if(!(t>e)){if(typeof A=="string"){h(A.length*2);return}if(typeof A=="symbol"){b(A);return}if(typeof A=="function"){t=e+1;return}if(A===null||typeof A!="object"){h(8);return}if(og?.(A)){t=e+1;return}if(O>=Si){t=e+1;return}if(o.has(A)){_(A),h(8);return}o.add(A),m(A,()=>{if(!h(16))return!1;let P=mg(A,y,O);return!gg(A,O,S,o,d,h,y,m)||P!==void 0&&!h(P.bytes)||!_g(A,P?.kind,(q,E)=>h(E)?(y(q,O+1),t<=e):!1)?!1:ep(A,P?.kind,O,d,h,y)})||(t=e+1)}};try{y(n,0)}catch{return}return t<=e?{scalarBytes:r,roots:s,nodes:a}:void 0}function Rg(n,e){if(n.size!==e.size)return!1;for(let t of n)if(!e.has(t))return!1;return!0}function yl(n,e){return n.bytes+wg+n.edges.size*tp+e*rp}function gl(n){return bg+n.scalarBytes+n.roots.size*tp}function Og(n,e,t,r){let o=new Set,i=[...n];for(;i.length;){if(r.remaining-=1,r.remaining<0)return;let s=i.pop();if(o.has(s))continue;let a=e.get(s)??t.get(s);if(!a)return;o.add(s);for(let c of a.edges)i.push(c)}return o}function bl(n,e,t,r,o){let i=r.get(n);if(i)return o&&(i.node=o),i;let s=o??e.nodes.get(n)??t.get(n);if(!s)return;let a={node:s,ownerDelta:0};return r.set(n,a),a}function Pg(n,e,t,r,o){let i=new Set([n]);for(let[s,a]of e.nodes){if(o.remaining-=1,o.remaining<0)return;let c=t.get(s);if(!c)continue;let d=!Rg(c.edges,a.edges);if((c.bytes!==a.bytes||d)&&bl(s,e,t,r,a),!!d)for(let h of c.owners){if(o.remaining-=1,o.remaining<0)return;i.add(h)}}return i}function xg(n,e,t,r,o,i){for(let s of n.identities){if(i.remaining-=1,i.remaining<0)return!1;if(!e.has(s)){let a=bl(s,t,r,o);if(!a)return!1;a.ownerDelta-=1}}for(let s of e){if(i.remaining-=1,i.remaining<0)return!1;if(!n.identities.has(s)){let a=bl(s,t,r,o);if(!a)return!1;a.ownerDelta+=1}}return!0}function vg(n,e,t,r,o,i){let s=new Map;for(let a of t){let c=a===n?e.roots:a.roots,d=Og(c,e.nodes,r,i);if(!d||!xg(a,d,e,r,o,i))return;s.set(a,d)}return s}function Ig(n,e,t,r,o,i){let s=n-(r?0:gl(e))+gl(t);for(let[a,c]of o){let d=i.get(a),h=(d?.owners.size??0)+c.ownerDelta;if(h<0)return;d&&(s-=yl(d,d.owners.size)),h&&(s+=yl(c.node,h))}return Number.isSafeInteger(s)&&s>=0&&s<=Oi?s:void 0}function Sg(n,e,t){for(let[r,o]of e){let i=n.get(r);(i?.owners.size??0)+o.ownerDelta&&(i?(i.bytes=o.node.bytes,i.edges=o.node.edges):n.set(r,{bytes:o.node.bytes,edges:o.node.edges,owners:new Set}))}for(let[r,o]of t){for(let i of r.identities)o.has(i)||n.get(i)?.owners.delete(r);for(let i of o)r.identities.has(i)||n.get(i).owners.add(r);r.identities=o}for(let r of e.keys())n.get(r)?.owners.size===0&&n.delete(r)}function Eg(){let n=new Map,e=0,t=(o,i,s)=>{let a={remaining:Ag},c=new Map,d=Pg(o,i,n,c,a);if(!d)return!1;let h=vg(o,i,d,n,c,a);if(!h)return!1;let _=Ig(e,o,i,s,c,n);return _===void 0?!1:(Sg(n,c,h),o.scalarBytes=i.scalarBytes,o.roots=i.roots,e=_,!0)};return{retain(o){let i={scalarBytes:0,roots:new Set,identities:new Set};return t(i,o,!0)?i:void 0},refresh(o,i){return t(o,i,!1)},release:o=>{e-=gl(o);for(let i of o.identities){let s=n.get(i);s?.owners.delete(o)&&(e-=rp,s.owners.size===0&&(e-=yl(s,0),n.delete(i)))}o.identities.clear()},clear(){n.clear(),e=0}}}var ir=class{constructor(){De.add(this),this.controller=new AbortController,uu.set(this,void 0),cu.set(this,()=>{}),Pi.set(this,()=>{}),Ai.set(this,void 0),lu.set(this,()=>{}),xi.set(this,()=>{}),Ze.set(this,Object.create(null)),vi.set(this,[]),Ii.set(this,new WeakMap),Ri.set(this,new Set),Xn.set(this,new Set),or.set(this,0),Wr.set(this,!1),fu.set(this,!1),pu.set(this,!1),Jn.set(this,!1),Ur.set(this,void 0),w(this,uu,new Promise((e,t)=>{w(this,cu,e,"f"),w(this,Pi,t,"f")}),"f"),w(this,Ai,new Promise((e,t)=>{w(this,lu,e,"f"),w(this,xi,t,"f")}),"f"),u(this,uu,"f").catch(()=>{}),u(this,Ai,"f").catch(()=>{})}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(r=>{t=!0,u(this,De,"m",du).call(this,r)}).then(()=>{if(!t){try{this._emitFinal()}catch(r){u(this,De,"m",du).call(this,r);return}this._emit("end")}})},0)}_connected(){this.ended||(u(this,cu,"f").call(this),this._emit("connect"))}get ended(){return u(this,Wr,"f")}get errored(){return u(this,fu,"f")}get aborted(){return u(this,pu,"f")}abort(){this.controller.abort()}_userAbortError(){let e=new V;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){u(this,De,"m",hl).call(this,e);return}if(u(this,vi,"f").some(r=>r.signal===e))return;let t=()=>u(this,De,"m",hl).call(this,e);e.addEventListener("abort",t,{once:!0}),u(this,vi,"f").push({signal:e,listener:t})}on(e,t){var r;return((r=u(this,Ze,"f"))[e]||(r[e]=[])).push({listener:t}),this}off(e,t){let r=u(this,Ze,"f")[e];if(!r)return this;let o=u(this,Ii,"f").get(t);if(o?.event===e&&!o.registration.removed&&!o.registration.detached)return u(this,De,"m",Vf).call(this,e,o.registration),this;let i=r.findIndex(s=>!s.removed&&s.listener===t);return i!==-1&&r.splice(i,1),this}once(e,t){var r;return((r=u(this,Ze,"f"))[e]||(r[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,Jn,!0,"f");let o=s=>{this.off(e,i),r(s)},i=(...s)=>{e!=="error"&&this.off("error",o),t(s.length>1?s:s[0])};e!=="error"&&u(this,De,"m",ml).call(this,"error",o),u(this,De,"m",ml).call(this,e,i)})}events(e){return this._createIterator(t=>{let r=(...o)=>{cl.add(o);try{t(o)}finally{cl.delete(o)}};return this.on(e,r),()=>this.off(e,r)},{rejectOnError:e!=="error",rejectOnAbort:e!=="abort"})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:r=!0,onReturn:o}={}){let i=fl(),s=fl(),a=fl(),c=Eg(),d=this.ended,h,_=!1,m=()=>{},b=()=>({value:void 0,done:!0}),y=()=>{for(;a.length;)a.dequeue().resolve(b())},A=()=>{!h||_||!a.length||(_=!0,a.dequeue().reject(h))},O=()=>{m(),this.off("end",v),t&&this.off("error",z),r&&this.off("abort",z)},S=I=>{I.active=!1,I.check&&(u(this,Xn,"f").delete(I.check),I.check=void 0)},P=(I=!1)=>{if(I){for(;s.length;)S(s.dequeue());i.clear(),c.clear()}let j=new f(`Event stream iterator buffer limit exceeded (${Nf} events or ${Oi} bytes); consume events as they arrive.`);try{u(this,De,"m",du).call(this,j)}finally{this.controller.abort()}return j},q=(I,j)=>{if(!j.active||u(this,Wr,"f"))return;let C=pl(I,Oi);(!C||!c.refresh(j.retention,C))&&P(!0)},E=I=>{if(d)return;let j=a.dequeue();if(j)j.resolve({value:I,done:!1});else{if(i.length>=Nf){P();return}let C=pl(I,Oi),$=C&&c.retain(C);if(!$){P();return}if(typeof I=="object"&&I!==null&&cl.has(I)){let K=I;for(let W=0;W<K.length;W+=1){let M=K[W];typeof M=="string"&&(K[W]=Hy(Qy(M)))}}let T={retention:$,active:!0,check:void 0};i.enqueue(I),s.enqueue(T);let F=()=>{T.check=void 0,q(I,T)};T.check=F,u(this,Xn,"f").add(F)}},z=I=>{h=I,i.length||A()},R=()=>{if(h)return;let I=u(this,Ur,"f");I&&(I.kind==="error"?t:r)&&(h=I.error)},v=()=>{d=!0,R(),O(),i.length||(A(),y())};return d||(m=e(E),this.on("end",v),t&&this.on("error",z),r&&this.on("abort",z)),{next:()=>{if(i.length){let I=i.dequeue(),j=s.dequeue();S(j);let C=pl(I,Oi);if(!C||!c.refresh(j.retention,C)){let $=P(!0);return _=!0,Promise.reject($)}return c.release(j.retention),Promise.resolve({value:I,done:!1})}return(d||this.ended)&&R(),h&&!_?(_=!0,Promise.reject(h)):d?Promise.resolve(b()):new Promise((I,j)=>{a.enqueue({resolve:I,reject:j})})},return:()=>{for(d=!0,_=!0;s.length;)S(s.dequeue());return i.clear(),c.clear(),O(),y(),o&&(this.done().catch(()=>{}),o()),Promise.resolve(b())},[Symbol.asyncIterator](){return this}}}async done(){w(this,Jn,!0,"f"),await u(this,Ai,"f")}_hasListeners(e){return!!u(this,Ze,"f")[e]?.some(t=>!t.removed)}_emit(e,...t){if(u(this,Wr,"f"))return;e==="end"&&(u(this,De,"m",Jf).call(this),w(this,Wr,!0,"f"),u(this,lu,"f").call(this));let r=u(this,Ze,"f")[e],o,i=!1;try{if(r){u(this,Ze,"f")[e]=r.filter(s=>(s.once&&(s.detached=!0),!s.once&&!s.removed)),w(this,or,u(this,or,"f")+1,"f");try{for(let s of r)if(!s.removed){let{listener:a}=s;a(...t)}}finally{if(w(this,or,u(this,or,"f")-1,"f"),u(this,or,"f")===0){u(this,De,"m",_l).call(this);for(let s of u(this,Xn,"f"))u(this,Xn,"f").delete(s),u(this,Wr,"f")||s()}}}}catch(s){o=s,i=!0}try{u(this,De,"m",Gf).call(this,e,t,!!r?.length)}catch(s){i||(o=s,i=!0)}if(i)throw o}_emitFinal(){}};uu=new WeakMap,cu=new WeakMap,Pi=new WeakMap,Ai=new WeakMap,lu=new WeakMap,xi=new WeakMap,Ze=new WeakMap,vi=new WeakMap,Ii=new WeakMap,Ri=new WeakMap,Xn=new WeakMap,or=new WeakMap,Wr=new WeakMap,fu=new WeakMap,pu=new WeakMap,Jn=new WeakMap,Ur=new WeakMap,De=new WeakSet,hl=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},Jf=function(){for(let{signal:e,listener:t}of u(this,vi,"f").splice(0))e.removeEventListener("abort",t)},ml=function(e,t){let r=u(this,Ze,"f")[e],o=r?.length??0;this.once(e,t);let i=u(this,Ze,"f")[e],[s]=i?.slice(-1)??[];(r===void 0||i===r)&&i?.length===o+1&&s?.listener===t&&s.once&&u(this,Ii,"f").set(t,{event:e,registration:s})},Vf=function(e,t){t.removed||(t.removed=!0,u(this,Ii,"f").delete(t.listener),u(this,Ri,"f").add(e),u(this,or,"f")===0&&u(this,De,"m",_l).call(this))},_l=function(){for(let e of u(this,Ri,"f")){let t=e,r=u(this,Ze,"f")[t];r&&(u(this,Ze,"f")[t]=r.filter(o=>!o.removed))}u(this,Ri,"f").clear()},du=function(e){if(w(this,fu,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=this._userAbortError()),e instanceof V)return w(this,pu,!0,"f"),this._emit("abort",e);if(e instanceof f)return this._emit("error",e);if(e instanceof Error){let t=new f(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new f(String(e)))},Gf=function(e,t,r){if(e==="abort"){let o=t[0];w(this,Ur,u(this,Ur,"f")??{kind:"abort",error:o},"f"),!u(this,Jn,"f")&&!r&&Promise.reject(o),u(this,Pi,"f").call(this,o),u(this,xi,"f").call(this,o),this._emit("end");return}if(e==="error"){let o=t[0];w(this,Ur,u(this,Ur,"f")??{kind:"error",error:o},"f"),!u(this,Jn,"f")&&!r&&Promise.reject(o),u(this,Pi,"f").call(this,o),u(this,xi,"f").call(this,o),this._emit("end")}};function np(n){return typeof n.parse=="function"}var Ie,Qr,yu,gu,wl,bu,Al,Rl,Ol,Pl,sp,op,Cg=10;function Tg(n){for(let e of n.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${Me()}`)}function kg(n){if(!zt(n))return n;let e={role:"assistant"};return n.audio!=null&&(e.audio={id:n.audio.id}),n.content!==void 0&&(e.content=n.content),n.function_call!=null&&(e.function_call=n.function_call),n.name!==void 0&&(e.name=n.name),n.refusal!=null&&(e.refusal=n.refusal),n.tool_calls!==void 0&&(e.tool_calls=n.tool_calls.map(t=>t.type==="custom"?{id:t.id,type:t.type,custom:{input:t.custom.input,name:t.custom.name}}:{id:t.id,type:t.type,function:{arguments:t.function.arguments,name:t.function.name}})),e}var Hr=class extends ir{constructor(){super(...arguments),Ie.add(this),this._chatCompletions=[],yu.set(this,!1),gu.set(this,!1),this.messages=[]}_addChatCompletion(e){w(this,yu,!this.controller.signal.aborted,"f"),Tg(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,r=!0){if(r&&!("content"in e)&&(e.content=null),this.messages.push(e),t){if(this._emit("message",e),bi(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(zt(e)&&e.tool_calls)for(let o of e.tool_calls)o.type==="function"&&this._emit("functionToolCall",o.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new f("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,Ie,"m",wl).call(this)}async finalMessage(){return await this.done(),u(this,Ie,"m",bu).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,Ie,"m",Al).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,Ie,"m",Rl).call(this)}async totalUsage(){return await this.done(),u(this,Ie,"m",Ol).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){u(this,gu,"f")&&u(this,Ie,"m",Pl).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=u(this,Ie,"m",bu).call(this);t&&this._emit("finalMessage",t);let r=u(this,Ie,"m",wl).call(this);r&&this._emit("finalContent",r);let o=u(this,Ie,"m",Al).call(this);o&&this._emit("finalFunctionToolCall",o);let i=u(this,Ie,"m",Rl).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(s=>s.usage)&&this._emit("totalUsage",u(this,Ie,"m",Ol).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),u(Qr,Qr,"m",sp).call(Qr,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(gi(o,t))}async _runChatCompletion(e,t,r){for(let o of t.messages)this._addMessage(o,!1,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r,o){let i="tool",{tool_choice:s="auto",stream:a,toolContext:c,...d}=t,h=c,_=typeof s!="string"&&s.type==="function"&&s?.function?.name,{maxChatCompletions:m=Cg,afterCompletion:b}=o||{},y=async E=>{b!=null&&(w(this,gu,!0,"f"),await b(E,r),u(this,Ie,"m",Pl).call(this))},A=t.tools.map(E=>{if(ct(E)){if(!E.$callback)throw new f("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:E.$callback,name:E.function.name,description:E.function.description||"",parameters:E.function.parameters,parse:E.$parseRaw,strict:!0}}}return E}),O=Object.create(null);for(let E of A)E.type==="function"&&(O[E.function.name||E.function.function.name]=E.function);let S="tools"in t?A.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,!1);let P=!1,q=async E=>{let z=P;if(P=!1,E.type!=="function")return{message:void 0,functionCalled:!1};let R=E.id,{name:v,arguments:I}=E.function,j=O[v];if(!j){let T=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(O).map(F=>JSON.stringify(F)).join(", ")}. Please try again`;return{message:{role:i,tool_call_id:R,content:T},functionCalled:!1}}if(_&&_!==v){let T=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(_)} requested. Please try again`;return{message:{role:i,tool_call_id:R,content:T},functionCalled:!1}}let C;if(np(j)){let T;try{T=await j.parse(I)}catch(F){if(this.controller.signal.aborted)throw this._userAbortError();let K=F instanceof Error?F.message:String(F);return{message:{role:i,tool_call_id:R,content:K},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{C=await j.function(T,r,h)}catch(F){throw this.controller.signal.aborted&&Object.is(F,this.controller.signal.reason)?this._userAbortError():F}}else{if(this.controller.signal.aborted&&!z)throw this._userAbortError();try{C=await j.function(I,r,h)}catch(T){throw this.controller.signal.aborted&&Object.is(T,this.controller.signal.reason)?this._userAbortError():T}}let $=u(Qr,Qr,"m",op).call(Qr,C);return{message:{role:i,tool_call_id:R,content:$},functionCalled:!0}};for(let E=0;E<m;++E){let z=await this._createChatCompletion(e,{...d,tool_choice:s,tools:S,messages:this.messages.map(kg)},o);P=this.controller.signal.aborted&&u(this,yu,"f");let R=z.choices[0]?.message;if(!R)throw new f("missing message in ChatCompletion response");if(!R.tool_calls?.length){await y(z);return}if(_||t.parallel_tool_calls===!1)for(let v of R.tool_calls){let I=await q(v);if(I.message&&this._addMessage(I.message),this.controller.signal.aborted)throw this._userAbortError();if(_&&I.functionCalled){await y(z);return}}else{let v=await Promise.allSettled(R.tool_calls.map(q));if(!this.controller.signal.aborted){for(let I of v)if(I.status==="rejected")throw I.reason}for(let I of v)I.status==="fulfilled"&&I.value.message&&this._addMessage(I.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await y(z)}}};Qr=Hr,yu=new WeakMap,gu=new WeakMap,Ie=new WeakSet,wl=function(){return u(this,Ie,"m",bu).call(this).content??null},bu=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(zt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new f("stream ended without producing a ChatCompletionMessage with role=assistant")},Al=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(zt(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let o=t.tool_calls[r];if(o?.type==="function")return o.function}}},Rl=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(bi(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(o=>o.type==="function"&&o.id===t.tool_call_id)))return t.content}},Ol=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)if(t){e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens;for(let r of["completion_tokens_details","prompt_tokens_details"]){let o=t[r];if(U(o)){let i=e[r]??(e[r]={});for(let s in o){if(!k(o,s))continue;let a=o[s];typeof a=="number"&&Object.defineProperty(i,s,{value:(k(i,s)?i[s]??0:0)+a,enumerable:!0,configurable:!0,writable:!0})}}}}return e},Pl=function(){if(this.controller.signal.aborted)throw this._userAbortError()},sp=function(e){if(e.n!=null&&e.n>1)throw new f("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},op=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Ei=class n extends Hr{static runTools(e,t,r){let o=new n,i={...r,__metadata:{...r?.__metadata,helperMethod:"runTools"}};return o._run(()=>o._runTools(e,t,o,i)),o}_addMessage(e,t=!0,r=!0){super._addMessage(e,t,r),t&&zt(e)&&e.content&&this._emit("content",e.content)}};var ge={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},xl=class extends Error{},Ci=class extends Error{};function jg(n,e=ge.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return qg(n.trim(),e)}var qg=(n,e)=>{let t=n.length,r=0,o=m=>{throw new xl(`${m} at position ${r}`)},i=m=>{throw new Ci(`${m} at position ${r}`)},s=()=>(_(),r>=t&&o("Unexpected end of input"),n[r]==='"'?a():n[r]==="{"?c():n[r]==="["?d():n.substring(r,r+4)==="null"||ge.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||ge.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||ge.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||ge.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||ge.MINUS_INFINITY&e&&t-r>1&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||ge.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,Number.NaN):h()),a=()=>{let m=r,b=!1;for(r++;r<t&&(n[r]!=='"'||b&&n[r-1]==="\\");)b=n[r]==="\\"?!b:!1,r++;if(n.charAt(r)==='"')try{return JSON.parse(n.substring(m,++r-Number(b)))}catch(y){i(String(y))}else if(ge.STR&e)try{return JSON.parse(n.substring(m,r-Number(b))+'"')}catch{return JSON.parse(n.substring(m,n.lastIndexOf("\\"))+'"')}o("Unterminated string literal")},c=()=>{r++,_();let m={};try{for(;n[r]!=="}";){if(_(),r>=t&&ge.OBJ&e)return m;let b=a();_(),r++;try{let y=s();Object.defineProperty(m,b,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(ge.OBJ&e)return m;throw y}_(),n[r]===","&&r++}}catch{if(ge.OBJ&e)return m;o("Expected '}' at end of object")}return r++,m},d=()=>{r++;let m=[];try{for(;n[r]!=="]";)m.push(s()),_(),n[r]===","&&r++}catch{if(ge.ARR&e)return m;o("Expected ']' at end of array")}return r++,m},h=()=>{if(r===0){n==="-"&&ge.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(n)}catch(y){if(ge.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}i(String(y))}}let m=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r===t&&!(ge.NUM&e)&&o("Unterminated number literal");let b=n.substring(m,r);try{return JSON.parse(b)}catch{b==="-"&&ge.NUM&e&&o("Not sure what '-' is");try{return JSON.parse(b.substring(0,b.lastIndexOf("e")))}catch(y){i(String(y))}}},_=()=>{for(;r<t&&`
22
+ \r `.includes(n[r]);)r++};return s()},ip=n=>jg(n,ge.ALL^ge.NUM);function vl(n){return Array.isArray(n?.choices)?{...n,choices:n.choices.map(e=>({...e,finish_reason:e.finish_reason??null}))}:n}function ap(n){let e=n[Symbol.asyncIterator].bind(n);return n[Symbol.asyncIterator]=async function*(){let r={[Symbol.asyncIterator]:e};for await(let o of r)yield vl(o)},n}var Y,ce,wu,ar,Xr,Se,et,Le,Il,Vn,Sl,El,Cl,Gn,Ti,up;function cp(n){try{return ip(n)}catch(e){if(e instanceof Ci||e instanceof SyntaxError)return Ft({type:"json_schema",$parseRaw:void 0},n);throw e}}var Bl="chat.completion.chunk.message:";function mp(n,e,t){let r={type:"message",message:e,...t?{tool_call_ids:t}:{}};return{id:n.id,choices:[],created:n.created,model:n.model,object:`${Bl}${JSON.stringify(r)}`}}function $g(n){return"type"in n&&n.type==="message"&&"message"in n||"object"in n&&typeof n.object=="string"&&n.object.startsWith(Bl)}function Dg(n){return"type"in n?n:JSON.parse(n.object.slice(Bl.length))}var Au=128,ur=128,Fg=16*1024*1024,zg=65536,Kl=128,_p=64*1024*1024,lp=1024;function Fl(){return{bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1}}function zl(n,e,t,r){if(e.fragments>=zg)throw new f("Chat completion stream exceeded its structured JSON fragment limit");let o=0,{depth:i,escaped:s,has_non_whitespace:a,in_string:c}=n,d=!1,h=!0;for(let m of t){let b=o,y=m.codePointAt(0);if(h&&n.pending_high_surrogate&&y>=56320&&y<=57343||y<=127?o+=1:y<=2047?o+=2:y<=65535?o+=3:o+=4,h=!1,e.bytes+o>Fg)throw new f("Chat completion stream exceeded its structured JSON byte limit");if(r&&r.work+o>_p)throw r.work+=b,new f("Chat completion stream exceeded its structured JSON parse-work limit");if(m!==" "&&m!==`
23
+ `&&m!=="\r"&&m!==" "&&(a=!0),c){s?s=!1:m==="\\"?s=!0:m==='"'&&(c=!1,d||(d=i===0));continue}if(m==='"')c=!0;else if(m==="{"||m==="["){if(i+=1,i>Kl)throw new f("Chat completion stream exceeded its structured JSON nesting depth limit")}else(m==="}"||m==="]")&&i>0&&(i-=1,d||(d=i===0))}if(n.bytes+=o,n.fragments+=1,n.depth=i,n.escaped=s,n.has_non_whitespace=a,n.in_string=c,t.length>0){let m=t.codePointAt(t.length-1)??0;n.pending_high_surrogate=m>=55296&&m<=56319}if(e.bytes+=o,e.fragments+=1,r&&(r.work+=o),!a||o===0)return!1;let _=Math.max(lp,Math.floor(n.last_parsed_bytes/2));return!(n.bytes>lp&&!d&&n.bytes-n.last_parsed_bytes<_)}function Ml(n,e){return e.work+n.bytes>_p?!1:(e.work+=n.bytes,n.work+=n.bytes,n.last_parsed_bytes=n.bytes,!0)}function tt(n,e){let t=Object.getOwnPropertyDescriptor(n,e);if(!t){let r=Object.getPrototypeOf(n);for(let o=0;r!==null;o+=1){if(o>=Kl||Object.getOwnPropertyDescriptor(r,e))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");r=Object.getPrototypeOf(r)}return}if(!("value"in t)||typeof t.value!="string"&&t.value!==null&&t.value!==void 0)throw new f("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}function ki(n){let e=Object.getOwnPropertyDescriptor(n,"message");if(!e||!("value"in e)||typeof e.value!="object"||e.value===null)throw new f("Chat completion stream contains an unsafe structured JSON snapshot");return e.value}function dp(n,e,t,r){let o=Object.getOwnPropertyDescriptor(n,e);if(!o){let s=Object.getPrototypeOf(n);for(let a=0;s!==null;a+=1){if(a>=Kl||Object.getOwnPropertyDescriptor(s,e))throw new f(`Chat completion stream contains an unsafe snapshot ${r} collection`);s=Object.getPrototypeOf(s)}return}if(!("value"in o)||!Array.isArray(o.value))throw new f(`Chat completion stream contains an unsafe snapshot ${r} collection`);let i=Object.getOwnPropertyDescriptor(o.value,"length");if(!i||!("value"in i)||!Number.isSafeInteger(i.value)||i.value>t)throw new f(`Chat completion stream exceeded its snapshot ${r} limit`);return o.value}function Tl(n,e){let t=Object.getOwnPropertyDescriptor(n,e);if(t){if(!("value"in t))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}}function fp(n,e,t,r){let o=Object.getOwnPropertyDescriptor(n,"length"),i=o&&"value"in o?o.value:void 0;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>e)throw new f(`Chat completion stream exceeded its snapshot ${t} limit`);let s=[];s.length=i;for(let a=0;a<i;a+=1){let c=Object.getOwnPropertyDescriptor(n,a);if(c){if(!("value"in c))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");s[a]=r(c.value,a)}}return s}function Jr(n,e,t){let r=Fl(),o=e??{bytes:0,fragments:0,work:0};if(zl(r,o,n,t),!Ml(r,o))throw new f("Chat completion stream exceeded its structured JSON parse-work limit");return n}function Ru(n){let e=Object.getOwnPropertyDescriptor(n,"type"),t=Object.getOwnPropertyDescriptor(n,"function");if(!e||!("value"in e)||e.value!=="function"||!t||!("value"in t)||typeof t.value!="object"||t.value===null)return;let r=Object.getOwnPropertyDescriptor(t.value,"name");if(!(!r||!("value"in r)||typeof r.value!="string"||r.value.length===0))return{type:"function",name:r.value}}function kl(n,e){let t=Ru(n);if(!t||t.name!==e.name||t.type!==e.type)throw new f("Chat completion stream contains a changed tool call identity")}function ji(n,e){return Object.prototype.propertyIsEnumerable.call(e,"__proto__")&&!k(n,"__proto__")&&Object.defineProperty(n,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(n,e)}function qi(n,e=[]){let t=Object.getOwnPropertyDescriptors(n);for(let r of e){let o=t[r];!o&&!(r in n)||(t[r]={value:o&&"value"in o?o.value:Reflect.get(n,r,n),enumerable:o?.enumerable??!1,configurable:o?.configurable??!0,writable:o&&"writable"in o?o.writable:!1})}return Object.create(Object.getPrototypeOf(n),t)}function Mg(n){let e=qi(n);if(n.tools){let t=[],r=Object.getOwnPropertyDescriptor(n.tools,"length"),o=r&&"value"in r?r.value:void 0,i=typeof o=="number"&&Number.isSafeInteger(o)&&o>=0?Math.min(o,ur):0;for(let s=0;s<i;s+=1){let a=Object.getOwnPropertyDescriptor(n.tools,String(s));if(!a||!("value"in a)){t.length=s+1;continue}let c=a.value,d=qi(c,["type","$brand","$parseRaw","$callback","function"]),h=Object.getOwnPropertyDescriptors(d);if(wt(d)){let _=h.function;h.function={..._&&"value"in _?_:{configurable:!0,enumerable:!0,writable:!0},value:qi(d.function,["name","strict"])}}t[s]=Object.create(Object.getPrototypeOf(c),h)}e.tools=t}return n.response_format&&(e.response_format=qi(n.response_format,["type","$brand","$parseRaw"])),e}var jl=4096,ql=JSON.stringify,Lg=1024*1024,Bg=64,$l=Symbol("omitted serialized parser value"),be=Symbol("unsafe serialized parser value");function yp(n,e){let t=new WeakSet,r=i=>!Number.isSafeInteger(i)||i<0||e.bytes+i>Lg?!1:(e.bytes+=i,!0),o=(i,s)=>{if(s>Bg||e.nodes>=jl)return be;if(e.nodes+=1,i===void 0||typeof i=="function"||typeof i=="symbol")return $l;if(typeof i=="bigint")return be;if(i===null||typeof i=="boolean"||typeof i=="number"){let d=ql(i);return typeof d=="string"&&r(d.length)?d:be}if(typeof i=="string")return r(i.length*6+2)?ql(i):be;if(typeof i!="object"||t.has(i))return be;let a=Array.isArray(i),c=Object.getPrototypeOf(i);if(a&&c!==Array.prototype||!a&&c!==null&&c!==Object.prototype)return be;for(let d=i;d!==null;d=Object.getPrototypeOf(d)){let h=Object.getOwnPropertyDescriptor(d,"toJSON");if(h){if(!("value"in h)||typeof h.value=="function")return be;break}}t.add(i);try{if(!r(2))return be;if(a){let m=Object.getOwnPropertyDescriptor(i,"length"),b=m&&"value"in m?m.value:void 0;if(typeof b!="number"||!Number.isSafeInteger(b)||b<0||b>jl-e.nodes)return be;let y=[];for(let A=0;A<b;A+=1){let O=String(A),S=Object.getOwnPropertyDescriptor(i,O);if(!S){if(Object.getOwnPropertyDescriptor(Array.prototype,O)||Object.getOwnPropertyDescriptor(Object.prototype,O)||(e.nodes+=1,!r(4)))return be;y.push("null");continue}if(!("value"in S))return be;let P=o(S.value,s+1);if(P===be)return P;y.push(P===$l?"null":P)}return`[${y.join(",")}]`}let d=Reflect.ownKeys(i);if(d.length>jl-e.nodes)return be;let h=[];for(let m of d){if(typeof m!="string")continue;let b=Object.getOwnPropertyDescriptor(i,m);if(!b)return be;if(b.enumerable){if(!("value"in b))return be;h.push([m,b.value])}}h.sort(([m],[b])=>m===b?0:m<b?-1:1);let _=[];for(let[m,b]of h){let y=o(b,s+1);if(y===be)return y;if(y!==$l){if(!r(m.length*6+3))return be;_.push(`${ql(m)}:${y}`)}}return`{${_.join(",")}}`}finally{t.delete(i)}};try{let i=o(n,0);return typeof i=="string"?i:void 0}catch{return}}function pp(n,e,t,r){let o=Object.getOwnPropertyDescriptor(e,"$parseRaw"),i=Object.getOwnPropertyDescriptor(t,r);if(!o||!("value"in o)||typeof o.value!="function"||!i||!("value"in i))return;let s=yp(i.value,{nodes:0,bytes:0});s!==void 0&&n.set(e,s)}function hp(n,e,t,r,o){let i=e&&n.get(e),s=Object.getOwnPropertyDescriptor(t,r);return i!==void 0&&s!==void 0&&"value"in s&&yp(o,{nodes:0,bytes:0})===i}function Yn(n,e){return n&&"value"in n?{...n,value:e}:{configurable:!0,enumerable:!0,writable:!0,value:e}}function Ll(n,e,t){for(let r of t){let o=n[r];!o&&!(r in e)||(n[r]=o&&"value"in o?{...o,value:void 0}:{configurable:o?.configurable??!0,enumerable:o?.enumerable??!1,writable:!1,value:void 0})}}function Kg(n){let e=n.source??{type:n.type,...n.type==="function"?{function:{}}:{}},t=Object.getOwnPropertyDescriptors(e);if(t.type=Yn(t.type,n.type),n.type!=="function"||!n.function)return t.function&&(t.function=Yn(t.function,void 0)),Ll(t,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),t);let r=t.function,o=r&&"value"in r&&typeof r.value=="object"&&r.value!==null?r.value:{},i=Object.getOwnPropertyDescriptors(o);return i.name=Yn(i.name,n.function.name),i.strict=Yn(i.strict,n.function.strict),t.function=Yn(r,Object.create(Object.getPrototypeOf(o),i)),n.function.schemaMatches||Ll(t,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),t)}function Ng(n){let e=n.source??{type:n.type},t=Object.getOwnPropertyDescriptors(e);return t.type=Yn(t.type,n.type),(n.type!=="json_schema"||!n.source||!n.schemaMatches)&&Ll(t,e,["$brand","$parseRaw"]),Object.create(Object.getPrototypeOf(e),t)}function Dl(n,e){let t=Object.getOwnPropertyDescriptor(n,e);if(!t||!("value"in t))return;let{value:r}=t;return typeof r=="object"&&r!==null?r:void 0}function Wg(n,e,t){let r=new WeakMap,o=new WeakMap;if(n.tools)for(let b=0;b<n.tools.length&&b<ur;b+=1){let y=Dl(n.tools,String(b)),A=e.tools?.[b];if(y&&A){r.set(y,A);let O=Dl(A,"function");O&&pp(o,A,O,"parameters")}}e.response_format&&pp(o,e.response_format,e.response_format,"json_schema");let i,s,a,c,d=[],h=new WeakMap,_=new Map,m=new WeakMap;return Qa(n,{value(b,y,A){if(!i&&y===""&&typeof A=="object"&&A!==null){i=A,s=void 0,a=void 0,c=void 0,d=[],h=new WeakMap,_=new Map,m=new WeakMap;return}if(b===i&&y==="response_format"){typeof A=="object"&&A!==null&&(a=A,c={source:Dl(b,y)===n.response_format?e.response_format:void 0,schemaMatches:!1});return}if(b===i&&y==="tools")return Array.isArray(A)?(s=new Proxy(A,{get(P,q){let E=Reflect.get(P,q,P);if(typeof q=="string"){let z=Number(q);Number.isSafeInteger(z)&&z>=0&&z<ur&&String(z)===q&&_.set(z,typeof E=="object"&&E!==null?E:void 0)}return E}}),s):void 0;if(b===s){let P=Number(y);if(!Number.isSafeInteger(P)||P<0||P>=ur||typeof A!="object"||A===null)return;let q=_.get(P),z={source:q?r.get(q):void 0};d[P]=z,h.set(A,z);return}let O=h.get(b);if(O){if(y==="type"&&typeof A=="string")O.type=A;else if(y==="function"&&typeof A=="object"&&A!==null){let P={source:O.source,schemaMatches:!1};O.function=P,m.set(A,P)}return}if(b===a&&c){y==="type"&&typeof A=="string"?c.type=A:y==="json_schema"&&(c.schemaMatches=hp(o,c.source,b,y,A));return}let S=m.get(b);S&&(y==="name"&&typeof A=="string"?S.name=A:y==="strict"&&typeof A=="boolean"?S.strict=A:y==="parameters"&&(S.schemaMatches=hp(o,S.source,b,y,A)))},complete(){if(!i)return;let b=qi(e);if(s){let y=[];for(let A=0;A<d.length;A+=1){let O=d[A];O&&(y[A]=Kg(O))}b.tools=y}else delete b.tools;c?b.response_format=Ng(c):delete b.response_format,t(b),i=void 0,s=void 0,a=void 0,c=void 0,d=[],h=new WeakMap,_=new Map,m=new WeakMap}})}var Vr=class n extends Hr{constructor(e){super(),Y.add(this),ce.set(this,void 0),wu.set(this,!1),ar.set(this,void 0),Xr.set(this,void 0),Se.set(this,void 0),et.set(this,void 0),Le.set(this,void 0),w(this,ce,e,"f"),w(this,ar,new Set,"f"),w(this,Xr,[],"f"),w(this,et,!1,"f");let t=e?.tools,r=t&&Object.getOwnPropertyDescriptor(t,"length"),o=r&&"value"in r?r.value:void 0;if(t&&typeof o=="number"&&Number.isSafeInteger(o)&&o>=0)for(let i=0;i<Math.min(o,ur);i+=1){let s=Object.getOwnPropertyDescriptor(t,String(i));if(!s||!("value"in s))continue;let a=s.value;if(wt(a)&&(ct(a)||a.function.strict===!0)){w(this,et,!0,"f");break}}w(this,Le,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return u(this,Se,"f")}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let o=new n(t);return o._run(()=>o._runChatCompletion(e,{...t,stream:!0},{...r,__metadata:{...r?.__metadata,helperMethod:"stream"}})),o}_runTools(e,t,r,o){return w(this,wu,!0,"f"),super._runTools(e,t,r,o)}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal);let o={...t,stream:!0};w(this,ce,o,"f"),u(this,Y,"m",Il).call(this);let i=Mg(o);w(this,ce,i,"f"),w(this,et,i.tools?.some(c=>wt(c)&&(ct(c)||c.function.strict===!0))??!1,"f");let s=o.tools||o.response_format?Wg(o,i,c=>{w(this,ce,c,"f"),w(this,et,c.tools?.some(d=>wt(d)&&(ct(d)||d.function.strict===!0))??!1,"f")}):void 0,a=await e.chat.completions.create(o,{...r,signal:this.controller.signal}).finally(s);this._connected();for await(let c of a)u(this,Y,"m",Sl).call(this,c);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(u(this,Y,"m",Ti).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,Y,"m",Il).call(this),this._connected();let r=$e.fromReadableStream(e,this.controller),o;for await(let s of r){if("error"in s&&k(s,"error")&&typeof s.error=="object"&&s.error!==null)throw new H(void 0,s.error,void 0,void 0);if($g(s)){let c=Dg(s);if(u(this,Se,"f")){let d=u(this,Se,"f").choices[0]?.message.tool_calls;for(let[h,_]of c.tool_call_ids?.entries()??[]){let m=d?.[h];m&&_&&(m.id=_)}this._addChatCompletion(u(this,Y,"m",Ti).call(this)),o=void 0}this._addMessage(c.message);continue}let a=vl(s);o&&a.id&&o!==a.id&&this._addChatCompletion(u(this,Y,"m",Ti).call(this)),u(this,Y,"m",Sl).call(this,a),a.id&&(o=a.id)}if(r.controller.signal?.aborted)throw this._userAbortError();if(u(this,Se,"f"))return this._addChatCompletion(u(this,Y,"m",Ti).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new f("request ended without sending any chunks")}[(ce=new WeakMap,wu=new WeakMap,ar=new WeakMap,Xr=new WeakMap,Se=new WeakMap,et=new WeakMap,Le=new WeakMap,Y=new WeakSet,Il=function(){this.ended||(w(this,ar,new Set,"f"),w(this,Se,void 0,"f"),w(this,Le,{bytes:0,fragments:0,work:0},"f"))},Vn=function(t){let r=u(this,Xr,"f")[t.index];return r||(r={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},u(this,Xr,"f")[t.index]=r,r)},Sl=function(t){if(this.ended)return;let r=new WeakMap,o=u(this,Y,"m",up).call(this,t,r);this._emit("chunk",t,o);for(let i of t.choices){let s=r.get(i),a=o.choices[s?.index??i.index],c=s?.tool_calls??[],{delta:d}=i,h=At(u(this,ce,"f")?.response_format),_=h||u(this,et,"f"),m=_?ki(a):a.message,b=_?tt(m,"refusal"):m.refusal,A=!b&&h?tt(m,"content"):m.content;d?.content!=null&&m.role==="assistant"&&A&&(this._emit("content",d.content,A),this._emit("content.delta",{delta:d.content,snapshot:A,parsed:m.parsed})),d?.refusal!=null&&m.role==="assistant"&&b&&this._emit("refusal.delta",{delta:d.refusal,snapshot:b}),i.logprobs?.content!=null&&m.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:a.logprobs?.content??[]}),i.logprobs?.refusal!=null&&m.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});let O=u(this,Y,"m",Vn).call(this,a);a.finish_reason&&(u(this,Y,"m",Cl).call(this,a),O.current_tool_call_index!=null&&u(this,Y,"m",El).call(this,a,O.current_tool_call_index));for(let S of c)O.current_tool_call_index!==S.index&&(u(this,Y,"m",Cl).call(this,a),O.current_tool_call_index!=null&&u(this,Y,"m",El).call(this,a,O.current_tool_call_index)),O.current_tool_call_index=S.index;for(let S of c){let P=m.tool_calls?.[S.index];if(P?.type)if(P.type==="function"){let q=O.tool_call_identities.get(S.index),E;if(q?.parseable){let z=tt(P.function,"arguments");if(typeof z!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");E=z}else E=P.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:P.function.name,index:S.index,arguments:E,parsed_arguments:P.function.parsed_arguments,arguments_delta:S.arguments_delta})}else P.type!=="custom"&&P}}},El=function(t,r){let o=u(this,Y,"m",Vn).call(this,t);if(o.done_tool_calls.has(r))return;let s=(u(this,et,"f")?ki(t):t.message).tool_calls?.[r];if(!s)throw new Error("no tool call snapshot");let a=o.tool_call_identities.get(r);if(a&&kl(s,a),!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let c=u(this,ce,"f")?.tools?.find(m=>wt(m)&&m.function.name===s.function.name),d=null,h=ct(c)||c?.function.strict===!0,_;if(h){u(this,Se,"f")&&u(this,Y,"m",Gn).call(this,u(this,Se,"f"));let m=tt(s.function,"arguments");if(typeof m!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");_=m}else _=s.function.arguments;ct(c)?d=c.$parseRaw(Jr(_)):c?.function.strict&&(d=Ft({type:"json_schema",$parseRaw:void 0},Jr(_))),t.finish_reason&&o.done_tool_calls.add(r),this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:r,arguments:_,parsed_arguments:d})}else s.type!=="custom"&&s},Cl=function(t){let r=u(this,Y,"m",Vn).call(this,t),o=At(u(this,ce,"f")?.response_format),i=o||u(this,et,"f"),s=i?ki(t):t.message,a=i?tt(s,"refusal"):s.refusal,c=!a&&o,d=c?tt(s,"content"):s.content;d!=null&&(d!==""||!a&&!s.tool_calls?.length&&!s.function_call)&&!r.content_done&&(c&&u(this,Se,"f")&&u(this,Y,"m",Gn).call(this,u(this,Se,"f")),r.content_done=!0,this._emit("content.done",{content:d,parsed:a?null:Ft(u(this,ce,"f")?.response_format,c?Jr(d):d)})),a&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:a})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Gn=function(t){let r={bytes:0,fragments:0,work:0},o=At(u(this,ce,"f")?.response_format),i=new WeakMap,s=dp(t,"choices",Au,"choice");if(!s)throw new f("Chat completion stream contains an unsafe snapshot choice collection");for(let a=0;a<s.length;a+=1){let c=Tl(s,a);if(!c)continue;let d=ki(c),h=tt(d,"refusal"),_=tt(d,"content"),m=new Map,b=dp(d,"tool_calls",ur,"tool-call");i.set(c,Object.freeze({message:d,content:_,refusal:h,toolCallCollection:b,toolCalls:m}));let y=u(this,Xr,"f")[c.index];o&&!h&&typeof _=="string"&&Jr(_,r,u(this,Le,"f"));for(let[A,O]of y?.tool_call_identities??[]){let S=b&&Tl(b,A);if(!S)throw new f("Chat completion stream contains a changed tool call identity");kl(S,O)}if(u(this,et,"f"))for(let A=0;A<(b?.length??0);A+=1){let O=Tl(b,A);if(!O)continue;let S=Ru(O);if(!S){let z=Object.getOwnPropertyDescriptor(O,"type");if(z&&!("value"in z))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");if(z?.value!=="function")continue;let R=Object.getOwnPropertyDescriptor(O,"function");if(R&&!("value"in R))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");if(R&&typeof R.value=="object"&&R.value!==null){let v=Object.getOwnPropertyDescriptor(R.value,"name");if(v&&!("value"in v))throw new f("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!ou(u(this,ce,"f"),{type:S.type,function:{name:S.name}}))continue;let P=Object.getOwnPropertyDescriptor(O,"function");if(!P||!("value"in P))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");let q=P.value,E=tt(q,"arguments");if(typeof E!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");Jr(E,r,u(this,Le,"f")),m.set(A,Object.freeze({tool:O,function:q,type:S.type,name:S.name,arguments:E}))}}return i},Ti=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");let t=u(this,Se,"f");if(!t)throw new f("request ended without sending any chunks");let r=u(this,Y,"m",Gn).call(this,t),o=u(this,ar,"f");return w(this,ar,new Set,"f"),w(this,Se,void 0,"f"),w(this,Xr,[],"f"),Ug(t,u(this,ce,"f"),o,r)},up=function(t,r){var o,i,s,a,c;let d=u(this,Se,"f"),{choices:h,obfuscation:_,...m}=t;if(d)t.id&&ji(d,m);else{let A={...m,choices:[]};w(this,Se,A,"f"),d=A}let b=u(this,ce,"f")?.n,y=typeof b=="number"&&Number.isSafeInteger(b)&&b>0?Math.min(b,Au):Au;for(let A of t.choices){let{delta:O,finish_reason:S,index:P,logprobs:q=null,...E}=A,z=[];if(r.set(A,Object.freeze({index:P,tool_calls:z})),!Number.isSafeInteger(P)||P<0||P>=y)throw new f(`Chat completion stream contains an invalid choice index: ${P}`);let R=d.choices[P];if(!R){let M={finish_reason:S??null,index:P,message:{},logprobs:null,...E};d.choices[P]=M,R=M}if((At(u(this,ce,"f")?.response_format)||u(this,et,"f"))&&tt(ki(R),"refusal"),q)if(R.logprobs){let{content:M,refusal:te,...X}=q;ji(R.logprobs,X),M&&((o=R.logprobs).content??(o.content=[]),R.logprobs.content.push(...M)),te&&((i=R.logprobs).refusal??(i.refusal=[]),R.logprobs.refusal.push(...te))}else R.logprobs={...q},q.content&&(R.logprobs.content=[...q.content]),q.refusal&&(R.logprobs.refusal=[...q.refusal]);if(S&&(R.finish_reason=S,u(this,ce,"f")&&(u(this,wu,"f")||ul(u(this,ce,"f"))))){if(S==="length")throw new rr;if(S==="content_filter")throw new nr}if(ji(R,E),!O){Object.freeze(z);continue}u(this,ar,"f").delete(P);let{audio:v,content:I,refusal:j,function_call:C,role:$,...T}=O,{tool_calls:F,...K}=T,W=k(T,"tool_calls")?F:O.tool_calls;if(ji(R.message,K),v?.expires_at!=null&&v.id==null&&v.data==null&&v.transcript==null&&I==null&&j==null&&C==null&&$==null&&W==null&&Object.keys(K).length===0&&u(this,ar,"f").add(P),j&&(R.message.refusal=(R.message.refusal||"")+j),$&&(R.message.role=$),v){let M=(s=R.message).audio??(s.audio={});v.id!=null&&(M.id=v.id),v.data!=null&&(M.data=(M.data??"")+v.data),v.transcript!=null&&(M.transcript=(M.transcript??"")+v.transcript),v.expires_at!=null&&(M.expires_at=v.expires_at)}if(C&&(R.message.function_call?(C.name&&(R.message.function_call.name=C.name),C.arguments&&((a=R.message.function_call).arguments??(a.arguments=""),R.message.function_call.arguments+=C.arguments)):R.message.function_call=C),I!=null)if(!R.message.refusal&&At(u(this,ce,"f")?.response_format)){let M=u(this,Y,"m",Vn).call(this,R),te=M.content_parse_state??(M.content_parse_state=Fl()),X=zl(te,u(this,Le,"f"),I);R.message.content=(tt(R.message,"content")||"")+I,te.has_non_whitespace?X&&Ml(te,u(this,Le,"f"))?(u(this,Y,"m",Gn).call(this,d),R.message.parsed=cp(Jr(R.message.content))):I.length>0&&(R.message.parsed=null):R.message.parsed=null}else R.message.content=(R.message.content||"")+I;if(W){let M=(c=R.message).tool_calls??(c.tool_calls=[]);for(let te of W){let{index:X,id:$a,type:Mn,function:Ln,custom:Et,...Ec}=te;if(!Number.isSafeInteger(X)||X<0||X>=ur)throw new f(`Chat completion stream contains an invalid tool call index: ${X}`);let Ue="",de=M[X]??(M[X]={}),at=Ln?.name,pt=u(this,et,"f")?u(this,Y,"m",Vn).call(this,R):void 0,Qe=pt?.tool_call_identities.get(X);if(Qe&&(kl(de,Qe),Mn!==void 0&&Mn!==Qe.type||at!==void 0&&at!==Qe.name))throw new f("Chat completion stream contains a changed tool call identity");if(ji(de,Ec),$a&&(de.id=$a),Mn&&(de.type=Mn),Et){let je=de.custom??(de.custom={name:Et.name??"",input:""});Et.name&&(je.name=Et.name),Et.input&&(je.input+=Et.input)}if(Ln){let je=de.function??(de.function={name:at??"",arguments:""});if(at&&(je.name=at),pt&&!Qe){let He=Ru(de),Cc=He&&u(this,ce,"f")?.tools?.find(ht=>wt(ht)&&ht.function.name===He.name);if(He&&(Qe={...He,parseable:Cc!==void 0&&ou(u(this,ce,"f"),{type:He.type,function:{name:He.name}})},pt.tool_call_identities.set(X,Qe),!Qe.parseable)){let ht=pt.tool_call_parse_states.get(X);ht&&(u(this,Le,"f").bytes-=ht.bytes,u(this,Le,"f").fragments-=ht.fragments,u(this,Le,"f").work-=ht.work,pt.tool_call_parse_states.delete(X))}}let Xt=Ln.arguments;if(Xt!=null)if(Ue=Xt,pt&&Qe?.parseable!==!1){let He=pt.tool_call_parse_states.get(X);He||(He=Fl(),pt.tool_call_parse_states.set(X,He));let Cc=zl(He,u(this,Le,"f"),Xt),ht=tt(je,"arguments");if(typeof ht!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");je.arguments=ht+Xt,Cc&&Qe?.parseable===!0&&Ml(He,u(this,Le,"f"))?(u(this,Y,"m",Gn).call(this,d),je.parsed_arguments=cp(Jr(je.arguments))):Xt.length>0&&k(je,"parsed_arguments")&&(je.parsed_arguments=void 0)}else je.arguments+=Xt}z.push(Object.freeze({index:X,arguments_delta:Ue}))}}Object.freeze(z)}return d},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=r=>e(r);return this.on("chunk",t),()=>this.off("chunk",t)},{onReturn:()=>this.abort()})}toReadableStream(){return new $e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Ug(n,e,t,r){let{id:o,choices:i,created:s,model:a,system_fingerprint:c,...d}=n,h={...d,id:o,choices:fp(i,Au,"choice",_=>{let m=r.get(_);if(!m)throw new f("Chat completion stream contains an unsafe structured JSON snapshot");let b=new Proxy(_,{get(T,F,K){return F==="message"?m.message:Reflect.get(T,F,K)}}),{message:y,finish_reason:A,index:O,logprobs:S,...P}=b,q=new Proxy(y,{get(T,F,K){return F==="content"?m.content:F==="refusal"?m.refusal:F==="tool_calls"?m.toolCallCollection:Reflect.get(T,F,K)}}),{content:E=null,function_call:z,tool_calls:R,audio:v,...I}=q,j=A??(t.has(O)&&Qg(v)?"stop":null);if(!j)throw new f(`missing finish_reason for choice ${O}`);let C=v?{audio:v}:{},$=q.role;if(!$)throw new f(`missing role for choice ${O}`);if(z){let{arguments:T,name:F}=z;if(T==null)throw new f(`missing function_call.arguments for choice ${O}`);if(!F)throw new f(`missing function_call.name for choice ${O}`);return{...P,message:{...C,content:E,function_call:{arguments:T,name:F},role:$,refusal:q.refusal??null},finish_reason:j,index:O,logprobs:S}}return R?{...P,index:O,finish_reason:j,logprobs:S,message:{...I,...C,role:$,content:E,refusal:q.refusal??null,tool_calls:fp(R,ur,"tool-call",(T,F)=>{let K=m.toolCalls.get(F);if(!K){let Ue=Ru(T);if(Ue&&ou(e,{type:Ue.type,function:{name:Ue.name}}))throw new f("Chat completion stream contains an unsafe structured JSON snapshot")}if(K&&K.tool!==T)throw new f("Chat completion stream contains a changed tool call identity");let W=K&&new Proxy(K.function,{get(Ue,de,at){return de==="arguments"?K.arguments:de==="name"?K.name:Reflect.get(Ue,de,at)}}),M=K&&W?new Proxy(T,{get(Ue,de,at){return de==="type"?K.type:de==="function"?W:Reflect.get(Ue,de,at)}}):T;if(M.type==null)throw new f(`missing choices[${O}].tool_calls[${F}].type`);if(M.type==="custom"){let{custom:Ue,type:de,id:at,...pt}=M,{input:Qe="",name:je,...Xt}=Ue||{};if(je==null)throw new f(`missing choices[${O}].tool_calls[${F}].custom.name`);return{...pt,id:at||`call_${Me()}`,type:de,custom:{...Xt,name:je,input:Qe}}}let{function:te,type:X,id:$a,...Mn}=M,{arguments:Ln,name:Et,...Ec}=te||{};if(Et==null)throw new f(`missing choices[${O}].tool_calls[${F}].function.name`);if(Ln==null)throw new f(`missing choices[${O}].tool_calls[${F}].function.arguments`);return{...Mn,id:$a||`call_${Me()}`,type:X,function:{...Ec,name:Et,arguments:Ln}}})}}:{...P,message:{...I,...C,content:E,role:$,refusal:q.refusal??null},finish_reason:j,index:O,logprobs:S}}),created:s,model:a,object:"chat.completion",...c?{system_fingerprint:c}:{}};return Bf(h,e)}function Qg(n){return n?.id!=null&&n.data!=null&&n.transcript!=null&&n.expires_at!=null}var $i=class n extends Vr{static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e,t,r=this._createIterator(i=>{let s=c=>{e=c,i(c)},a=c=>{if(zt(c)){t=c.tool_calls?.map(d=>d.id);return}if(bi(c)){if(!e)throw new f("cannot serialize a tool message before receiving any chunks");i(mp(e,c,t)),t=void 0}};return this.on("chunk",s),this.on("message",a),()=>{this.off("chunk",s),this.off("message",a)}},{onReturn:()=>this.abort()});return new $e(()=>r,this.controller).toReadableStream()}static runTools(e,t,r){let o=new n(t),i={...r,__metadata:{...r?.__metadata,helperMethod:"runTools"}};return o._run(()=>o._runTools(e,t,o,i)),o}};function Di(n,e){return Promise.resolve(n).then(e)}function Hg(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var gp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Xg(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>gp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!gp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var cr=class extends p{constructor(){super(...arguments),this.messages=new Nr(this._client)}create(e,t){return this._client.post("/chat/completions",Di(t,r=>Hg({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))._thenUnwrap((r,o)=>o.options.stream?ap(r):r)}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,Di(t,r=>({...r,__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,Di(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}list(e={},t){let r=Xg(e,["after","limit","metadata","model","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/chat/completions",x,Di(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,Di(t,r=>({...r,__security:{bearerAuth:!0}})))}parse(e,t){return Kf(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap(r=>gi(r,e))}runTools(e,t){return e.stream?$i.runTools(this._client,e,t):Ei.runTools(this._client,e,t)}stream(e,t){return Vr.createChatCompletion(this._client,e,t)}};cr.Messages=Nr;var lr=class extends p{constructor(){super(...arguments),this.completions=new cr(this._client)}};lr.Completions=cr;function Ou(n,e){return Promise.resolve(n).then(e)}var bp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Vg(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>bp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!bp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Zn=class extends p{create(e,t){return this._client.post("/organization/admin_api_keys",Ou(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/admin_api_keys/${e}`,Ou(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=Vg(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/admin_api_keys",x,Ou(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/admin_api_keys/${e}`,Ou(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function Yg(n,e){return Promise.resolve(n).then(e)}var wp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Zg(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>wp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!wp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var es=class extends p{list(e={},t){let r=Zg(e,["actor_emails","actor_ids","after","before","effective_at","event_types","limit","project_ids","resource_ids","tenant_only"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/audit_logs",N,Yg(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}};function Gr(n,e){return Promise.resolve(n).then(e)}var Ap=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Rp(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Ap.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Ap.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ts=class extends p{create(e,t){return this._client.post("/organization/certificates",Gr(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t={},r){let o=Rp(t,["include"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.get(l`/organization/certificates/${e}`,Gr(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/certificates/${e}`,Gr(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=Rp(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/certificates",N,Gr(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/certificates/${e}`,Gr(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",_e,Gr(t,r=>({body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})))}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",_e,Gr(t,r=>({body:e,method:"post",...r,__security:{adminAPIKeyAuth:!0}})))}};function Op(n,e){return Promise.resolve(n).then(e)}var rs=class extends p{retrieve(e){return this._client.get("/organization/data_retention",Op(e,t=>({...t,__security:{adminAPIKeyAuth:!0}})))}update(e,t){return this._client.post("/organization/data_retention",Op(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}};function Fi(n,e){return Promise.resolve(n).then(e)}var Pp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function nb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Pp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Pp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ns=class extends p{create(e,t){return this._client.post("/organization/external_keys",Fi(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/external_keys/${e}`,Fi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=nb(e,["after","limit","order","purpose"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/external_keys",x,Fi(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/external_keys/${e}`,Fi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}validate(e,t){return this._client.post(l`/organization/external_keys/${e}/validate`,Fi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function zi(n,e){return Promise.resolve(n).then(e)}var xp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function ob(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>xp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!xp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ss=class extends p{create(e,t){return this._client.post("/organization/external_storage",zi(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/external_storage/${e}`,zi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=ob(e,["after","limit","order","project_id"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/external_storage",x,zi(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/external_storage/${e}`,zi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}validate(e,t){return this._client.post(l`/organization/external_storage/${e}/validate`,zi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function Pu(n,e){return Promise.resolve(n).then(e)}var vp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function ab(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>vp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!vp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var os=class extends p{create(e,t){return this._client.post("/organization/invites",Pu(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/invites/${e}`,Pu(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=ab(e,["after","limit"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/invites",N,Pu(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/invites/${e}`,Pu(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function Mi(n,e){return Promise.resolve(n).then(e)}var Ip=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function cb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Ip.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Ip.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var is=class extends p{create(e,t){return this._client.post("/organization/roles",Mi(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/roles/${e}`,Mi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/roles/${e}`,Mi(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=cb(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/roles",se,Mi(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/roles/${e}`,Mi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function Li(n,e){return Promise.resolve(n).then(e)}var Sp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function db(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Sp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Sp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var as=class extends p{create(e,t){return this._client.post("/organization/spend_alerts",Li(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/spend_alerts/${e}`,Li(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/spend_alerts/${e}`,Li(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=db(e,["after","before","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/spend_alerts",N,Li(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/spend_alerts/${e}`,Li(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function Nl(n,e){return Promise.resolve(n).then(e)}var us=class extends p{retrieve(e){return this._client.get("/organization/spend_limit",Nl(e,t=>({...t,__security:{adminAPIKeyAuth:!0}})))}update(e,t){return this._client.post("/organization/spend_limit",Nl(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}delete(e){return this._client.delete("/organization/spend_limit",Nl(e,t=>({...t,__security:{adminAPIKeyAuth:!0}})))}};function rt(n,e){return Promise.resolve(n).then(e)}var cs=class extends p{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}completions(e,t){return this._client.get("/organization/usage/completions",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}costs(e,t){return this._client.get("/organization/costs",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}decisions(e,t){return this._client.get("/organization/usage/decisions",rt(t,r=>({query:Object.fromEntries(Object.entries(e).filter(([,o])=>o!==null)),...r,__security:{adminAPIKeyAuth:!0}})))}embeddings(e,t){return this._client.get("/organization/usage/embeddings",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}images(e,t){return this._client.get("/organization/usage/images",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}moderations(e,t){return this._client.get("/organization/usage/moderations",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",rt(t,r=>({query:e,...r,__security:{adminAPIKeyAuth:!0}})))}};function xu(n,e){return Promise.resolve(n).then(e)}var Ep=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function mb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Ep.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Ep.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ls=class extends p{create(e,t,r){return this._client.post(l`/organization/groups/${e}/roles`,xu(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{group_id:o}=t;return this._client.get(l`/organization/groups/${o}/roles/${e}`,xu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=mb(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/groups/${e}/roles`,se,xu(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{group_id:o}=t;return this._client.delete(l`/organization/groups/${o}/roles/${e}`,xu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function vu(n,e){return Promise.resolve(n).then(e)}var Cp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function yb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Cp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Cp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ds=class extends p{create(e,t,r){return this._client.post(l`/organization/groups/${e}/users`,vu(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{group_id:o}=t;return this._client.get(l`/organization/groups/${o}/users/${e}`,vu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=yb(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/groups/${e}/users`,se,vu(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{group_id:o}=t;return this._client.delete(l`/organization/groups/${o}/users/${e}`,vu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function Bi(n,e){return Promise.resolve(n).then(e)}var Tp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function bb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Tp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Tp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var dr=class extends p{constructor(){super(...arguments),this.users=new ds(this._client),this.roles=new ls(this._client)}create(e,t){return this._client.post("/organization/groups",Bi(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/groups/${e}`,Bi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/groups/${e}`,Bi(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=bb(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/groups",se,Bi(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/groups/${e}`,Bi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};dr.Users=ds;dr.Roles=ls;function Iu(n,e){return Promise.resolve(n).then(e)}var kp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Ab(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>kp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!kp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var fs=class extends p{retrieve(e,t,r){let{project_id:o}=t;return this._client.get(l`/organization/projects/${o}/api_keys/${e}`,Iu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/organization/projects/${o}/api_keys/${e}`,Iu(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=Ab(t,["after","limit","owner_project_access"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/api_keys`,N,Iu(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o}=t;return this._client.delete(l`/organization/projects/${o}/api_keys/${e}`,Iu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function Wl(n,e){return Promise.resolve(n).then(e)}var jp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Ob(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>jp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!jp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ps=class extends p{list(e,t={},r){let o=Ob(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/certificates`,N,Wl(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}activate(e,t,r){return this._client.getAPIList(l`/organization/projects/${e}/certificates/activate`,_e,Wl(r,o=>({body:t,method:"post",...o,__security:{adminAPIKeyAuth:!0}})))}deactivate(e,t,r){return this._client.getAPIList(l`/organization/projects/${e}/certificates/deactivate`,_e,Wl(r,o=>({body:t,method:"post",...o,__security:{adminAPIKeyAuth:!0}})))}};function qp(n,e){return Promise.resolve(n).then(e)}var hs=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/data_retention`,qp(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/projects/${e}/data_retention`,qp(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}};function $p(n,e){return Promise.resolve(n).then(e)}var ms=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/hosted_tool_permissions`,$p(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/projects/${e}/hosted_tool_permissions`,$p(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}};function Ul(n,e){return Promise.resolve(n).then(e)}var _s=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/model_permissions`,Ul(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/projects/${e}/model_permissions`,Ul(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/projects/${e}/model_permissions`,Ul(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function Dp(n,e){return Promise.resolve(n).then(e)}var Fp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Sb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Fp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Fp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ys=class extends p{listRateLimits(e,t={},r){let o=Sb(t,["after","before","limit"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/rate_limits`,N,Dp(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}updateRateLimit(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/organization/projects/${o}/rate_limits/${e}`,Dp(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}};function Ki(n,e){return Promise.resolve(n).then(e)}var zp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Cb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>zp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!zp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var gs=class extends p{create(e,t,r){return this._client.post(l`/projects/${e}/roles`,Ki(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{project_id:o}=t;return this._client.get(l`/projects/${o}/roles/${e}`,Ki(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/projects/${o}/roles/${e}`,Ki(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=Cb(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/projects/${e}/roles`,se,Ki(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o}=t;return this._client.delete(l`/projects/${o}/roles/${e}`,Ki(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function Mp(n,e){return Promise.resolve(n).then(e)}var bs=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/service_tier_settings`,Mp(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/projects/${e}/service_tier_settings`,Mp(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}};function Ni(n,e){return Promise.resolve(n).then(e)}var Lp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function jb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Lp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Lp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ws=class extends p{create(e,t,r){return this._client.post(l`/organization/projects/${e}/spend_alerts`,Ni(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{project_id:o}=t;return this._client.get(l`/organization/projects/${o}/spend_alerts/${e}`,Ni(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/organization/projects/${o}/spend_alerts/${e}`,Ni(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=jb(t,["after","before","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/spend_alerts`,N,Ni(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o}=t;return this._client.delete(l`/organization/projects/${o}/spend_alerts/${e}`,Ni(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function Ql(n,e){return Promise.resolve(n).then(e)}var As=class extends p{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/spend_limit`,Ql(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/projects/${e}/spend_limit`,Ql(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/projects/${e}/spend_limit`,Ql(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};function Su(n,e){return Promise.resolve(n).then(e)}var Rs=class extends p{create(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/projects/${o}/groups/${e}/roles`,Su(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{project_id:o,group_id:i}=t;return this._client.get(l`/projects/${o}/groups/${i}/roles/${e}`,Su(r,s=>({...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t,r){let{project_id:o,...i}=t;return this._client.getAPIList(l`/projects/${o}/groups/${e}/roles`,se,Su(r,s=>({query:i,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o,group_id:i}=t;return this._client.delete(l`/projects/${o}/groups/${i}/roles/${e}`,Su(r,s=>({...s,__security:{adminAPIKeyAuth:!0}})))}};function Eu(n,e){return Promise.resolve(n).then(e)}var Bp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Fb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Bp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Bp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Yr=class extends p{constructor(){super(...arguments),this.roles=new Rs(this._client)}create(e,t,r){return this._client.post(l`/organization/projects/${e}/groups`,Eu(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{project_id:o,...i}=t;return this._client.get(l`/organization/projects/${o}/groups/${e}`,Eu(r,s=>({query:i,...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=Fb(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/groups`,se,Eu(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o}=t;return this._client.delete(l`/organization/projects/${o}/groups/${e}`,Eu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};Yr.Roles=Rs;function Mb(n,e){return Promise.resolve(n).then(e)}var Os=class extends p{create(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/organization/projects/${o}/service_accounts/${e}/api_keys`,Mb(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}};function Wi(n,e){return Promise.resolve(n).then(e)}var Kp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Bb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Kp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Kp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Zr=class extends p{constructor(){super(...arguments),this.apiKeys=new Os(this._client)}create(e,t,r){return this._client.post(l`/organization/projects/${e}/service_accounts`,Wi(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{project_id:o}=t;return this._client.get(l`/organization/projects/${o}/service_accounts/${e}`,Wi(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/organization/projects/${o}/service_accounts/${e}`,Wi(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=Bb(t,["after","limit"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/service_accounts`,N,Wi(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o}=t;return this._client.delete(l`/organization/projects/${o}/service_accounts/${e}`,Wi(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};Zr.APIKeys=Os;function Cu(n,e){return Promise.resolve(n).then(e)}var Ps=class extends p{create(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/projects/${o}/users/${e}/roles`,Cu(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{project_id:o,user_id:i}=t;return this._client.get(l`/projects/${o}/users/${i}/roles/${e}`,Cu(r,s=>({...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t,r){let{project_id:o,...i}=t;return this._client.getAPIList(l`/projects/${o}/users/${e}/roles`,se,Cu(r,s=>({query:i,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o,user_id:i}=t;return this._client.delete(l`/projects/${o}/users/${i}/roles/${e}`,Cu(r,s=>({...s,__security:{adminAPIKeyAuth:!0}})))}};function Ui(n,e){return Promise.resolve(n).then(e)}var Np=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Wb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Np.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Np.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var en=class extends p{constructor(){super(...arguments),this.roles=new Ps(this._client)}create(e,t,r){return this._client.post(l`/organization/projects/${e}/users`,Ui(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{project_id:o}=t;return this._client.get(l`/organization/projects/${o}/users/${e}`,Ui(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){let{project_id:o,...i}=t;return this._client.post(l`/organization/projects/${o}/users/${e}`,Ui(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=Wb(t,["after","limit"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/users`,N,Ui(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{project_id:o}=t;return this._client.delete(l`/organization/projects/${o}/users/${e}`,Ui(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};en.Roles=Ps;function Qi(n,e){return Promise.resolve(n).then(e)}var Wp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Qb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Wp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Wp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var pe=class extends p{constructor(){super(...arguments),this.users=new en(this._client),this.serviceAccounts=new Zr(this._client),this.apiKeys=new fs(this._client),this.rateLimits=new ys(this._client),this.modelPermissions=new _s(this._client),this.serviceTierSettings=new bs(this._client),this.hostedToolPermissions=new ms(this._client),this.groups=new Yr(this._client),this.roles=new gs(this._client),this.dataRetention=new hs(this._client),this.spendLimit=new As(this._client),this.spendAlerts=new ws(this._client),this.certificates=new ps(this._client)}create(e,t){return this._client.post("/organization/projects",Qi(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/projects/${e}`,Qi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/projects/${e}`,Qi(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=Qb(e,["after","include_archived","limit"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/projects",N,Qi(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}archive(e,t){return this._client.post(l`/organization/projects/${e}/archive`,Qi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};pe.Users=en;pe.ServiceAccounts=Zr;pe.APIKeys=fs;pe.RateLimits=ys;pe.ModelPermissions=_s;pe.ServiceTierSettings=bs;pe.HostedToolPermissions=ms;pe.Groups=Yr;pe.Roles=gs;pe.DataRetention=hs;pe.SpendLimit=As;pe.SpendAlerts=ws;pe.Certificates=ps;function Tu(n,e){return Promise.resolve(n).then(e)}var Up=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Xb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Up.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Up.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var xs=class extends p{create(e,t,r){return this._client.post(l`/organization/users/${e}/roles`,Tu(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{user_id:o}=t;return this._client.get(l`/organization/users/${o}/roles/${e}`,Tu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=Xb(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/users/${e}/roles`,se,Tu(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{user_id:o}=t;return this._client.delete(l`/organization/users/${o}/roles/${e}`,Tu(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function ku(n,e){return Promise.resolve(n).then(e)}var Qp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Vb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Qp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Qp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var tn=class extends p{constructor(){super(...arguments),this.roles=new xs(this._client)}retrieve(e,t){return this._client.get(l`/organization/users/${e}`,ku(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){return this._client.post(l`/organization/users/${e}`,ku(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=Vb(e,["after","emails","limit"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/users",N,ku(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/users/${e}`,ku(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};tn.Roles=xs;function Hi(n,e){return Promise.resolve(n).then(e)}var Hp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Yb(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Hp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Hp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var vs=class extends p{create(e,t,r){return this._client.post(l`/organization/workload_identity_providers/${e}/federation_rules`,Hi(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,r){let{workload_identity_provider_id:o}=t;return this._client.get(l`/organization/workload_identity_providers/${o}/federation_rules/${e}`,Hi(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,r){let{workload_identity_provider_id:o,...i}=t;return this._client.post(l`/organization/workload_identity_providers/${o}/federation_rules/${e}`,Hi(r,s=>({body:i,...s,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=Yb(t,["after","limit","order","service_account_id"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/organization/workload_identity_providers/${e}/federation_rules`,x,Hi(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{workload_identity_provider_id:o}=t;return this._client.delete(l`/organization/workload_identity_providers/${o}/federation_rules/${e}`,Hi(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function Xi(n,e){return Promise.resolve(n).then(e)}var Xp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function ew(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Xp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Xp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var rn=class extends p{constructor(){super(...arguments),this.federationRules=new vs(this._client)}create(e,t){return this._client.post("/organization/workload_identity_providers",Xi(t,r=>({body:e,...r,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/workload_identity_providers/${e}`,Xi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}update(e,t={},r){return this._client.post(l`/organization/workload_identity_providers/${e}`,Xi(r,o=>({body:t,...o,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let r=ew(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/organization/workload_identity_providers",x,Xi(t,o=>({query:e,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/workload_identity_providers/${e}`,Xi(t,r=>({...r,__security:{adminAPIKeyAuth:!0}})))}};rn.FederationRules=vs;var ae=class extends p{constructor(){super(...arguments),this.auditLogs=new es(this._client),this.adminAPIKeys=new Zn(this._client),this.usage=new cs(this._client),this.invites=new os(this._client),this.users=new tn(this._client),this.groups=new dr(this._client),this.roles=new is(this._client),this.dataRetention=new rs(this._client),this.externalKeys=new ns(this._client),this.workloadIdentityProviders=new rn(this._client),this.externalStorage=new ss(this._client),this.spendLimit=new us(this._client),this.spendAlerts=new as(this._client),this.certificates=new ts(this._client),this.projects=new pe(this._client)}};ae.AuditLogs=es;ae.AdminAPIKeys=Zn;ae.Usage=cs;ae.Invites=os;ae.Users=tn;ae.Groups=dr;ae.Roles=is;ae.DataRetention=rs;ae.ExternalKeys=ns;ae.WorkloadIdentityProviders=rn;ae.ExternalStorage=ss;ae.SpendLimit=us;ae.SpendAlerts=as;ae.Certificates=ts;ae.Projects=pe;var fr=class extends p{constructor(){super(...arguments),this.organization=new ae(this._client)}};fr.Organization=ae;function nw(n,e){return Promise.resolve(n).then(e)}var Is=class extends p{create(e,t){return this._client.post("/audio/speech",nw(t,r=>({body:e,...r,headers:g([{Accept:"application/octet-stream"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function ow(n,e){return Promise.resolve(n).then(e)}function iw(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Ss=class extends p{create(e,t){return this._client.post("/audio/transcriptions",ow(t,r=>ee(iw((o=>({...o,__metadata:{model:e.model}}))({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}}),{streamFromBody:!0}),this._client)))}};function uw(n,e){return Promise.resolve(n).then(e)}var Es=class extends p{create(e,t){return this._client.post("/audio/translations",uw(t,r=>ee((o=>({...o,__metadata:{model:e.model}}))({body:e,...r,__security:{bearerAuth:!0}}),this._client)))}};function Ji(n,e){return Promise.resolve(n).then(e)}var Jp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function lw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Jp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Jp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Cs=class extends p{create(e,t){return this._client.post("/audio/voice_consents",Ji(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(l`/audio/voice_consents/${e}`,Ji(t,r=>({...r,__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/audio/voice_consents/${e}`,Ji(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}list(e={},t){let r=lw(e,["after","limit"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/audio/voice_consents",x,Ji(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/audio/voice_consents/${e}`,Ji(t,r=>({...r,__security:{bearerAuth:!0}})))}};function Vp(n,e){return Promise.resolve(n).then(e)}var Ts=class extends p{create(e,t){return this._client.post("/audio/voices",Vp(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}delete(e,t){return this._client.delete(l`/audio/voices/${e}`,Vp(t,r=>({...r,__security:{bearerAuth:!0}})))}};var nt=class extends p{constructor(){super(...arguments),this.transcriptions=new Ss(this._client),this.translations=new Es(this._client),this.speech=new Is(this._client),this.voices=new Ts(this._client),this.voiceConsents=new Cs(this._client)}};nt.Transcriptions=Ss;nt.Translations=Es;nt.Speech=Is;nt.Voices=Ts;nt.VoiceConsents=Cs;function ju(n,e){return Promise.resolve(n).then(e)}var Gp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function pw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Gp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Gp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var nn=class extends p{create(e,t){return this._client.post("/batches",ju(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/batches/${e}`,ju(t,r=>({...r,__security:{bearerAuth:!0}})))}list(e={},t){let r=pw(e,["after","limit"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/batches",x,ju(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,ju(t,r=>({...r,__security:{bearerAuth:!0}})))}};function Vi(n,e){return Promise.resolve(n).then(e)}var Yp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function hw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Yp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Yp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var ks=class extends p{create(e,t){return this._client.post("/assistants",Vi(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/assistants/${e}`,Vi(t,r=>({...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/assistants/${e}`,Vi(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=hw(e,["after","before","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/assistants",x,Vi(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/assistants/${e}`,Vi(t,r=>({...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}};function Hl(n,e){return Promise.resolve(n).then(e)}var Zp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function _w(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Zp.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Zp.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var js=class extends p{create(e,t){return this._client.post(l`/agents/automations/${e}/invocations`,Hl(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,r){let{automation_id:o}=t;return this._client.get(l`/agents/automations/${o}/invocations/${e}`,Hl(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=_w(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/agents/automations/${e}/invocations`,x,Hl(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function sn(n,e){return Promise.resolve(n).then(e)}var eh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function gw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>eh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!eh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var on=class extends p{constructor(){super(...arguments),this.invocations=new js(this._client)}create(e,t){return this._client.post("/agents/automations",sn(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/automations/${e}`,sn(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/agents/automations/${e}`,sn(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=gw(e,["after","limit","order","session_id"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/agents/automations",x,sn(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/automations/${e}`,sn(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}pause(e,t){return this._client.post(l`/agents/automations/${e}/pause`,sn(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}resume(e,t){return this._client.post(l`/agents/automations/${e}/resume`,sn(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}};on.Invocations=js;var qu=class extends f{constructor(e,t){super("Agent file preparation or staging failed; uploaded files remain caller-owned."),this.name="AgentFileUploadError",this.uploadedFiles=e,Object.defineProperty(this,"cause",{value:t,configurable:!0})}};function ww(n){let e=n.split("/"),t=e[2]??"";if(!n.startsWith("/workspace/")||n.includes("\\")||n.includes("\0")||e.slice(1).some(r=>r===""||r==="."||r==="..")||t===".codex"||t===".managed-agents"||t.startsWith(".managed-agents-")||n==="/workspace/outputs")throw new f("Agent files require a non-reserved absolute file path inside /workspace")}function Aw(n,e){let t=Object.entries(n),r=g([e.headers]);if(t.length>1&&(r.values.has("idempotency-key")||!r.nulls.has("idempotency-key")&&e?.idempotencyKey!==void 0))throw new f("Do not reuse an Idempotency-Key across multiple file uploads");let o={children:new Map};for(let[i]of t){ww(i);let s=o;for(let a of i.split("/")){if(s.file)throw new f("Agent file destinations conflict");let c=s.children.get(a);c||(c={children:new Map},s.children.set(a,c)),s=c}if(s.children.size>0)throw new f("Agent file destinations conflict");s.file=!0}return t}async function Xl(n,e,t){let r={...t},o=g([n._options.defaultHeaders,r.headers]);r.headers=o;let i=Aw(e,r);i.length>1&&o.nulls.add("idempotency-key");let s={files:[],uploadedFiles:[]};try{for(let[a,c]of i){let d=await n.files.create({file:c,purpose:"user_data"},r);s.uploadedFiles.push(d),s.files.push({type:"file_id",file_id:d.id,path:a})}return s}catch(a){throw new qu(s.uploadedFiles,a)}}async function th(n,e,t,r,o){let i=await Xl(n,{[r.path]:r.file},o),[s]=i.files,[a]=i.uploadedFiles;if(!s||!a)throw new f("Missing prepared agent file");try{return{uploadedFile:a,environmentFile:await e.create(t,s,o)}}catch(c){throw new qu(i.uploadedFiles,c)}}function rh(n,e){return Promise.resolve(n).then(e)}var qs=class extends p{create(e,t,r){return this._client.post(l`/agents/environments/${e}/files`,rh(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){return this._client.getAPIList(l`/agents/environments/${e}/files`,Nn,rh(r,o=>({query:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}prepare(e,t){return Xl(this._client,e,t)}upload(e,t,r){return th(this._client,this,e,t,r)}};function Gi(n,e){return Promise.resolve(n).then(e)}var nh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Ow(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>nh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!nh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var $s=class extends p{create(e={},t){return this._client.post("/agents/environments/templates",Gi(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/environments/templates/${e}`,Gi(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},r){return this._client.post(l`/agents/environments/templates/${e}`,Gi(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=Ow(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/agents/environments/templates",x,Gi(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/environments/templates/${e}`,Gi(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}};function Jl(n,e){return Promise.resolve(n).then(e)}var sh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function xw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>sh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!sh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var pr=class extends p{constructor(){super(...arguments),this.files=new qs(this._client),this.templates=new $s(this._client)}create(e,t){let{"Idempotency-Key":r,...o}=e;return this._client.post("/agents/environments",Jl(t,i=>({body:o,...i,headers:g([{"OpenAI-Beta":"agents=v1",...r!=null?{"Idempotency-Key":r}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/environments/${e}`,Jl(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=xw(e,["after","limit","order","type"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/agents/environments",Vl,Jl(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}},Vl=class extends x{constructor(e,t,r,o){super(e,t,r,o),this.object=r.object,this.first_id=r.first_id,this.last_id=r.last_id}};pr.Files=qs;pr.Templates=$s;async function*oh(n){let e;for(;;){let t=await n(e);if(yield*t.data,!t.has_more)return;let r=t.body,o=t.data[t.data.length-1],i=U(r)&&typeof r.last_id=="string"?r.last_id:o?.id;if(!i||i===e)throw new f("Agent pagination cannot advance to the next page");e=i}}var Ds,an,$u,Du=class{constructor(e,t){Ds.set(this,void 0),an.set(this,void 0),$u.set(this,void 0),w(this,Ds,e,"f"),w(this,an,t.session_id,"f"),w(this,$u,t.turn_id,"f")}async retrieve(e,t){let r;for await(let o of oh(i=>u(this,Ds,"f").list(u(this,an,"f"),{},{...t,query:{...t?.query,after:i,environment_id:void 0}})))if(o.session_id===u(this,an,"f")&&o.turn_id===u(this,$u,"f")&&o.path===e){if(r)throw new f("Multiple artifacts match this result and path");r=o}if(!r)throw new f("No artifact matches this result and path");return r}async content(e,t){let r=await this.retrieve(e,t);return u(this,Ds,"f").content(r.id,{session_id:u(this,an,"f")},t)}async download(e,t){let{path:r,to:o}=e,i=await this.retrieve(r,t),s=await u(this,Ds,"f").content(i.id,{session_id:u(this,an,"f")},t);if(!s.body)throw new f("Artifact response has no content stream");try{await s.body.pipeTo(o,t?.signal?{signal:t.signal}:{})}catch(a){try{await s.body.cancel()}catch{}throw a}return i}};Ds=new WeakMap,an=new WeakMap,$u=new WeakMap;function Fu(n,e){return Promise.resolve(n).then(e)}var ih=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Iw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>ih.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!ih.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Fs=class extends p{retrieve(e,t,r){let{session_id:o}=t;return this._client.get(l`/agents/sessions/${o}/artifacts/${e}`,Fu(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=Iw(t,["after","environment_id","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/artifacts`,x,Fu(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,r){let{session_id:o}=t;return this._client.delete(l`/agents/sessions/${o}/artifacts/${e}`,Fu(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}content(e,t,r){let{session_id:o}=t;return this._client.get(l`/agents/sessions/${o}/artifacts/${e}/content`,Fu(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}forResult(e){return new Du(this,e)}};function ah(n,e){return Promise.resolve(n).then(e)}var zs=class extends p{create(e,t,r){let{"Idempotency-Key":o,...i}=t;return this._client.post(l`/agents/sessions/${e}/events`,ah(r,s=>({body:i,...s,headers:g([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...o!=null?{"Idempotency-Key":o}:void 0},s?.headers]),__security:{bearerAuth:!0}})))}stream(e,t={},r){return arguments.length<3&&(r=t,t={}),t=t,this._client.get(l`/agents/sessions/${e}/events`,ah(r,o=>({query:t,...o,headers:g([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},o?.headers]),stream:!0,__streamMode:"events",__security:{bearerAuth:!0}})))}};function Cw(n,e){return Promise.resolve(n).then(e)}var uh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Tw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>uh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!uh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Ms=class extends p{list(e,t={},r){let o=Tw(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/items`,x,Cw(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function jw(n,e){return Promise.resolve(n).then(e)}var ch=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function qw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>ch.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!ch.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Ls=class extends p{list(e,t={},r){let o=qw(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/traces`,x,jw(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function Dw(n,e){return Promise.resolve(n).then(e)}var Bs=class extends p{list(e,t,r){let{session_id:o,...i}=t;return this._client.getAPIList(l`/agents/sessions/${o}/subagents/${e}/items`,x,Dw(r,s=>({query:i,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}};function zw(n,e){return Promise.resolve(n).then(e)}var Ks=class extends p{list(e,t,r){let{session_id:o,subagent_id:i,...s}=t;return this._client.getAPIList(l`/agents/sessions/${o}/subagents/${i}/turns/${e}/items`,x,zw(r,a=>({query:s,...a,headers:g([{"OpenAI-Beta":"agents=v1"},a?.headers]),__security:{bearerAuth:!0}})))}};function lh(n,e){return Promise.resolve(n).then(e)}var un=class extends p{constructor(){super(...arguments),this.items=new Ks(this._client)}retrieve(e,t,r){let{session_id:o,subagent_id:i}=t;return this._client.get(l`/agents/sessions/${o}/subagents/${i}/turns/${e}`,lh(r,s=>({...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e,t,r){let{session_id:o,...i}=t;return this._client.getAPIList(l`/agents/sessions/${o}/subagents/${e}/turns`,x,lh(r,s=>({query:i,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}};un.Items=Ks;function dh(n,e){return Promise.resolve(n).then(e)}var fh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Bw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>fh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!fh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var hr=class extends p{constructor(){super(...arguments),this.items=new Bs(this._client),this.turns=new un(this._client)}retrieve(e,t,r){let{session_id:o}=t;return this._client.get(l`/agents/sessions/${o}/subagents/${e}`,dh(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=Bw(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/subagents`,x,dh(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};hr.Items=Bs;hr.Turns=un;function Nw(n,e){return Promise.resolve(n).then(e)}var Ns=class extends p{list(e,t,r){let{session_id:o,...i}=t;return this._client.getAPIList(l`/agents/sessions/${o}/turns/${e}/items`,N,Nw(r,s=>({query:i,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}};function ph(n,e){return Promise.resolve(n).then(e)}var hh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Uw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>hh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!hh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var cn=class extends p{constructor(){super(...arguments),this.items=new Ns(this._client)}retrieve(e,t,r){let{session_id:o}=t;return this._client.get(l`/agents/sessions/${o}/turns/${e}`,ph(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=Uw(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/turns`,x,ph(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};cn.Items=Ns;var ln,Yi,dn,zu,Ws=class{constructor(){ln.set(this,void 0),Yi.set(this,!1),dn.set(this,new Set),zu.set(this,new Set)}accept(e){if(u(this,dn,"f").has(e.event_id))return!1;if(u(this,dn,"f").size===1024){let t=u(this,dn,"f").values().next();t.done||u(this,dn,"f").delete(t.value)}return u(this,dn,"f").add(e.event_id),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&u(this,ln,"f")===void 0&&w(this,ln,e.turn_id,"f"),(e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled")&&u(this,ln,"f")!==void 0&&e.turn_id===u(this,ln,"f")&&w(this,Yi,!0,"f"),!0}terminal(e,t){return e.type==="agent.session.failed"||e.type==="agent.session.budget_reached"&&e.session.id===t&&(u(this,ln,"f")===void 0||u(this,Yi,"f"))||e.type==="agent.session.idle"&&u(this,Yi,"f")}call(e){if(e.type!=="agent.session.turn.item.added"||e.item.type!=="function_call")return;let t=e.item,r=JSON.stringify([t.turn_id,t.call_id]);if(!u(this,zu,"f").has(r))return u(this,zu,"f").add(r),t}};ln=new WeakMap,Yi=new WeakMap,dn=new WeakMap,zu=new WeakMap;function mh(n){if(!U(n))return!1;let e=n,t;if(e.type==="input_text")t="text";else if(e.type==="input_image")t="image_url";else return!1;return k(e,"type")&&k(e,t)&&typeof e[t]=="string"}var _h=Symbol.for("openai.beta.agents.toolStages");var Re,Zi,Lu,Bu,fn,Us,yh,pn,Gl,Mu,gh;function Hw(n){if(n===null)return null;if(typeof n=="string"||Array.isArray(n)&&n.every(mh))return n;throw new f("Tool output must be text, content, a JSON object, or null")}function Xw(n,e){let t=U(e)?JSON.stringify(e):e,r=JSON.stringify(t);if(r===void 0)throw new f("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:n.turn_id,call_id:n.call_id,success:!0,output:Hw(typeof t=="string"?t:JSON.parse(r))}}var Qs=class{constructor(e,t,r,o,i){Re.add(this),Zi.set(this,void 0),Lu.set(this,void 0),Bu.set(this,void 0),fn.set(this,void 0),Us.set(this,void 0),w(this,Bu,e,"f"),w(this,fn,r,"f"),w(this,Us,i,"f"),w(this,Zi,new Map(Object.entries(t)),"f");let s=g([o?.headers]);s.values.delete("idempotency-key"),s.nulls.delete("idempotency-key");let{idempotencyKey:a,...c}=o??{};w(this,Lu,{...c,headers:s,signal:r.signal},"f")}canHandle(e){return typeof u(this,Zi,"f").get(e)=="function"}prepare(e,t){let r=e&&u(this,Zi,"f").get(e.name);if(!e||typeof r!="function")return;if(!t)throw new f("Tool call received before the session creation event");let o=structuredClone(e);return async()=>{u(this,Re,"m",pn).call(this);let i=await u(this,Re,"m",yh).call(this,o,r,t);u(this,Re,"m",pn).call(this),await u(this,Re,"m",gh).call(this,t,i)}}};Zi=new WeakMap,Lu=new WeakMap,Bu=new WeakMap,fn=new WeakMap,Us=new WeakMap,Re=new WeakSet,yh=async function(e,t,r){let o="arguments";try{let i=typeof e.arguments=="string"?JSON.parse(e.arguments):e.arguments;if(!U(i))throw new f("Function arguments must be a JSON object");o="execution";let s=i,a=await u(this,Re,"m",Mu).call(this,()=>u(this,Us,"f")&&t[_h]?t(s,c=>{o=c}):t(s));return o="output",Xw(e,a)}catch(i){if(u(this,Re,"m",pn).call(this),u(this,Us,"f")){let s=Object.freeze({error:i,stage:o,tool_name:e.name,session_id:r,turn_id:e.turn_id,call_id:e.call_id});try{await u(this,Re,"m",Mu).call(this,()=>u(this,Us,"f")?.call(this,s))}catch{u(this,Re,"m",pn).call(this)}}return{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!1,error:"Tool handler failed."}}},pn=function(){if(u(this,fn,"f").signal.aborted)throw u(this,Re,"m",Gl).call(this)},Gl=function(){let e=new V;return Object.defineProperty(e,"cause",{value:u(this,fn,"f").signal.reason,writable:!0,configurable:!0}),e},Mu=async function(e){let t,r=new Promise((o,i)=>{t=()=>i(u(this,Re,"m",Gl).call(this)),u(this,fn,"f").signal.addEventListener("abort",t,{once:!0})});try{u(this,Re,"m",pn).call(this);let o=async()=>await e();return await Promise.race([o(),r])}finally{t&&u(this,fn,"f").signal.removeEventListener("abort",t)}},gh=async function n(e,t,r=Me(),o=0){u(this,Re,"m",pn).call(this);try{await u(this,Bu,"f").events.create(e,{events:[t],"Idempotency-Key":r},u(this,Lu,"f"))}catch(i){let s=[100,300,600][o];if(s===void 0||!(i instanceof mt)||i.code!=="invalid_request_error"||!i.error||!("message"in i.error)||i.error.message!==`Unknown pending tool call: ${t.call_id}`)throw i;let a;try{await u(this,Re,"m",Mu).call(this,()=>new Promise(c=>{a=setTimeout(c,s)}))}finally{a!==void 0&&clearTimeout(a)}await u(this,Re,"m",n).call(this,e,t,r,o+1)}};function bh(n){return n.content.map(e=>e.type==="output_text"?e.text:"").join("")}var Hs=class{constructor(e,t){this.turn=e,this.messages=t}get session_id(){return this.turn.session_id}get turn_id(){return this.turn.id}get output_text(){return this.messages.map(bh).join("")}};var Ku=class extends Hs{constructor(e,t){super(e.turn,e.messages),this.raw_result=e,this.output_parsed=t}};var Nu,ea=class extends f{constructor(e){super("The completed agent output could not be parsed"),this.name="AgentOutputParseError",Nu.set(this,void 0),w(this,Nu,e,"f")}get raw_result(){return u(this,Nu,"f")}};Nu=new WeakMap;function Jw(n,e){try{if(!e)return n;let t;for(let r of n.messages)for(let o of r.content)if(o.type==="output_text"){let i=e.$parseRaw(o.text);t??(t={value:i})}if(!t)throw new ea(n);return new Ku(n,t.value)}catch{throw new ea(n)}}function Xs(n,e){let t=n&&Object.getOwnPropertyDescriptor(n,e);return t?.enumerable&&"value"in t?t.value:void 0}function Zl(n){if(!n)return;let e=Object.getOwnPropertyDescriptor(n,"$parseRaw");if(!e||!("value"in e)||typeof e.value!="function")return;let t=Xs(n,"schema");if(Xs(n,"type")!=="json_schema"||!t)throw new f("Typed agent formats require own enumerable type and schema data properties");let r=e.value;return{type:"json_schema",schema:t,$parseRaw:o=>r.call(n,o)}}function Yl(n,e,t=r=>r){let r=Object.getOwnPropertyDescriptor(n,e);if(!r?.enumerable)return n;let o=t(n[e]);return"value"in r&&o===r.value?n:Object.create(Object.getPrototypeOf(n),{...Object.getOwnPropertyDescriptors(n),[e]:{value:o,enumerable:!0,configurable:r.configurable,writable:!0}})}function wh(n,e){let t=Yl(n,"agent",c=>c&&Yl(c,"text",d=>d&&Yl(d,"format"))),r=Xs(t,"agent"),o=Xs(r,"text"),i=Zl(Xs(o,"format"));if(!i)return{body:t,options:e};let s=structuredClone(i.schema);for(let c of[t,r,o])if(c&&"toJSON"in c)throw new f("Typed agent requests cannot customize body, agent, or text serialization");let a={...e};if(Xs(a,"body")!==void 0)throw new f("Typed agent requests cannot override the body in request options");return delete a.body,{options:a,body:{...t,agent:{...r,text:{...o,format:{type:"json_schema",schema:s}}}},format:i}}async function Wu(n,e){return Jw(await n,e)}var Js=class extends f{constructor(e,t,r,o,i=[],s){super(`Could not collect the agent turn result: ${e}`),this.name="AgentTurnResultError",this.reason=e,this.session_id=t,this.turn=r,this.messages=o,this.required_actions=i,this.cause=s}get turn_id(){return this.turn?.id}};var Zs,mr,Be,eo,Vs,Gs,ta,hn,Ys,Rh,Ah,ed,Uu=class{constructor(e){Zs.add(this),mr.set(this,void 0),Be.set(this,void 0),eo.set(this,new Map),Vs.set(this,[]),Gs.set(this,void 0),ta.set(this,!1),hn.set(this,!1),Ys.set(this,!1),w(this,mr,e,"f")}accept(e){if(this.ready)return;"session"in e&&(w(this,mr,u(this,mr,"f")??e.session.id,"f"),w(this,Vs,structuredClone(e.session.required_actions??[]),"f"),w(this,Gs,void 0,"f"),w(this,ta,u(this,ta,"f")||e.type==="agent.session.failed","f"),w(this,Ys,u(this,Ys,"f")||e.type==="agent.session.idle"&&u(this,hn,"f")||e.type==="agent.session.budget_reached"&&e.session.id===u(this,mr,"f")&&(!u(this,Be,"f")||u(this,hn,"f")),"f")),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&!u(this,Be,"f")&&(w(this,Be,structuredClone(e.turn),"f"),w(this,mr,e.turn.session_id,"f"));let t="turn_id"in e?e.turn_id:void 0;"item"in e&&(t=e.item.turn_id),!(!u(this,Be,"f")||t!==u(this,Be,"f").id)&&u(this,Zs,"m",Rh).call(this,e)}error(e,t){return new Js(e,u(this,mr,"f"),u(this,Be,"f"),u(this,Zs,"m",ed).call(this),u(this,Vs,"f"),t)}checkAction(e){if(u(this,ta,"f")||u(this,Be,"f")?.status==="failed")throw this.error("failed");if(u(this,Be,"f")?.status==="cancelled")throw this.error("cancelled");if(u(this,Gs,"f")!==e){if(u(this,Vs,"f").some(t=>t.type!=="function_call"||!e(t.name)))throw this.error("requires_action");w(this,Gs,e,"f")}}get ready(){return u(this,Ys,"f")}release(){u(this,eo,"f").clear(),w(this,Vs,[],"f"),w(this,Gs,void 0,"f")}finish(){if(this.checkAction(()=>this.ready),!u(this,hn,"f")||u(this,Be,"f")?.status!=="completed"||!u(this,Ys,"f"))throw this.error("observation");return new Hs(u(this,Be,"f"),u(this,Zs,"m",ed).call(this))}};mr=new WeakMap,Be=new WeakMap,eo=new WeakMap,Vs=new WeakMap,Gs=new WeakMap,ta=new WeakMap,hn=new WeakMap,Ys=new WeakMap,Zs=new WeakSet,Rh=function(e){"turn"in e&&(w(this,Be,structuredClone(e.turn),"f"),w(this,hn,u(this,hn,"f")||e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled","f")),u(this,Zs,"m",Ah).call(this,e)},Ah=function(e){e.type!=="agent.session.turn.item.done"||e.item.type!=="message"||e.item.status!=="completed"||e.item.phase==="commentary"||u(this,eo,"f").has(e.item.id)||u(this,eo,"f").set(e.item.id,{index:e.output_index,message:structuredClone(e.item)})},ed=function(){return[...u(this,eo,"f").values()].sort((e,t)=>e.index-t.index).map(({message:e})=>e)};var Qu,to,Hu,ro,Ju,ra,Xu,Vu,na,Gu,Oh,Ph,no=class{constructor(e,t=()=>!1,r,o){Qu.add(this),to.set(this,void 0),Hu.set(this,!1),ro.set(this,!1),Ju.set(this,!1),ra.set(this,void 0),Xu.set(this,void 0),Vu.set(this,void 0),na.set(this,void 0),Gu.set(this,void 0),w(this,Vu,e,"f"),w(this,na,o,"f"),w(this,Gu,t,"f"),this.collector=new Uu(r)}enable(){if(!u(this,ro,"f")&&u(this,Ju,"f"))throw new f("Call withResultCollection() before consuming events, or call finalResult() on a fresh stream.");w(this,ro,!0,"f")}iterate(){if(u(this,to,"f"))throw new f("An agent result stream can only be consumed once");return w(this,to,u(this,Qu,"m",Oh).call(this),"f")}finalResult(){return w(this,Xu,u(this,Xu,"f")??u(this,Qu,"m",Ph).call(this),"f")}};to=new WeakMap,Hu=new WeakMap,ro=new WeakMap,Ju=new WeakMap,ra=new WeakMap,Xu=new WeakMap,Vu=new WeakMap,na=new WeakMap,Gu=new WeakMap,Qu=new WeakSet,Oh=async function*(){let e=u(this,Vu,"f").call(this),t=!1;try{for(;;){let r=await e.next();if(r.done){t=!0;return}u(this,ro,"f")?this.collector.accept(r.value):w(this,Ju,!0,"f"),yield r.value}}catch(r){throw u(this,ro,"f")&&w(this,ra,r,"f"),r}finally{w(this,Hu,!0,"f"),t||await e.return?.()}},Ph=async function(){this.enable();try{let e=u(this,to,"f")??this.iterate();for(;!u(this,Hu,"f")&&!this.collector.ready&&(this.collector.checkAction(u(this,Gu,"f")),!(await e.next()).done););if(u(this,ra,"f")!==void 0&&!this.collector.ready)throw u(this,ra,"f");if(!this.collector.ready&&u(this,na,"f")?.aborted)throw this.collector.error("observation",u(this,na,"f").reason);return this.collector.finish()}catch(e){throw e instanceof Js?e:this.collector.error("observation",e)}finally{try{await u(this,to,"f")?.return()}finally{this.collector.release()}}};var Ot,Yu,sa,Zu,so,io,ec,tc,ao,_r,rc,oa,uo,oo,vh,mn,xh;async function Vw(n){try{await n?.body?.cancel()}catch{}}var nc=class{constructor(e,t,r,o){Ot.add(this),this.controller=new AbortController,Yu.set(this,!1),sa.set(this,void 0),Zu.set(this,void 0),so.set(this,void 0),io.set(this,void 0),ec.set(this,void 0),tc.set(this,!1),ao.set(this,void 0),_r.set(this,void 0),rc.set(this,void 0),oa.set(this,void 0),uo.set(this,void 0),oo.set(this,void 0);let i=typeof r.input=="string"?[{role:"user",content:[{type:"input_text",text:r.input}]}]:r.input;if(r.input.length===0)throw new f("input must not be empty");if(w(this,sa,Zl(r.outputFormat),"f"),r.outputFormat&&!u(this,sa,"f"))throw new f("outputFormat must have its own parser function");w(this,ao,e,"f"),w(this,_r,t,"f"),w(this,rc,{type:"agent.session.input.message",input:i},"f");let s=g([o?.headers]);w(this,uo,s.nulls.has("idempotency-key")?void 0:s.values.get("idempotency-key")??r.idempotencyKey??o?.idempotencyKey??Me(),"f"),s.values.delete("idempotency-key"),s.nulls.delete("idempotency-key");let{idempotencyKey:a,...c}=o??{};w(this,oo,{...c,headers:s},"f"),w(this,oa,new Qs(e,r.toolHandlers??{},this.controller,u(this,oo,"f"),r.onToolError),"f"),w(this,so,new no(()=>u(this,Ot,"m",vh).call(this),d=>u(this,oa,"f").canHandle(d),t),"f")}abort(e){this.controller.abort(e),u(this,io,"f")?.controller.abort(this.controller.signal.reason),u(this,tc,"f")||Vw(u(this,ec,"f"))}[(Yu=new WeakMap,sa=new WeakMap,Zu=new WeakMap,so=new WeakMap,io=new WeakMap,ec=new WeakMap,tc=new WeakMap,ao=new WeakMap,_r=new WeakMap,rc=new WeakMap,oa=new WeakMap,uo=new WeakMap,oo=new WeakMap,Ot=new WeakSet,Symbol.asyncIterator)](){if(u(this,Yu,"f"))throw new f("An AgentSessionStream can only be consumed once");return w(this,Yu,!0,"f"),u(this,so,"f").iterate()}withResultCollection(){return u(this,so,"f").enable(),this}finalResult(){return w(this,Zu,u(this,Zu,"f")??Wu(u(this,so,"f").finalResult(),u(this,sa,"f")),"f")}};vh=async function*(){let e=u(this,oo,"f").signal,t=()=>this.abort(e?.aborted?e.reason:this.controller.signal.reason);e?.addEventListener("abort",t,{once:!0}),this.controller.signal.addEventListener("abort",t,{once:!0});let r={...u(this,oo,"f"),signal:this.controller.signal},o=new Ws;try{if(e?.aborted&&this.abort(e.reason),u(this,Ot,"m",mn).call(this),(await u(this,ao,"f").retrieve(u(this,_r,"f"),r)).status!=="idle")throw new f("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let s=await u(this,ao,"f").events.stream(u(this,_r,"f"),{},r).withResponse();w(this,io,s.data,"f"),w(this,ec,s.response,"f"),u(this,Ot,"m",mn).call(this),await u(this,ao,"f").events.create(u(this,_r,"f"),{events:[u(this,rc,"f")],...u(this,uo,"f")===void 0?{}:{"Idempotency-Key":u(this,uo,"f")}},{...r,headers:g([r.headers,{"Idempotency-Key":u(this,uo,"f")??null}])}),u(this,Ot,"m",mn).call(this),w(this,tc,!0,"f");for await(let a of u(this,io,"f")){if(u(this,Ot,"m",mn).call(this),!o.accept(a))continue;let c=o.terminal(a,u(this,_r,"f")),d=u(this,oa,"f").prepare(o.call(a),u(this,_r,"f"));if(c&&u(this,io,"f").controller.abort(),yield a,c)return;u(this,Ot,"m",mn).call(this),await d?.()}throw u(this,Ot,"m",mn).call(this),new f("Session event stream ended before the turn reached idle or failed")}finally{e?.removeEventListener("abort",t),this.controller.signal.removeEventListener("abort",t),this.abort()}},mn=function(){if(this.controller.signal.aborted)throw u(this,Ot,"m",xh).call(this)},xh=function(){let e=new V;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e};async function*Gw(n,e,t){let r=new Ws,o;for await(let i of{[Symbol.asyncIterator]:n}){i.type==="agent.session.created"&&(o??(o=i.session.id));let s=r.accept(i)?e.prepare(r.call(i),o):void 0;if(yield i,t.aborted)return;try{await s?.()}catch(a){if(t.aborted&&a instanceof V)return;throw a}}}function Ih(n,e,t){let r;n.__betaTransformIterator(s=>{let{path:a,method:c,stream:d,...h}=t?.options??{},_=t&&new Qs(t.sessions,t.handlers,n.controller,h);return r=new no(_?()=>Gw(s,_,n.controller.signal):s,_?m=>_.canHandle(m):void 0,void 0,n.controller.signal),()=>r.iterate()});let o,i=Object.assign(n,{finalResult:()=>o??(o=Wu(r.finalResult(),e)),withResultCollection:()=>(r.enable(),i)});return i}function Sh(n,e){let t=Object.getOwnPropertyDescriptor(n,"toolHandlers");if(!t)return{body:n,options:e};let r=n.toolHandlers;if(r===void 0&&"value"in t)return{body:n,options:e};let o=Object.getOwnPropertyDescriptors(n);delete o.toolHandlers;let i={...e};if("toJSON"in n||i.body!==void 0)throw new f("Creation tool handlers cannot customize request body serialization");if(r===void 0)return{body:Object.create(Object.getPrototypeOf(n),o),options:i};let{stream:s}=n;if(s!==!0)throw new f("toolHandlers requires stream: true");return i.headers=g([i.headers]),o.stream={value:s,enumerable:!0,configurable:!0,writable:!0},{body:Object.create(Object.getPrototypeOf(n),o),options:i,handlers:r&&Object.fromEntries(Object.entries(r))}}function ia(n,e){return Promise.resolve(n).then(e)}function Yw(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Eh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Zw(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Eh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Eh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var st=class extends p{constructor(){super(...arguments),this.subagents=new hr(this._client),this.artifacts=new Fs(this._client),this.items=new Ms(this._client),this.events=new zs(this._client),this.traces=new Ls(this._client),this.turns=new cn(this._client)}create(e,t){let r=Sh(e,t),o=wh(r.body,r.options);return((s,a)=>this._client.post("/agents/sessions",ia(a,c=>Yw({body:s,...c,headers:g([{"OpenAI-Beta":"agents=v1"},c?.headers]),stream:s.stream??!1,__streamMode:"events",__security:{bearerAuth:!0}},{streamFromBody:!0}))))(o.body,o.options)._thenUnwrap((s,{options:a})=>a.stream?Ih(s,o.format,r.handlers?{sessions:this,handlers:r.handlers,options:o.options}:void 0):s)}retrieve(e,t){return this._client.get(l`/agents/sessions/${e}`,ia(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},r){return this._client.post(l`/agents/sessions/${e}`,ia(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=Zw(e,["after","agent_id","limit","metadata","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/agents/sessions",x,ia(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/sessions/${e}`,ia(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}stream(e,t,r){return new nc(this,e,t,r)}};st.Subagents=hr;st.Artifacts=Fs;st.Items=Ms;st.Events=zs;st.Traces=Ls;st.Turns=cn;function aa(n,e){return Promise.resolve(n).then(e)}var Ch=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function tA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Ch.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Ch.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var co=class extends p{create(e,t,r){return this._client.post(l`/vaults/${e}/credentials`,aa(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,r){let{vault_id:o}=t;return this._client.get(l`/vaults/${o}/credentials/${e}`,aa(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){let{vault_id:o,...i}=t;return this._client.post(l`/vaults/${o}/credentials/${e}`,aa(r,s=>({body:i,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=tA(t,["after","limit","metadata","order","status"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/vaults/${e}/credentials`,x,aa(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,r){let{vault_id:o}=t;return this._client.delete(l`/vaults/${o}/credentials/${e}`,aa(r,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function ua(n,e){return Promise.resolve(n).then(e)}var Th=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function nA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Th.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Th.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var _n=class extends p{constructor(){super(...arguments),this.credentials=new co(this._client)}create(e={},t){return this._client.post("/vaults",ua(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/vaults/${e}`,ua(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/vaults/${e}`,ua(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=nA(e,["after","limit","metadata","order","status"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/vaults",x,ua(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/vaults/${e}`,ua(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}};_n.Credentials=co;function ca(n,e){return Promise.resolve(n).then(e)}var kh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function oA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>kh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!kh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Pt=class extends p{constructor(){super(...arguments),this.automations=new on(this._client),this.environments=new pr(this._client),this.vaults=new _n(this._client),this.sessions=new st(this._client)}create(e,t){return this._client.post("/agents",ca(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/${e}`,ca(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},r){return this._client.post(l`/agents/${e}`,ca(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=oA(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/agents",x,ca(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/${e}`,ca(t,r=>({...r,headers:g([{"OpenAI-Beta":"agents=v1"},r?.headers]),__security:{bearerAuth:!0}})))}};Pt.Automations=on;Pt.Environments=pr;Pt.Vaults=_n;Pt.Sessions=st;function jh(n,e){return Promise.resolve(n).then(e)}var lo=class extends p{create(e,t){return this._client.post("/chatkit/sessions",jh(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,jh(t,r=>({...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})))}};function sc(n,e){return Promise.resolve(n).then(e)}var qh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function $h(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>qh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!qh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var fo=class extends p{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,sc(t,r=>({...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=$h(e,["after","before","limit","order","user"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/chatkit/threads",N,sc(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,sc(t,r=>({...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})))}listItems(e,t={},r){let o=$h(t,["after","before","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/chatkit/threads/${e}/items`,N,sc(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};var yr=class extends p{constructor(){super(...arguments),this.sessions=new lo(this._client),this.threads=new fo(this._client)}};yr.Sessions=lo;yr.Threads=fo;function lA(n,e){return Promise.resolve(n).then(e)}var Dh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function dA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Dh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Dh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var po=class extends p{list(e,t={},r){let o=dA(t,["after","betas","include","limit","order"],r);o!==void 0&&(r=o,t={}),t=t;let{betas:i,...s}=t??{};return this._client.getAPIList(l`/responses/${e}/input_items?beta=true`,x,lA(r,a=>({query:s,...a,headers:g([{...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},a?.headers]),__security:{bearerAuth:!0}})))}};function pA(n,e){return Promise.resolve(n).then(e)}var ho=class extends p{count(e={},t){let{betas:r,...o}=e??{};return this._client.post("/responses/input_tokens?beta=true",pA(t,i=>({body:o,...i,headers:g([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}};function la(n,e){return Promise.resolve(n).then(e)}function mA(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Fh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function _A(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Fh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Fh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var gr=class extends p{constructor(){super(...arguments),this.inputItems=new po(this._client),this.inputTokens=new ho(this._client)}create(e,t){let{betas:r,...o}=e;return this._client.post("/responses?beta=true",la(t,i=>mA({body:o,...i,headers:g([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},i?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}retrieve(e,t={},r){let o=_A(t,["betas","include","include_obfuscation","starting_after","stream"],r);o!==void 0&&(r=o,t={}),t=t;let{betas:i,...s}=t??{};return this._client.get(l`/responses/${e}?beta=true`,la(r,a=>({query:s,...a,headers:g([{...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},a?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})))}delete(e,t={},r){let{betas:o}=t??{};return this._client.delete(l`/responses/${e}?beta=true`,la(r,i=>({...i,headers:g([{Accept:"*/*",...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t={},r){let{betas:o}=t??{};return this._client.post(l`/responses/${e}/cancel?beta=true`,la(r,i=>({...i,headers:g([{...o?.toString()!=null?{"openai-beta":o?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}compact(e,t){let{betas:r,...o}=e;return this._client.post("/responses/compact?beta=true",la(t,i=>({body:o,...i,headers:g([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}};gr.InputItems=po;gr.InputTokens=ho;function da(n,e){return Promise.resolve(n).then(e)}var zh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function gA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>zh.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!zh.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var mo=class extends p{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,da(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,r){let{thread_id:o}=t;return this._client.get(l`/threads/${o}/messages/${e}`,da(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){let{thread_id:o,...i}=t;return this._client.post(l`/threads/${o}/messages/${e}`,da(r,s=>({body:i,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=gA(t,["after","before","limit","order","run_id"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/threads/${e}/messages`,x,da(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,r){let{thread_id:o}=t;return this._client.delete(l`/threads/${o}/messages/${e}`,da(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}};function Mh(n,e){return Promise.resolve(n).then(e)}var _o=class extends p{retrieve(e,t,r){let{thread_id:o,run_id:i,...s}=t;return this._client.get(l`/threads/${o}/runs/${i}/steps/${e}`,Mh(r,a=>({query:s,...a,headers:g([{"OpenAI-Beta":"assistants=v2"},a?.headers]),__security:{bearerAuth:!0}})))}list(e,t,r){let{thread_id:o,...i}=t;return this._client.getAPIList(l`/threads/${o}/runs/${e}/steps`,x,Mh(r,s=>({query:i,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}};function AA(n,e){return new Promise((t,r)=>{let o,i,s=!1,a=h=>{try{e.removeEventListener("abort",h)}catch{}},c=()=>{if(o!==void 0&&(clearTimeout(o),o=void 0),i){let h=i;i=void 0,a(h)}},d=()=>{if(!s){s=!0,c();try{let h=new V;Object.defineProperty(h,"cause",{value:e.reason,writable:!0,configurable:!0}),r(h)}catch(h){r(h)}}};if(e.aborted){d();return}o=setTimeout(()=>{s||(s=!0,c(),t())},n),i=d;try{e.addEventListener("abort",d,{once:!0}),s?a(d):e.aborted&&d()}catch(h){s?a(d):(s=!0,c(),r(h))}})}async function fa(n,e,t,r){let o=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:s}=await n(o).withResponse(),{status:a}=i;if(e.includes(a)){let c=5e3,d=r?.pollIntervalMs;if(d||d===0)c=d;else{let _=s.headers.get("openai-poll-after-ms");if(_){let m=Number.parseInt(_);Number.isNaN(m)||(c=m)}}let h=r&&Object.prototype.propertyIsEnumerable.call(r,"signal")?r.signal:void 0;await(h?AA(c,h):Bn(c))}else if(t.includes(a))return i}}function Lh(n,e,t,r){return fa(o=>n.retrieve(e,t,{...r,headers:{...r?.headers,...o}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],r)}var oc=n=>{if(typeof globalThis.Buffer<"u"){let e=globalThis.Buffer.from(n,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof atob<"u"){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}throw new f("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Bh=n=>{if(typeof Buffer<"u"){let e=Buffer.from(n,"base64");if(e.length%Float32Array.BYTES_PER_ELEMENT!==0)throw new RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(n),t=e.length,r=new Uint8Array(t);for(let o=0;o<t;o++)r[o]=e.charCodeAt(o);return Array.from(new Float32Array(r.buffer))}};var Ee=n=>{try{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()||void 0}catch{return}};var Nh=1024,RA=65536;function OA(n){switch(n){case"value":case"arguments":case"input":case"text":case"content":case"annotations":case"metadata":case"name":case"role":case"status":case"tool_calls":case"step_details":return n;default:return"unknown"}}var pa=new WeakMap,br=new WeakSet;function Wh(n){return{arrays:new Map,cacheArrays:n,records:new WeakMap}}function Uh(n){for(let[e,t]of n.arrays)t.cacheable&&!br.has(e)?pa.set(e,{length:t.length,ownEntryCount:t.ownEntryCount}):pa.delete(e)}function Kh(n){return typeof n=="string"||typeof n=="number"}function Qh(n,e){return e.every(Kh)&&n.every(Kh)}function PA(n){let e=0;for(let t of Object.keys(n)){let r=Number(t);Number.isSafeInteger(r)&&r>=0&&r<n.length&&String(r)===t&&(e+=1)}return e}function xA(n,e,t){return e?t?.length===n.length?t.ownEntryCount:PA(n):0}function vA(n,e,t){let{index:r}=n;if(e==="array"&&r==null)throw new Error("Expected array delta entry to have an `index` property");if(e==="array"&&typeof r!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(r)||r<0||r>=t+Nh||r>=RA){let o=typeof r=="number"?r:"unknown";throw new f(`Assistant stream delta contains an invalid ${e} index: ${o}`)}return r}function Hh(n,e,t,r,o){let i=r.arrays.get(n);if(!i){let s=r.cacheArrays&&!br.has(n),a=s?pa.get(n):void 0;i={baselineLength:n.length,cacheable:s,enforceSparseHoleBudget:s,entries:new Map,length:n.length,ownEntryCount:xA(n,s,a)},r.arrays.set(n,i)}for(let s of e){if(!U(s))throw new Error("Expected array delta entry to be an object but got an invalid value");let a=vA(s,t,i.baselineLength),c;i.entries.has(a)?c=i.entries.get(a):k(n,a)?(c=n[a],c==null&&i.entries.set(a,s)):(i.entries.set(a,s),i.ownEntryCount+=1);let d=Math.max(i.length,a+1);if(i.enforceSparseHoleBudget&&d-i.ownEntryCount>Nh)throw new f(`Assistant stream delta contains an invalid ${t} index: ${a}`);U(c)&&o(c,s,r),i.length=d}}function ic(n,e,t){let r=t.records.get(n);for(let[o,i]of Object.entries(e)){if(o==="index"||o==="type")continue;let s;if(r?.has(o)?s=r.get(o):k(n,o)&&(s=n[o]),s==null){r||(r=new Map,t.records.set(n,r)),r.set(o,i);continue}U(s)&&U(i)?ic(s,i,t):Array.isArray(s)&&Array.isArray(i)&&!Qh(s,i)&&Hh(s,i,"array",t,ic)}}function ac(n){return(U(n)||Array.isArray(n))&&br.has(n)}function lt(n){if(!(!U(n)&&!Array.isArray(n)||br.has(n))){br.add(n),Array.isArray(n)&&pa.delete(n);for(let e of Reflect.ownKeys(n)){let t=Object.getOwnPropertyDescriptor(n,e);t&&"value"in t&&lt(t.value)}}}function rd(n,e,t){br.has(n)&&lt(t),Object.defineProperty(n,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}function IA(n){let{index:e}=n;if(e==null)throw new Error("Expected array delta entry to have an `index` property");if(typeof e!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return e}function SA(n,e,t){if(Qh(n,e)){n.push(...e),pa.delete(n);return}for(let r of e){if(!U(r))throw new Error("Expected array delta entry to be an object but got an invalid value");let o=IA(r);if(k(n,o)){let i=n[o];i==null?(br.has(n)&&lt(r),n[o]=r):n[o]=t(i,r)}else rd(n,o,r)}}function td(n,e){let t=br.has(n);for(let[r,o]of Object.entries(e)){if(r==="__proto__"||r==="constructor"||r==="prototype")throw new f(`Assistant stream delta contains an unsafe property: ${r}`);if(!k(n,r)){t&&lt(o),n[r]=o;continue}let i=n[r];if(i==null){t&&lt(o),n[r]=o;continue}if(r==="index"||r==="type"){n[r]=o;continue}if(typeof i=="string"&&typeof o=="string")i+=o;else if(typeof i=="number"&&typeof o=="number")i+=o;else if(U(i)&&U(o))i=td(i,o);else if(Array.isArray(i)&&Array.isArray(o)){SA(i,o,td);continue}else throw new TypeError(`Unhandled record type: ${OA(r)}`);n[r]=i}return n}function ha(n){if(!(!U(n)&&!Array.isArray(n)))for(let[e,t]of Object.entries(n)){if(e==="__proto__"||e==="constructor"||e==="prototype")throw new f(`Assistant stream delta contains an unsafe property: ${e}`);ha(t)}}function uc(n,e,t=!1){ha(e);let r=n,o=e,i=Wh(t&&!ac(n));return ic(r,o,i),td(r,o),Uh(i),n}function Xh(n,e,t,r=!0){ha(e);let o=Wh(r&&!ac(n));return Hh(n,e,t,o,ic),()=>Uh(o)}var L,Ce,wr,ot,bo,go,Oe,Mt,gn,Ar,Lt,yn,Fe,_a,ya,Rr,ga,ba,Jh,yo,Vh,ma,Gh,Yh,le,Zh,em,tm,rm,nm;function EA(n){let e=Object.getOwnPropertyDescriptor(n,"event"),t=Object.getOwnPropertyDescriptor(n,"data"),r=Reflect.get(n,"event",n),o=Reflect.get(n,"data",n),i=o;if(r==="thread.message.created"||r==="thread.message.in_progress"||r==="thread.message.delta"||r==="thread.message.completed"||r==="thread.message.incomplete"||r==="thread.run.step.created"||r==="thread.run.step.in_progress"||r==="thread.run.step.delta"||r==="thread.run.step.completed"||r==="thread.run.step.failed"||r==="thread.run.step.cancelled"||r==="thread.run.step.expired"){let c=Object.getOwnPropertyDescriptor(o,"id");if(c&&"value"in c&&o.id!==c.value){let d=c.value;i=new Proxy(o,{get(h,_){return _==="id"?d:Reflect.get(h,_,h)}})}}let s=Object.freeze({event:r,data:i}),a=e!==void 0&&"value"in e&&e.value===r&&t!==void 0&&"value"in t&&t.value===o&&i===o;return{event:s,exposedEvent:a?n:{event:r,data:i}}}var Or=class n extends ir{constructor(){super(...arguments),L.add(this),Ce.set(this,Object.create(null)),wr.set(this,new Map),ot.set(this,void 0),bo.set(this,Object.create(null)),go.set(this,new Map),Oe.set(this,void 0),Mt.set(this,void 0),gn.set(this,void 0),Ar.set(this,void 0),Lt.set(this,void 0),yn.set(this,void 0),Fe.set(this,void 0),_a.set(this,void 0),ya.set(this,void 0),Rr.set(this,void 0)}[(Ce=new WeakMap,wr=new WeakMap,ot=new WeakMap,bo=new WeakMap,go=new WeakMap,Oe=new WeakMap,Mt=new WeakMap,gn=new WeakMap,Ar=new WeakMap,Lt=new WeakMap,yn=new WeakMap,Fe=new WeakMap,_a=new WeakMap,ya=new WeakMap,Rr=new WeakMap,L=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=r=>e(structuredClone(r));return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}static fromReadableStream(e){let t=new n;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=$e.fromReadableStream(e,this.controller);for await(let o of r)u(this,L,"m",ga).call(this,o);if(r.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,L,"m",ba).call(this))}toReadableStream(){return new $e(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,o){let i=new n;return i._run(()=>i._runToolAssistantStream(e,t,r,{...o,__metadata:{...o?.__metadata,helperMethod:"stream"}})),i}async _createToolAssistantStream(e,t,r,o){this._listenForAbort(o?.signal);let i={...r,stream:!0},s=await e.submitToolOutputs(t,i,{...o,signal:this.controller.signal});this._connected();for await(let a of s)u(this,L,"m",ga).call(this,a);if(s.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,L,"m",ba).call(this))}static createThreadAssistantStream(e,t,r){let o=new n;return o._run(()=>o._threadAssistantStream(e,t,{...r,__metadata:{...r?.__metadata,helperMethod:"stream"}})),o}static createAssistantStream(e,t,r,o){let i=new n;return i._run(()=>i._runAssistantStream(e,t,r,{...o,__metadata:{...o?.__metadata,helperMethod:"stream"}})),i}currentEvent(){return lt(u(this,_a,"f")),u(this,_a,"f")}currentRun(){return lt(u(this,ya,"f")),u(this,ya,"f")}currentMessageSnapshot(){return lt(u(this,Oe,"f")),u(this,Oe,"f")}currentRunStepSnapshot(){return lt(u(this,Rr,"f")),u(this,Rr,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,Ce,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,bo,"f"))}async finalRun(){if(await this.done(),!u(this,gn,"f"))throw new Error("Final run was not received.");return u(this,gn,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let s of i)u(this,L,"m",ga).call(this,s);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,L,"m",ba).call(this))}async _createAssistantStream(e,t,r,o){this._listenForAbort(o?.signal);let i={...r,stream:!0},s=await e.create(t,i,{...o,signal:this.controller.signal});this._connected();for await(let a of s)u(this,L,"m",ga).call(this,a);if(s.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,L,"m",ba).call(this))}static accumulateDelta(e,t){return uc(e,t)}_addRun(e){return u(this,L,"m",le).call(this,"run",e),e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,o){return await this._createAssistantStream(t,e,r,o)}async _runToolAssistantStream(e,t,r,o){return await this._createToolAssistantStream(t,e,r,o)}};ga=function(e){if(this.ended)return;let{event:t,exposedEvent:r}=EA(e),o,i,s,a;switch(t.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{o=u(this,L,"m",Vh).call(this,t),i=t.data;break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{s=u(this,L,"m",Jh).call(this,t),a=t.data;break}}switch(w(this,_a,r,"f"),u(this,L,"m",Zh).call(this,r),o!==void 0&&i!==void 0&&u(this,L,"m",ma).call(this,i,o),s!==void 0&&a!==void 0&&u(this,L,"m",yo).call(this,a,s),s===void 0&&u(this,ot,"f")!==void 0&&u(this,Rr,"f")&&u(this,L,"m",yo).call(this,u(this,Rr,"f"),u(this,ot,"f")),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":{u(this,L,"m",nm).call(this,t);break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(s===void 0)throw new f("Received assistant run-step event without a canonical run-step ID");let c=u(this,Ce,"f")[s];c&&u(this,L,"m",yo).call(this,c,s),u(this,L,"m",Yh).call(this,t,s),u(this,L,"m",yo).call(this,t.data,s);let d=u(this,Ce,"f")[s];d&&u(this,L,"m",yo).call(this,d,s);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{if(o!==void 0&&u(this,Oe,"f")&&u(this,L,"m",ma).call(this,u(this,Oe,"f"),o),u(this,L,"m",Gh).call(this,t),o!==void 0){u(this,L,"m",ma).call(this,t.data,o);let c=u(this,bo,"f")[o];c&&u(this,L,"m",ma).call(this,c,o)}break}case"error":throw new H(void 0,t.data,void 0,void 0);default:}},ba=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");if(!u(this,gn,"f"))throw new Error("Final run has not been received");return u(this,gn,"f")},Jh=function(e){let t=Object.getOwnPropertyDescriptor(e.data,"id"),r=t&&"value"in t?t.value:void 0;if(typeof r!="string"||r.length===0)throw new f("Received assistant run-step event with an invalid run-step ID");if(e.event==="thread.run.step.delta"){let o=e.data.delta;if(o&&k(o,"id"))throw new f("Run-step deltas must not contain an id field")}if(e.event==="thread.run.step.created"){if(u(this,ot,"f")!==void 0)throw new f(`Received run-step creation for "${r}" before the active run step "${u(this,ot,"f")}" reached a terminal state`);if(k(u(this,Ce,"f"),r)||u(this,wr,"f").has(r))throw new f(`Received run-step creation for run step "${r}", which has already been created`);return w(this,ot,r,"f"),u(this,wr,"f").set(r,r),r}if(u(this,ot,"f")!==void 0){if(r!==u(this,ot,"f"))throw new f(`Received ${e.event} for run step "${r}", which does not match the active run step "${u(this,ot,"f")}"`);return r}if(e.event==="thread.run.step.delta")throw k(u(this,Ce,"f"),r)?new f(`Received run-step delta for "${r}" with no active run step`):new f("Received a RunStepDelta before creation of a snapshot");if(k(u(this,Ce,"f"),r)||u(this,wr,"f").has(r))throw new f(`Received run-step event for run step "${r}", which has already been created`);return u(this,wr,"f").set(r,r),e.event==="thread.run.step.in_progress"&&w(this,ot,r,"f"),r},yo=function(e,t){let r=Object.getOwnPropertyDescriptor(e,"id"),o=r&&"value"in r?r.value:void 0;if(typeof o!="string"||o.length===0)throw new f("Received assistant run-step event with an invalid run-step ID");let i=u(this,wr,"f").get(o);if(i!==void 0&&i!==t)throw new f(`Received run-step creation for run step "${o}", which has already been created`);u(this,wr,"f").set(o,t)},Vh=function(e){let t=Object.getOwnPropertyDescriptor(e.data,"id"),r=t&&"value"in t?t.value:void 0;if(typeof r!="string"||r.length===0)throw new f("Received assistant message event with an invalid message ID");if(e.event==="thread.message.created"){if(u(this,Oe,"f"))throw new f(`Received message creation for "${r}" before the active message "${u(this,Mt,"f")}" reached a terminal state`);if(k(u(this,bo,"f"),r)||u(this,go,"f").has(r))throw new f(`Received message creation for message "${r}", which has already been created`);return w(this,Mt,r,"f"),u(this,go,"f").set(r,r),r}if(!u(this,Oe,"f"))throw e.event==="thread.message.delta"?new f("Received a delta with no existing snapshot (there should be one from message creation)"):new f("Received thread message event with no existing snapshot");if(r!==u(this,Mt,"f"))throw new f(`Received ${e.event} for message "${r}", which does not match the active message "${u(this,Mt,"f")}"`);return r},ma=function(e,t){let r=Object.getOwnPropertyDescriptor(e,"id"),o=r&&"value"in r?r.value:void 0;if(typeof o!="string"||o.length===0)throw new f("Received assistant message event with an invalid message ID");let i=u(this,go,"f").get(o);if(i!==void 0&&i!==t)throw new f(`Received message creation for message "${o}", which has already been created`);u(this,go,"f").set(o,t)},Gh=function(e){let[t,r]=u(this,L,"m",tm).call(this,e,u(this,Oe,"f"));if(w(this,Oe,t,"f"),!u(this,Mt,"f"))throw new f("Received thread message event with no active message ID");u(this,bo,"f")[u(this,Mt,"f")]=t;for(let o of r){let i=t.content[o.index];i?.type==="text"&&u(this,L,"m",le).call(this,"textCreated",i.text)}switch(e.event){case"thread.message.created":{w(this,Ar,void 0,"f"),w(this,Lt,void 0,"f"),u(this,L,"m",le).call(this,"messageCreated",e.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(u(this,L,"m",le).call(this,"messageDelta",e.data.delta,t),e.data.delta.content)for(let o of e.data.delta.content){if(o.type==="text"&&o.text){let i=o.text,s=t.content[o.index];if(s&&s.type==="text")u(this,L,"m",le).call(this,"textDelta",i,s.text);else throw new Error("The snapshot associated with this text delta is not text or missing")}if(o.index!==u(this,Ar,"f")){if(u(this,Lt,"f"))switch(u(this,Lt,"f").type){case"text":{u(this,L,"m",le).call(this,"textDone",u(this,Lt,"f").text,u(this,Oe,"f"));break}case"image_file":{u(this,L,"m",le).call(this,"imageFileDone",u(this,Lt,"f").image_file,u(this,Oe,"f"));break}}w(this,Ar,o.index,"f")}w(this,Lt,t.content[o.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(u(this,Ar,"f")!==void 0){let o=e.data.content[u(this,Ar,"f")];if(o)switch(o.type){case"image_file":{u(this,L,"m",le).call(this,"imageFileDone",o.image_file,u(this,Oe,"f"));break}case"text":{u(this,L,"m",le).call(this,"textDone",o.text,u(this,Oe,"f"));break}}}u(this,Oe,"f")&&u(this,L,"m",le).call(this,"messageDone",e.data),w(this,Ar,void 0,"f"),w(this,Lt,void 0,"f"),w(this,Oe,void 0,"f"),w(this,Mt,void 0,"f")}}},Yh=function(e,t){let r=u(this,L,"m",em).call(this,e,t);switch(w(this,Rr,r,"f"),e.event){case"thread.run.step.created":{w(this,yn,void 0,"f"),w(this,Fe,void 0,"f"),u(this,L,"m",le).call(this,"runStepCreated",e.data);break}case"thread.run.step.delta":{let o=e.data.delta;if(o.step_details&&o.step_details.type==="tool_calls"&&o.step_details.tool_calls&&r.step_details.type==="tool_calls")for(let i of o.step_details.tool_calls)i.index===u(this,yn,"f")?u(this,L,"m",le).call(this,"toolCallDelta",i,r.step_details.tool_calls[i.index]):(u(this,Fe,"f")&&u(this,L,"m",le).call(this,"toolCallDone",u(this,Fe,"f")),w(this,yn,i.index,"f"),w(this,Fe,r.step_details.tool_calls[i.index],"f"),u(this,Fe,"f")&&u(this,L,"m",le).call(this,"toolCallCreated",u(this,Fe,"f")));u(this,L,"m",le).call(this,"runStepDelta",e.data.delta,r);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{w(this,Rr,void 0,"f"),w(this,ot,void 0,"f"),e.data.step_details.type==="tool_calls"&&u(this,Fe,"f")&&u(this,L,"m",le).call(this,"toolCallDone",u(this,Fe,"f")),u(this,L,"m",le).call(this,"runStepDone",e.data,r),w(this,yn,void 0,"f"),w(this,Fe,void 0,"f");break}case"thread.run.step.in_progress":break}},le=function(e,...t){if(this._hasListeners(e))for(let r of t)lt(r);this._emit(e,...t)},Zh=function(e){u(this,L,"m",le).call(this,"event",e)},em=function(e,t){switch(e.event){case"thread.run.step.created":return u(this,Ce,"f")[t]=e.data,e.data;case"thread.run.step.delta":{let r=u(this,Ce,"f")[t];if(!r)throw new Error("Received a RunStepDelta before creation of a snapshot");let o=e.data.delta;if(o){if(k(o,"id"))throw new f("Run-step deltas must not contain an id field");let i=uc(r,o,!0);u(this,Ce,"f")[t]=i}return u(this,Ce,"f")[t]}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":{u(this,Ce,"f")[t]=e.data;break}}if(u(this,Ce,"f")[t])return u(this,Ce,"f")[t];throw new Error("No snapshot available")},tm=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":{if(!t)throw new Error("Received a delta with no existing snapshot (there should be one from message creation)");let o=e.data;if(o.delta.content){ha(o.delta);let i=!ac(t),s=Xh(t.content,o.delta.content,"content",i);for(let a of o.delta.content)if(k(t.content,a.index)){let c=t.content[a.index];t.content[a.index]=u(this,L,"m",rm).call(this,a,c,i)}else rd(t.content,a.index,a),r.push(a);s()}return[t,r]}case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":{if(t)return[e.event==="thread.message.in_progress"?t:e.data,r];throw new Error("Received thread message event with no existing snapshot")}}throw new Error("Tried to accumulate a non-message event")},rm=function(e,t,r){return uc(t,e,r)},nm=function(e){switch(w(this,ya,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":{w(this,gn,e.data,"f"),u(this,Fe,"f")&&u(this,L,"m",le).call(this,"toolCallDone",u(this,Fe,"f")),w(this,yn,void 0,"f"),w(this,Fe,void 0,"f");break}case"thread.run.cancelling":break}};function wo(n,e){return Promise.resolve(n).then(e)}function sm(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var om=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function CA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>om.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!om.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var bn=class extends p{constructor(){super(...arguments),this.steps=new _o(this._client)}create(e,t,r){let{include:o,...i}=t;return this._client.post(l`/threads/${e}/runs`,wo(r,s=>sm({query:{include:o},body:i,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async createAndPoll(e,t,r){let o=await this.create(e,t,r);return await this.poll(o.id,{thread_id:e},r)}createAndStream(e,t,r){return Or.createAssistantStream(e,this._client.beta.threads.runs,t,r)}retrieve(e,t,r){let{thread_id:o}=t;return this._client.get(l`/threads/${o}/runs/${e}`,wo(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){let{thread_id:o,...i}=t;return this._client.post(l`/threads/${o}/runs/${e}`,wo(r,s=>({body:i,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=CA(t,["after","before","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/threads/${e}/runs`,x,wo(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t,r){let{thread_id:o}=t;return this._client.post(l`/threads/${o}/runs/${e}/cancel`,wo(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}async poll(e,t,r){return await Lh(this,e,t,r)}stream(e,t,r){return Or.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:o,...i}=t;return this._client.post(l`/threads/${o}/runs/${e}/submit_tool_outputs`,wo(r,s=>sm({body:i,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async submitToolOutputsAndPoll(e,t,r){let o=await this.submitToolOutputs(e,t,r);return await this.poll(o.id,t,r)}submitToolOutputsStream(e,t,r){return Or.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};bn.Steps=_o;function wa(n,e){return Promise.resolve(n).then(e)}function kA(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Pr=class extends p{constructor(){super(...arguments),this.runs=new bn(this._client),this.messages=new mo(this._client)}create(e={},t){return this._client.post("/threads",wa(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/threads/${e}`,wa(t,r=>({...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/threads/${e}`,wa(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/threads/${e}`,wa(t,r=>({...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}createAndRun(e,t){return this._client.post("/threads/runs",wa(t,r=>kA({body:e,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Or.createThreadAssistantStream(e,this._client.beta.threads,t)}};Pr.Runs=bn;Pr.Messages=mo;var Ao=class extends p{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Ro=class extends p{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var xr=class extends p{constructor(){super(...arguments),this.sessions=new Ao(this._client),this.transcriptionSessions=new Ro(this._client)}};xr.Sessions=Ao;xr.TranscriptionSessions=Ro;var Ke=class extends p{constructor(){super(...arguments),this.realtime=new xr(this._client),this.agents=new Pt(this._client),this.responses=new gr(this._client),this.chatkit=new yr(this._client),this.assistants=new ks(this._client),this.threads=new Pr(this._client)}};Ke.Realtime=xr;Ke.Agents=Pt;Ke.Responses=gr;Ke.ChatKit=yr;Ke.Assistants=ks;Ke.Threads=Pr;function FA(n,e){return Promise.resolve(n).then(e)}function zA(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var wn=class extends p{create(e,t){return this._client.post("/completions",FA(t,r=>zA({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}};function MA(n,e){return Promise.resolve(n).then(e)}var Oo=class extends p{retrieve(e,t,r){let{container_id:o}=t;return this._client.get(l`/containers/${o}/files/${e}/content`,MA(r,i=>({...i,headers:g([{Accept:"application/binary"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function cc(n,e){return Promise.resolve(n).then(e)}function BA(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var im=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function KA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>im.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!im.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var An=class extends p{constructor(){super(...arguments),this.content=new Oo(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,cc(r,o=>bt(BA({body:t,...o,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client)))}retrieve(e,t,r){let{container_id:o}=t;return this._client.get(l`/containers/${o}/files/${e}`,cc(r,i=>({...i,__security:{bearerAuth:!0}})))}list(e,t={},r){let o=KA(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/containers/${e}/files`,x,cc(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,r){let{container_id:o}=t;return this._client.delete(l`/containers/${o}/files/${e}`,cc(r,i=>({...i,headers:g([{Accept:"*/*"},i?.headers]),__security:{bearerAuth:!0}})))}};An.Content=Oo;function lc(n,e){return Promise.resolve(n).then(e)}var am=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function WA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>am.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!am.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var vr=class extends p{constructor(){super(...arguments),this.files=new An(this._client)}create(e,t){return this._client.post("/containers",lc(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/containers/${e}`,lc(t,r=>({...r,__security:{bearerAuth:!0}})))}list(e={},t){let r=WA(e,["after","limit","name","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/containers",x,lc(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/containers/${e}`,lc(t,r=>({...r,headers:g([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})))}};vr.Files=An;function UA(n,e){return Promise.resolve(n).then(e)}var Rn=class extends p{create(e,t){return this._client.post("/content_provenance_checks",UA(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}};function dc(n,e){return Promise.resolve(n).then(e)}var um=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function QA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>um.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!um.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Po=class extends p{create(e,t,r){let{include:o,...i}=t;return this._client.post(l`/conversations/${e}/items`,dc(r,s=>({query:{include:o},body:i,...s,__security:{bearerAuth:!0}})))}retrieve(e,t,r){let{conversation_id:o,...i}=t;return this._client.get(l`/conversations/${o}/items/${e}`,dc(r,s=>({query:i,...s,__security:{bearerAuth:!0}})))}list(e,t={},r){let o=QA(t,["after","include","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/conversations/${e}/items`,N,dc(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,r){let{conversation_id:o}=t;return this._client.delete(l`/conversations/${o}/items/${e}`,dc(r,i=>({...i,__security:{bearerAuth:!0}})))}};function fc(n,e){return Promise.resolve(n).then(e)}var Ir=class extends p{constructor(){super(...arguments),this.items=new Po(this._client)}create(e={},t){return this._client.post("/conversations",fc(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/conversations/${e}`,fc(t,r=>({...r,__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/conversations/${e}`,fc(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/conversations/${e}`,fc(t,r=>({...r,__security:{bearerAuth:!0}})))}};Ir.Items=Po;function XA(n,e){return Promise.resolve(n).then(e)}var On=class extends p{create(e,t){return this._client.post("/decisions",XA(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}};function cm(n,e,t){let r=!!e.encoding_format,o=r?e.encoding_format:"base64";r&&ie(n).debug("embeddings/user defined encoding_format:",e.encoding_format);let s={body:{...e,encoding_format:o},...t,__security:{bearerAuth:!0}},a=n.post("/embeddings",s);return r?a:(ie(n).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(c=>{let d=c?.data;if(d!==void 0){if(!Array.isArray(d))throw new TypeError("Expected embeddings response data to be an array");let{length:h}=d;for(let _=0;_<h;_+=1)if(_ in d){let m=d[_],{embedding:b}=m;if(Array.isArray(b))continue;m.embedding=Bh(b)}}return c}))}var Pn=class extends p{create(e,t){return cm(this._client,e,t)}};function lm(n,e){return Promise.resolve(n).then(e)}var xo=class extends p{retrieve(e,t,r){let{eval_id:o,run_id:i}=t;return this._client.get(l`/evals/${o}/runs/${i}/output_items/${e}`,lm(r,s=>({...s,__security:{bearerAuth:!0}})))}list(e,t,r){let{eval_id:o,...i}=t;return this._client.getAPIList(l`/evals/${o}/runs/${e}/output_items`,x,lm(r,s=>({query:i,...s,__security:{bearerAuth:!0}})))}};function Aa(n,e){return Promise.resolve(n).then(e)}var dm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function VA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>dm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!dm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var xn=class extends p{constructor(){super(...arguments),this.outputItems=new xo(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,Aa(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}retrieve(e,t,r){let{eval_id:o}=t;return this._client.get(l`/evals/${o}/runs/${e}`,Aa(r,i=>({...i,__security:{bearerAuth:!0}})))}list(e,t={},r){let o=VA(t,["after","limit","order","status"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/evals/${e}/runs`,x,Aa(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,r){let{eval_id:o}=t;return this._client.delete(l`/evals/${o}/runs/${e}`,Aa(r,i=>({...i,__security:{bearerAuth:!0}})))}cancel(e,t,r){let{eval_id:o}=t;return this._client.post(l`/evals/${o}/runs/${e}/cancel`,Aa(r,i=>({...i,__security:{bearerAuth:!0}})))}};xn.OutputItems=xo;function Ra(n,e){return Promise.resolve(n).then(e)}var fm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function YA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>fm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!fm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Sr=class extends p{constructor(){super(...arguments),this.runs=new xn(this._client)}create(e,t){return this._client.post("/evals",Ra(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/evals/${e}`,Ra(t,r=>({...r,__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/evals/${e}`,Ra(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}list(e={},t){let r=YA(e,["after","limit","order","order_by"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/evals",x,Ra(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/evals/${e}`,Ra(t,r=>({...r,__security:{bearerAuth:!0}})))}};Sr.Runs=xn;async function pm(n,e,t,r){let o=new Set(["processed","error","deleted"]),i=performance.now(),s=await n.retrieve(e);for(;!s.status||!o.has(s.status);)if(await Bn(t),s=await n.retrieve(e),performance.now()-i>r)throw new re({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return s}function Oa(n,e){return Promise.resolve(n).then(e)}var hm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function ZA(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>hm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!hm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var vn=class extends p{create(e,t){return this._client.post("/files",Oa(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(l`/files/${e}`,Oa(t,r=>({...r,__security:{bearerAuth:!0}})))}list(e={},t){let r=ZA(e,["after","limit","order","purpose"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/files",x,Oa(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/files/${e}`,Oa(t,r=>({...r,__security:{bearerAuth:!0}})))}content(e,t){return this._client.get(l`/files/${e}/content`,Oa(t,r=>({...r,headers:g([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){return await pm(this,e,t,r)}};var vo=class extends p{};function mm(n,e){return Promise.resolve(n).then(e)}var Io=class extends p{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",mm(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",mm(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}};var In=class extends p{constructor(){super(...arguments),this.graders=new Io(this._client)}};In.Graders=Io;function pc(n,e){return Promise.resolve(n).then(e)}var _m=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function ym(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>_m.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!_m.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var So=class extends p{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,_e,pc(r,o=>({body:t,method:"post",...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t={},r){let o=ym(t,["after","limit","order","project_id"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,pc(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},r){let o=ym(t,["after","limit","order","project_id"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,N,pc(r,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,r){let{fine_tuned_model_checkpoint:o}=t;return this._client.delete(l`/fine_tuning/checkpoints/${o}/permissions/${e}`,pc(r,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};var Sn=class extends p{constructor(){super(...arguments),this.permissions=new So(this._client)}};Sn.Permissions=So;function oR(n,e){return Promise.resolve(n).then(e)}var gm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function iR(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>gm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!gm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Eo=class extends p{list(e,t={},r){let o=iR(t,["after","limit"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,oR(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}};function En(n,e){return Promise.resolve(n).then(e)}var bm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function wm(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>bm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!bm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Cn=class extends p{constructor(){super(...arguments),this.checkpoints=new Eo(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",En(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,En(t,r=>({...r,__security:{bearerAuth:!0}})))}list(e={},t){let r=wm(e,["after","limit","metadata"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/fine_tuning/jobs",x,En(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,En(t,r=>({...r,__security:{bearerAuth:!0}})))}listEvents(e,t={},r){let o=wm(t,["after","limit"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,x,En(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,En(t,r=>({...r,__security:{bearerAuth:!0}})))}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,En(t,r=>({...r,__security:{bearerAuth:!0}})))}};Cn.Checkpoints=Eo;var dt=class extends p{constructor(){super(...arguments),this.methods=new vo(this._client),this.jobs=new Cn(this._client),this.checkpoints=new Sn(this._client),this.alpha=new In(this._client)}};dt.Methods=vo;dt.Jobs=Cn;dt.Checkpoints=Sn;dt.Alpha=In;var Co=class extends p{};var Er=class extends p{constructor(){super(...arguments),this.graderModels=new Co(this._client)}};Er.GraderModels=Co;function nd(n,e){return Promise.resolve(n).then(e)}function Am(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Tn=class extends p{createVariation(e,t){return this._client.post("/images/variations",nd(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}edit(e,t){return this._client.post("/images/edits",nd(t,r=>ee(Am((o=>{let i=(s,a)=>s===null||typeof s!="object"||Array.isArray(s)?s:Object.fromEntries(Object.entries(s).map(([c,d])=>{let h=a.filter(m=>m[0]===c);if(d===null&&h.some(m=>m.length===1))return[c,void 0];let _=h.filter(m=>m.length>1).map(m=>m.slice(1));return[c,_.length===0?d:i(d,_)]}));return{...o,body:i(o.body??{},[["safety_identifier"],["complexity"],["frame_count"],["frame_duration_ms"],["svg"],["svg","reasoning"]])}})({body:e,...r,stream:e.stream??!1,__metadata:{...r?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}}),{streamFromBody:!0}),this._client)))}generate(e,t){return this._client.post("/images/generations",nd(t,r=>Am({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}};function To(n,e){return Promise.resolve(n).then(e)}var ko=class extends p{accept(e,t,r){return this._client.post(l`/live/sessions/${e}/accept`,To(r,o=>({body:t,...o,headers:g([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})))}downloadRecording(e,t){return this._client.get(l`/live/sessions/${e}/content`,To(t,r=>({...r,headers:g([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}fork(e,t,r){return this._client.post(l`/live/sessions/${e}/fork`,To(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}hangup(e,t){return this._client.post(l`/live/sessions/${e}/hangup`,To(t,r=>({...r,headers:g([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})))}refer(e,t,r){return this._client.post(l`/live/sessions/${e}/refer`,To(r,o=>({body:t,...o,headers:g([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})))}reject(e,t,r){return this._client.post(l`/live/sessions/${e}/reject`,To(r,o=>({body:t,...o,headers:g([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})))}};var jo=class extends p{};var qo=class extends p{};function pR(n,e){return Promise.resolve(n).then(e)}var xt=class extends p{constructor(){super(...arguments),this.sideband=new qo(this._client),this.forks=new jo(this._client),this.sessions=new ko(this._client)}create(e,t){return this._client.post("/live/sessions",pR(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}};xt.Sideband=qo;xt.Forks=jo;xt.Sessions=ko;function sd(n,e){return Promise.resolve(n).then(e)}var kn=class extends p{retrieve(e,t){return this._client.get(l`/models/${e}`,sd(t,r=>({...r,__security:{bearerAuth:!0}})))}list(e){return this._client.getAPIList("/models",_e,sd(e,t=>({...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/models/${e}`,sd(t,r=>({...r,__security:{bearerAuth:!0}})))}};function hR(n,e){return Promise.resolve(n).then(e)}var jn=class extends p{create(e,t){return this._client.post("/moderations",hR(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}};async function Rm(n,e,t,r=null){if(n.body===null||typeof n.body!="object"||Array.isArray(n.body))throw new TypeError("Multipart request body must be an object");let o=Object.fromEntries(Object.entries(n.body).filter(([,c])=>c!==void 0));if(r!==null&&Object.keys(o).length===1&&Object.prototype.hasOwnProperty.call(o,r)){let c=o[r];if(typeof c!="string")throw new TypeError("Raw multipart alternative must be a string");return{...n,body:c,headers:g([n.headers,{"content-type":t[r].content_type}])}}let i=[];for(let[c,d]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(o,c))continue;let h=o[c],_=d.json?JSON.stringify(h):h;if(typeof _!="string")throw new TypeError(`Multipart field ${c} must encode as a string`);i.push([c,Dt([_],"",{type:d.content_type})]),delete o[c]}let a=(await ee({...n,body:o},e)).body;if(!(a instanceof FormData))throw await a.cancel(),new TypeError("Unexpected streaming upload in typed multipart request body");for(let[c,d]of i)a.append(c,d,"");return{...n,body:a,headers:g([n.headers,{"content-type":null}])}}function Pa(n,e){return Promise.resolve(n).then(e)}var $o=class extends p{create(e,t){return this._client.post("/realtime/calls",Pa(t,r=>Rm({body:e,...r,headers:g([{Accept:"application/sdp"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:"application/sdp",json:!1},session:{content_type:"application/json",json:!0}},"sdp")))}accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,Pa(r,o=>({body:t,...o,headers:g([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})))}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,Pa(t,r=>({...r,headers:g([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})))}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,Pa(r,o=>({body:t,...o,headers:g([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})))}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,Pa(r,o=>({body:t,...o,headers:g([{Accept:"*/*"},o?.headers]),__security:{bearerAuth:!0}})))}};function _R(n,e){return Promise.resolve(n).then(e)}var Do=class extends p{create(e,t){return this._client.post("/realtime/client_secrets",_R(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}};function gR(n,e){return Promise.resolve(n).then(e)}var Fo=class extends p{create(e,t){return this._client.post("/realtime/translations/client_secrets",gR(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}};var qn=class extends p{constructor(){super(...arguments),this.clientSecrets=new Fo(this._client)}};qn.ClientSecrets=Fo;var vt=class extends p{constructor(){super(...arguments),this.clientSecrets=new Do(this._client),this.calls=new $o(this._client),this.translations=new qn(this._client)}};vt.ClientSecrets=Do;vt.Calls=$o;vt.Translations=qn;function AR(n,e){return Promise.resolve(n).then(e)}var Om=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function RR(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Om.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Om.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var zo=class extends p{list(e,t={},r){let o=RR(t,["after","include","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/responses/${e}/input_items`,x,AR(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}};function PR(n,e){return Promise.resolve(n).then(e)}var Mo=class extends p{count(e={},t){return this._client.post("/responses/input_tokens",PR(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}};function Pm(n){return U(n)&&typeof n.type=="string"}function Lo({body:n},e){if(e===null||!U(n))return e??null;let{input:t}=n;if(Array.isArray(t))for(let i=t.length-1;i>=0;i-=1){let s=t[i];if(!U(s)||s.type!=="configuration_update")continue;let{text:a}=s;if(!U(a))continue;let{format:c}=a;if(Pm(c)){if(c.type==="text"&&e!==void 0)throw new f("Cannot use parseAs with a plain-text format update.");return e??c}}let{text:r}=n,o=U(r)?r.format:null;return e??(Pm(o)?o:null)}function xa(n,e){let t=e&&k(e,"parseAs")?e.parseAs:void 0;t!=null&&Lo({body:n},t);let r={...e};delete r.parseAs;let o;return r.__metadata={...e?.__metadata,captureResponseParser(i){let s=Lo(i,t);o=s===null?null:{type:s.type,$brand:"$brand"in s?s.$brand:void 0,$parseRaw:"$parseRaw"in s?s.$parseRaw:void 0}}},{getTextFormat:i=>o===void 0?Lo(i,t):o,requestOptions:r}}function xm(n,e,t=e&&Lo({body:e})){if(!e||!vR(e,t)){let r={...n,output_parsed:null,output:n.output.map(o=>o.type==="function_call"?{...o,parsed_arguments:null}:o.type==="message"?{...o,content:o.content.map(i=>({...i,parsed:null}))}:o)};return vm(n,r)&&Cr(r),r}return id(n,e,t)}function id(n,e,t=Lo({body:e})){let r=!n.status||n.status==="completed",o=n.output.map(s=>{if(s.type==="function_call")return r?SR(e,s):{...s,parsed_arguments:null};if(s.type==="message"){let a=s.content.map(c=>c.type==="output_text"?{...c,parsed:r&&(s.phase==null||s.phase==="final_answer")?Ft(t,c.text):null}:c);return{...s,content:a}}return s}),i={...n,output:o};return vm(n,i)&&Cr(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let s of i.output)if(s.type==="message"){for(let a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),i}function vR(n,e=Lo({body:n})){return At(e)?!0:Array.isArray(n.tools)&&n.tools.some(t=>od(t)||t.type==="function"&&t.strict===!0||t.type==="namespace"&&t.tools.some(r=>r.type==="function"&&(od(r)||r.strict===!0)))}function od(n){return n?.$brand==="auto-parseable-tool"}function IR(n,e,t){for(let r of n)if(t==null){if(r.type==="function"&&r.name===e)return r}else if(r.type==="namespace"&&r.name===t)return r.tools.find(o=>o.type==="function"&&o.name===e);if(t===e)return n.find(r=>r.type==="function"&&r.name===e&&r.defer_loading===!0)}function SR(n,e){let t=IR(n.tools??[],e.name,e.namespace),r=null;return od(t)?r=t.$parseRaw(e.arguments):t?.strict&&(r=Ft({type:"json_schema",$parseRaw:void 0},e.arguments)),{...e,parsed_arguments:r}}function vm(n,e){return!Object.getOwnPropertyDescriptor(n,"output_text")||e.output_text==null}function Cr(n){let e=[];for(let t of n.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var Bo=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw new RangeError(`missing output at index ${e}`);let r=this.capacity+e,o=t-(this.values[r]??0);if(o!==0)for(;r>=1;)this.values[r]=(this.values[r]??0)+o,r=Math.floor(r/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw new RangeError(`missing output at index ${e}`);let t=this.capacity,r=this.capacity+e,o=0;for(;t<r;)t%2===1&&(o+=this.values[t]??0,t+=1),r%2===1&&(r-=1,o+=this.values[r]??0),t=Math.floor(t/2),r=Math.floor(r/2);return o}grow(){let e=this.capacity;this.capacity*=2;let t=Array.from({length:this.capacity*2},()=>0);for(let r=0;r<this.size;r+=1)t[this.capacity+r]=this.values[e+r]??0;for(let r=this.capacity-1;r>0;r-=1)t[r]=(t[r*2]??0)+(t[r*2+1]??0);this.values=t}};function ad(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Bo}}function Ko(n,e){if(e.type!=="message")return"";let t="";for(let r of e.content)r.type==="output_text"&&(t+=r.text);return n.outputTextLengths.set(e,t.length),t}function ft(n,e){if(n.deferOutputText){n.canonicalSnapshot=void 0;return}if(n.canonicalSnapshot===e)return;let t=new Bo,r="";for(let o of e.output){let i=Ko(n,o);r+=i,t.append(i.length)}e.output_text=r,n.outputTextIndex=t,n.canonicalSnapshot=e}function Sm(n,e){n.canonicalSnapshot=void 0,n.outputTextLengths=new WeakMap,n.outputTextIndex=new Bo;let t=structuredClone(e);return!Object.getOwnPropertyDescriptor(t,"output_text")||t.output_text===null||t.output_text===void 0?ft(n,t):t.output.length===0&&t.output_text===""&&(n.canonicalSnapshot=t),t}function va(n,e,t,r,o){if(n.deferOutputText)return;let i=n.outputTextLengths.get(e);if(i!==void 0){let s=i-r.length+o.length;n.outputTextLengths.set(e,s),n.outputTextIndex.update(t,s)}}function Im(n,e,t){if(e.length===0){n.output_text+=t;return}n.output_text=n.output_text.slice(0,n.output_text.length-e.length)+t}function ER(n,e,t,r){if(t===void 0||e?.type!=="message")return 0;if(t<e.content.length-t-1){let s=0;for(let a=0;a<t;a+=1){let c=e.content[a];c?.type==="output_text"&&(s+=c.text.length)}return s}let o=0;for(let s=t+1;s<e.content.length;s+=1){let a=e.content[s];a?.type==="output_text"&&(o+=a.text.length)}return(n.outputTextLengths.get(e)??Ko(n,e).length)-o-r.length}function No(n,e,t,r,o,i){if(r===o)return;if(n.deferOutputText){n.outputTextDirty=!0;return}let s=e.output[t];if(t===e.output.length-1&&(i===void 0||s?.type==="message"&&i===s.content.length-1)){Im(e,r,o);return}let a=ER(n,s,i,o),c=n.outputTextIndex.prefixSum(t)+a;if(c+r.length===e.output_text.length){Im(e,r,o);return}e.output_text=e.output_text.slice(0,c)+o+e.output_text.slice(c+r.length)}var ud=new WeakMap;function Tr(n,e,t,r=!1){if(!Array.isArray(n)||!Number.isSafeInteger(e)||e<0||e>n.length||(e===n.length?!r||e in n:!k(n,e)))throw new f(`missing ${t} at index ${e}`)}function mc(n,e,t){if(e!==n.length)throw new f(`missing ${t} at index ${e}`);Tr(n,e,t,!0)}function B(n,e){Tr(n.output,e,"output");let t=n.output[e];if(!t)throw new f(`missing output at index ${e}`);return t}function Ia(n){return n.type==="function_call"||n.type==="custom_tool_call"||n.type==="shell_call"||n.type==="shell_call_output"}function _c(n,e){if(!k(n,"type")||typeof n.type!="string")throw new f(`expected an own output item type for ${e}`);let t=n.type==="function_call"||n.type==="custom_tool_call",r=[];if(k(n,"id")){if(typeof n.id!="string"||n.id.length===0&&n.type!=="computer_call")throw new f(`expected a non-empty output item id for ${e}`);r.push(`id:${n.id}`)}else if(!t)throw new f(`expected a non-empty output item id for ${e}`);if(Ia(n)){if(!k(n,"call_id")||typeof n.call_id!="string"||n.call_id.length===0&&n.type!=="function_call")throw new f(`expected a non-empty output item call_id for ${e}`);r.push(`call:${n.type}:${n.call_id}`)}return r}function km(n,e){for(let t of e)if(n.has(t))throw new f(`duplicate output item identity '${t}'`)}function cd(n,e){km(n,e);for(let t of e)n.add(t)}function jm(n){let e={snapshot:n,output:n.output,length:n.output.length,identities:new Set};for(let t=0;t<n.output.length;t+=1){let r=B(n,t);cd(e.identities,_c(r,"response snapshot"))}return e}function qm(n,e){let t=ud.get(n);if(t&&t.snapshot===e&&t.output===e.output&&t.length===e.output.length)return t;let r=jm(e);return ud.set(n,r),r}function yc(n,e){let t=ad(),r=Sm(t,e),o=jm(r);return n.canonicalSnapshot=t.canonicalSnapshot,n.outputTextLengths=t.outputTextLengths,n.outputTextIndex=t.outputTextIndex,ud.set(n,o),r}var ld={"response.output_text.delta":"message","response.output_text.done":"message","response.output_text.annotation.added":"message","response.refusal.delta":"message","response.refusal.done":"message","response.function_call_arguments.delta":"function_call","response.function_call_arguments.done":"function_call","response.custom_tool_call_input.delta":"custom_tool_call","response.custom_tool_call_input.done":"custom_tool_call","response.mcp_call_arguments.delta":"mcp_call","response.mcp_call_arguments.done":"mcp_call","response.mcp_call.in_progress":"mcp_call","response.mcp_call.completed":"mcp_call","response.mcp_call.failed":"mcp_call","response.shell_call_output_content.delta":"shell_call_output","response.shell_call_output_content.done":"shell_call_output","response.reasoning_text.delta":"reasoning","response.reasoning_text.done":"reasoning","response.reasoning_summary_part.added":"reasoning","response.reasoning_summary_part.done":"reasoning","response.reasoning_summary_text.delta":"reasoning","response.reasoning_summary_text.done":"reasoning","response.code_interpreter_call_code.delta":"code_interpreter_call","response.code_interpreter_call_code.done":"code_interpreter_call","response.code_interpreter_call.in_progress":"code_interpreter_call","response.code_interpreter_call.interpreting":"code_interpreter_call","response.code_interpreter_call.completed":"code_interpreter_call","response.file_search_call.in_progress":"file_search_call","response.file_search_call.searching":"file_search_call","response.file_search_call.completed":"file_search_call","response.web_search_call.in_progress":"web_search_call","response.web_search_call.searching":"web_search_call","response.web_search_call.completed":"web_search_call","response.image_generation_call.in_progress":"image_generation_call","response.image_generation_call.generating":"image_generation_call","response.image_generation_call.completed":"image_generation_call","response.image_generation_call.partial_image":"image_generation_call","response.mcp_list_tools.in_progress":"mcp_list_tools","response.mcp_list_tools.completed":"mcp_list_tools","response.mcp_list_tools.failed":"mcp_list_tools","response.compaction.compacting":"compaction"};function CR(n){return n.type==="response.content_part.added"||n.type==="response.content_part.done"?n.part.type==="reasoning_text"?"reasoning":"message":ld[n.type]}function Sa(n,e,t){if(_c(n,t),_c(e,t),!k(e,"type")||n.type!==e.type)throw new f(`expected output item type '${n.type}', got '${e.type}'`);let r=k(n,"id")?n.id:void 0,o=k(e,"id")?e.id:void 0,i=r===void 0&&(n.type==="function_call"||n.type==="custom_tool_call");if(r!==o&&!i)throw new f(`expected output item id '${r}', got '${o}'`);if(Ia(n)&&Ia(e)&&n.call_id!==e.call_id)throw new f(`expected output item call_id '${n.call_id}', got '${e.call_id}'`)}function TR(n,e,t){if(n.type==="response.output_item.done")return;if(t&&(n.type==="response.shell_call_command.added"||n.type==="response.shell_call_command.delta"||n.type==="response.shell_call_command.done")){let a=B(e,n.output_index);if(!k(a,"type")||a.type!=="shell_call")throw new f(`expected output item type 'shell_call', got '${a.type}'`);return}if(n.type!=="response.content_part.added"&&n.type!=="response.content_part.done"&&!k(ld,n.type))return;let r=n;if(!k(n,"item_id")||typeof r.item_id!="string"||r.item_id.length===0)throw new f(`expected a non-empty item_id for ${n.type}`);let o=B(e,r.output_index),i=k(o,"id")?o.id:void 0;if(i!==r.item_id)throw new f(`expected item_id '${i}', got '${r.item_id}'`);let s=CR(r);if(o.type!==s)throw new f(`expected output item type '${s}', got '${o.type}'`)}function ze(n,e){Tr(n,e,"content");let t=n[e];if(!t)throw new f(`missing content at index ${e}`);return t}function Em(n,e,t){let r=n.output.find(o=>o.type==="shell_call"&&o.call_id===e.call_id);for(r?Tr(r.action.commands,t,"command"):Tr(e.output,t,"content",!0);e.output.length<=t;)e.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return ze(e.output,t)}function kR(n){return new Set(n)}var jR=kR(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.compaction.compacting","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);function hc(n){throw new f("Unhandled response stream event: unknown")}var qR=["item_id","output_index","content_index","annotation_index","command_index","summary_index"];function $R(n){let e;try{e=Object.getOwnPropertyDescriptor(n,"type")}catch{return hc(n)}let t=e?.value;if(typeof t!="string"||!jR.has(t))return hc(n);let r=new Map([["type",t]]);if(t==="response.output_item.added"||t==="response.output_item.done"||t==="response.content_part.added"||t==="response.content_part.done"||t==="response.shell_call_command.added"||t==="response.shell_call_command.delta"||t==="response.shell_call_command.done"||k(ld,t))try{for(let i of qR){let s=Object.getOwnPropertyDescriptor(n,i);r.set(i,s?n[i]:void 0)}t==="response.output_item.added"||t==="response.output_item.done"?r.set("item",structuredClone(n.item)):(t==="response.content_part.added"||t==="response.content_part.done")&&r.set("part",structuredClone(n.part))}catch{return hc(n)}return new Proxy(n,{get(i,s){return r.has(s)?r.get(s):Reflect.get(i,s,i)}})}function dd(n,e,t,r,o=!0){let i=B(e,t);if(Sa(i,r,"response.output_item.done"),!k(i,"id")&&k(r,"id")){let{identities:c}=qm(n,e);cd(c,[`id:${r.id}`])}if(!o){e.output[t]=r;return}let s=Ko(n,i);(i.type==="message"||r.type==="message")&&ft(n,e),e.output[t]=r;let a=Ko(n,r);n.canonicalSnapshot===e&&n.outputTextIndex.update(t,a.length),No(n,e,t,s,a)}function DR(n,e,t){switch(n.type){case"response.output_item.added":{mc(e.output,n.output_index,"output");let r=qm(t,e),o=n.item,i=_c(o,n.type);km(r.identities,i),o.type==="message"&&ft(t,e),e.output.push(o),cd(r.identities,i),r.length=e.output.length;let s=Ko(t,o);return t.canonicalSnapshot===e&&t.outputTextIndex.append(s.length),s&&(t.deferOutputText?t.outputTextDirty=!0:e.output_text+=s),!0}case"response.output_item.done":return dd(t,e,n.output_index,n.item),!0;default:return!1}}function FR(n,e,t){switch(n.type){case"response.content_part.added":{let r=B(e,n.output_index),{type:o}=r,{part:i}=n;if(o==="message"&&i.type!=="reasoning_text"){mc(r.content,n.content_index,"content");let s=i;s.type==="output_text"&&ft(t,e),r.content.push(s),s.type==="output_text"&&(va(t,r,n.output_index,"",s.text),No(t,e,n.output_index,"",s.text,n.content_index))}else if(o==="reasoning"&&i.type==="reasoning_text"){let s=r.content??[];mc(s,n.content_index,"content"),r.content||(r.content=s),s.push(i)}return!0}default:return!1}}function zR(n,e,t){switch(n.type){case"response.content_part.done":{let r=B(e,n.output_index),{part:o}=n;if(r.type==="message"&&o.type!=="reasoning_text"){let i=ze(r.content,n.content_index),s=i.type==="output_text"?i.text:"",a=o;(i.type==="output_text"||a.type==="output_text")&&ft(t,e),r.content[n.content_index]=a;let c=a.type==="output_text"?a.text:"";va(t,r,n.output_index,s,c),No(t,e,n.output_index,s,c,n.content_index)}else if(r.type==="reasoning"&&o.type==="reasoning_text"){let{content:i}=r;if(!i)throw new f(`missing content at index ${n.content_index}`);ze(i,n.content_index),i[n.content_index]=o}return!0}default:return!1}}function Cm(n){return U(n)&&typeof n.token=="string"&&typeof n.logprob=="number"&&Array.isArray(n.bytes)&&n.bytes.every(e=>typeof e=="number")}function MR(n){return Array.isArray(n)&&n.every(e=>Cm(e)&&"top_logprobs"in e&&Array.isArray(e.top_logprobs)&&e.top_logprobs.every(Cm))}function Tm(n,e){let t=structuredClone(e.logprobs);if(MR(t)){if(e.type==="response.output_text.done")(t.length>0||Array.isArray(n.logprobs)&&n.logprobs.length>0)&&(n.logprobs=t);else if(t.length>0){Array.isArray(n.logprobs)||(n.logprobs=[]);for(let r of t)n.logprobs.push(r)}}}function LR(n,e,t){switch(n.type){case"response.output_text.delta":{let r=B(e,n.output_index);if(r.type==="message"){let o=ze(r.content,n.content_index);if(o.type!=="output_text")throw new f(`expected content to be 'output_text', got ${o.type}`);Tm(o,n);let i=o.text;ft(t,e),o.text=i+n.delta,va(t,r,n.output_index,i,o.text),n.output_index===e.output.length-1&&n.content_index===r.content.length-1?t.deferOutputText?n.delta!==""&&(t.outputTextDirty=!0):e.output_text+=n.delta:No(t,e,n.output_index,i,o.text,n.content_index)}return!0}case"response.output_text.done":{let r=B(e,n.output_index);if(r.type==="message"){let o=ze(r.content,n.content_index);if(o.type!=="output_text")throw new f(`expected content to be 'output_text', got ${o.type}`);Tm(o,n);let i=o.text;ft(t,e),o.text=n.text,va(t,r,n.output_index,i,n.text),No(t,e,n.output_index,i,n.text,n.content_index)}return!0}case"response.output_text.annotation.added":{let r=B(e,n.output_index);if(r.type==="message"){let o=ze(r.content,n.content_index);if(o.type!=="output_text")throw new f(`expected content to be 'output_text', got ${o.type}`);Tr(o.annotations,n.annotation_index,"annotation",!0),o.annotations[n.annotation_index]=structuredClone(n.annotation)}return!0}default:return!1}}function BR(n,e){switch(n.type){case"response.refusal.delta":{let t=B(e,n.output_index);if(t.type==="message"){let r=ze(t.content,n.content_index);if(r.type!=="refusal")throw new f(`expected content to be 'refusal', got ${r.type}`);r.refusal+=n.delta}return!0}case"response.refusal.done":{let t=B(e,n.output_index);if(t.type==="message"){let r=ze(t.content,n.content_index);if(r.type!=="refusal")throw new f(`expected content to be 'refusal', got ${r.type}`);r.refusal=n.refusal}return!0}case"response.function_call_arguments.delta":{let t=B(e,n.output_index);return t.type==="function_call"&&(t.arguments+=n.delta),!0}case"response.function_call_arguments.done":{let t=B(e,n.output_index);return t.type==="function_call"&&(t.arguments=n.arguments),!0}case"response.custom_tool_call_input.delta":{let t=B(e,n.output_index);return t.type==="custom_tool_call"&&(t.input+=n.delta),!0}case"response.custom_tool_call_input.done":{let t=B(e,n.output_index);return t.type==="custom_tool_call"&&(t.input=n.input),!0}case"response.mcp_call_arguments.delta":{let t=B(e,n.output_index);return t.type==="mcp_call"&&(t.arguments+=n.delta),!0}case"response.mcp_call_arguments.done":{let t=B(e,n.output_index);return t.type==="mcp_call"&&(t.arguments=n.arguments),!0}default:return!1}}function KR(n,e){switch(n.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let t=B(e,n.output_index);if(t.type==="shell_call"){let r=n.type==="response.shell_call_command.added";Tr(t.action.commands,n.command_index,"command",r),t.action.commands[n.command_index]=n.command}return!0}case"response.shell_call_command.delta":{let t=B(e,n.output_index);return t.type==="shell_call"&&(Tr(t.action.commands,n.command_index,"command"),t.action.commands[n.command_index]+=n.delta),!0}case"response.shell_call_output_content.delta":{let t=B(e,n.output_index);if(t.type==="shell_call_output"){let r=Em(e,t,n.command_index);r.stdout+=n.delta.stdout??"",r.stderr+=n.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{let t=B(e,n.output_index);if(t.type==="shell_call_output"){let r=ze(n.output,0);Em(e,t,n.command_index),t.output[n.command_index]=structuredClone(r)}return!0}default:return!1}}function NR(n,e){switch(n.type){case"response.reasoning_text.delta":{let t=B(e,n.output_index);if(t.type==="reasoning"){if(!t.content)throw new f(`missing content at index ${n.content_index}`);let r=ze(t.content,n.content_index);if(r.type!=="reasoning_text")throw new f(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=n.delta}return!0}case"response.reasoning_text.done":{let t=B(e,n.output_index);if(t.type==="reasoning"){if(!t.content)throw new f(`missing content at index ${n.content_index}`);let r=ze(t.content,n.content_index);if(r.type!=="reasoning_text")throw new f(`expected content to be 'reasoning_text', got ${r.type}`);r.text=n.text}return!0}case"response.reasoning_summary_part.added":{let t=B(e,n.output_index);return t.type==="reasoning"&&(mc(t.summary,n.summary_index,"content"),t.summary.push(structuredClone(n.part))),!0}case"response.reasoning_summary_part.done":{let t=B(e,n.output_index);return t.type==="reasoning"&&(ze(t.summary,n.summary_index),t.summary[n.summary_index]=structuredClone(n.part)),!0}case"response.reasoning_summary_text.delta":{let t=B(e,n.output_index);if(t.type==="reasoning"){let r=ze(t.summary,n.summary_index);r.text+=n.delta}return!0}case"response.reasoning_summary_text.done":{let t=B(e,n.output_index);if(t.type==="reasoning"){let r=ze(t.summary,n.summary_index);r.text=n.text}return!0}default:return!1}}function WR(n,e){switch(n.type){case"response.code_interpreter_call_code.delta":{let t=B(e,n.output_index);return t.type==="code_interpreter_call"&&(t.code=(t.code??"")+n.delta),!0}case"response.code_interpreter_call_code.done":{let t=B(e,n.output_index);return t.type==="code_interpreter_call"&&(t.code=n.code),!0}case"response.code_interpreter_call.in_progress":{let t=B(e,n.output_index);return t.type==="code_interpreter_call"&&(t.status="in_progress"),!0}case"response.code_interpreter_call.interpreting":{let t=B(e,n.output_index);return t.type==="code_interpreter_call"&&(t.status="interpreting"),!0}case"response.code_interpreter_call.completed":{let t=B(e,n.output_index);return t.type==="code_interpreter_call"&&(t.status="completed"),!0}default:return!1}}function UR(n,e){switch(n.type){case"response.file_search_call.in_progress":{let t=B(e,n.output_index);return t.type==="file_search_call"&&(t.status="in_progress"),!0}case"response.file_search_call.searching":{let t=B(e,n.output_index);return t.type==="file_search_call"&&(t.status="searching"),!0}case"response.file_search_call.completed":{let t=B(e,n.output_index);return t.type==="file_search_call"&&(t.status="completed"),!0}case"response.web_search_call.in_progress":{let t=B(e,n.output_index);return t.type==="web_search_call"&&(t.status="in_progress"),!0}case"response.web_search_call.searching":{let t=B(e,n.output_index);return t.type==="web_search_call"&&(t.status="searching"),!0}case"response.web_search_call.completed":{let t=B(e,n.output_index);return t.type==="web_search_call"&&(t.status="completed"),!0}default:return!1}}function QR(n,e){switch(n.type){case"response.image_generation_call.in_progress":{let t=B(e,n.output_index);return t.type==="image_generation_call"&&(t.status="in_progress"),!0}case"response.image_generation_call.generating":{let t=B(e,n.output_index);return t.type==="image_generation_call"&&(t.status="generating"),!0}case"response.image_generation_call.completed":{let t=B(e,n.output_index);return t.type==="image_generation_call"&&(t.status="completed"),!0}case"response.mcp_call.in_progress":{let t=B(e,n.output_index);return t.type==="mcp_call"&&(t.status="in_progress"),!0}case"response.mcp_call.completed":{let t=B(e,n.output_index);return t.type==="mcp_call"&&(t.status="completed"),!0}case"response.mcp_call.failed":{let t=B(e,n.output_index);return t.type==="mcp_call"&&(t.status="failed"),!0}default:return!1}}function HR(n){switch(n.type){case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":return!0;default:return!1}}function XR(n){switch(n.type){case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.compaction.compacting":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":return!0;default:return!1}}function Wo(){return ad()}function JR(n,e,t,r){return TR(n,e,r),!!(DR(n,e,t)||FR(n,e,t)||zR(n,e,t)||LR(n,e,t)||BR(n,e)||KR(n,e)||NR(n,e)||WR(n,e)||UR(n,e)||QR(n,e)||XR(n))}function $m(n,e,t,r=!1,o){let i=$R(n);if(o&&i.type!=="keepalive"){let s=o(i);if(s===null){if(!e)throw new f("Cannot ignore a response event before response.created.");return e}i=s}if(!e){if(i.type!=="response.created")throw new f(`When snapshot hasn't been set yet, expected 'response.created' event, got ${i.type}`);return yc(t,i.response)}return JR(i,e,t,r)?e:HR(i)?yc(t,i.response):hc(i)}var he,gc,Pe,bc,it,Ne,Bt,Kt,xe,We,fd,Dm,Fm,wc,zm,Mm,Ac,Lm,pd,hd,VR={annotation:!0,annotation_index:!0,arguments:!0,background:!0,code:!0,command:!0,command_index:!0,content_index:!0,delta:!0,input:!0,item:!0,item_id:!0,logprobs:!0,message:!0,obfuscation:!0,output:!0,output_format:!0,output_index:!0,param:!0,part:!0,partial_image_b64:!0,partial_image_index:!0,quality:!0,refusal:!0,response:!0,sequence_number:!0,size:!0,status:!0,summary_index:!0,text:!0,type:!0},Rc=class n extends ir{constructor(e){super(),he.add(this),gc.set(this,void 0),Pe.set(this,void 0),bc.set(this,void 0),it.set(this,Wo()),Ne.set(this,new Map),Bt.set(this,new Map),Kt.set(this,!1),xe.set(this,new Map),We.set(this,new Map),w(this,gc,e,"f"),this.once("end",()=>{u(this,Ne,"f").clear(),u(this,Bt,"f").clear(),u(this,xe,"f").clear(),u(this,We,"f").clear()})}static createResponse(e,t,r){let{getTextFormat:o,requestOptions:i}=xa(t,r),s=new n(Array.isArray(t.tools)?{tools:t.tools}:{});return s._run(()=>s._createOrRetrieveResponse(e,t,{...i,__metadata:{...i?.__metadata,helperMethod:"stream"}},o)),s}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,r,o=xa(t).getTextFormat){this._listenForAbort(r?.signal),u(this,he,"m",fd).call(this);let i,s,a=null;if("response_id"in t)s=o({body:t}),i=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=t.starting_after??null;else{let c={...t,stream:!0},d={body:c},h=null,_=e.responses.create(c,{...r,signal:this.controller.signal});_ instanceof kt&&(_=_._thenUnwrap((m,b)=>(d=b.options,h=b.response.body,m))),i=await _;try{s=o(d)}catch(m){throw this.abort(),i.controller.abort(),GR(h),m}}this._connected();for await(let c of i)u(this,he,"m",pd).call(this,c,a);if(i.controller.signal?.aborted)throw this._userAbortError();return u(this,he,"m",hd).call(this,s)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,he,"m",fd).call(this),this._connected();let r=$e.fromReadableStream(e,this.controller);for await(let o of r)u(this,he,"m",pd).call(this,o,null);if(r.controller.signal?.aborted)throw this._userAbortError();return u(this,he,"m",hd).call(this)}[(gc=new WeakMap,Pe=new WeakMap,bc=new WeakMap,it=new WeakMap,Ne=new WeakMap,Bt=new WeakMap,Kt=new WeakMap,xe=new WeakMap,We=new WeakMap,he=new WeakSet,fd=function(){this.ended||(w(this,Pe,void 0,"f"),w(this,it,Wo(),"f"),u(this,Ne,"f").clear(),u(this,Bt,"f").clear(),w(this,Kt,!1,"f"),u(this,xe,"f").clear(),u(this,We,"f").clear())},Dm=function(t){if(t.type==="response.created"||t.type==="response.queued"||t.type==="response.in_progress"||t.type==="response.completed"||t.type==="response.failed"||t.type==="response.incomplete"){if(!k(t,"response"))throw new f("Lifecycle events require their own response field.");let{response:r,...o}=t;if(!U(r))throw new f("Lifecycle events require a response object.");let i=structuredClone(r);if(u(this,Pe,"f")&&i.id!==u(this,Pe,"f").id)throw new f("Lifecycle response identity changed.");if(!k(i,"output")||i.output==null){let s;t.type==="response.completed"?s=[...u(this,xe,"f")].sort(([a],[c])=>a-c).map(([,a])=>structuredClone(a)):t.type==="response.failed"||t.type==="response.incomplete"?s=[...u(this,Ne,"f").keys()].sort((a,c)=>a-c).map(a=>structuredClone(u(this,he,"m",wc).call(this,a))):s=[],i={...i,output:s},(t.type==="response.completed"||t.type==="response.failed"||t.type==="response.incomplete")&&Cr(i)}return t.type==="response.completed"&&u(this,he,"m",zm).call(this,i),{...o,type:t.type,sequence_number:t.sequence_number,response:i}}return u(this,he,"m",Fm).call(this,t)},Fm=function(t){if(!u(this,Pe,"f")||!k(t,"output_index")||!("output_index"in t))return t;let r=t.output_index;if(!Number.isSafeInteger(r)||r<0)throw new f("Invalid response output index.");let o;if(t.type==="response.output_item.added"){if(t.item==null)return null;if(u(this,xe,"f").has(r)||u(this,We,"f").has(r))throw new f(`Duplicate response output index ${r}.`);o=u(this,Pe,"f").output.length}else{let i=u(this,Ne,"f").get(r);if(i===void 0)throw new f(`missing output at index ${r}`);o=i}return new Proxy(t,{get(i,s){return s==="output_index"?o:Reflect.get(i,s,i)}})},wc=function(t){let r=u(this,Ne,"f").get(t);return u(this,xe,"f").get(t)??(r===void 0?void 0:u(this,Pe,"f")?.output[r])},zm=function(t){if(u(this,We,"f").size===0&&u(this,xe,"f").size===0)return;let r=new Map((t.output??[]).map(o=>[Nt(o),o]));for(let o of u(this,xe,"f").values()){let i=r.get(Nt(o));i&&Sa(o,i,"response.completed")}for(let[o,i]of u(this,We,"f")){let s=r.get(i);if(!s)throw new f("Cannot complete response with unfinished output items.");let a=u(this,he,"m",wc).call(this,o);if(!a)throw new f("Cannot complete response with a missing output identity.");Sa(a,s,"response.completed")}},Mm=function(t,r,o){if(t.type==="response.completed"){w(this,Kt,!1,"f");return}if(r!==u(this,Pe,"f")){let i=new Map;for(let[a,c]of u(this,xe,"f"))i.set(Nt(c),a);for(let[a,c]of u(this,We,"f"))i.set(c,a);let s=new Map;u(this,Bt,"f").clear();for(let[a,c]of r.output.entries()){let d=Nt(c),_=i.get(d)??a,m=u(this,xe,"f").get(_),b=u(this,We,"f").get(_);if(s.has(_)||m&&Nt(m)!==d||b!==void 0&&b!==d)throw new f("Response snapshot has conflicting output positions.");let y=u(this,he,"m",wc).call(this,_);y&&Sa(y,c,t.type),s.set(_,a),u(this,Bt,"f").set(d,_),m?u(this,xe,"f").set(_,structuredClone(c)):u(this,We,"f").set(_,d)}w(this,Ne,s,"f"),w(this,Kt,!["response.failed","response.incomplete"].includes(t.type),"f"),["response.created","response.queued","response.in_progress"].includes(t.type)&&u(this,he,"m",Ac).call(this,r);return}if(o!==void 0){if(t.type==="response.output_item.added"&&t.item!=null){u(this,Ne,"f").set(t.output_index,o);let i=Nt(t.item);u(this,We,"f").set(t.output_index,i),u(this,Bt,"f").set(i,t.output_index),w(this,Kt,!0,"f")}else if(t.type==="response.output_item.done"){let i=r.output[o];if(!i)throw new f(`missing output at index ${t.output_index}`);u(this,xe,"f").set(t.output_index,structuredClone(i)),u(this,We,"f").delete(t.output_index)}}},Ac=function(t){if(!u(this,Kt,"f"))return;let r=[...u(this,Ne,"f")];if(r.sort(([o],[i])=>o-i),r.some(([,o],i)=>o!==i)){let o=u(this,it,"f").canonicalSnapshot===t;t.output=r.map(([,i])=>t.output[i]),w(this,Ne,new Map(r.map(([i],s)=>[i,s])),"f"),w(this,it,Wo(),"f"),o&&ft(u(this,it,"f"),t)}w(this,Kt,!1,"f")},Lm=function(t,r){if(!Array.isArray(t.output))return!1;let o=k(t,"output_text")?t.output_text:void 0;if(t.output.length!==0){let a=yc(Wo(),t),c=[];for(let h of a.output){let _=u(this,Bt,"f").get(Nt(h)),m=_===void 0?void 0:u(this,Ne,"f").get(_);if(_===void 0||m===void 0)return!1;c.push({wire:_,position:m,item:h})}let d=o==null;d||(u(this,it,"f").canonicalSnapshot=void 0);for(let{wire:h,position:_,item:m}of c)dd(u(this,it,"f"),r,_,m,d),u(this,xe,"f").has(h)&&u(this,xe,"f").set(h,structuredClone(m));u(this,he,"m",Ac).call(this,r)}let{output:i}=r,s=o;s==null?(ft(u(this,it,"f"),r),s=r.output_text):u(this,it,"f").canonicalSnapshot=void 0;for(let a of Object.keys(r))k(t,a)||Reflect.deleteProperty(r,a);return Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t,output:i,output_text:s})),!0},pd=function(t,r){if(this.ended)return;let o=(h,_)=>{(r==null||_.sequence_number>r)&&this._emit(h,_)};if(t.type==="error"){let h="error"in t&&typeof t.error=="object"&&t.error!==null?t.error:t;throw new H(void 0,h,t.message,void 0)}let i=t,s,a=$m(t,u(this,Pe,"f"),u(this,it,"f"),!0,h=>{i=h;let _=u(this,he,"m",Dm).call(this,h);if(_){if(k(_,"output_index")&&"output_index"in _)s=_.output_index;else if(k(_,"response")&&"response"in _&&(i=_,(_.type==="response.created"||_.type==="response.queued"||_.type==="response.in_progress")&&u(this,Pe,"f"))){if(u(this,he,"m",Lm).call(this,_.response,u(this,Pe,"f")))return null;let m=new Set(_.response.output.map(Nt)),b=u(this,Pe,"f").output.filter(y=>!m.has(Nt(y)));if(b.length)return{..._,response:{..._.response,output:[..._.response.output,...b]}}}}return _});if(u(this,he,"m",Mm).call(this,i,a,s),w(this,Pe,a,"f"),i.type==="response.output_item.added"&&i.item==null)return;let c={...i};for(let h of Object.keys(VR)){let _=Object.getOwnPropertyDescriptor(i,h);_&&!_.enumerable&&Object.defineProperty(c,h,{value:Reflect.get(i,h,i),enumerable:!0})}let d=structuredClone(c);switch(o("event",d),c.type){case"response.output_text.delta":{let h=a.output[s??c.output_index];if(!h)throw new f(`missing output at index ${c.output_index}`);if(h.type==="message"){let _=h.content[c.content_index];if(!_)throw new f(`missing content at index ${c.content_index}`);if(_.type!=="output_text")throw new f(`expected content to be 'output_text', got ${_.type}`);o("response.output_text.delta",{...structuredClone(c),snapshot:_.text})}break}case"response.function_call_arguments.delta":{let h=a.output[s??c.output_index];if(!h)throw new f(`missing output at index ${c.output_index}`);h.type==="function_call"&&o("response.function_call_arguments.delta",{...structuredClone(c),snapshot:h.arguments});break}default:{o(c.type,d);break}}},hd=function(t){if(this.ended)throw new f("stream has ended, this shouldn't happen");let r=u(this,Pe,"f");if(!r)throw new f("request ended without sending any events");u(this,he,"m",Ac).call(this,r),w(this,Pe,void 0,"f"),w(this,it,Wo(),"f"),u(this,Ne,"f").clear(),u(this,Bt,"f").clear(),w(this,Kt,!1,"f"),u(this,xe,"f").clear(),u(this,We,"f").clear();let o=YR(r,u(this,gc,"f"),t);return w(this,bc,o,"f"),o},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=r=>e(r);return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=u(this,bc,"f");if(!e)throw new f("stream ended without producing a Response");return e}};async function GR(n){try{await ut(n)}catch{}}function Nt(n){return JSON.stringify([n.type,!Ia(n)&&k(n,"id")?n.id:null,k(n,"call_id")&&"call_id"in n?n.call_id:null])}function YR(n,e,t){return xm(n,e,t)}function Ea(n,e){return Promise.resolve(n).then(e)}function ZR(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Bm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function eO(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Bm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Bm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var It=class extends p{constructor(){super(...arguments),this.inputItems=new zo(this._client),this.inputTokens=new Mo(this._client)}create(e,t){return this._client.post("/responses",Ea(t,r=>ZR({body:e,...r,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))._thenUnwrap(r=>("object"in r&&r.object==="response"&&Cr(r),r))}retrieve(e,t={},r){let o=eO(t,["include","include_obfuscation","starting_after","stream"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.get(l`/responses/${e}`,Ea(r,i=>({query:t,...i,stream:t?.stream??!1,__security:{bearerAuth:!0}})))._thenUnwrap(i=>("object"in i&&i.object==="response"&&Cr(i),i))}delete(e,t){return this._client.delete(l`/responses/${e}`,Ea(t,r=>({...r,headers:g([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,Ea(t,r=>({...r,__security:{bearerAuth:!0}})))}compact(e,t){return this._client.post("/responses/compact",Ea(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}parse(e,t){let{getTextFormat:r,requestOptions:o}=xa(e,t);return this._client.responses.create(e,o)._thenUnwrap((i,{options:s})=>id(i,e,r(s)))}stream(e,t){return Rc.createResponse(this._client,e,t)}};It.InputItems=zo;It.InputTokens=Mo;function tO(n,e){return Promise.resolve(n).then(e)}var Uo=class extends p{retrieve(e,t){return this._client.get(l`/safety/alerts/${e}`,tO(t,r=>({...r,__security:{bearerAuth:!0}})))}};function nO(n,e){return Promise.resolve(n).then(e)}var Qo=class extends p{retrieve(e,t){return this._client.get(l`/safety/cases/${e}`,nO(t,r=>({...r,__security:{bearerAuth:!0}})))}};var Wt=class extends p{constructor(){super(...arguments),this.cases=new Qo(this._client),this.alerts=new Uo(this._client)}};Wt.Cases=Qo;Wt.Alerts=Uo;function oO(n,e){return Promise.resolve(n).then(e)}var Ho=class extends p{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,oO(t,r=>({...r,headers:g([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function aO(n,e){return Promise.resolve(n).then(e)}var Xo=class extends p{retrieve(e,t,r){let{skill_id:o}=t;return this._client.get(l`/skills/${o}/versions/${e}/content`,aO(r,i=>({...i,headers:g([{Accept:"application/binary"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function md(n,e){return Promise.resolve(n).then(e)}function cO(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Km=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function lO(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Km.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Km.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var $n=class extends p{constructor(){super(...arguments),this.content=new Xo(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,bt(cO({body:t,...r,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client,{stripFilenames:!1}))}retrieve(e,t,r){let{skill_id:o}=t;return this._client.get(l`/skills/${o}/versions/${e}`,md(r,i=>({...i,__security:{bearerAuth:!0}})))}list(e,t={},r){let o=lO(t,["after","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/skills/${e}/versions`,x,md(r,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,r){let{skill_id:o}=t;return this._client.delete(l`/skills/${o}/versions/${e}`,md(r,i=>({...i,__security:{bearerAuth:!0}})))}};$n.Content=Xo;function Oc(n,e){return Promise.resolve(n).then(e)}function fO(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Nm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function pO(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Nm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Nm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Ut=class extends p{constructor(){super(...arguments),this.content=new Ho(this._client),this.versions=new $n(this._client)}create(e={},t){return this._client.post("/skills",bt(fO({body:e,...t,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(l`/skills/${e}`,Oc(t,r=>({...r,__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/skills/${e}`,Oc(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}list(e={},t){let r=pO(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/skills",x,Oc(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/skills/${e}`,Oc(t,r=>({...r,__security:{bearerAuth:!0}})))}};Ut.Content=Ho;Ut.Versions=$n;function hO(n,e){return Promise.resolve(n).then(e)}var Jo=class extends p{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,hO(r,o=>ee({body:t,...o,__security:{bearerAuth:!0}},this._client)))}};function _d(n,e){return Promise.resolve(n).then(e)}var kr=class extends p{constructor(){super(...arguments),this.parts=new Jo(this._client)}create(e,t){return this._client.post("/uploads",_d(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,_d(t,r=>({...r,__security:{bearerAuth:!0}})))}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,_d(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}};kr.Parts=Jo;function Wm(n,e,t,r){return fa(o=>n.retrieve(t,{vector_store_id:e},{...r,headers:o}),["in_progress"],["failed","cancelled","completed"],r)}function Um(n,e,t,r){return fa(o=>n.retrieve(t,{vector_store_id:e},{...r,headers:o}),["in_progress"],["failed","cancelled","completed"],r)}var Qm=async n=>{let e=await Promise.allSettled(n),t=e.filter(o=>o.status==="rejected");if(t.length)throw Object.defineProperty(new Error(`${t.length} promise(s) failed`),"rejections",{configurable:!0,value:t.map(({reason:o})=>o),writable:!0});let r=[];for(let o of e)o.status==="fulfilled"&&r.push(o.value);return r};async function Hm(n,e,t,r,o,i){if(r==null||r.length===0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=i?.maxConcurrency??5,a=Math.min(s,r.length);if(a===0)throw new RangeError("maxConcurrency must be greater than 0");let c=r.values(),d=[...o];async function h(m){for(let b of m){let y=await e.files.create({file:b,purpose:"assistants"},i);d.push(y.id)}}let _=[];_.length=a;for(let m=0;m<_.length;m+=1)_[m]=h(c);return await Qm(_),await n.createAndPoll(t,{file_ids:d},i)}function Pc(n,e){return Promise.resolve(n).then(e)}var Vo=class extends p{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,Pc(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,r){let{vector_store_id:o}=t;return this._client.get(l`/vector_stores/${o}/file_batches/${e}`,Pc(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t,r){let{vector_store_id:o}=t;return this._client.post(l`/vector_stores/${o}/file_batches/${e}/cancel`,Pc(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(e,t,r){let o=await this.create(e,t,r);return await this.poll(e,o.id,r)}listFiles(e,t,r){let{vector_store_id:o,...i}=t;return this._client.getAPIList(l`/vector_stores/${o}/file_batches/${e}/files`,x,Pc(r,s=>({query:i,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}async poll(e,t,r){return await Um(this,e,t,r)}async uploadAndPoll(e,{files:t,fileIds:r=[]},o){return await Hm(this,this._client,e,t,r,o)}};function Go(n,e){return Promise.resolve(n).then(e)}var Xm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function yO(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Xm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Xm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Yo=class extends p{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,Go(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,r){let{vector_store_id:o}=t;return this._client.get(l`/vector_stores/${o}/files/${e}`,Go(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){let{vector_store_id:o,...i}=t;return this._client.post(l`/vector_stores/${o}/files/${e}`,Go(r,s=>({body:i,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},r){let o=yO(t,["after","before","filter","limit","order"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.getAPIList(l`/vector_stores/${e}/files`,x,Go(r,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,r){let{vector_store_id:o}=t;return this._client.delete(l`/vector_stores/${o}/files/${e}`,Go(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(e,t,r){let o=await this.create(e,t,r);return await this.poll(e,o.id,r)}async poll(e,t,r){return await Wm(this,e,t,r)}async upload(e,t,r){let o=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:o.id},r)}async uploadAndPoll(e,t,r){let o=await this.upload(e,t,r);return await this.poll(e,o.id,r)}content(e,t,r){let{vector_store_id:o}=t;return this._client.getAPIList(l`/vector_stores/${o}/files/${e}/content`,_e,Go(r,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}};function Zo(n,e){return Promise.resolve(n).then(e)}var Jm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function bO(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Jm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Jm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Qt=class extends p{constructor(){super(...arguments),this.files=new Yo(this._client),this.fileBatches=new Vo(this._client)}create(e,t){return this._client.post("/vector_stores",Zo(t,r=>({body:e,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,Zo(t,r=>({...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,Zo(r,o=>({body:t,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let r=bO(e,["after","before","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/vector_stores",x,Zo(t,o=>({query:e,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,Zo(t,r=>({...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})))}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,_e,Zo(r,o=>({body:t,method:"post",...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}};Qt.Files=Yo;Qt.FileBatches=Vo;function St(n,e){return Promise.resolve(n).then(e)}function wO(n,e){return{...n,__metadata:{...n.__metadata,...e}}}var Vm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Gm(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>Vm.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!Vm.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var Dn=class extends p{create(e,t){return this._client.post("/videos",St(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(l`/videos/${e}`,St(t,r=>({...r,__security:{bearerAuth:!0}})))}list(e={},t){let r=Gm(e,["after","limit","order"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/videos",N,St(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/videos/${e}`,St(t,r=>({...r,__security:{bearerAuth:!0}})))}createCharacter(e,t){return this._client.post("/videos/characters",St(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}downloadContent(e,t={},r){let o=Gm(t,["variant"],r);return o!==void 0&&(r=o,t={}),t=t,this._client.get(l`/videos/${e}/content`,St(r,i=>({query:t,...i,headers:g([{Accept:"application/binary"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}edit(e,t){return this._client.post("/videos/edits",St(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}extend(e,t){return this._client.post("/videos/extensions",St(t,r=>ee({body:e,...r,__security:{bearerAuth:!0}},this._client)))}getCharacter(e,t){return this._client.get(l`/videos/characters/${e}`,St(t,r=>({...r,__security:{bearerAuth:!0}})))}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,St(r,o=>bt(wO({body:t,...o,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client)))}};function AO(n,e){return Promise.resolve(n).then(e)}var ei=class extends p{list(e){return this._client.get("/webhook_event_types",AO(e,t=>({...t,__security:{bearerAuth:!0}})))}};var Ym=32,OO=32;function yd(n){return n.split(" ",Ym+1).length>Ym}function*gd(n){let e=0;for(;e<=n.length;){let t=n.indexOf(" ",e),r=n.slice(e,t===-1?void 0:t);if(yield r.startsWith("v1,")?r.slice(3):r,t===-1)break;e=t+1}}function Zm(n){try{let e=oc(n);return e.byteLength===OO?e:void 0}catch{return}}function PO(n){for(let e of gd(n)){let t=Zm(e);if(t)return t}}function xO(n,e,t){let r=t;for(let o of gd(n)){let i=Zm(o);if(!i)continue;let s=0;for(let[a,c]of i.entries())s|=c^(e[a]??0);s===0&&(r=i)}return r}async function e_(n,e,t,r,o,i){let s=Number.parseInt(t,10);if(Number.isNaN(s))throw new qe("Invalid webhook timestamp format");let a=Math.floor(Date.now()/1e3);if(a-s>i)throw new qe("Webhook timestamp is too old");if(s>a+i)throw new qe("Webhook timestamp is too new");let c=yd(e),d=c?PO(e):void 0;if(c&&!d)throw new qe("The given webhook signature does not match the expected signature");let h=Uint8Array.from(o.startsWith("whsec_")?oc(o.slice(6)):me(o)),_=r?`${r}.${t}.${n}`:`${t}.${n}`,m=Uint8Array.from(me(_)),b=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,c?["sign","verify"]:["verify"]);if(c&&d){let y=new Uint8Array(await crypto.subtle.sign("HMAC",b,m)),A=xO(e,y,d);try{if(await crypto.subtle.verify("HMAC",b,Uint8Array.from(A),m))return}catch{}throw new qe("The given webhook signature does not match the expected signature")}for(let y of gd(e))try{let A=Uint8Array.from(oc(y));if(await crypto.subtle.verify("HMAC",b,A,m))return}catch{}throw new qe("The given webhook signature does not match the expected signature")}var ti,r_,xc;function Fn(n,e){return Promise.resolve(n).then(e)}var t_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function vO(n,e,t){if(typeof n!="object"||n===null)return;let r=Object.entries(Object.getOwnPropertyDescriptors(n)).filter(([,s])=>s.enumerable&&(!("value"in s)||s.value!==void 0)),o=r.map(([s])=>s);if(o.some(s=>t_.has(s)&&!e.includes(s))){if(t!==void 0||o.some(s=>!t_.has(s)||e.includes(s)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(o.some(s=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(s)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(r.map(([s,a])=>"value"in a?[s,a.value]:[s,a.get?Reflect.apply(a.get,n,[]):void 0]))}}var jr=class extends p{constructor(){super(...arguments),ti.add(this),this.eventTypes=new ei(this._client)}create(e,t){return this._client.post("/webhook_endpoints",Fn(t,r=>({body:e,...r,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/webhook_endpoints/${e}`,Fn(t,r=>({...r,__security:{bearerAuth:!0}})))}update(e,t={},r){return this._client.post(l`/webhook_endpoints/${e}`,Fn(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}list(e={},t){let r=vO(e,["after","limit"],t);return r!==void 0&&(t=r,e={}),e=e,this._client.getAPIList("/webhook_endpoints",x,Fn(t,o=>({query:e,...o,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/webhook_endpoints/${e}`,Fn(t,r=>({...r,__security:{bearerAuth:!0}})))}rotateSecret(e,t={},r){return this._client.post(l`/webhook_endpoints/${e}/rotate_secret`,Fn(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}test(e,t,r){return this._client.post(l`/webhook_endpoints/${e}/test`,Fn(r,o=>({body:t,...o,__security:{bearerAuth:!0}})))}async unwrap(e,t,r=this._client.webhookSecret,o=300){return await this.verifySignature(e,t,r,o),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,o=300){if(typeof crypto>"u"||typeof crypto.subtle?.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");u(this,ti,"m",r_).call(this,r);let i=g([t]).values,s=u(this,ti,"m",xc).call(this,i,"webhook-signature"),a=u(this,ti,"m",xc).call(this,i,"webhook-timestamp"),c=u(this,ti,"m",xc).call(this,i,"webhook-id");if(yd(s)&&typeof crypto.subtle.sign!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");return await e_(e,s,a,c,r,o)}};ti=new WeakSet,r_=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},xc=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};jr.EventTypes=ei;var vc=Symbol.for("openai.privateBedrockClient");function bd(n){if(/^[\t ]|[\t ]$/.test(n))throw new TypeError("Bedrock bearer credential contains an invalid HTTP header value.");for(let e of n){let t=e.codePointAt(0)??0;if(t<32&&t!==9||t===127||t>255)throw new TypeError("Bedrock bearer credential contains an invalid HTTP header value.")}}function s_(n,e,t){let r=new Map(Object.entries(e).map(([o,i])=>[o.toLowerCase(),i]));for(let o of t)r.delete(o);for(let[o,i]of Object.entries(n.headers??{}))r.set(o,i);return{...n,headers:Object.fromEntries(r)}}var o_=new WeakMap;var Ic=Symbol.for("openai.realtimeAPIKeyCacheContext"),IO;function i_(n){let e=n[Ic]?.getStore();return e?.client===n?e:void 0}function Ca(n,e){return e!==null&&vc in n&&bd(e),e}async function wd(n,e=!1){let t,r={client:n,commit:()=>t===void 0?n.apiKey:t},o=c=>{t=c},i=()=>n._callApiKey(o),s=n[Ic]??IO;e&&s&&!n[Ic]&&Object.defineProperty(n,Ic,{value:s});let a=await(s?s.run(e?r:void 0,i):i());return{apiKey:t===void 0?n.apiKey:t,isProvider:a,commit:()=>{let c=r.providerKey!==void 0&&t!==void 0&&t!==r.providerKey?Ca(n,t):void 0,d=r.commit();return c===void 0?Ca(n,d):c}}}var a_=Symbol.for("openai.node.providerTimeout.v1");function u_(n){return n instanceof re||n instanceof Error&&a_ in n&&n[a_]===!0}var c_=Symbol.for("openai.node.providerDefinitions.v1"),l_=globalThis,d_=l_[c_],f_=d_??new WeakMap;d_||Object.defineProperty(l_,c_,{value:f_});function p_(n){let e=f_.get(n);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var ke,Te,Ta,Z,Sc,Ht,qa,ka,Ad,g_,ja,zn,h_,b_;function m_(){if(Bd())return!0;let n=globalThis;return typeof n.WorkerGlobalScope=="function"&&n instanceof n.WorkerGlobalScope&&typeof n.WorkerNavigator=="function"&&n.navigator instanceof n.WorkerNavigator&&typeof n.navigator?.userAgent=="string"&&n.navigator.userAgent!=="Cloudflare-Workers"&&n.process?.versions?.node===void 0&&n.Deno===void 0&&n.Bun===void 0&&n.EdgeRuntime===void 0&&n.WebSocketPair===void 0}var SO="workload-identity-auth",__=Symbol("inheritedDataResidencySelection"),D=class{constructor(e={}){ke.add(this),Ta.set(this,void 0),Z.set(this,void 0),Sc.set(this,void 0),Ht.set(this,void 0),qa.set(this,!1),ka.set(this,new WeakMap),this._apiKeyInvocation=0,this._lastCachedAPIKeyInvocation=0,this.decisions=new On(this),this.completions=new wn(this),this.chat=new lr(this),this.embeddings=new Pn(this),this.files=new vn(this),this.images=new Tn(this),this.contentProvenanceChecks=new Rn(this),this.audio=new nt(this),this.moderations=new jn(this),this.models=new kn(this),this.fineTuning=new dt(this),this.graders=new Er(this),this.vectorStores=new Qt(this),this.safety=new Wt(this),this.webhooks=new jr(this),this.beta=new Ke(this),this.batches=new nn(this),this.uploads=new kr(this),this.admin=new fr(this),this.responses=new It(this),this.live=new xt(this),this.realtime=new vt(this),this.conversations=new Ir(this),this.evals=new Sr(this),this.containers=new vr(this),this.skills=new Ut(this),this.videos=new Dn(this);let{credential:t,options:r}=xf(e);e=r;let o=Wc(e),i=e.provider,{baseURL:s=i?null:Ee("OPENAI_BASE_URL"),dataResidency:a,[__]:c=!1,apiKey:d=i?null:Ee("OPENAI_API_KEY")??null,adminAPIKey:h=i?null:Ee("OPENAI_ADMIN_KEY")??null,organization:_=i?null:Ee("OPENAI_ORG_ID")??null,project:m=i?null:Ee("OPENAI_PROJECT_ID")??null,webhookSecret:b=Ee("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:y,x509Transport:A,credential:O,...S}=e;if(i){let j=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter(C=>(C==="workloadIdentity"?y:e[C])!=null);if(j.length)throw new f(`The \`provider\` option cannot be used with ${j.map(C=>`\`${C}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let P=Za(y)?{x509:y,legacy:void 0}:{x509:void 0,legacy:y},q=P.x509,E=q!==void 0,z=i?p_(i):void 0,R={apiKey:d,adminAPIKey:h,organization:_,project:m,webhookSecret:b,workloadIdentity:y,x509Transport:A,provider:i,...S,baseURL:z?.baseURL??o??(s||(E?rf:"https://api.openai.com/v1"))};if(A&&!E)throw new f("An X.509 transport requires an X.509 workload identity.");if(E){if(o!==void 0||c)throw new f("X.509 workload identity does not support data residency selection.");if(e.fetch!==void 0)throw new f("X.509 workload identity does not support a custom fetch implementation.");if(Wn(R.baseURL),hi(R.fetchOptions),this.fetchWithAuth!==Te.prototype.fetchWithAuth||this.fetchWithTimeout!==Te.prototype.fetchWithTimeout)throw new f("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(d&&y)throw new f("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!z&&!d&&!h&&!y)throw new f("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!R.dangerouslyAllowBrowser&&m_())throw new f(`It looks like you're running in a browser-like environment.
24
+
25
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
26
+ If you understand the risks and have appropriate mitigations in place,
27
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
28
+
29
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
30
+
31
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
32
+ `);this.baseURL=R.baseURL,w(this,qa,o!==void 0||c,"f"),this.timeout=R.timeout??Te.DEFAULT_TIMEOUT,this.logger=u(this,ke,"m",b_).call(this,R.logger??console);let v="warn";this.logLevel=v,this.logLevel=$c(R.logLevel,"ClientOptions.logLevel",this)??$c(Ee("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??v,this.fetchOptions=R.fetchOptions,this.maxRetries=u(this,ke,"m",ja).call(this,R.maxRetries),this.fetch=R.fetch??oi(),w(this,Ta,Nd,"f");let I=i||t?void 0:Ee("OPENAI_CUSTOM_HEADERS");if(I){let j={};for(let C of I.split(`
33
+ `)){let $=C.indexOf(":");$>=0&&(j[C.substring(0,$).trim()]=C.substring($+1).trim())}R.defaultHeaders=g([j,R.defaultHeaders])}if(this._options=R,this._provider=z,q){let j=new Ae(q,A,_,m);this._workloadIdentityAuth=j,w(this,Z,j,"f"),w(this,Sc,t,"f"),w(this,Ht,j.fetch(),"f"),this.fetch=u(this,Ht,"f"),pf(this)}else P.legacy&&(this._workloadIdentityAuth=new Xa(P.legacy,this.fetch));this.apiKey=typeof d=="string"?d:null,this.adminAPIKey=h,this.organization=_,this.project=m,this.webhookSecret=b}withOptions(e){let t=Wc(e),r=u(this,Z,"f"),o={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:u(this,Z,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:r?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:i,provider:s}=vf(o,e,u(this,Sc,"f"),r!==void 0);t!==void 0&&delete o.baseURL;let a={...o,...e,credential:i,provider:s,[__]:u(this,qa,"f")&&t===void 0&&!k(e,"baseURL")&&e.credential===void 0&&!s},c=new this.constructor(a);return s&&new URL(c.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(c._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),c.fetchOptions=e.fetchOptions,c.fetch=e.fetch??oi(),c.organization=e.organization??null,c.project=e.project??null),u(this,Z,"f")&&u(c,Z,"f")&&this.baseURL===c.baseURL&&u(this,Z,"f").matches(u(c,Z,"f"))&&(c._workloadIdentityAuth=u(this,Z,"f"),w(c,Z,u(this,Z,"f"),"f"),w(c,Ht,u(this,Ht,"f"),"f")),c}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e,t){let r=o_.get(this);if(r?.baseHeaders)return s_({headers:r.baseHeaders},e,r.removedHeaders??new Set).headers;let o=g([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]);o.nulls.forEach(s=>(t??r?.removedHeaders)?.add(s));let i=Object.fromEntries(o.values);return r&&(r.baseHeaders={...i}),i}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return(u(this,Z,"f")??this._workloadIdentityAuth)instanceof Ae&&t.adminAPIKeyAuth&&this.adminAPIKey!==null?await this.adminAPIKeyAuth(e):g([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=u(this,Z,"f")??this._workloadIdentityAuth;if(t){if(t instanceof Ae){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==Te.prototype.fetchWithAuth||this.fetchWithTimeout!==Te.prototype.fetchWithTimeout))throw new f("X.509 workload identity does not support overridden fetch dispatch hooks.");let i=t.headerSnapshots();if(!Ae.shouldAuthenticate(e,i.defaultHeaders,i.requestHeaders))return}let o=t instanceof Ae?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken();return g([{Authorization:`Bearer ${o}`}])}let{apiKey:r}=await wd(this);if(r!=null)return g([{Authorization:`Bearer ${r}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return g([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return ef(e)}getUserAgent(){return`${this.constructor.name}/JS ${sr}`}defaultIdempotencyKey(){return`stainless-node-retry-${Me()}`}makeStatusError(e,t,r,o){let i=t&&typeof t=="object"&&t.error==null?{error:t}:t;return H.generate(e,i,r,o)}_hasApiKeyProvider(){return typeof this._options.apiKey=="function"}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;let t=this._options.apiKey;if(typeof t!="function")return e?.(this.apiKey),!1;let r=i_(this),o=++this._apiKeyInvocation,i;try{i=await t()}catch(d){throw d instanceof f?d:new f(`Failed to get token from 'apiKey' function: ${d.message}`,{cause:d})}if(typeof i!="string"||!i)throw new f(`Expected 'apiKey' function argument to return a string but it returned ${i}`);let s=i,a=()=>{if(e&&Ca(this,s),o<this._lastCachedAPIKeyInvocation)return s;this.apiKey=s;let d=e?this.apiKey:s;return this._lastCachedAPIKeyInvocation=o,d};r&&(r.providerKey=s,r.commit=a);let c=r?Ca(this,s):a();return e?.(c),!0}buildURL(e,t,r){let o=!u(this,ke,"m",g_).call(this)&&r||this.baseURL,i,s={},a;if(Od(e))i=new URL(e);else if(o.includes("?")){let _=new URL(o);a=new URLSearchParams(_.search),s=Object.fromEntries(a),_.search="",_.hash="",i=new URL(_.toString()+(_.pathname.endsWith("/")&&e.startsWith("/")?e.slice(1):e))}else i=new URL(o+(o.endsWith("/")&&e.startsWith("/")?e.slice(1):e));let c=this.defaultQuery(),d=Object.fromEntries(i.searchParams),h;if((!Da(s)||!Da(c)||!Da(d))&&(h={...d,...c,...t},t={...s,...h}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t),a&&h)){let _=new Set,m=new Set;for(let b of a.keys())_.has(b)&&!k(h,b)&&m.add(b),_.add(b);if(m.size){let b=new URLSearchParams;for(let[y,A]of i.searchParams)m.has(y)||b.append(y,A);for(let[y,A]of a)m.has(y)&&b.append(y,A);i.search=b.toString()}}return i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}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,r){return this.request(Promise.resolve(r).then(o=>({method:e,path:t,...o})))}request(e,t=null){let r=u(this,Z,"f")??this._workloadIdentityAuth,o=r instanceof Ae?Promise.resolve(e).then(i=>r.runRequest(()=>this.makeRequest(i,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(o)}responsePromise(e,t=(r,o)=>this.parseResponseWithTimeout(r,o)){let r=new kt(this,e,(o,i)=>{let s=u(this,ka,"f").get(i.controller)?.continueRequest;return s?s(()=>t(o,i)):t(o,i)});return r.withResponse=async()=>{let o=await r,{response:i}=await e;return{data:o,response:i,request_id:i.headers.get("x-request-id")}},r._thenUnwrap=o=>this.responsePromise(e,async(i,s)=>li(o(await t(i,s),s),s.response)),r}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||t.response.status===204||t.response.headers.get("content-length")==="0")return Fr(e,t);for(;;){let r=u(this,ka,"f").get(t.controller),o=r?.timeout??t.options.timeout??this.timeout,i=r?.authentication,s=i?t.controller.signal:t.options.signal,a=()=>i&&s?this._makeUserAbortError(s):new V,c;try{c=i?.remainingTimeout(t.options,o)??Math.max(0,t.startTime+o-Date.now())}catch(m){let b=s?.aborted?a():void 0;throw t.controller.abort(),ut(t.response.body).catch(()=>{}),b??m}let d,h,_=!1;try{if(s?.aborted&&r?.helperMethod!=="runTools")throw a();let m=new Promise((b,y)=>{d=setTimeout(()=>{_=!0,t.controller.abort(),y(new re)},c),s&&(h=()=>{_||y(a())},s.addEventListener("abort",h,{once:!0}))});return await Promise.race([Fr(e,t),m])}catch(m){if(s?.aborted&&!_)throw a();if(!_)throw i&&m instanceof SyntaxError?new SyntaxError("X.509 workload identity API response contains invalid JSON."):i&&!(m instanceof f)?new Xe({message:"X.509 workload identity API response body could not be read."}):m;let b=r?.retriesRemaining??0;if(!b||r?.hasStreamingBody||t.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&t.options.body instanceof globalThis.ReadableStream||typeof t.options.body=="object"&&t.options.body!==null&&(Symbol.asyncIterator in t.options.body||Symbol.iterator in t.options.body&&"next"in t.options.body&&typeof t.options.body.next=="function"))throw new re;d!==void 0&&clearTimeout(d),h&&s?.removeEventListener("abort",h),h=void 0;let y=await this.retryRequest(t.options,b,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,y)}finally{d!==void 0&&clearTimeout(d),h&&s?.removeEventListener("abort",h)}}}async readX509ResponseError(e,t,r,o,i){let s=new AbortController,a=o.signal,c=!1,d=()=>s.abort(a.reason);a.addEventListener("abort",d,{once:!0}),a.aborted&&d();try{let h=i.remainingTimeout(t,r),_=i.waitForRetry(h,s.signal).then(()=>{throw new re}),m=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),_]);if(a.aborted)throw this._makeUserAbortError(a);return m}catch(h){throw h instanceof re&&(c=!a.aborted,o.abort(),ut(e.body).catch(()=>{})),a.aborted&&!c?this._makeUserAbortError(a):h}finally{a.removeEventListener("abort",d),s.abort()}}async makeRequest(e,t,r){let o=await e,i=u(this,ke,"m",ja).call(this,o.maxRetries??this.maxRetries);t==null?t=i:t=Math.min(u(this,ke,"m",ja).call(this,t),i);let s=u(this,Z,"f");s?.beginRequestPreparation(),await this.prepareOptions(o),s?.beginRequestPlanning();let a;try{let $=await this.buildRequest(o,{retryCount:i-t});if(a={req:$.req,url:$.url,timeout:$.timeout},s){Tc("timeout",a.timeout),s.authorizePlannedRequest(a.url,a.req,a.timeout),Ae.isStreamingRequestBody(a.req.body)&&(o.__metadata={...o.__metadata,hasStreamingBody:!0}),await this.prepareRequest(a.req,{url:a.url,options:o}),await this._provider?.prepareRequest?.(a.req,{url:a.url,options:o,timeout:a.timeout}),s.beginRequestPlanning(),s.authorizePlannedRequest(a.url,a.req,a.timeout,!0),Ae.isStreamingRequestBody(a.req.body)&&(o.__metadata={...o.__metadata,hasStreamingBody:!0});let T=s.requestSnapshot().signal;if(T?.aborted||a.req.signal?.aborted)throw this._makeUserAbortError(T?.aborted?T:a.req.signal);s.setEffectiveSignal(a.req.signal||T?y_(a.req.signal??T,T).signal:void 0),s.beginRequestNetwork();let F=o.__security??{bearerAuth:!0},K=await this.authHeaders(o,F),W=s.headerSnapshots(),M=g([W.defaultHeaders,W.requestHeaders]);for(let[te,X]of K?.values??[])!M.nulls.has(te)&&!a.req.headers.has(te)&&a.req.headers.set(te,X);this.validateHeaders(g([M,a.req.headers]),F)}}catch($){if(s?.retireRequestBody(),s&&t&&!o.__metadata?.hasStreamingBody&&Ae.isRetryableFailure($))return await this.retryRequest(o,t,r??"x509-token-exchange",Ae.retryHeaders($));throw $}let{req:c,url:d}=a,h=s?Math.min(a.timeout,s.requestSnapshot().timeout):a.timeout;s?.bindRequest(o,c,this.adminAPIKey);let _=o.__metadata?.hasStreamingBody===!0,m,b;if(!s){await this.prepareRequest(c,{url:d,options:o}),this._provider?.timeoutIncludesAuth&&(m={wallTime:Date.now(),monotonicTime:performance.now()});try{await this._provider?.prepareRequest?.(c,{url:d,options:o,timeout:h})}catch($){if(!m||!u_($))throw $;b=$}}s?.adoptRequestHeaders(c),s&&Ae.isStreamingRequestBody(c.body)&&(_=!0);let y="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),A=r===void 0?"":`, retryOf: ${r}`,O=s?.requestStartedAt(o)??m?.wallTime??Date.now();if(this.logLevel==="debug"){let $=typeof c.body=="string"?{type:"string",length:c.body.length}:c.body;ie(this).debug(`[${y}] sending request`,Tt({retryOfRequestLogID:r,method:o.method,url:d,options:s?{body:$,...s.requestSnapshot()}:{...o,body:$},headers:c.headers}))}let S=s?s.requestSnapshot().signal:o.signal;if(S?.aborted||c.signal?.aborted)throw this._makeUserAbortError(S?.aborted?S:c.signal);let P=o.__security??{bearerAuth:!0},q=s||this.fetchWithTimeout===Te.prototype.fetchWithTimeout?y_(c.signal??(s?S:void 0),s?S:void 0):new AbortController,E=s?.remainingTimeout(o,h)??(m?h-(performance.now()-m.monotonicTime):h);m&&E<=0&&(b??(b=new re));let z=s?Te.prototype.fetchWithAuth:this.fetchWithAuth;s?.releaseRequestBody(c.body);let R=b??await z.call(this,d,c,E,q,P).catch(ri),v=Date.now();if(R instanceof globalThis.Error){let $=`retrying, ${t} attempts remaining`;if(S?.aborted||c.signal?.aborted)throw this._makeUserAbortError(S?.aborted?S:c.signal);let T=Ct(R)||/timed? ?out/i.test(String(R)+("cause"in R?String(R.cause):""));if(t&&!_&&(!s||Va(R)))return ie(this).info(`[${y}] connection ${T?"timed out":"failed"} - ${$}`),ie(this).debug(`[${y}] connection ${T?"timed out":"failed"} (${$})`,Tt({retryOfRequestLogID:r,url:d,durationMs:v-O,message:s?"X.509 workload identity API connection failed.":R.message})),this.retryRequest(o,t,r??y,void 0,c.signal);let F=_?"error; streaming body cannot be retried":"error; no more retries left";if(ie(this).info(`[${y}] connection ${T?"timed out":"failed"} - ${F}`),ie(this).debug(`[${y}] connection ${T?"timed out":"failed"} (${F})`,Tt({retryOfRequestLogID:r,url:d,durationMs:v-O,message:s?"X.509 workload identity API connection failed.":R.message})),R instanceof Je||R instanceof qr)throw R;if(T){let K="cause"in R?R.cause:void 0,M=typeof K=="object"&&K!==null&&"code"in K&&K.code==="UND_ERR_HEADERS_TIMEOUT"?new re({message:"Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout."}):new re;throw s?new re:Object.assign(M,{cause:R})}throw s?new Xe({message:"X.509 workload identity API connection failed."}):new Xe({message:EO(R),cause:R})}let I=[...R.headers.entries()].filter(([$])=>$==="x-request-id").map(([$,T])=>", "+$+": "+JSON.stringify(T)).join(""),j=`[${y}${A}${I}] ${c.method} ${Ba(d)} ${R.ok?"succeeded":"failed"} with status ${R.status} in ${v-O}ms`;if(!R.ok){let $=R.status===401&&s&&P.bearerAuth&&s.usedWorkloadToken(o);if($&&s.invalidateToken(),R.status===401&&(s||this._workloadIdentityAuth)&&P.bearerAuth&&(!s||s.usedWorkloadToken(o))&&(!s||t>0)&&!_&&!o.__metadata?.workloadIdentityTokenRefreshed){s?ut(R.body).catch(()=>{}):(await ut(R.body),this._workloadIdentityAuth?.invalidateToken());let X={...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(X,s?t-1:t,r??y)}let T=$&&o.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(R);if(t&&T&&!_){let X=`retrying, ${t} attempts remaining`;return s?ut(R.body).catch(()=>{}):await ut(R.body),ie(this).info(`${j} - ${X}`),ie(this).debug(`[${y}] response error (${X})`,Tt({retryOfRequestLogID:r,url:R.url,status:R.status,headers:R.headers,durationMs:v-O})),this.retryRequest(o,t,r??y,R.headers,c.signal)}let F=T?_?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";ie(this).info(`${j} - ${F}`);let K=s?await this.readX509ResponseError(R,o,h,q,s):await R.text().catch(X=>ri(X).message),W=xd(K),M=W?void 0:K;throw ie(this).debug(`[${y}] response error (${F})`,Tt({retryOfRequestLogID:r,url:R.url,status:R.status,headers:R.headers,message:M,durationMs:Date.now()-O})),this.makeStatusError(R.status,W,M,R.headers)}ie(this).info(j),ie(this).debug(`[${y}] response start`,Tt({retryOfRequestLogID:r,url:R.url,status:R.status,headers:R.headers,durationMs:v-O}));let C=s?.continuation();return s?.releaseRequestCredentials(),u(this,ka,"f").set(q,{timeout:h,retriesRemaining:t,hasStreamingBody:_,...s?{authentication:s}:{},helperMethod:o.__metadata?.helperMethod,...C?{continueRequest:C}:{}}),{response:R,options:o,controller:q,requestSignal:c.signal,requestLogID:y,retryOfRequestLogID:r,startTime:O}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(o=>({method:"get",path:e,...o})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=u(this,Z,"f")??this._workloadIdentityAuth,o=r instanceof Ae?Promise.resolve(t).then(a=>r.runRequest(()=>this.makeRequest(a,null,void 0),this)):this.makeRequest(t,null,void 0),i=new pi(this,o,e),s=this.responsePromise(o,async(a,c)=>{let d=await this.parseResponseWithTimeout(a,c);return new e(a,c.response,d,c.options)});return i.then=s.then.bind(s),i.catch=s.catch.bind(s),i.finally=s.finally.bind(s),i.withResponse=s.withResponse.bind(s),i._thenUnwrap=s._thenUnwrap.bind(s),i}async fetchWithAuth(e,t,r,o,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!u(this,Ht,"f")&&i.bearerAuth){let c=t.headers;if(c.get("Authorization")===`Bearer ${SO}`){let h=await this._workloadIdentityAuth.getToken();c.set("Authorization",`Bearer ${h}`)}}return await(u(this,Ht,"f")?Te.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,r,o)}async fetchWithTimeout(e,t,r,o){let{signal:i,method:s,...a}=t||{},c=this._makeAbort(o),d=!!i&&w_.get(o)===i,h=i&&!d?Id(i,c,o.signal):void 0,_=setTimeout(c,r),m=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,b={signal:o.signal,...m?{duplex:"half"}:{},method:"GET",...a};s&&(b.method=s.toUpperCase());try{let y=await(u(this,Ht,"f")??this.fetch).call(void 0,e,b);return h&&kc(y.body??y,c,o.signal),y}catch(y){throw h?.(),y}finally{clearTimeout(_)}}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,r,o,i=e.signal){let s,a=o?.get("retry-after-ms");if(a){let h=parseFloat(a);Number.isNaN(h)||(s=h)}let c=o?.get("retry-after");if(c&&s===void 0){let h=parseFloat(c);Number.isNaN(h)?s=Date.parse(c)-Date.now():s=h*1e3}if(s===void 0||!Number.isFinite(s)||s<0||s>60*1e3){let h=u(this,ke,"m",ja).call(this,e.maxRetries??this.maxRetries);s=this.calculateDefaultRetryTimeoutMillis(t,h)}let d=u(this,Z,"f");if(d){let h=d.remainingTimeout(e,d.requestSnapshot().timeout);if(s>=h)throw new re}if(d)await d.waitForRetry(s,d.effectiveSignal());else{let h=i===e.signal?[i]:[i,e.signal];try{await Bn(s,...h)}catch(_){let m=h.find(b=>b?.aborted);throw m?this._makeUserAbortError(m):_}}return this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,s=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return s*a*1e3}async buildRequest(e,{retryCount:t=0}={}){if(u(this,Z,"f")&&!u(this,Z,"f").inRequest(this)){let W=u(this,Z,"f");return await W.runRequest(async()=>{let M=await Te.prototype.buildRequest.call(this,e,{retryCount:t});return W.releaseRequestBody(M.req.body),M},this)}let r={...e},o=u(this,Z,"f"),i=o?.snapshotTenant(this.organization,this.project),s=o?.snapshotHeaders(this._options.defaultHeaders,r.headers);s&&(r.headers=s.requestHeaders);let a=o?Yc(this.fetchOptions):void 0,c=o?Yc(r.fetchOptions):void 0,{method:d,path:h,query:_,defaultBaseURL:m}=r,b=this.buildURL(h,_,m);o?.snapshotAPIURL(b);let y="timeout"in r;if(y&&Tc("timeout",r.timeout),r.timeout=r.timeout??this.timeout,o&&c&&o.snapshotRequest(r.signal,r.timeout,c),o){let W=o.requestSnapshot();r.timeout=W.timeout,W.signal===void 0?delete r.signal:r.signal=W.signal}let A=this._provider||o?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0});if(r.__metadata?.finalizeMultipart===!0&&_i(r.body)){let W=g([r.headers]);W.values.delete("content-type"),W.nulls.delete("content-type");let M=await bt({...r,headers:W},this,r.__metadata?.preserveMultipartFilenames===!0?{stripFilenames:!1}:void 0);e.body=r.body=M.body,r.headers=M.headers,e.__metadata=r.__metadata={...M.__metadata,finalizedMultipart:{body:M.body,contentType:g([M.headers]).values.get("content-type")}}}r.__metadata?.streamFromBody===!0&&(jf(r),e.stream=r.stream);let O=JSON.isRawJSON,S,P=!1,q=!1,E=!1,z=r.__metadata?.streamFromBody===!0&&typeof r.body=="object"&&r.body!==null?Qa(r.body,{value(W,M,te){if(!P)P=!0,S=te;else if(W===S&&M==="stream"){if(q=te===!0,O?.(te))q=te.rawJSON==="true";else if(te!==null&&typeof te=="object")try{q=Boolean.prototype.valueOf.call(te)}catch{}}},complete(){E=!0}}):void 0,R;try{R=this.buildBody({options:r})}finally{z?.()}let{bodyHeaders:v,body:I,isStreamingBody:j}=R,C=r.__metadata?.captureResponseParser;typeof C=="function"&&C(r),r.__metadata?.streamFromBody===!0&&(I instanceof FormData?e.stream=r.stream=I.get("stream")==="true":E&&S!==null&&typeof S=="object"&&!Array.isArray(S)&&!O?.(S)&&(e.stream=r.stream=q)),j&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},o?.ownRequestBody(I,r.body));let $,T=r.__metadata?.finalizedMultipart;if(typeof T=="object"&&T!==null&&"body"in T&&"contentType"in T){let{body:W,contentType:M}=T;W===I&&(typeof M=="string"?$=M:M===null&&($=null))}let F=await this.buildHeaders({options:e,method:d,bodyHeaders:v,authenticationHeaders:A,retryCount:t,x509Headers:s,x509Timeout:y?r.timeout:void 0,x509Tenant:i});return $===null?F.delete("content-type"):$!==void 0&&F.set("content-type",$),{req:{method:d,headers:F,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&I instanceof globalThis.ReadableStream&&{duplex:"half"},...I&&{body:I},...(o?a:this.fetchOptions)??{},...(o?c:r.fetchOptions)??{}},url:b,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,authenticationHeaders:o,retryCount:i,x509Headers:s,x509Timeout:a,x509Tenant:c}){let d={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),d[this.idempotencyHeader]=e.idempotencyKey);let h=e.__metadata?.helperMethod,_=s?a:e.timeout,m=g([d,{Accept:"application/json",...m_()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(i),..._?{"X-Stainless-Timeout":String(Math.trunc(_/1e3))}:{},...Kd(),...typeof h=="string"?{"X-Stainless-Helper-Method":h}:{},"OpenAI-Organization":c?c.organization:this.organization,"OpenAI-Project":c?c.project:this.project},u(this,Z,"f")&&!u(this,Z,"f").isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):o,s?.defaultHeaders??this._options.defaultHeaders,r,s?.requestHeaders??e.headers]);return!this._provider&&!u(this,Z,"f")?.isPlanningRequest()&&this.validateHeaders(m,e.__security??{bearerAuth:!0}),m.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new V;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...u(this,Ta,"f").call(this,{body:t,headers:g([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let o=g([r]),i=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,s=!i&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&o.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!s}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:ii(t),isStreamingBody:!0}:typeof t=="object"&&o.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...u(this,Ta,"f").call(this,{body:t,headers:o}),isStreamingBody:!1}}};Te=D,Ta=new WeakMap,Z=new WeakMap,Sc=new WeakMap,Ht=new WeakMap,qa=new WeakMap,ka=new WeakMap,ke=new WeakSet,g_=function(){return u(this,qa,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"},ja=function(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:2},zn=function(e){let t=e.replace(/[^a-z0-9]/gi,"").toLowerCase();if(/authorization|authentication|cookie|session|signature|assertion|connectionstring|devicecode|codeverifier|accountkey|mtlskey|proxyauth|^(?:auth|key|sig|sas|jwt|bearer|pfx|p12)$|(?:sid|token|secret|password|passwd|pwd|credential|passphrase|apikey|accesskey|privatekey|username)s?$/.test(t))return!0;let r=/api|access|secret|private|security|refresh|id|bearer|aws|azure|openai|admin|client|proxy|auth/.exec(t);return r!==null&&/key|token|secret|password|passwd|pwd|credential|auth/.test(t.slice(r.index+r[0].length))},h_=function(e,t){let i=b=>b.replace(/(\/\/)([^/\s?#]*@)(?=[^/\s?#]+)/g,"$1[REDACTED]@").replace(/(^|[\s/])([^/\s]+)/g,(y,A,O)=>{let S=A==="/"?O.search(/[=(]/)+1:0;if(A==="/"&&S===0)return y;let P=O.indexOf(":",S+1),q=O.length-2;for(;q>=0&&(O[q]!=="@"||O[q+1]==="@");)q--;return P>=0&&q>P?`${A}${O.slice(0,S)}[REDACTED]${O.slice(q)}`:y}).replace(/(^|[\s,;])([a-z][a-z0-9_-]*)(\s*:\s*)([^\r\n,;]+)/gi,(y,A,O,S)=>u(this,ke,"m",zn).call(this,O)?`${A}${O}${S}[REDACTED]`:y).replace(/(^|[?&#;])([^=&;\s?#/]+)=([^&;\s#]+)/g,(y,A,O)=>{let S=O;try{S=globalThis.decodeURIComponent(O)}catch{}return u(this,ke,"m",zn).call(this,S)?`${A}${O}=[REDACTED]`:y}),s=b=>{try{return globalThis.String.prototype.valueOf.call(b)}catch{return}},a=b=>{let y=s(b);if(y!==void 0)return u(this,ke,"m",zn).call(this,y);try{return b instanceof globalThis.String}catch{return!0}},c=[],d=[],h,_=(b,y)=>{try{return{descriptor:globalThis.Object.getOwnPropertyDescriptor(b,y),failed:!1}}catch{return{descriptor:void 0,failed:!0}}},m=(b,y,A)=>{if(y>64||c.length>=4096){A("[REDACTED]");return}c.push({value:b,depth:y,assign:A})};m(e,0,b=>{h=b});for(let b=0;b<c.length;b+=1){let{value:y,depth:A,assign:O}=c[b];if(typeof y=="string"){O(i(y));continue}if(typeof y=="function"||typeof y=="symbol"){O("[REDACTED]");continue}if(typeof y!="object"||y===null){O(y);continue}let S=t.get(y);if(S!==void 0){O(S);continue}try{let P=s(y);if(P!==void 0){let v=new globalThis.String(i(P));t.set(y,v),O(v);continue}if(y instanceof globalThis.String){t.set(y,"[REDACTED]"),O("[REDACTED]");continue}let q=globalThis.Headers;if(typeof q=="function"&&y instanceof q){let v=new q;t.set(y,v),O(v),q.prototype.forEach.call(y,(I,j)=>{v.set(j,u(this,ke,"m",zn).call(this,j)?"[REDACTED]":i(I))});continue}if(y instanceof URL){let v=new URL(URL.prototype.toString.call(y));t.set(y,v),O(v),v.username&&(v.username="[REDACTED]"),v.password&&(v.password="[REDACTED]");for(let[I]of v.searchParams)u(this,ke,"m",zn).call(this,I)&&v.searchParams.set(I,"[REDACTED]");v.hash&&(v.hash=i(v.hash));continue}if(Array.isArray(y)){let v=_(y,"length");if(v.failed||!v.descriptor||!("value"in v.descriptor)||typeof v.descriptor.value!="number"){t.set(y,"[REDACTED]"),O("[REDACTED]");continue}let I=[];t.set(y,I),O(I);let j=Math.min(v.descriptor.value,4096),C=_(y,"0"),$=!C.failed&&C.descriptor&&"value"in C.descriptor?C.descriptor.value:void 0;for(let T=0;T<j;T+=1){let F=T===0?C:_(y,`${T}`);if(F.failed){I[T]="[REDACTED]";continue}let K=F.descriptor;if(K?.enumerable){if(T===1&&(C.failed||C.descriptor&&!("value"in C.descriptor)||a($))){I[T]="[REDACTED]";continue}if(!("value"in K)){I[T]="[REDACTED]";continue}m(K.value,A+1,W=>{I[T]=W})}}I.length=j,v.descriptor.value>j&&(I[j]="[REDACTED]");continue}if(y instanceof globalThis.Map){let v=new globalThis.Map,I=[];d.push({map:v,entries:I}),t.set(y,v),O(v),globalThis.Map.prototype.forEach.call(y,(j,C)=>{let $=["[REDACTED]","[REDACTED]"];I.push($),m(C,A+1,T=>{typeof T!="function"&&typeof T!="symbol"&&!(typeof C=="object"&&C!==null&&T===C)&&($[0]=T)}),!a(C)&&m(j,A+1,T=>{$[1]=T})});continue}if(y instanceof globalThis.Set){let v=new globalThis.Set;t.set(y,v),O(v),globalThis.Set.prototype.forEach.call(y,I=>{m(I,A+1,j=>{v.add(j)})});continue}if(y instanceof globalThis.Date){O(new globalThis.Date(globalThis.Date.prototype.getTime.call(y)));continue}let E=globalThis.ReadableStream;if(typeof E=="function"&&y instanceof E||y instanceof globalThis.ArrayBuffer||globalThis.ArrayBuffer.isView(y)){t.set(y,"[REDACTED]"),O("[REDACTED]");continue}let z;try{z=globalThis.Reflect.ownKeys(y)}catch{t.set(y,"[REDACTED]"),O("[REDACTED]");continue}let R={};t.set(y,R),O(R);for(let v of z){if(typeof v!="string")continue;let I=_(y,v);if(I.failed){R[v]="[REDACTED]";continue}let j=I.descriptor;if(j?.enumerable){if(u(this,ke,"m",zn).call(this,v)){R[v]="[REDACTED]";continue}if(!("value"in j)){R[v]="[REDACTED]";continue}m(j.value,A+1,C=>{R[v]=C})}}}catch{t.set(y,"[REDACTED]"),O("[REDACTED]")}}for(let{map:b,entries:y}of d)for(let[A,O]of y)b.set(A,O);return h},b_=function(e){if(u(Te,Te,"f",Ad).has(e))return e;let t=new globalThis.Proxy(Object.create(null),{get:(r,o)=>{let i=globalThis.Reflect.get(e,o,e);return typeof i!="function"?i:typeof o!="string"||!["debug","info","warn","error","trace","log"].includes(o)?i.bind(e):(...s)=>{let a=new WeakMap;return globalThis.Reflect.apply(i,e,s.map(c=>u(this,ke,"m",h_).call(this,c,a)))}},set:(r,o,i)=>globalThis.Reflect.set(e,o,i,e)});return u(Te,Te,"f",Ad).add(t),t};Ad={value:new globalThis.WeakSet};D.OpenAI=Te;D.DEFAULT_TIMEOUT=6e5;D.OpenAIError=f;D.APIError=H;D.APIConnectionError=Xe;D.APIConnectionTimeoutError=re;D.APIUserAbortError=V;D.NotFoundError=Gt;D.ConflictError=Yt;D.RateLimitError=er;D.BadRequestError=mt;D.AuthenticationError=Jt;D.InternalServerError=tr;D.PermissionDeniedError=Vt;D.UnprocessableEntityError=Zt;D.InvalidWebhookSignatureError=qe;D.toFile=su;D.toStreamingFile=tu;D.Decisions=On;D.Completions=wn;D.Chat=lr;D.Embeddings=Pn;D.Files=vn;D.Images=Tn;D.ContentProvenanceChecks=Rn;D.Audio=nt;D.Moderations=jn;D.Models=kn;D.FineTuning=dt;D.Graders=Er;D.VectorStores=Qt;D.Safety=Wt;D.Webhooks=jr;D.Beta=Ke;D.Batches=nn;D.Uploads=kr;D.Admin=fr;D.Responses=It;D.Live=xt;D.Realtime=vt;D.Conversations=Ir;D.Evals=Sr;D.Containers=vr;D.Skills=Ut;D.Videos=Dn;D.ConversationCursorPage=N;D.CursorPage=x;D.NextCursorPage=se;D.Page=_e;D.TokenPage=Nn;var w_=new WeakMap;function y_(n,e){let t=new AbortController;if(!n)return t;let r=globalThis.AbortSignal;if(typeof r?.any!="function"||!(n instanceof r))return t;try{let o=[t.signal,n];e&&e!==n&&o.push(e);let i=r.any(o);Object.defineProperty(t,"signal",{value:i,configurable:!0}),w_.set(t,n)}catch{}return t}function EO(n){if(CO(n))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 CO(n){let e=n;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Rd=class extends D{constructor({baseURL:e=Ee("OPENAI_BASE_URL"),apiKey:t=Ee("AZURE_OPENAI_API_KEY"),apiVersion:r=Ee("OPENAI_API_VERSION"),endpoint:o,deployment:i,azureADTokenProvider:s,dangerouslyAllowBrowser:a,dataResidency:c,...d}={}){if(Uc(c,"AzureOpenAI"),!r)throw new f("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof s=="function"&&(a??(a=!0)),!s&&!t)throw new f("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(s&&t)throw new f("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(d.defaultQuery={...d.defaultQuery,"api-version":r},e){if(o)throw new f("baseURL and endpoint are mutually exclusive")}else{if(o||(o=process.env.AZURE_OPENAI_ENDPOINT),!o)throw new f("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let h=o.length;for(;h>0&&o[h-1]==="/";)h--;e=`${o.slice(0,h)}/openai`}super({apiKey:s??t,baseURL:e,...d,...a===void 0?{}:{dangerouslyAllowBrowser:a}}),this.apiVersion="",this.apiVersion=r,this.deploymentName=i}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};return k(e,"endpoint")&&e.endpoint!==void 0&&!k(e,"baseURL")&&(t.baseURL=void 0),super.withOptions(t)}async buildRequest(e,t={}){if(kO.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!U(e.body))throw new Error("Expected request body to be an object");let o=this.deploymentName||e.body.model||e.__metadata?.model;o!==void 0&&!TO(this.baseURL)&&(e.path=l`/deployments/${o}`+e.path)}let r=await super.buildRequest(e,t);return r.req.headers.has("api-key")&&(r.req.redirect="manual"),r}async fetchWithAuth(e,t,r,o,i){return new Headers(t.headers).has("api-key")&&(t.redirect="manual"),super.fetchWithAuth(e,t,r,o,i)}async authHeaders(e,t){let r=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return r.bearerAuth&&typeof this._options.apiKey=="string"?g([{"api-key":this.apiKey}]):super.authHeaders(e,r)}};function TO(n){try{return new URL(n).pathname.split("/").includes("deployments")}catch{return!1}}var kO=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var jO;jO=vc;export{D as a,Rd as b};