drizzle-cube 0.9.7 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/dist/adapters/ActivityGridChart.config-BW77mjsu.cjs +1 -0
  2. package/dist/adapters/ActivityGridChart.config-DQRnTU6e.js +2 -0
  3. package/dist/adapters/AreaChart.config-DbvLVr-Y.cjs +1 -0
  4. package/dist/adapters/AreaChart.config-JbVNmary.js +2 -0
  5. package/dist/adapters/BarChart.config-Bkpwgqbk.js +2 -0
  6. package/dist/adapters/BarChart.config-jgDE3NUv.cjs +1 -0
  7. package/dist/adapters/BoxPlotChart.config-9wKKOZfN.cjs +1 -0
  8. package/dist/adapters/BoxPlotChart.config-Di99sPNJ.js +2 -0
  9. package/dist/adapters/BubbleChart.config-Cdg9nPFz.js +2 -0
  10. package/dist/adapters/BubbleChart.config-CwDXzdxC.cjs +1 -0
  11. package/dist/adapters/CandlestickChart.config-B45GmJYV.js +2 -0
  12. package/dist/adapters/CandlestickChart.config-C8BXzmbD.cjs +1 -0
  13. package/dist/adapters/DataTable.config-c-24M_qU.cjs +1 -0
  14. package/dist/adapters/DataTable.config-fic2OroS.js +2 -0
  15. package/dist/adapters/DotStripChart.config-BcNT3Les.cjs +1 -0
  16. package/dist/adapters/DotStripChart.config-Cqmgw5_z.js +2 -0
  17. package/dist/adapters/FunnelChart.config-D1E5zSay.cjs +1 -0
  18. package/dist/adapters/FunnelChart.config-DPjSoYex.js +2 -0
  19. package/dist/adapters/GaugeChart.config-BDcvnYln.js +2 -0
  20. package/dist/adapters/GaugeChart.config-DQnx37Jf.cjs +1 -0
  21. package/dist/adapters/HeatMapChart.config-BWd863ik.js +2 -0
  22. package/dist/adapters/HeatMapChart.config-HEbSm_Zt.cjs +1 -0
  23. package/dist/adapters/KpiDelta.config-Bj3kfmWv.js +2 -0
  24. package/dist/adapters/KpiDelta.config-CaLnl2w_.cjs +1 -0
  25. package/dist/adapters/KpiNumber.config-Da9HxGT8.cjs +1 -0
  26. package/dist/adapters/KpiNumber.config-n4SwHHlD.js +2 -0
  27. package/dist/adapters/KpiText.config-8VzcnlPF.cjs +1 -0
  28. package/dist/adapters/KpiText.config-CItv_gG6.js +2 -0
  29. package/dist/adapters/LineChart.config-DQ7nHYrr.js +2 -0
  30. package/dist/adapters/LineChart.config-_98RmRA_.cjs +1 -0
  31. package/dist/adapters/MarkdownChart.config-BpbqJDoz.cjs +1 -0
  32. package/dist/adapters/MarkdownChart.config-Dz7KZ621.js +2 -0
  33. package/dist/adapters/MeasureProfileChart.config-BTCTP7L0.js +2 -0
  34. package/dist/adapters/MeasureProfileChart.config-DzPxIxB5.cjs +1 -0
  35. package/dist/adapters/PieChart.config-BhjlnVFv.js +2 -0
  36. package/dist/adapters/PieChart.config-DJlGNsBY.cjs +1 -0
  37. package/dist/adapters/ProportionBarChart.config-Byp_8diR.cjs +1 -0
  38. package/dist/adapters/ProportionBarChart.config-RyjNhw3T.js +2 -0
  39. package/dist/adapters/RadarChart.config-BWdv4uyp.js +2 -0
  40. package/dist/adapters/RadarChart.config-kW4oIVi4.cjs +1 -0
  41. package/dist/adapters/RadialBarChart.config-CFYPoRQY.cjs +1 -0
  42. package/dist/adapters/RadialBarChart.config-D2-_-Z64.js +2 -0
  43. package/dist/adapters/RecordsTable.config-B7KFt3kd.cjs +1 -0
  44. package/dist/adapters/RecordsTable.config-S_aiXGKe.js +2 -0
  45. package/dist/adapters/RetentionCombinedChart.config-CVGWozL3.js +2 -0
  46. package/dist/adapters/RetentionCombinedChart.config-Cd0pTdHY.cjs +1 -0
  47. package/dist/adapters/RetentionHeatmap.config-BNqtWFjQ.js +2 -0
  48. package/dist/adapters/RetentionHeatmap.config-CMi1h_5M.cjs +1 -0
  49. package/dist/adapters/SankeyChart.config-COIfx3Ua.cjs +1 -0
  50. package/dist/adapters/SankeyChart.config-DIh4nEk2.js +2 -0
  51. package/dist/adapters/ScatterChart.config-CrSQhlT4.js +2 -0
  52. package/dist/adapters/ScatterChart.config-DRgg-HAm.cjs +1 -0
  53. package/dist/adapters/SunburstChart.config-08-ufQaK.cjs +1 -0
  54. package/dist/adapters/SunburstChart.config-DmNgAJrO.js +2 -0
  55. package/dist/adapters/TreeMapChart.config-7k2repRB.cjs +1 -0
  56. package/dist/adapters/TreeMapChart.config-C3vzB2dD.js +2 -0
  57. package/dist/adapters/WaterfallChart.config-AV2pHgrb.js +2 -0
  58. package/dist/adapters/WaterfallChart.config-USpcvapo.cjs +1 -0
  59. package/dist/adapters/express/index.cjs +1 -1
  60. package/dist/adapters/express/index.js +1 -1
  61. package/dist/adapters/fastify/index.cjs +1 -1
  62. package/dist/adapters/fastify/index.js +1 -1
  63. package/dist/adapters/{handler-DtX1YNOn.js → handler-B1_zd-qo.js} +30 -30
  64. package/dist/adapters/{handler-CTSg1daG.cjs → handler-CfZt5W8b.cjs} +2 -2
  65. package/dist/adapters/hono/index.cjs +1 -1
  66. package/dist/adapters/hono/index.js +1 -1
  67. package/dist/adapters/mcp-app-html-BNg78ecJ.js +5 -0
  68. package/dist/adapters/mcp-app-html-N18EJEvv.cjs +1 -0
  69. package/dist/adapters/mcp-app-html.cjs +1 -1
  70. package/dist/adapters/mcp-app-html.js +1 -1
  71. package/dist/adapters/mcp-tools.cjs +1 -1
  72. package/dist/adapters/mcp-tools.js +1 -1
  73. package/dist/adapters/nextjs/index.cjs +1 -1
  74. package/dist/adapters/nextjs/index.d.ts +7 -1
  75. package/dist/adapters/nextjs/index.js +1 -1
  76. package/dist/adapters/{openai-CWnhWp3I.js → openai-BpcMIv4e.js} +1 -1
  77. package/dist/adapters/openai-Br__Bn2t.cjs +19 -0
  78. package/dist/adapters/{openai-BwtOIJIk.cjs → openai-C32tey5N.cjs} +1 -1
  79. package/dist/adapters/{openai-Dqrs3PGo.js → openai-yfJF-3Rv.js} +3178 -2648
  80. package/dist/cjs/adapters/nextjs/index.d.ts +7 -1
  81. package/dist/cjs/client/components/AnalysisBuilder/AnalysisModeErrorBoundary.d.ts +1 -1
  82. package/dist/cjs/client/components/AnalysisBuilder/FilterValueInput.d.ts +1 -1
  83. package/dist/cjs/client/components/AnalysisBuilder/hooks/useFieldSearchKeyboard.d.ts +1 -1
  84. package/dist/cjs/client/components/AnalyticsPortlet.d.ts +1 -1
  85. package/dist/cjs/client/components/ChartErrorBoundary.d.ts +1 -1
  86. package/dist/cjs/client/components/DashboardFilters/CompactFilterBarParts.d.ts +2 -2
  87. package/dist/cjs/client/components/DashboardFilters/CustomDateDropdown.d.ts +1 -1
  88. package/dist/cjs/client/components/DashboardFilters/FilterValuePopover.d.ts +1 -1
  89. package/dist/cjs/client/components/DashboardFilters/XTDDropdown.d.ts +1 -1
  90. package/dist/cjs/client/components/DashboardFilters/useCompactFilterBar.d.ts +2 -2
  91. package/dist/cjs/client/components/DashboardFilters/useDashboardFilterConfigModal.d.ts +1 -1
  92. package/dist/cjs/client/components/DashboardFilters/useFilterDropdowns.d.ts +1 -1
  93. package/dist/cjs/client/components/charts/ChartTooltip.d.ts +2 -2
  94. package/dist/cjs/client/components/charts/recordsTableHooks.d.ts +3 -3
  95. package/dist/cjs/client/components/charts/useChartDimensions.d.ts +1 -1
  96. package/dist/cjs/client/components/charts/useKpiDimensions.d.ts +2 -2
  97. package/dist/cjs/client/components/dashboardPortletCard/usePortletCardActions.d.ts +1 -1
  98. package/dist/cjs/client/components/shared/dateRangeUtils.d.ts +7 -3
  99. package/dist/cjs/client/components/shared/filterItem/FilterFieldDropdown.d.ts +1 -1
  100. package/dist/cjs/client/components/shared/filterValueSelector/FilterValueInputs.d.ts +1 -1
  101. package/dist/cjs/client/components/shared/filterValueSelector/useFilterValueSelectorState.d.ts +1 -1
  102. package/dist/client/chunks/{DashboardEditModal-DfaeSZGf.js → DashboardEditModal-P-HUNrcp.js} +654 -532
  103. package/dist/client/chunks/DashboardEditModal-P-HUNrcp.js.map +1 -0
  104. package/dist/client/chunks/DotStripChart-in6QHc0b.js.map +1 -1
  105. package/dist/client/chunks/ProportionBarChart-CjuOm7NT.js.map +1 -1
  106. package/dist/client/chunks/RecordsTable-CXXsiaV1.js.map +1 -1
  107. package/dist/client/chunks/RetentionCombinedChart-DFCeEFkx.js.map +1 -1
  108. package/dist/client/chunks/RetentionHeatmap-jpshJ2Af.js.map +1 -1
  109. package/dist/client/chunks/af-ZA-C0dGb_53.js.map +1 -1
  110. package/dist/client/chunks/{analysis-builder-fPK8NgJW.js → analysis-builder-CRghdHVl.js} +36 -36
  111. package/dist/client/chunks/analysis-builder-CRghdHVl.js.map +1 -0
  112. package/dist/client/chunks/{analysis-builder-shared--4LqPSum.js → analysis-builder-shared-DBSxWIj8.js} +747 -939
  113. package/dist/client/chunks/analysis-builder-shared-DBSxWIj8.js.map +1 -0
  114. package/dist/client/chunks/chart-activity-grid-DGazwi4C.js.map +1 -1
  115. package/dist/client/chunks/chart-area-zyLGD-ym.js.map +1 -1
  116. package/dist/client/chunks/chart-bar-DMCBq8qJ.js.map +1 -1
  117. package/dist/client/chunks/chart-box-plot-5Z55A-it.js.map +1 -1
  118. package/dist/client/chunks/chart-bubble-YD28dX8w.js.map +1 -1
  119. package/dist/client/chunks/chart-candlestick-BUMpBI08.js.map +1 -1
  120. package/dist/client/chunks/chart-config-activity-grid-C4vXGQNu.js.map +1 -1
  121. package/dist/client/chunks/chart-config-area-DsrZCIwF.js.map +1 -1
  122. package/dist/client/chunks/chart-config-bar-BixSs43E.js.map +1 -1
  123. package/dist/client/chunks/chart-config-box-plot-DMuJZqkr.js.map +1 -1
  124. package/dist/client/chunks/chart-config-bubble-1IyZinH0.js.map +1 -1
  125. package/dist/client/chunks/chart-config-candlestick-QwQwJB_-.js.map +1 -1
  126. package/dist/client/chunks/chart-config-data-table-CrGyS7aJ.js.map +1 -1
  127. package/dist/client/chunks/chart-config-funnel-DMLLKtPF.js.map +1 -1
  128. package/dist/client/chunks/chart-config-gauge-CJktdjox.js.map +1 -1
  129. package/dist/client/chunks/chart-config-heat-map-CJF65SyL.js.map +1 -1
  130. package/dist/client/chunks/chart-config-kpi-delta-Cl7k6jTj.js.map +1 -1
  131. package/dist/client/chunks/chart-config-kpi-number-DCcnANWC.js.map +1 -1
  132. package/dist/client/chunks/chart-config-kpi-text-DnnxvOSA.js.map +1 -1
  133. package/dist/client/chunks/chart-config-line-CBF9Px9b.js.map +1 -1
  134. package/dist/client/chunks/chart-config-markdown-CK8PAWUg.js.map +1 -1
  135. package/dist/client/chunks/chart-config-measure-profile-CRSRIpKh.js.map +1 -1
  136. package/dist/client/chunks/chart-config-pie-DZLa6Eqm.js.map +1 -1
  137. package/dist/client/chunks/chart-config-radar-DR6vHHyd.js.map +1 -1
  138. package/dist/client/chunks/chart-config-radial-bar-DVFou4fB.js.map +1 -1
  139. package/dist/client/chunks/chart-config-sankey-De8E0C1A.js.map +1 -1
  140. package/dist/client/chunks/chart-config-scatter-CWA89oX4.js.map +1 -1
  141. package/dist/client/chunks/chart-config-sunburst-B4NUYHMH.js.map +1 -1
  142. package/dist/client/chunks/chart-config-tree-map-Uhise6Bx.js.map +1 -1
  143. package/dist/client/chunks/chart-config-waterfall-DlQb_PLh.js.map +1 -1
  144. package/dist/client/chunks/chart-data-table-BdMo3zVh.js.map +1 -1
  145. package/dist/client/chunks/chart-funnel-BRyZS6ie.js.map +1 -1
  146. package/dist/client/chunks/chart-gauge-DxgHlZKp.js.map +1 -1
  147. package/dist/client/chunks/chart-heat-map-5jHm3f-V.js.map +1 -1
  148. package/dist/client/chunks/chart-kpi-delta-C84P-mwu.js.map +1 -1
  149. package/dist/client/chunks/chart-kpi-number-D9GqtBWw.js.map +1 -1
  150. package/dist/client/chunks/chart-kpi-text-D3HqxXzU.js.map +1 -1
  151. package/dist/client/chunks/chart-line-IEgiF8Nv.js.map +1 -1
  152. package/dist/client/chunks/chart-markdown-B_2Ed7FJ.js.map +1 -1
  153. package/dist/client/chunks/chart-measure-profile-CWsPrQhH.js.map +1 -1
  154. package/dist/client/chunks/chart-pie-BEB2sCXF.js.map +1 -1
  155. package/dist/client/chunks/chart-radar-BbSbXKbP.js.map +1 -1
  156. package/dist/client/chunks/chart-radial-bar-CNYD7tkM.js.map +1 -1
  157. package/dist/client/chunks/chart-sankey-DKnTIvSr.js.map +1 -1
  158. package/dist/client/chunks/chart-scatter-CSWF6-lx.js.map +1 -1
  159. package/dist/client/chunks/chart-sunburst-CdGzCq7q.js.map +1 -1
  160. package/dist/client/chunks/chart-tree-map-BiXB7EiM.js.map +1 -1
  161. package/dist/client/chunks/chart-waterfall-5rSDeLEZ.js.map +1 -1
  162. package/dist/client/chunks/charts-core-CKpkoMCa.js.map +1 -1
  163. package/dist/client/chunks/charts-loader-BTI0UPK4.js.map +1 -1
  164. package/dist/client/chunks/core-BWRP9s8x.js.map +1 -1
  165. package/dist/client/chunks/dashboardExport-Db3rmUP1.js.map +1 -1
  166. package/dist/client/chunks/dist-COqN0-Yj.js.map +1 -1
  167. package/dist/client/chunks/en-US-HP6FHuNy.js.map +1 -1
  168. package/dist/client/chunks/exceljs.min-CdNVdwM3.js.map +1 -1
  169. package/dist/client/chunks/javascript-D6aJaG8F.js.map +1 -1
  170. package/dist/client/chunks/json-BrJhaXJI.js.map +1 -1
  171. package/dist/client/chunks/nl-NL-kRjxedTf.js.map +1 -1
  172. package/dist/client/chunks/providers-DwQCKdGW.js.map +1 -1
  173. package/dist/client/chunks/retention-ChW9jYdy.js.map +1 -1
  174. package/dist/client/chunks/schema-visualization-BbvL74Sf.js.map +1 -1
  175. package/dist/client/chunks/sql-CmVzGP4w.js.map +1 -1
  176. package/dist/client/chunks/useDirtyStateTracking-BfG1lX_3.js.map +1 -1
  177. package/dist/client/chunks/useExplainAI-CDFhgmpE.js.map +1 -1
  178. package/dist/client/chunks/useNotebookLayout-Ck3Z3uzg.js.map +1 -1
  179. package/dist/client/chunks/utils-CToHkuhU.js.map +1 -1
  180. package/dist/client/chunks/vendor-DeckzF1j.js.map +1 -1
  181. package/dist/client/components/AnalysisBuilder/AnalysisModeErrorBoundary.d.ts +1 -1
  182. package/dist/client/components/AnalysisBuilder/FilterValueInput.d.ts +1 -1
  183. package/dist/client/components/AnalysisBuilder/hooks/useFieldSearchKeyboard.d.ts +1 -1
  184. package/dist/client/components/AnalyticsPortlet.d.ts +1 -1
  185. package/dist/client/components/ChartErrorBoundary.d.ts +1 -1
  186. package/dist/client/components/DashboardFilters/CompactFilterBarParts.d.ts +2 -2
  187. package/dist/client/components/DashboardFilters/CustomDateDropdown.d.ts +1 -1
  188. package/dist/client/components/DashboardFilters/FilterValuePopover.d.ts +1 -1
  189. package/dist/client/components/DashboardFilters/XTDDropdown.d.ts +1 -1
  190. package/dist/client/components/DashboardFilters/useCompactFilterBar.d.ts +2 -2
  191. package/dist/client/components/DashboardFilters/useDashboardFilterConfigModal.d.ts +1 -1
  192. package/dist/client/components/DashboardFilters/useFilterDropdowns.d.ts +1 -1
  193. package/dist/client/components/charts/ChartTooltip.d.ts +2 -2
  194. package/dist/client/components/charts/recordsTableHooks.d.ts +3 -3
  195. package/dist/client/components/charts/useChartDimensions.d.ts +1 -1
  196. package/dist/client/components/charts/useKpiDimensions.d.ts +2 -2
  197. package/dist/client/components/dashboardPortletCard/usePortletCardActions.d.ts +1 -1
  198. package/dist/client/components/shared/dateRangeUtils.d.ts +7 -3
  199. package/dist/client/components/shared/filterItem/FilterFieldDropdown.d.ts +1 -1
  200. package/dist/client/components/shared/filterValueSelector/FilterValueInputs.d.ts +1 -1
  201. package/dist/client/components/shared/filterValueSelector/useFilterValueSelectorState.d.ts +1 -1
  202. package/dist/client/components.js +2 -2
  203. package/dist/client/index.js +8 -8
  204. package/dist/client/index.js.map +1 -1
  205. package/dist/client/utils.js.map +1 -1
  206. package/dist/client-bundle-stats.html +1 -1
  207. package/dist/mcp-app/mcp-app.html +147 -148
  208. package/dist/server/index.cjs +1 -1
  209. package/dist/server/index.js +1 -1
  210. package/dist/server/{openai-D346-vmt.cjs → openai-1GZyKucn.cjs} +1 -1
  211. package/dist/server/openai-DjP9PbWc.cjs +19 -0
  212. package/dist/server/{openai-SILGL2q_.js → openai-Dkcj08jM.js} +1 -1
  213. package/dist/server/{openai-D0vh48Oi.js → openai-DvjrXVVl.js} +3178 -2648
  214. package/package.json +19 -16
  215. package/dist/adapters/ActivityGridChart.config-C2kT9qd6.cjs +0 -1
  216. package/dist/adapters/ActivityGridChart.config-Crkwyx_5.js +0 -2
  217. package/dist/adapters/AreaChart.config-Cn4fTDQH.js +0 -2
  218. package/dist/adapters/AreaChart.config-DSBAn4xT.cjs +0 -1
  219. package/dist/adapters/BarChart.config-2r2_F09O.cjs +0 -1
  220. package/dist/adapters/BarChart.config-CorT50Sr.js +0 -2
  221. package/dist/adapters/BoxPlotChart.config-BM4SbL34.cjs +0 -1
  222. package/dist/adapters/BoxPlotChart.config-Dki3qfhN.js +0 -2
  223. package/dist/adapters/BubbleChart.config-DA768T1u.cjs +0 -1
  224. package/dist/adapters/BubbleChart.config-LJ2w0ZAz.js +0 -2
  225. package/dist/adapters/CandlestickChart.config-C00YG927.cjs +0 -1
  226. package/dist/adapters/CandlestickChart.config-D-vVDHaQ.js +0 -2
  227. package/dist/adapters/DataTable.config-Ml6Q3VEP.cjs +0 -1
  228. package/dist/adapters/DataTable.config-jwBiAUpg.js +0 -2
  229. package/dist/adapters/DotStripChart.config-C_dgJFje.js +0 -2
  230. package/dist/adapters/DotStripChart.config-D5M4xxNE.cjs +0 -1
  231. package/dist/adapters/FunnelChart.config-DBkjp0wh.js +0 -2
  232. package/dist/adapters/FunnelChart.config-Jc6DVjCx.cjs +0 -1
  233. package/dist/adapters/GaugeChart.config-BqW6WqXS.cjs +0 -1
  234. package/dist/adapters/GaugeChart.config-CyD4y_yf.js +0 -2
  235. package/dist/adapters/HeatMapChart.config-C_TKjH9_.cjs +0 -1
  236. package/dist/adapters/HeatMapChart.config-Di1KFl9H.js +0 -2
  237. package/dist/adapters/KpiDelta.config-qlIY4kju.js +0 -2
  238. package/dist/adapters/KpiDelta.config-zaqkGeS2.cjs +0 -1
  239. package/dist/adapters/KpiNumber.config-D1hq68b3.cjs +0 -1
  240. package/dist/adapters/KpiNumber.config-D9LpXMmo.js +0 -2
  241. package/dist/adapters/KpiText.config-BBBV_4aK.cjs +0 -1
  242. package/dist/adapters/KpiText.config-pqFid-lb.js +0 -2
  243. package/dist/adapters/LineChart.config-CFGa_jpk.js +0 -2
  244. package/dist/adapters/LineChart.config-DRTr24Jl.cjs +0 -1
  245. package/dist/adapters/MarkdownChart.config--Teyo7aa.cjs +0 -1
  246. package/dist/adapters/MarkdownChart.config-Cnptz8gx.js +0 -2
  247. package/dist/adapters/MeasureProfileChart.config-BlAnkNf6.js +0 -2
  248. package/dist/adapters/MeasureProfileChart.config-c4K6xVET.cjs +0 -1
  249. package/dist/adapters/PieChart.config-BX5FcoZn.cjs +0 -1
  250. package/dist/adapters/PieChart.config-DT1TCBFA.js +0 -2
  251. package/dist/adapters/ProportionBarChart.config-CN5ov6e6.js +0 -2
  252. package/dist/adapters/ProportionBarChart.config-DdrZQypv.cjs +0 -1
  253. package/dist/adapters/RadarChart.config-CYpWy1MI.js +0 -2
  254. package/dist/adapters/RadarChart.config-Cm14F-JW.cjs +0 -1
  255. package/dist/adapters/RadialBarChart.config-BXEmrEW0.js +0 -2
  256. package/dist/adapters/RadialBarChart.config-bJL8ZwT5.cjs +0 -1
  257. package/dist/adapters/RecordsTable.config-BifW_6cA.cjs +0 -1
  258. package/dist/adapters/RecordsTable.config-DOu5dLR9.js +0 -2
  259. package/dist/adapters/RetentionCombinedChart.config-BLTS46q4.js +0 -2
  260. package/dist/adapters/RetentionCombinedChart.config-DkIUp-uU.cjs +0 -1
  261. package/dist/adapters/RetentionHeatmap.config-Csnntt4P.js +0 -2
  262. package/dist/adapters/RetentionHeatmap.config-Xljn01Px.cjs +0 -1
  263. package/dist/adapters/SankeyChart.config-BExGzO93.cjs +0 -1
  264. package/dist/adapters/SankeyChart.config-DEBF3E7J.js +0 -2
  265. package/dist/adapters/ScatterChart.config-B9fxyVl8.cjs +0 -1
  266. package/dist/adapters/ScatterChart.config-CNWNsjv_.js +0 -2
  267. package/dist/adapters/SunburstChart.config-DyBJr_Ah.js +0 -2
  268. package/dist/adapters/SunburstChart.config-vXKPV3lF.cjs +0 -1
  269. package/dist/adapters/TreeMapChart.config-CoXSasFP.js +0 -2
  270. package/dist/adapters/TreeMapChart.config-iq-fCkIZ.cjs +0 -1
  271. package/dist/adapters/WaterfallChart.config-Coyj2j_7.cjs +0 -1
  272. package/dist/adapters/WaterfallChart.config-Dyf-p2Z2.js +0 -2
  273. package/dist/adapters/mcp-app-html-Bu4j3yZM.cjs +0 -1
  274. package/dist/adapters/mcp-app-html-D3GsxPcx.js +0 -5
  275. package/dist/adapters/openai-ClwjvwzT.cjs +0 -19
  276. package/dist/client/chunks/DashboardEditModal-DfaeSZGf.js.map +0 -1
  277. package/dist/client/chunks/analysis-builder-fPK8NgJW.js.map +0 -1
  278. package/dist/client/chunks/analysis-builder-shared--4LqPSum.js.map +0 -1
  279. package/dist/server/openai-C6tdx3yN.cjs +0 -19
@@ -0,0 +1,19 @@
1
+ const e=require("./rolldown-runtime-DF3sbh8G.cjs");function t(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function n(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var r=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return r=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(+e^n()&15>>e/4).toString(16))};function i(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var a=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=`cause`in e,n=Error(e.message,t?{cause:e.cause}:{});return e.stack&&(n.stack=e.stack),t&&!Object.prototype.hasOwnProperty.call(n,`cause`)&&(n.cause=e.cause),e.name&&(n.name=e.name),n}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},o=class extends Error{},s=class e extends o{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new l({message:r,cause:a(n)});let o=n?.error;return t===400?new d(t,o,r,i):t===401?new f(t,o,r,i):t===403?new p(t,o,r,i):t===404?new m(t,o,r,i):t===409?new h(t,o,r,i):t===422?new g(t,o,r,i):t===429?new _(t,o,r,i):t>=500?new v(t,o,r,i):new e(t,o,r,i)}},c=class extends s{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},l=class extends s{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},u=class extends l{constructor({message:e}={}){super({message:e??`Request timed out.`})}},d=class extends s{},f=class extends s{},p=class extends s{},m=class extends s{},h=class extends s{},g=class extends s{},_=class extends s{},v=class extends s{},y=class extends o{constructor(){super(`Could not parse response content as the length limit was reached`)}},b=class extends o{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},x=class extends Error{constructor(e){super(e)}},S=class extends s{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},C=class extends o{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},w=/^[a-z][a-z0-9+.-]*:/i,ee=e=>w.test(e),T=e=>(T=Array.isArray,T(e)),te=T;function ne(e){return typeof e==`object`?e??{}:{}}function re(e){if(!e)return!0;for(let t in e)return!1;return!0}function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function D(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ie=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new o(`${e} must be an integer`);if(t<0)throw new o(`${e} must be a positive integer`);return t},ae=e=>{try{return JSON.parse(e)}catch{return}},oe=(e,...t)=>new Promise((n,r)=>{let i=[...new Set(t.filter(e=>e!=null))],a,o=!1,s=()=>{for(let e of i)try{e.removeEventListener(`abort`,l)}catch{}},c=e=>{o||(o=!0,a!==void 0&&(clearTimeout(a),a=void 0),s(),e())},l=()=>{c(()=>r())};if(i.some(e=>e.aborted)){l();return}a=setTimeout(()=>{c(n)},e);for(let e of i){if(o)break;try{e.addEventListener(`abort`,l,{once:!0})}catch(e){c(()=>r(e))}}i.some(e=>e.aborted)&&l()}),se=globalThis,ce=typeof se.FinalizationRegistry==`function`?new se.FinalizationRegistry(e=>{try{e()}catch{}}):void 0,le=new WeakMap,ue=new WeakMap;function de(e,t,n){let r=ue.get(e);if(!r){let t=new Set,i=()=>{ue.delete(e);for(let e of t)n.unregister(e),e.deref()?.();t.clear()};r={callbacks:t,abort:i},e.addEventListener(`abort`,i,{once:!0}),ue.set(e,r)}let i=r;return i.callbacks.add(t),()=>{i.callbacks.delete(t),n.unregister(t),i.callbacks.size===0&&(ue.get(e)===i&&ue.delete(e),e.removeEventListener(`abort`,i.abort))}}function fe(e,t,n){e.addEventListener(`abort`,()=>t.deref()?.delete(n),{once:!0})}function pe(e,t,n){if(typeof se.WeakRef==`function`&&ce&&!n.aborted){let r=le.get(e);r||(r=new Set,le.set(e,r)),r.add(t),fe(n,new se.WeakRef(r),t)}}function me(e,t,n){if(e.aborted)return t(),()=>{};if(typeof se.WeakRef!=`function`||!ce)return e.addEventListener(`abort`,t,{once:!0}),()=>e.removeEventListener(`abort`,t);let r=new se.WeakRef(t),i=de(e,r,ce);return ce.register(t,i,r),pe(n,t,n),i}function he(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function ge(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function _e(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ge({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ve(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ye(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var be;function xe(e){let t;return(be??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Se;function Ce(e){let t;return(Se??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var we,O,k,A,Te,Ee,De,Oe=65536,ke=class{constructor(){we.add(this),O.set(this,void 0),k.set(this,void 0),A.set(this,void 0),Te.set(this,void 0),Ee.set(this,void 0),t(this,O,new Uint8Array,`f`),t(this,k,0,`f`),t(this,A,0,`f`),t(this,Te,0,`f`),t(this,Ee,!1,`f`)}decode(e){if(e==null)return[];let r;if(r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?xe(e):e,r.length===0||n(this,Ee,`f`)&&(t(this,Ee,!1,`f`),r[0]===10&&(r=r.subarray(1)),r.length===0))return[];n(this,we,`m`,De).call(this,r);let i=[],a;for(;(a=Ae(n(this,O,`f`),n(this,Te,`f`),n(this,A,`f`)))!=null;){let e=Ce(n(this,O,`f`).subarray(n(this,k,`f`),a.preceding));i.push(e),t(this,k,a.index,`f`),a.carriage&&(n(this,k,`f`)<n(this,A,`f`)&&n(this,O,`f`)[n(this,k,`f`)]===10?t(this,k,n(this,k,`f`)+1,`f`):n(this,k,`f`)===n(this,A,`f`)&&t(this,Ee,!0,`f`)),t(this,Te,n(this,k,`f`),`f`)}if(t(this,Te,n(this,A,`f`),`f`),n(this,k,`f`)===n(this,A,`f`))t(this,k,0,`f`),t(this,A,0,`f`),t(this,Te,0,`f`),n(this,O,`f`).length>Oe&&t(this,O,new Uint8Array,`f`);else if(i.length>0&&n(this,O,`f`).length>Oe){let e=n(this,A,`f`)-n(this,k,`f`);if(e<=Oe||n(this,O,`f`).length>e*4){let r=e<=Oe?Math.min(Math.max(e*2,256),Oe):e*2,i=new Uint8Array(r);i.set(n(this,O,`f`).subarray(n(this,k,`f`),n(this,A,`f`))),t(this,O,i,`f`),t(this,k,0,`f`),t(this,A,e,`f`),t(this,Te,e,`f`)}}return i}flush(){return t(this,Ee,!1,`f`),n(this,k,`f`)===n(this,A,`f`)?[]:this.decode(`
2
+ `)}};O=new WeakMap,k=new WeakMap,A=new WeakMap,Te=new WeakMap,Ee=new WeakMap,we=new WeakSet,De=function(e){if(n(this,A,`f`)+e.length>n(this,O,`f`).length){let r=n(this,A,`f`)-n(this,k,`f`);if(n(this,k,`f`)>=n(this,O,`f`).length/2&&r+e.length<=n(this,O,`f`).length)n(this,O,`f`).copyWithin(0,n(this,k,`f`),n(this,A,`f`));else{let i=Math.max(n(this,O,`f`).length*2,r+e.length,256),a=new Uint8Array(i);a.set(n(this,O,`f`).subarray(n(this,k,`f`),n(this,A,`f`))),t(this,O,a,`f`)}t(this,Te,n(this,Te,`f`)-n(this,k,`f`),`f`),t(this,A,r,`f`),t(this,k,0,`f`)}n(this,O,`f`).set(e,n(this,A,`f`)),t(this,A,n(this,A,`f`)+e.length,`f`)},ke.NEWLINE_CHARS=new Set([`
3
+ `,`\r`]),ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ae(e,t,n){for(let r=t;r<n;r++){if(e[r]===10)return{preceding:r,index:r+1,carriage:!1};if(e[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function je(e){for(let t=0;t<e.length-1;t++){let n=Me(e,t);if(n>0){let r=t+n,i=Me(e,r);if(i>0)return r+i}}return-1}function Me(e,t){return e[t]===10?1:e[t]===13?e[t+1]===10?2:1:0}var Ne={off:0,error:200,warn:300,info:400,debug:500},Pe=(e,t,n)=>{if(e){if(E(Ne,e))return e;j(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ne))}`)}};function Fe(){}function Ie(e,t,n){return!t||Ne[e]>Ne[n]?Fe:t[e].bind(t)}var Le={error:Fe,warn:Fe,info:Fe,debug:Fe},Re=new WeakMap;function j(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Le;let r=Re.get(t);if(r&&r[0]===n)return r[1];let i={error:Ie(`error`,t,n),warn:Ie(`warn`,t,n),info:Ie(`info`,t,n),debug:Ie(`debug`,t,n)};return Re.set(t,[n,i]),i}var ze=new Set([`apikey`,`accesstoken`,`refreshtoken`,`sessiontoken`,`sessionid`,`idtoken`,`authtoken`,`authorization`,`token`,`password`,`clientsecret`,`signingsecret`,`xamzsecuritytoken`,`xamzsignature`,`xamzcredential`]);function Be(e){let t=e.toLowerCase().replace(/[-_]/gu,``);return ze.has(t)||ze.has(t.replace(/^x/u,``))}var Ve=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 He(e){return Ve.has(e.toLowerCase().replace(/_/gu,`-`))||Be(e)}function Ue(e){let t=new URL(e);t.username=``,t.password=``,t.hash=``;for(let e of t.searchParams.keys())Be(e)&&t.searchParams.set(e,`***`);return t.href}var We=e=>{if(e.options){if(e.options={...e.options},delete e.options.headers,e.options.path){let t=e.options.path,n=new URL(Ue(new URL(t,`https://redacted.invalid`).href));e.options.path=n.origin===`https://redacted.invalid`?`${t.startsWith(`/`)?`/`:``}${n.pathname.slice(1)}${n.search}`:n.href}e.options.query&&(e.options.query=Object.fromEntries(Object.entries(e.options.query).map(([e,t])=>[e,Be(e)?`***`:t])))}return e.url&&=Ue(e.url),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,He(e)?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e},Ge,Ke,qe,Je;function Ye(e){return!(e instanceof s)&&i(e)}function Xe(){let e=[],t=0,n=!1;return{get length(){return e.length-t},get canceled(){return n},enqueue(t){n||e.push(t)},dequeue(){if(t===e.length)return;let n=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&t*2>=e.length&&(e=e.slice(t),t=0),n},cancel(){n=!0,e.length=0,t=0}}}var Ze=class e{constructor(e,n,r){Ge.add(this),Ke.set(this,void 0),qe.set(this,!1),this.iterator=e,this.controller=n,t(this,Ke,r,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,c=r?j(r):console;async function*l(){if(a)throw new o("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1,r=!1,l=$e(t,n),u=l.return.bind(l);l.return=e=>(r||n.abort(),u(e));try{for await(let e of l){if(e.data===`[DONE]`){r=!0;break}if(e.event===null||!e.event.startsWith(`thread.`)){let n;try{n=JSON.parse(e.data)}catch{throw c.error(`Could not parse message into JSON:`),c.error(`From chunk:`),SyntaxError(`Error reading response: malformed server-sent event JSON.`)}if(e.event===`error`)throw new s(void 0,n?.error??n,void 0,t.headers);if(n&&n.error)throw new s(void 0,n.error,void 0,t.headers);yield i?{event:e.event,data:n}:n}else{let t;try{t=JSON.parse(e.data)}catch{throw c.error(`Could not parse message into JSON:`),c.error(`From chunk:`),SyntaxError(`Error reading response: malformed server-sent event JSON.`)}yield{event:e.event,data:t}}}e=!0}catch(e){if(r||Ye(e)||n.signal.aborted&&e===n.signal.reason)return;throw e}finally{e||n.abort()}}return new e(l,n,r)}static fromReadableStream(t,n,r){let a=!1;async function*s(){let e=new ke,r=t.getReader(),i=!1,a,o=()=>{a??=r.cancel(),a.catch(()=>void 0)};n.signal.addEventListener(`abort`,o,{once:!0});try{if(n.signal.aborted){o();return}for(;;){let{value:t,done:a}=await r.read();if(a){i=!0;break}if(n.signal.aborted)return;for(let r of e.decode(t)){if(n.signal.aborted)return;yield r}}if(n.signal.aborted)return;for(let t of e.flush()){if(n.signal.aborted)return;yield t}}finally{n.signal.removeEventListener(`abort`,o),i||o(),r.releaseLock()}}async function*c(){if(a)throw new o("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let e of s())if(e){let t;try{t=JSON.parse(e)}catch(e){throw e instanceof SyntaxError?SyntaxError(`Error reading response: malformed newline-delimited JSON.`):e}yield t}e=!0}catch(e){if(n.signal.aborted||i(e))return;throw e}finally{e||n.abort()}}return new e(c,n,r)}[(Ke=new WeakMap,qe=new WeakMap,Ge=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}__betaTransformIterator(e){this.iterator=e(this.iterator.bind(this))}tee(){let{controller:r}=this,i=Xe(),a=Xe(),o=this.iterator(),s=e=>({next:()=>{if(e.canceled)return Promise.resolve({value:void 0,done:!0});if(e.length===0){let e=o.next();i.enqueue(e),a.enqueue(e)}return e.dequeue()},return:async()=>(e.canceled||(e.cancel(),i.canceled&&a.canceled&&await n(this,Ge,`m`,Je).call(this,o,r)),{value:void 0,done:!0})}),c=i=>{let a=new e(()=>s(i),r,n(this,Ke,`f`));return t(a,qe,!0,`f`),a};return[c(i),c(a)]}toReadableStream(){let{controller:e}=this,t,r,i=()=>r??=n(this,Ge,`m`,Je).call(this,t,e);return ge({start:async()=>{t=this[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=xe(JSON.stringify(n)+`
4
+ `);e.enqueue(i)}catch(t){e.error(t),i().catch(()=>void 0)}},cancel:i})}};Je=async function(e,t){let r=e.return;r&&(n(this,qe,`f`)||t.abort(),await Reflect.apply(r,e,[]))};function Qe(e,t){let n=typeof e.getReader==`function`?e.getReader():void 0,r=n?{next:()=>n.read(),return:()=>n.cancel()}:ve(e)[Symbol.asyncIterator](),a={value:void 0,done:!0},o=!1,s=!1,c,l,u=()=>new Promise(e=>{l=e}),d=()=>{if(s||o)return c;s=!0;try{c=Promise.resolve(r.return?.())}catch(e){c=Promise.reject(e)}return c.catch(()=>void 0),c},f=()=>{queueMicrotask(()=>{l?.(),d()})};return{iterator:{async next(){if(t.aborted)return a;let e=u().then(()=>a);try{let n=await Promise.race([r.next(),e]);return t.aborted?a:n.done?(o=!0,a):{value:n.value,done:!1}}catch(e){if(t.aborted&&(i(e)||e===t.reason))return a;throw e}finally{l=void 0}},async return(){let e=d();if(e&&!t.aborted){let n=u();try{t.aborted||await Promise.race([e,n])}finally{l=void 0}}return a},[Symbol.asyncIterator](){return this}},start(){t.addEventListener(`abort`,f,{once:!0}),t.aborted&&f()},async cleanup(e){let r;try{t.removeEventListener(`abort`,f)}catch(e){r=e}if(!o){let n=d();if(n&&!e&&!t.aborted)try{await n}catch(e){r??=e}}if(n)try{n.releaseLock()}catch(e){r??=e}if(r!==void 0&&!e&&!t.aborted)throw r}}}async function*$e(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new o(`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 o(`Attempted to iterate over a response with no body`);let n=new nt,r=new ke,{signal:a}=t,s=Qe(e.body,a),c=!1;try{s.start();for await(let e of tt(s.iterator)){if(a.aborted)return;for(let t of r.decode(e)){if(a.aborted)return;let e=n.decode(t);e&&(yield e)}}if(a.aborted)return;for(let e of r.flush()){if(a.aborted)return;let t=n.decode(e);t&&(yield t)}if(a.aborted)return;let e=n.flush();e&&(yield e)}catch(e){if(c=!0,!a.aborted||!i(e)&&e!==a.reason)throw e}finally{await s.cleanup(c)}}var et=3;async function*tt(e){let t=new Uint8Array,n=0,r=0,i=0;for await(let a of e){if(a==null)continue;let e;if(e=a instanceof ArrayBuffer?new Uint8Array(a):typeof a==`string`?xe(a):a,r+e.length>t.length){let a=r-n;if(n>=t.length/2&&a+e.length<=t.length)t.copyWithin(0,n,r);else{let i=new Uint8Array(Math.max(t.length*2,a+e.length));i.set(t.subarray(n,r)),t=i}i-=n,n=0,r=a}t.set(e,r),r+=e.length;let o;for(;(o=je(t.subarray(i,r)))!==-1;)o+=i,yield t.slice(n,o),n=o,i=n;i=Math.max(n,r-et)}r>n&&(yield t.slice(n,r))}var nt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.slice(0,-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,,n]=rt(e,`:`),r=n;return r.startsWith(` `)&&(r=r.slice(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}flush(){return this.decode(``)}};function rt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.slice(0,n),t,e.slice(n+t.length)]}async function it(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o,s=await(async()=>{if(t.options.stream)return j(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):Ze.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(r?.includes(`application/json`)||r?.endsWith(`+json`)){if(n.headers.get(`content-length`)===`0`)return;let e=await n.text();if(!e)return;let t=JSON.parse(e);return o=e.length,ot(t,n)}return await n.text()})().catch(e=>{throw at(e,t.controller.signal)});return e.logLevel===`debug`&&j(e).debug(`[${r}] response parsed`,We({retryOfRequestLogID:i,url:n.url,status:n.status,body:o===void 0?s:{type:`json`,length:o},durationMs:Date.now()-a})),s}function at(e,t){if(!t.aborted||e!==t.reason||i(e))return e;let n=`This operation was aborted`,r=globalThis.DOMException;return typeof r==`function`?new r(n,`AbortError`):Object.assign(Error(n),{name:`AbortError`})}function ot(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var st=`7.27.0`,ct=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function lt(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var ut=()=>{let e=lt();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":st,"X-Stainless-OS":pt(Deno.build.os),"X-Stainless-Arch":ft(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":st,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process?.version??`unknown`};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":st,"X-Stainless-OS":pt(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ft(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=dt();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":st,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":st,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function dt(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var ft=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,pt=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),mt,ht=()=>mt??=ut(),gt=new WeakMap;function _t(e,t){let n=gt.get(e);return n||(n=new Set,gt.set(e,n)),n.add(t),()=>{let n=gt.get(e);n&&(n.delete(t),n.size===0&&gt.delete(e))}}var vt=({headers:e,body:t})=>{let n=typeof t==`object`&&t?gt.get(t):void 0,r;if(!n||n.size===0)r=JSON.stringify(t);else{let e=[...n];r=JSON.stringify(t,function(t,n){let r=n;for(let n of e){let e=n.value(this,t,r);e!==void 0&&(r=e)}return r});for(let t of e)t.complete()}return{bodyHeaders:{"content-type":`application/json`},body:r}},yt=`RFC3986`,bt=String,xt={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:bt},St,Ct=(e,t)=>{let n=St??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return St=n,n(e,t)},wt=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Tt=1024,Et=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,e=>`%26%23`+Number.parseInt(e.slice(2),16)+`%3B`);let o=``;for(let e=0;e<a.length;){let t=Math.min((Math.floor(e/Tt)+1)*Tt,a.length);t<a.length&&a.codePointAt(t-1)>65535&&(t+=1);let n=a.length>=Tt?a.slice(e,t):a,r=[];for(let e=0;e<n.length;++e){let t=n.charCodeAt(e);if(t===45||t===46||t===95||t===126||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||i===`RFC1738`&&(t===40||t===41)){r[r.length]=n.charAt(e);continue}if(t<128){r[r.length]=wt[t];continue}if(t<2048){r[r.length]=wt[192|t>>6]+wt[128|t&63];continue}if(t<55296||t>=57344){r[r.length]=wt[224|t>>12]+wt[128|t>>6&63]+wt[128|t&63];continue}e+=1,t=65536+((t&1023)<<10|n.charCodeAt(e)&1023),r[r.length]=wt[240|t>>18]+wt[128|t>>12&63]+wt[128|t>>6&63]+wt[128|t&63]}o+=r.join(``),e=t}return o};function Dt(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Ot(e,t){if(T(e)){let n=[];for(let r of e)n.push(t(r));return n}return t(e)}var kt={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},At=function(e,t){Array.prototype.push.apply(e,T(t)?t:[t])},jt,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Et,encodeValuesOnly:!1,format:yt,formatter:bt,indices:!1,serializeDate(e){return(jt??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Mt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Nt={};function Pt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(Nt))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(Nt)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&T(v)&&(v=Ot(v,e=>e instanceof Date?f?.(e):e)),v===null){if(a)return c&&!h?c(t,M.encoder,g,`key`,p):t;v=``}if(Mt(v)||Dt(v)){if(c){let e=h?t:c(t,M.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,M.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let S=[];if(v===void 0)return S;let C;if(n===`comma`&&T(v))h&&c&&(v=Ot(v,c)),C=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(T(l))C=l;else{let e=Object.keys(v);u&&e.sort(u),C=e}let w=s?String(t).replace(/\./g,`%2E`):String(t),ee=r&&T(v)&&v.length===1?w+`[]`:w;if(i&&T(v)&&v.length===0)return ee+`[]`;for(let t of C){let y=typeof t==`object`&&t.value!==void 0?t.value:v[t];if(o&&y===null)continue;let x=d&&s?t.replace(/\./g,`%2E`):t,C;C=T(v)?typeof n==`function`?n(ee,x):ee:ee+(d?`.`+x:`[`+x+`]`),_.set(e,b);let w=new WeakMap([[Nt,_]]);At(S,Pt(y,C,n,r,i,a,o,s,n===`comma`&&h&&T(v)?null:c,l,u,d,f,p,m,h,g,w))}return S}function Ft(e=M){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||M.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=yt;if(e.format!==void 0){if(!Ct(xt,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=xt[n],i=M.filter;(typeof e.filter==`function`||T(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in kt?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:M.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o;return o=e.allowDots===void 0?e.encodeDotInKeys?!0:M.allowDots:!!e.allowDots,{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:M.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?M.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:M.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:M.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:M.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:M.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:M.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:M.strictNullHandling}}function It(e,t={}){let n=e,r=Ft(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):T(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=kt[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e of i)r.skipNulls&&n[e]===null||At(o,Pt(n[e],e,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l));let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(d+=r.charset===`iso-8859-1`?`utf8=%26%2310003%3B&`:`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Lt(e){return It(e,{arrayFormat:`brackets`})}var Rt=new Map([[`global`,`https://api.openai.com/v1`],[`us`,`https://us.api.openai.com/v1`],[`eu`,`https://eu.api.openai.com/v1`],[`ae`,`https://ae.api.openai.com/v1`]]);function zt(e){if(e.dataResidency===null||e.dataResidency===void 0)return;if(E(e,`baseURL`))throw new o("The `dataResidency` and `baseURL` options are mutually exclusive.");let t=Rt.get(e.dataResidency);if(t===void 0)throw new o("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return t}function Bt(e,t){if(e!=null)throw new o(`${t} does not support \`dataResidency\`.`)}var Vt,Ht=class e extends Promise{constructor(e,n,r=it){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,Vt.set(this,void 0),t(this,Vt,e,`f`)}_thenUnwrap(t){return new e(n(this,Vt,`f`),this.responsePromise,async(e,n)=>ot(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(n(this,Vt,`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)}};Vt=new WeakMap;var Ut,Wt=class{constructor(e,n,r,i){Ut.set(this,void 0),t(this,Ut,e,`f`),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new o("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await n(this,Ut,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ut=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Gt=class extends Ht{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await it(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Kt=class extends Wt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},N=class extends Wt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...ne(this.options.query),after:t}}:null}},P=class extends Wt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ne(this.options.query),after:e}}:null}},qt=class extends Wt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ne(this.options.query),after:e}}:null}},Jt=class extends Wt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ne(this.options.query),page:e}}:null}},Yt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Xt=`urn:ietf:params:oauth:grant-type:token-exchange`,Zt=.5;function Qt(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new o(`Token exchange response has invalid 'expires_in' field`);let n=Date.now(),r=n+e*1e3;if(!Number.isSafeInteger(r)||r<=n)throw new o(`Token exchange response has invalid 'expires_in' field`);let i=r-(performance.now()-t);if(i<=n)throw new o(`Workload identity token expired before its exchange completed.`);return i}function $t(e,t,n){let r=(n??1200)*1e3;return e-Math.min(r,t*1e3*Zt)}var en=Response.prototype,tn=en.arrayBuffer;function nn(e,t){let n=Object.getOwnPropertyDescriptor(t,`constructor`)?.value;if(t===e||typeof n!=`function`||Object.getOwnPropertyDescriptor(n,`name`)?.value!==`Response`||Object.getOwnPropertyDescriptor(n,`prototype`)?.value!==t)return!1;let r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);return(r?.value===`Response`||typeof r?.get==`function`)&&typeof Object.getOwnPropertyDescriptor(t,`headers`)?.get==`function`&&typeof Object.getOwnPropertyDescriptor(t,`ok`)?.get==`function`&&typeof Object.getOwnPropertyDescriptor(t,`status`)?.get==`function`}function rn(e,t){if(e===t)return!0;let n=Object.getOwnPropertyDescriptor(e,`constructor`)?.value;return t!==null&&Object.getPrototypeOf(t)===e&&typeof n==`function`&&Object.getOwnPropertyDescriptor(n,`name`)?.value===`Body`&&Object.getOwnPropertyDescriptor(n,`prototype`)?.value===e}function an(e){return new TextDecoder(`utf-8`,{ignoreBOM:typeof globalThis.Bun?.version==`string`}).decode(e)}async function on(e){let t,n=null;for(let r=0,i=e;i!==null&&r<16&&i!==en;i=Object.getPrototypeOf(i),r+=1){nn(e,i)&&(n=i);let r=Object.getOwnPropertyDescriptor(i,`json`);if(!r)continue;if(typeof r.value!=`function`)break;let a=Object.getOwnPropertyDescriptor(i,`text`)?.value;if(typeof a==`function`&&rn(i,n)){t=a;break}return r.value.call(e)}let r=t===void 0?an(await tn.call(e)):await t.call(e);try{return JSON.parse(r)}catch{throw SyntaxError(`Token exchange response contains invalid JSON`)}}function sn(e){return typeof globalThis.Bun?.version==`string`?/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(e):/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(e)}var cn=class e{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`;let{identityProviderId:n,serviceAccountId:r,clientId:i,refreshBufferSeconds:a,provider:o}=e;this.config={identityProviderId:n,serviceAccountId:r,...i===void 0?{}:{clientId:i},...a===void 0?{}:{refreshBufferSeconds:a},provider:{tokenType:o.tokenType,getToken:o.getToken.bind(o)}},this.fetch=t??he()}async getToken(){if(!this.cachedToken||e.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;let e=this.refreshToken(this.tokenGeneration);this.refreshPromise=e;try{return await e}finally{this.refreshPromise===e&&(this.refreshPromise=null)}}if(e.needsRefresh(this.cachedToken)&&!this.refreshPromise){let e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){let t={grant_type:Xt,subject_token:await this.config.provider.getToken(),subject_token_type:Yt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let n=performance.now(),r=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),redirect:`manual`});if(!r.ok){let e=await r.text(),t;try{t=JSON.parse(e)}catch{}throw r.status===400||r.status===401||r.status===403?new S(r.status,t,r.headers):s.generate(r.status,t,`Token exchange failed with status ${r.status}`,r.headers)}let i=await on(r),a=typeof i==`object`&&i&&`access_token`in i?i.access_token:void 0;if(typeof a!=`string`||a.trim().length===0||sn(a))throw new o(`Token exchange response missing 'access_token' field`);let c=i.expires_in??3600,l=Qt(c,n);return this.tokenGeneration===e&&(this.cachedToken={token:a,expiresAt:l,refreshAt:$t(l,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}};function ln(e){let t;try{t=new URL(e)}catch{throw new o(`X.509 workload identity requires the approved global mTLS API origin.`)}if(t.origin!==`https://mtls.api.openai.com`||t.username||t.password)throw new o(`X.509 workload identity requires the approved global mTLS API origin.`);for(let e of t.searchParams.keys())if(Be(e))throw new o(`X.509 workload identity cannot send conflicting query authentication credentials.`);return t}var un=Symbol(`brand.privateNullableHeaders`),dn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*fn(e){if(!e)return;if(un in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n,r=Symbol.iterator in e?e[Symbol.iterator]:void 0;typeof r==`function`?n={[Symbol.iterator]:()=>r.call(e)}:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=te(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var F=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of fn(r)){if(!dn.test(i))throw TypeError(`Header name must be a valid HTTP token ["${i}"]`);let r=i.toLowerCase();e.has(r)||(t.delete(r),e.add(r)),a===null?(t.delete(r),n.add(r)):(t.append(r,a),n.delete(r))}}return{[un]:!0,values:t,nulls:n}},pn=e.n({findRegisteredX509Transport:()=>bn,findX509Credential:()=>jn,findX509OAuthError:()=>kn,isApprovedX509Client:()=>Dn,isRetryableX509IssuerError:()=>Tn,isTransientX509ConnectionError:()=>Cn,markApprovedX509Client:()=>En,markRetryableX509IssuerError:()=>wn,markTransientX509ConnectionError:()=>Sn,rememberRegisteredX509Transport:()=>xn,rememberX509Credential:()=>An,rememberX509OAuthError:()=>On}),mn=new WeakMap,hn=new WeakSet,gn=new WeakSet,_n=new WeakSet,vn=new WeakMap,yn=new WeakMap,bn=WeakMap.prototype.get.bind(mn),xn=WeakMap.prototype.set.bind(mn),Sn=WeakSet.prototype.add.bind(hn),Cn=WeakSet.prototype.has.bind(hn),wn=WeakSet.prototype.add.bind(gn),Tn=WeakSet.prototype.has.bind(gn),En=WeakSet.prototype.add.bind(_n),Dn=WeakSet.prototype.has.bind(_n),On=WeakMap.prototype.set.bind(vn),kn=WeakMap.prototype.get.bind(vn),An=WeakMap.prototype.set.bind(yn),jn=WeakMap.prototype.get.bind(yn),Mn=e.t(((e,t)=>{if(t!==void 0&&t!==globalThis.module&&e!==void 0&&t.exports===e){Object.defineProperty(e,"__esModule",{value:!0}),e.findX509Credential=e.rememberX509Credential=e.findX509OAuthError=e.rememberX509OAuthError=e.isApprovedX509Client=e.markApprovedX509Client=e.isRetryableX509IssuerError=e.markRetryableX509IssuerError=e.isTransientX509ConnectionError=e.markTransientX509ConnectionError=e.rememberRegisteredX509Transport=e.findRegisteredX509Transport=void 0;let t=new WeakMap,n=new WeakSet,r=new WeakSet,i=new WeakSet,a=new WeakMap,o=new WeakMap;e.findRegisteredX509Transport=WeakMap.prototype.get.bind(t),e.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(t),e.markTransientX509ConnectionError=WeakSet.prototype.add.bind(n),e.isTransientX509ConnectionError=WeakSet.prototype.has.bind(n),e.markRetryableX509IssuerError=WeakSet.prototype.add.bind(r),e.isRetryableX509IssuerError=WeakSet.prototype.has.bind(r),e.markApprovedX509Client=WeakSet.prototype.add.bind(i),e.isApprovedX509Client=WeakSet.prototype.has.bind(i),e.rememberX509OAuthError=WeakMap.prototype.set.bind(a),e.findX509OAuthError=WeakMap.prototype.get.bind(a),e.rememberX509Credential=WeakMap.prototype.set.bind(o),e.findX509Credential=WeakMap.prototype.get.bind(o)}})),Nn=e.r(Mn(),1),{findRegisteredX509Transport:Pn,rememberRegisteredX509Transport:Fn,markTransientX509ConnectionError:In,isTransientX509ConnectionError:Ln,markRetryableX509IssuerError:Rn,isRetryableX509IssuerError:zn,markApprovedX509Client:Bn,isApprovedX509Client:Vn,rememberX509OAuthError:Hn,findX509OAuthError:Un,rememberX509Credential:Wn,findX509Credential:Gn}=typeof Nn.findRegisteredX509Transport==`function`?Nn:pn;function Kn(e){if(!e||typeof e!=`object`)throw new o(`X.509 workload identity requires an approved X.509 transport capability.`);let t=Pn(e);if(!t)throw new o(`X.509 workload identity requires an approved X.509 transport capability.`);return t}var I,qn,Jn,Yn,Xn,Zn,Qn,$n,L,er,tr,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,R,fr,pr=[`dispatcher`,`agent`,`client`,`tls`,`proxy`],mr=(e,t)=>Headers.prototype.get.call(e,t),hr=12e5,gr=1e3,_r=e=>{let t=new c;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t};function vr(e){for(let t of Headers.prototype.keys.call(e)){let e=t.toLowerCase().split(`_`).join(`-`);if(e!==`authorization`&&He(e)||e===`host`)throw new o(`X.509 workload identity cannot send conflicting authentication credentials.`)}}function yr(e,t){let n=new AbortController,r=e===void 0?void 0:setTimeout(()=>n.abort(new u),e),i=r;typeof i==`object`&&i&&`unref`in i&&typeof i.unref==`function`&&i.unref();let a=()=>n.abort(t?.reason);return t?.addEventListener(`abort`,a,{once:!0}),t?.aborted&&a(),{signal:n.signal,dispose:()=>{t?.removeEventListener(`abort`,a),r&&clearTimeout(r)}}}function br(e,t){let n,r=new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});return{result:Promise.race([e.promise,r]),dispose:()=>{n&&t.removeEventListener(`abort`,n)}}}function xr(e){if(!e||typeof e!=`object`)return!1;let t=e;for(;t!==null&&t!==Object.prototype;){let e=Object.getOwnPropertyDescriptor(t,`provider`);if(e){if(!(`value`in e)||e.value!==void 0)return!1;break}t=Object.getPrototypeOf(t)}let n=e;for(;n!==null&&n!==Object.prototype;){let e=Object.getOwnPropertyDescriptor(n,`type`);if(e){if(!(`value`in e))throw new o(`X.509 workload identity type must be a plain data property.`);return e.value===`x509`}n=Object.getPrototypeOf(n)}return!1}function Sr(e){if(!e)return;for(let t of pr)if(E(e,t))throw new o(`X.509 workload identity cannot override its approved transport capability.`);let t=Object.getOwnPropertyDescriptor(e,`redirect`)?.value;if(t!==void 0&&t!==`manual`)throw new o(`X.509 workload identity requests require manual redirects.`)}function Cr(e){if(Sr(e),e&&[`body`,`headers`,`method`,`signal`].some(t=>E(e,t)))throw new o(`X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.`)}function wr(e){Cr(e);let t={...e};return Cr(t),t}var Tr=class{constructor(e,r,i,a){if(I.add(this),Jn.set(this,void 0),Yn.set(this,void 0),Xn.set(this,void 0),Zn.set(this,void 0),Qn.set(this,void 0),$n.set(this,void 0),L.set(this,void 0),er.set(this,void 0),tr.set(this,void 0),nr.set(this,void 0),rr.set(this,0),t(this,L,Kn(r),`f`),t(this,Jn,e.identityProviderId,`f`),t(this,Yn,e.serviceAccountId,`f`),t(this,Xn,e.refreshBufferMs,`f`),t(this,Zn,e.refreshBufferSeconds,`f`),t(this,Qn,i,`f`),t(this,$n,a,`f`),n(this,Xn,`f`)!==void 0&&n(this,Zn,`f`)!==void 0)throw new o(`X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.`);if(n(this,Xn,`f`)!==void 0&&(!Number.isSafeInteger(n(this,Xn,`f`))||n(this,Xn,`f`)<0))throw new o(`X.509 workload identity requires a nonnegative integer refreshBufferMs.`);if(n(this,Zn,`f`)!==void 0&&(!Number.isSafeInteger(n(this,Zn,`f`))||n(this,Zn,`f`)<0||!Number.isSafeInteger(n(this,Zn,`f`)*1e3)))throw new o(`X.509 workload identity requires a nonnegative integer refreshBufferSeconds.`);t(this,er,n(this,Zn,`f`)===void 0?n(this,Xn,`f`)??hr:n(this,Zn,`f`)*1e3,`f`)}identitySnapshot(){return{type:`x509`,identityProviderId:n(this,Jn,`f`),serviceAccountId:n(this,Yn,`f`),...n(this,Xn,`f`)===void 0?{}:{refreshBufferMs:n(this,Xn,`f`)},...n(this,Zn,`f`)===void 0?{}:{refreshBufferSeconds:n(this,Zn,`f`)}}}static shouldAuthenticate(e,t,n=e.headers){return!F([t,n]).nulls.has(`authorization`)}snapshotHeaders(e,t){let r=n(this,I,`m`,R).call(this);return r.defaultHeaders??=F([e]),r.requestHeaders??=F([t]),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:t}=n(this,I,`m`,R).call(this);if(!e||!t)throw new o(`X.509 workload identity requires snapshotted request headers.`);return{defaultHeaders:e,requestHeaders:t}}snapshotTenant(e,t){if(e!==n(this,Qn,`f`)||t!==n(this,$n,`f`))throw new o(`X.509 workload identity cannot override its enrolled organization or project.`);let r=n(this,I,`m`,R).call(this);return r.tenant={organization:e,project:t},r.tenant}tenantSnapshot(){let{tenant:e}=n(this,I,`m`,R).call(this);if(!e)throw new o(`X.509 workload identity requires snapshotted tenant selectors.`);return e}snapshotAPIURL(e){ln(e),n(this,I,`m`,R).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=n(this,I,`m`,R).call(this);if(e===void 0)throw new o(`X.509 workload identity requires a snapshotted API destination.`);return e}snapshotRequest(e,t,r){var i;(i=n(this,I,`m`,R).call(this)).request??(i.request={signal:e,timeout:t,fetchOptions:r})}requestSnapshot(){let{request:e}=n(this,I,`m`,R).call(this);if(!e)throw new o(`X.509 workload identity requires snapshotted request settings.`);return e}beginRequestPreparation(){let e=n(this,I,`m`,R).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){n(this,I,`m`,R).call(this).phase=`planning`}beginRequestNetwork(){let e=n(this,I,`m`,R).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 n(this,I,`m`,R).call(this).phase===`planning`}authorizePlannedRequest(e,t,r,i=!1){let a=n(this,I,`m`,R).call(this),s=Object.getOwnPropertyDescriptor(t,`headers`),c=Object.getOwnPropertyDescriptor(t,`body`),l=Object.getOwnPropertyDescriptor(t,`signal`),u=Object.getOwnPropertyDescriptor(t,`redirect`);if(a.phase!==`planning`||!s||!(s.value instanceof Headers)||!c&&`body`in t||[c,l,u].some(e=>e&&!(`value`in e)))throw new o(`X.509 workload identity requires an approved final request.`);this.snapshotAPIURL(e),Sr(t);try{vr(s.value)}catch{throw new o(`X.509 workload identity cannot use caller-supplied authentication credentials.`)}if(mr(s.value,`Authorization`)!==null)throw new o(`X.509 workload identity cannot use caller-supplied authorization credentials.`);if(n(this,I,`m`,fr).call(this,s.value),!i&&(l?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new o(`X.509 workload identity must preserve its approved request signal.`);let d=this.requestSnapshot();a.request={...d,timeout:Math.min(d.timeout,r)},a.phase=`authorizing`}ownRequestBody(e,t){e instanceof ReadableStream&&e!==t&&(n(this,I,`m`,R).call(this).materializedBody=e)}static isStreamingRequestBody(e){return globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream||typeof e==`object`&&!!e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)}retireRequestBody(){let e=n(this,I,`m`,R).call(this),t=e.materializedBody;delete e.materializedBody,t&&n(qn,qn,`m`,ir).call(qn,t)}releaseRequestBody(e){let t=n(this,I,`m`,R).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?n(this,I,`m`,R).call(this).effectiveSignal=e:delete n(this,I,`m`,R).call(this).effectiveSignal}effectiveSignal(){let e=n(this,I,`m`,R).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,t){return n(this,L,`f`).run(async()=>{let r=n(this,L,`f`).current();if(!r)throw new o(`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=n(this,L,`f`).current();return t?.owner===this&&t.requestOwner===e&&t.phase!==`authorizing`}matches(e){return n(this,L,`f`)===n(e,L,`f`)&&n(this,Jn,`f`)===n(e,Jn,`f`)&&n(this,Yn,`f`)===n(e,Yn,`f`)&&n(this,Qn,`f`)===n(e,Qn,`f`)&&n(this,$n,`f`)===n(e,$n,`f`)&&n(this,er,`f`)===n(e,er,`f`)}continuation(){let{wallStartedAt:e,monotonicStartedAt:t,deadlineArmed:r,request:i,requestOwner:a,effectiveSignal:o}=n(this,I,`m`,R).call(this),s={wallStartedAt:e,monotonicStartedAt:t,owner:this,...r?{deadlineArmed:r}:{},...i?{request:i}:{},...o?{effectiveSignal:o}:{},...a?{requestOwner:a}:{}};return e=>n(this,L,`f`).resume(s,async()=>{try{return await e()}finally{this.releaseRequestCredentials(),delete s.requestOwner,delete s.owner}})}releaseRequestCredentials(){let e=n(this,I,`m`,R).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 n(this,L,`f`).current()?.wallStartedAt}usedWorkloadToken(e){return n(this,L,`f`).current()?.token!==void 0}remainingTimeout(e,t){let r=n(this,L,`f`).current();if(r===void 0)return t;let i=t-(performance.now()-r.monotonicStartedAt);if(i<=0)throw new u;return i}async waitForRetry(e,t){try{await n(this,L,`f`).sleep(e,t)}catch(e){throw t?.aborted?_r(t):e}}static isRetryableFailure(e){return typeof e==`object`&&!!e&&(Ln(e)||zn(e))}static retryHeaders(e){if(!e||typeof e!=`object`||!zn(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 _r(r);e&&Cr(t?t.fetchOptions:e.fetchOptions),n(this,I,`m`,dr).call(this,t);let i=e?n(this,I,`m`,R).call(this):void 0,a=n(this,tr,`f`);if(a&&performance.now()<a.refreshAt&&Date.now()<a.wallRefreshAt)return n(qn,qn,`m`,ar).call(qn,i,a);let{signal:o,dispose:s}=yr(t&&e?this.remainingTimeout(e,t.timeout):t?.timeout,r);if(r?.aborted)throw s(),_r(r);let l=n(this,nr,`f`)??n(this,I,`m`,lr).call(this);l.waiters+=1;let u=br(l,o);try{let e=await u.result,t=n(this,tr,`f`);if(!t||t.accessToken!==e.accessToken)throw new c;return n(qn,qn,`m`,ar).call(qn,i,t)}catch(r){return await n(this,I,`m`,or).call(this,r,l,a,i,e,t)}finally{u.dispose(),s(),--l.waiters,n(this,I,`m`,cr).call(this,l)}}invalidateToken(){let e=n(this,L,`f`).current();if(!e?.token||n(this,tr,`f`)?.accessToken!==e.token||n(this,tr,`f`).generation!==e.tokenGeneration)return;t(this,rr,n(this,rr,`f`)+1,`f`),t(this,tr,void 0,`f`);let r=n(this,nr,`f`);t(this,nr,void 0,`f`),r?.controller.abort(new c)}bindRequest(e,t,r){if(!(t.headers instanceof Headers))throw new o(`X.509 workload identity requires the original workload authorization headers.`);let i=n(this,I,`m`,R).call(this),{token:a}=i,s=e.__security??{bearerAuth:!0},c=a?`Bearer ${a}`:null;!a&&s.adminAPIKeyAuth&&r!==null&&mr(t.headers,`Authorization`)!==null&&(c=new Headers({Authorization:`Bearer ${r}`}).get(`Authorization`)),i.headers=t.headers,i.authorization=c,this.assertRequest(t)}adoptRequestHeaders(e){let t=n(this,I,`m`,R).call(this),r=t.headers;if(!(r instanceof Headers)||!(e.headers instanceof Headers))throw new o(`X.509 workload identity must preserve its issued workload authorization.`);t.headers=e.headers;try{this.assertRequest(e)}catch(e){throw t.headers=r,e}}assertRequest(e){let{headers:t}=e;if(!(t instanceof Headers))throw new o(`X.509 workload identity must preserve its issued workload authorization.`);let r=n(this,L,`f`).current();if(!r||r.headers!==t||r.authorization===void 0||mr(t,`Authorization`)!==r.authorization)throw new o(`X.509 workload identity must preserve its issued workload authorization.`);n(this,I,`m`,fr).call(this,t),vr(t)}fetch(){return async(e,t={})=>{let r=ln(typeof e==`string`||e instanceof URL?e:e.url);Sr(t),this.assertRequest(t);let i=t.headers;if(!(i instanceof Headers))throw new o(`X.509 workload identity must preserve its issued workload authorization.`);let a=new Headers([...Headers.prototype.entries.call(i)]);return vr(a),t.headers=a,t.redirect=`manual`,await n(this,L,`f`).dispatch(r,t)}}};qn=Tr,Jn=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,L=new WeakMap,er=new WeakMap,tr=new WeakMap,nr=new WeakMap,rr=new WeakMap,I=new WeakSet,ir=async function(e){try{await ye(e)}catch{}},ar=function(e,t){return e&&(e.token=t.accessToken,e.tokenGeneration=t.generation),t.accessToken},or=async function(e,t,r,i,a,o){let s=o?o.signal:a?.signal;if(s?.aborted)throw _r(s);if(t.controller.signal.aborted&&t.generation!==n(this,rr,`f`))return await this.getToken(a,o);let c=n(this,I,`m`,sr).call(this,e,r,i);if(c!==void 0)return c;if(e&&typeof e==`object`&&!(e instanceof S)){let t=Un(e);if(t)throw new S(t.status,t.error,t.headers)}throw e},sr=function(e,t,r){if(!t||t!==n(this,tr,`f`)||performance.now()>=t.expiresAt||Date.now()>=t.wallExpiresAt||!qn.isRetryableFailure(e))return;let i=qn.retryHeaders(e),a=i?.get(`retry-after-ms`),o=a?Number(a):void 0,s=i?.get(`retry-after`);if(s&&(o===void 0||Number.isNaN(o))){let e=Number(s);o=Number.isNaN(e)?Date.parse(s)-Date.now():e*1e3}let c=o!==void 0&&Number.isFinite(o)&&o>=0&&o<=6e4?Math.max(gr,o):gr;return t.refreshAt=Math.min(t.expiresAt,performance.now()+c),t.wallRefreshAt=Math.min(t.wallExpiresAt,Date.now()+c),n(qn,qn,`m`,ar).call(qn,r,t)},cr=function(e){e.waiters===0&&n(this,nr,`f`)===e&&queueMicrotask(()=>{e.waiters===0&&n(this,nr,`f`)===e&&(t(this,nr,void 0,`f`),t(this,rr,n(this,rr,`f`)+1,`f`),e.controller.abort(new c))})},lr=function(){let e=new AbortController,r=n(this,rr,`f`),i={controller:e,generation:r,waiters:0,promise:n(this,I,`m`,ur).call(this,e,r)};return t(this,nr,i,`f`),i},ur=async function(e,r){let i=performance.now(),a=Date.now();try{let s=await n(this,L,`f`).exchange(n(this,Jn,`f`),n(this,Yn,`f`),e.signal),l=s.expiresIn*1e3,u=i+l,d=a+l;if(performance.now()>=u||Date.now()>=d)throw new o(`X.509 workload identity token expired before its exchange completed.`);if(n(this,rr,`f`)!==r||e.signal.aborted||n(this,nr,`f`)?.controller!==e)throw new c;return t(this,rr,n(this,rr,`f`)+1,`f`),t(this,tr,{accessToken:s.accessToken,generation:n(this,rr,`f`),expiresAt:u,refreshAt:u-Math.min(n(this,er,`f`),l/2),wallExpiresAt:d,wallRefreshAt:d-Math.min(n(this,er,`f`),l/2)},`f`),s}finally{n(this,nr,`f`)?.controller===e&&t(this,nr,void 0,`f`)}},dr=function(e){if(!e)return;if(e.organization!==n(this,Qn,`f`)||e.project!==n(this,$n,`f`))throw new o(`X.509 workload identity cannot override its enrolled organization or project.`);ln(e.apiURL);let t=F([e.defaultHeaders,e.requestHeaders]);if(n(this,Qn,`f`)!==null&&t.nulls.has(`openai-organization`)||n(this,$n,`f`)!==null&&t.nulls.has(`openai-project`))throw new o(`X.509 workload identity cannot omit its enrolled organization or project.`);for(let n of t.values.keys()){let r=n.toLowerCase().split(`_`).join(`-`);if((r===`openai-organization`||r===`openai-project`)&&(n!==r||mr(t.values,n)!==(r===`openai-organization`?e.organization:e.project)))throw new o(`X.509 workload identity cannot override its enrolled organization or project.`);if(He(r)||r===`host`)throw new o(`X.509 workload identity cannot use caller-supplied authentication credentials.`)}},R=function(){let e=n(this,L,`f`).current();if(!e||e.owner!==this)throw new o(`X.509 workload identity requires an active certificate request scope.`);return e},fr=function(e){if(mr(e,`OpenAI-Organization`)!==n(this,Qn,`f`)||mr(e,`OpenAI-Project`)!==n(this,$n,`f`))throw new o(`X.509 workload identity cannot override its enrolled organization or project.`);for(let t of Headers.prototype.keys.call(e)){let e=t.toLowerCase().split(`_`).join(`-`);if((e===`openai-organization`||e===`openai-project`)&&t!==e)throw new o(`X.509 workload identity cannot override its enrolled organization or project.`)}};function Er(e){let{credential:t}=e;if(t===void 0)return{credential:t,options:e};let n=Gn(t);if(!n)throw new o(`An X.509 credential must be created by the SDK authentication helper.`);let r=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`x509Transport`].filter(t=>e[t]!=null);if(r.length>0)throw new o(`The \`credential\` option cannot be combined with ${r.map(e=>`\`${e}\``).join(`, `)}.`);return{credential:t,options:{...e,apiKey:null,adminAPIKey:null,baseURL:e.baseURL??null,organization:e.organization??null,project:e.project??null,workloadIdentity:n.identity,x509Transport:n.transport}}}function Dr({apiKey:e,adminAPIKey:t}){return e!=null||t!=null}function Or(e,t){let n=e.provider,r=t.credential??t.workloadIdentity,i=t.provider??(r?void 0:n);return i!==n&&(delete e.baseURL,delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions,delete e.fetch),i&&(delete e.apiKey,delete e.adminAPIKey,delete e.credential,delete e.workloadIdentity,delete e.x509Transport,delete e.baseURL),i}function kr(e,t,n,r){let i=E(t,`workloadIdentity`)?t.workloadIdentity:e.workloadIdentity,a=n!==void 0&&(Dr(t)&&t.workloadIdentity===void 0||t.provider!==void 0);n!==void 0&&E(t,`workloadIdentity`)&&delete e.x509Transport;let o=n!==void 0&&!a&&t.credential===void 0&&!E(t,`workloadIdentity`)&&!E(t,`x509Transport`)?n:void 0,s=t.credential===void 0?o:t.credential,c=s!==void 0||!a&&xr(i);return r!==c&&(delete e.fetch,delete e.baseURL,delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions,c?e.apiKey=null:(delete e.x509Transport,a&&delete e.workloadIdentity)),s!==void 0&&(delete e.apiKey,delete e.adminAPIKey,delete e.workloadIdentity,delete e.x509Transport,e.credential=s,t.credential!==void 0&&(delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions)),{credential:s,provider:Or(e,t)}}var Ar=Symbol(`brand.privateStreamingFile`);function jr(e,t,n){if(typeof t!=`string`||!t)throw TypeError(`toStreamingFile requires a non-empty file name`);let r=n?.type;return r&&ii(r),{[Ar]:!0,data:e,name:t,...r?{type:r}:{}}}var Mr=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&Number.parseInt(e.versions.node.split(`.`),10)<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function Nr(e,t,n){return Mr(),new File(e,t??`unknown_file`,n)}function Pr(e,t){if(typeof e!=`object`||!e)return;let n=`name`in e?e.name:void 0,r=n&&String(n)||`filename`in e&&e.filename&&String(e.filename);if(r)return t?.stripFilename===!1?Ir(r):Fr(r);let i=`url`in e&&e.url&&String(e.url);if(i)try{return Fr(new URL(i).pathname)}catch{return Fr(i)}let a=`path`in e&&e.path&&String(e.path);return a?Fr(a):void 0}function Fr(e){return e.split(/[\\/]/).pop()||void 0}function Ir(e){let t=e.replace(/\\/g,`/`);if(t.startsWith(`/`)||/^[A-Za-z]:/.test(t)||t.split(`/`).includes(`..`))throw TypeError(`Upload file name must be a safe relative path without parent directory segments`);return t}var Lr=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,`byteLength`)?.get;function Rr(e){try{return Lr?.call(e)!==void 0}catch{return!1}}var zr=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Br=async(e,t,n)=>Xr(e.body)?Yr(e.body)?Qr(e,n):{...e,body:await Wr(e.body,t,n)}:e,Vr=async(e,t,n)=>Yr(e.body)?Qr(e,n):{...e,body:await Wr(e.body,t,n)},Hr=new WeakMap;function Ur(e){let t=typeof e==`function`?e:e.fetch,n=Hr.get(t);if(n)return n;let r=(async()=>{try{let e;if(`Response`in t)e=t.Response;else{let n=await t(`data:,`);await n.arrayBuffer(),e=n.constructor}let n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Hr.set(t,r),r}var Wr=async(e,t,n={})=>{if(!await Ur(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>ci(r,e,t,n))),r},Gr=e=>e instanceof Blob,Kr=e=>typeof e==`object`&&!!e&&`getReader`in e&&typeof e.getReader==`function`,qr=e=>typeof e==`object`&&!!e&&Ar in e,Jr=e=>typeof e==`object`&&!!e&&(e instanceof Response||zr(e)||Kr(e)||qr(e)||Gr(e)),Yr=e=>{if(qr(e)||zr(e)||Kr(e))return!0;if(Array.isArray(e))return e.some(Yr);if(e&&typeof e==`object`&&!Gr(e)&&!(e instanceof Response)){for(let t of Object.keys(e))if(Yr(e[t]))return!0}return!1},Xr=e=>{if(Jr(e))return!0;if(Array.isArray(e))return e.some(Xr);if(e&&typeof e==`object`){for(let t of Object.keys(e))if(Xr(e[t]))return!0}return!1},Zr=(e,t)=>{let n=[];for(let r of e)Jr(r.value)&&!t.has(r.value)&&t.set(r.value,ni(r.value,{stripFilenames:!1})),n.push(r);return n},Qr=(e,t={})=>{let n=ei(e.body),r=t.stripFilenames===!1?new WeakMap:void 0,i=r?Zr(n,r):n,a=`openai-${Math.random().toString(36).slice(2)}`,o=_e($r(i,a,t,r));return{...e,body:o,headers:F([{"content-type":`multipart/form-data; boundary=${a}`},e.headers])}};async function*$r(e,t,n,r){for await(let{key:i,value:a}of e){if(Jr(a)){let e=r?.get(a)??ni(a,n),o=ri(a);yield xe(`--${t}\r\n`),yield xe(`Content-Disposition: form-data; name="${si(i)}"; filename="${si(e)}"\r\nContent-Type: ${o}\r\n\r\n`),yield*oi(ai(a))}else yield xe(`--${t}\r\n`),yield xe(`Content-Disposition: form-data; name="${si(i)}"\r\n\r\n${String(a)}`);yield xe(`\r
6
+ `)}yield xe(`--${t}--\r\n`)}function*ei(e){if(e&&typeof e==`object`)for(let[t,n]of Object.entries(e))yield*ti(t,n)}function*ti(e,t){if(t!==void 0){if(t==null)throw TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`||Jr(t))yield{key:e,value:t};else if(Array.isArray(t))for(let n of t)yield*ti(e+`[]`,n);else if(typeof t==`object`)for(let[n,r]of Object.entries(t))yield*ti(`${e}[${n}]`,r);else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}}function ni(e,t){if(qr(e)){let{name:n}=e;if(typeof n!=`string`||!n)throw TypeError(`Streaming upload file name must be a non-empty string`);return t.stripFilenames===!1?Ir(n):Fr(n)??`unknown_file`}return Pr(e,{stripFilename:t.stripFilenames})??`unknown_file`}function ri(e){let t;return qr(e)||Gr(e)?{type:t}=e:e instanceof Response&&(t=e.headers.get(`content-type`)??void 0),ii(t||`application/octet-stream`)}function ii(e){if(typeof e!=`string`)throw TypeError(`Streaming upload content type must be a string`);for(let t=0;t<e.length;t+=1){let n=e.codePointAt(t)??0;if(n<=31||n===127)throw TypeError(`Streaming upload content type must not contain control characters`)}return e}function ai(e){return qr(e)?e.data:e}async function*oi(e){if(typeof e==`string`)yield xe(e);else if(ArrayBuffer.isView(e))yield new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(Rr(e))yield new Uint8Array(e);else if(e instanceof Response)yield*oi(e.body||await e.blob());else if(e instanceof Blob)typeof e.stream==`function`?yield*oi(e.stream()):yield new Uint8Array(await e.arrayBuffer());else if(Kr(e))for await(let t of ve(e))yield*oi(t);else if(zr(e))for await(let t of e)yield*oi(t);else throw TypeError(`Invalid streaming file chunk: ${String(e)}`)}function si(e){return Array.from(e,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e===`"`||e===`\\`?encodeURIComponent(e):e}).join(``)}var ci=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i=await n.blob();e.append(t,Nr([i],Pr(n,{stripFilename:r.stripFilenames}),{type:i.type}))}else if(zr(n))e.append(t,Nr([await new Response(_e(n)).blob()],Pr(n,{stripFilename:r.stripFilenames})));else if(Gr(n)){let i=Pr(n,{stripFilename:r.stripFilenames});i===void 0?e.append(t,n):e.append(t,n,i)}else if(Array.isArray(n)){let i=await Promise.all(n.map(async e=>{let n=new FormData;return await ci(n,t+`[]`,e,r),n}));for(let t of i)if(t)for(let[n,r]of t.entries())e.append(n,r)}else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>ci(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},li=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,ui=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&li(e),di=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`,fi=(e,t)=>t?.type!=null&&t.type!==e.type||t?.lastModified!=null&&t.lastModified!==e.lastModified||t?.endings!=null,pi=(e,t,n)=>(t==null||t===e.name)&&!fi(e,n);async function mi(e,t,n){if(Mr(),e=await e,ui(e)){let r={...n,type:n?.type??e.type,lastModified:n?.lastModified??e.lastModified};return e instanceof File?pi(e,t,n)?e:Nr([e],t??e.name,r):Nr([await e.arrayBuffer()],t??e.name,r)}if(di(e)){let r=await e.blob();t??=Pr(e);let i=n?.type===void 0&&r.type?{...n,type:r.type}:n;return Nr(await hi(r),t,i)}let r=await hi(e);if(t??=Pr(e),n?.type===void 0){let e=r.find(e=>typeof e==`object`&&`type`in e&&!!e.type);e&&(n={...n,type:e.type})}return Nr(r,t,n)}async function hi(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||Rr(e))t.push(e);else if(li(e))t.push(e instanceof Blob?e:new Blob([await e.arrayBuffer()],{type:e.type}));else if(zr(e))for await(let n of e)t.push(...await hi(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${gi(e)}`)}return t}function gi(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var z=class{constructor(e){this._client=e}};function _i(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var vi=Object.freeze(Object.create(null)),B=((e=_i)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=``;for(let o=0;o<t.length;o+=1)if(o in t){let s=t[o];/[?#]/.test(s)&&(r=!0);let c=n[o],l=(r?encodeURIComponent:e)(``+c);o!==n.length&&(c==null||typeof c==`object`&&c.toString===Object.getPrototypeOf(Object.getPrototypeOf(c.hasOwnProperty??vi)??vi)?.toString)&&(l=c+``,i.push({start:a.length+s.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),a+=s+(o===n.length?``:l)}let s=a.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(s))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=``;for(let n of i){let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);e=n.start+n.length,t+=r+i}throw new o(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
7
+ `)}\n${a}\n${t}`)}return a})(_i);function yi(e,t){return Promise.resolve(e).then(t)}var bi=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function xi(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>bi.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!bi.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Si=class extends z{list(e,t={},n){let r=xi(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/chat/completions/${e}/messages`,N,yi(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}};function Ci(e){return e!==void 0&&`function`in e&&e.function!==void 0}function wi(e){return e?.$brand===`auto-parseable-response-format`}function Ti(e){return wi(e)||e?.type===`json_schema`}function Ei(e,t){if(!Ti(e))return null;if(typeof e==`object`&&e&&`$parseRaw`in e&&typeof e.$parseRaw==`function`)return e.$parseRaw(t);try{return JSON.parse(t)}catch(e){throw e instanceof SyntaxError?SyntaxError(`Error reading response: invalid structured output JSON.`):e}}function Di(e){return e?.$brand===`auto-parseable-tool`}function Oi(e,t){return!t||!Ni(t)?{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:ki(e,t)}function ki(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new y;if(e.finish_reason===`content_filter`)throw new b;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>ji(t,e))??void 0}:void 0,parsed:e.message.content!==null&&e.message.content!==void 0&&!e.message.refusal&&(e.message.content!==``||!e.message.tool_calls?.length&&!e.message.function_call)?Ai(t,e.message.content):null}}});return{...e,choices:n}}function Ai(e,t){return Ei(e.response_format,t)}function ji(e,t){if(t.type===`custom`)return t;if(t.type!==`function`){let e=t.type;throw new o(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${e}\``)}let n=e.tools?.find(e=>Ci(e)&&e.function?.name===t.function.name),r=null;return Di(n)?r=n.$parseRaw(t.function.arguments):n?.function.strict&&(r=Ei({type:`json_schema`,$parseRaw:void 0},t.function.arguments)),{...t,function:{...t.function,parsed_arguments:r}}}function Mi(e,t){if(!e||!(`tools`in e)||!e.tools||t.type!==`function`)return!1;let n=e.tools?.find(e=>Ci(e)&&e.function?.name===t.function?.name);return Ci(n)&&(Di(n)||n?.function.strict||!1)}function Ni(e){return Ti(e.response_format)?!0:e.tools?.some(e=>Di(e)||e.type===`function`&&e.function.strict===!0)??!1}function Pi(e){for(let t of e??[])if(t.type!==`custom`){if(t.type!==`function`){let e=t.type;throw new o(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${e}\``)}if(t.function.strict!==!0)throw new o(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Fi=e=>e?.role===`assistant`,Ii=e=>e?.role===`tool`,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa,ca=4096,la=8388608,ua=4096,da=256,fa=JSON.stringify,pa=JSON.parse,ma=new WeakSet,ha=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`buffer`)?.get,ga=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`length`)?.get,_a=Object.getOwnPropertyDescriptor(DataView.prototype,`buffer`)?.get,va=Object.getOwnPropertyDescriptor(Symbol.prototype,`description`)?.get,ya=Date.prototype.getTime,ba=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,`byteLength`)?.get,xa=typeof SharedArrayBuffer==`function`?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,`byteLength`)?.get:void 0,Sa=Object.getOwnPropertyDescriptor(Error(`native stack descriptor`),`stack`),Ca=Function.prototype.toString,wa=Object.prototype.toString,Ta=Object.getOwnPropertyDescriptor(Error,`isError`),Ea=Ta&&`value`in Ta&&typeof Ta.value==`function`?Ta.value:void 0,Da=Ca.call(Error),Oa=Ca.call(Date),ka=Ca.call(Function),Aa=new Set([l.prototype,u.prototype,s.prototype,o.prototype,c.prototype,f.prototype,d.prototype,h.prototype,b.prototype,v.prototype,x.prototype,y.prototype,m.prototype,S.prototype,p.prototype,_.prototype,C.prototype,g.prototype]),ja=new Set,Ma=new Map,Na=new WeakMap;function Pa(){if(typeof process<`u`)try{let e=Object.getOwnPropertyDescriptor(process,`getBuiltinModule`);if(!e||!(`value`in e)||typeof e.value!=`function`)return;let t=Reflect.apply(e.value,process,[`node:util`]);if(typeof t!=`object`||!t)return;let n=Object.getOwnPropertyDescriptor(t,`types`);if(!n||!(`value`in n)||typeof n.value!=`object`||n.value===null)return;let r=Object.getOwnPropertyDescriptor(n.value,`isProxy`);return!r||!(`value`in r)||typeof r.value!=`function`?void 0:r.value}catch{return}}var Fa=Pa();function Ia(e){if(typeof e!=`function`)return;let t=Object.getOwnPropertyDescriptor(e,`prototype`);if(!t||!(`value`in t)||typeof t.value!=`object`&&typeof t.value!=`function`)return;Aa.add(t.value);let n=Ca.call(e);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n)&&t.configurable===!1&&t.writable===!1){ja.add(n);let e=new Map;for(let n of Reflect.ownKeys(t.value)){let r=Object.getOwnPropertyDescriptor(t.value,n);r&&e.set(n,r)}Ma.set(n,e)}}for(let e 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])Ia(e);for(let e of[`SharedArrayBuffer`,`AggregateError`,`Float16Array`,`BigInt64Array`,`BigUint64Array`,`Blob`,`File`,`Headers`]){let t=Object.getOwnPropertyDescriptor(globalThis,e);t&&`value`in t&&Ia(t.value)}var La=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`constructor`);La&&`value`in La&&Ia(La.value),typeof Buffer==`function`&&Ia(Buffer);var Ra=(()=>{if(typeof Blob==`function`)try{let e=new Blob([]);for(let t of Object.getOwnPropertySymbols(e)){let n=Object.getOwnPropertyDescriptor(e,t);if(n&&`value`in n&&typeof n.value==`object`&&n.value)return Object.getPrototypeOf(n.value)}}catch{return}})(),za=Map.prototype.entries,Ba=Set.prototype.values,Va=typeof Headers==`function`?Object.getOwnPropertyDescriptor(Headers.prototype,`entries`):void 0,Ha=Va&&`value`in Va&&typeof Va.value==`function`?Va.value:void 0,Ua=new Set([`ArrayBuffer`,`SharedArrayBuffer`,`Blob`,`File`,`Map`,`Date`,`Set`,`Headers`]);function Wa(e){let t=Object.getOwnPropertyDescriptor(e,`constructor`);if(!t||!(`value`in t)||typeof t.value!=`function`)return;let n=t.value,r=Ca.call(n),i=Ma.get(r);if(!ja.has(r)||!i)return;let a=Object.getOwnPropertyDescriptor(n,`prototype`);if(a&&`value`in a&&a.value===e&&a.configurable===!1&&a.writable===!1)return{constructor:n,descriptors:i,functionPrototype:Object.getPrototypeOf(n)}}function Ga(e){return Aa.has(e)||Wa(e)!==void 0}function Ka(e,t,n){if(t===void 0)return e===void 0;if(typeof e!=`function`||typeof t!=`function`)return!1;let r=Ca.call(t);if(Ca.call(e)!==r)return!1;let i=Object.getPrototypeOf(e);if(i===n)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(r))return!1;let a=Wa(i);return a!==void 0&&Ca.call(a.constructor)===ka}function qa(e,t,n){return!t||e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t?!1:`value`in e&&`value`in t?e.writable===t.writable?typeof t.value==`function`?Ka(e.value,t.value,n):t.value!==null&&typeof t.value==`object`?!1:Object.is(e.value,t.value):!1:Ka(e.get,t.get,n)&&Ka(e.set,t.set,n)}function Ja(e){if(Ea)return Ea.call(Error,e);let t=e;for(let e=0;t!==null&&e<da;e+=1){if(Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))return!1;t=Object.getPrototypeOf(t)}return t===null&&wa.call(e)===`[object Error]`}function Ya(e,t){if(typeof t.get!=`function`||typeof t.set!=`function`)return;let n=Object.getPrototypeOf(e);for(let e=0;n!==null&&e<da;e+=1){let e=Object.getOwnPropertyDescriptor(n,`constructor`);if(e&&`value`in e&&typeof e.value==`function`){let r=e.value;if(Ca.call(r)===Da&&Ga(n)){let e=Object.getPrototypeOf(r);return Object.getPrototypeOf(t.get)===e&&Object.getPrototypeOf(t.set)===e?{constructor:r,prototype:n}:void 0}}n=Object.getPrototypeOf(n)}}function Xa(e,t){if(!Ja(e))return!1;if(Sa&&!(`value`in Sa)&&typeof Sa.get==`function`&&Object.prototype.isPrototypeOf.call(Error.prototype,e)&&t.get===Sa.get&&t.set===Sa.set)return!0;let n=Ya(e,t);if(!n)return!1;let r=Na.get(n.prototype);if(!r){let e=Reflect.construct(n.constructor,[]);if(typeof e!=`object`||!e||!Ja(e)||Object.getPrototypeOf(e)!==n.prototype||(r=Object.getOwnPropertyDescriptor(e,`stack`),!r||`value`in r||typeof r.get!=`function`||typeof r.set!=`function`))return!1;Na.set(n.prototype,r)}return t.get===r.get&&t.set===r.set}function Za(){let e=[],t=0;return{get length(){return e.length-t},enqueue(t){e.push(t)},dequeue(){if(t===e.length)return;let n=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&t*2>=e.length&&(e=e.slice(t),t=0),n},clear(){e=[],t=0}}}function Qa(e){let t=Object.getPrototypeOf(e);for(let e=0;t!==null&&e<da;e+=1){if(t===Date.prototype)return`Date`;if(!Aa.has(t)){let e=Object.getOwnPropertyDescriptor(t,`constructor`);if(e&&`value`in e&&typeof e.value==`function`&&Ca.call(e.value)===Oa&&Wa(t))return`Date`}let e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);if(e&&`value`in e&&typeof e.value==`string`&&Ua.has(e.value))return e.value;t=Object.getPrototypeOf(t)}}function $a(e,t,n){if(ArrayBuffer.isView(e)){let r,i=`typed-array`;try{r=ha?.call(e)}catch{i=`data-view`,r=_a?.call(e)}return typeof r!=`object`||!r?{bytes:1/0,kind:i}:(t(r,n+1),{bytes:0,kind:i})}let r=Qa(e);if(!r)return;let i;switch(r){case`ArrayBuffer`:i=ba;break;case`SharedArrayBuffer`:i=xa;break;case`Blob`:case`File`:return{bytes:1/0,kind:`blob`};case`Map`:return{bytes:0,kind:`map`};case`Date`:return Reflect.apply(ya,e,[]),{bytes:8,kind:`date`};case`Set`:return{bytes:0,kind:`set`};case`Headers`:return{bytes:0,kind:`headers`};default:return}let a=i?.call(e);return{bytes:typeof a==`number`&&Number.isSafeInteger(a)&&a>=0?a:1/0,kind:`buffer`}}function eo(e,t,n){if(t===`map`){for(let[t,r]of za.call(e))if(!n(t,8)||!n(r,8))return!1}if(t===`set`){for(let t of Ba.call(e))if(!n(t,8))return!1}if(t===`headers`){if(!Ha)return!1;for(let[t,r]of Ha.call(e))if(!n(t,8)||!n(r,8))return!1}return!0}function to(e,t,n){if(Array.isArray(e)){let t=Object.getOwnPropertyDescriptor(e,`length`),r=t&&`value`in t?t.value:void 0;if(typeof r!=`number`||!Number.isSafeInteger(r)||r<0||r>Math.floor(n/16))return}if(t!==`typed-array`)return Reflect.ownKeys(e);let r=ga?.call(e);if(!(typeof r!=`number`||!Number.isSafeInteger(r)||r<0||r>ua))return Reflect.ownKeys(e).filter(e=>{if(typeof e!=`string`)return!0;let t=Number(e);return!Number.isInteger(t)||t<0||t>=r||String(t)!==e})}function no(e,t,n,r,i,a){let o=to(e,t,r());if(o===void 0)return!1;for(let r of o){if(!i(typeof r==`string`?r.length*2+8:8))return!1;typeof r==`symbol`&&a(r,n+1);let o=Object.getOwnPropertyDescriptor(e,r);if(!o)return!1;if(!(`value`in o)){if(r===`stack`&&Xa(e,o))continue;return!1}a(o.value,n+1,t===`blob`)}return!0}function ro(e,t,n,r,i,a,o,s){let c=Object.getPrototypeOf(e);for(let e=t+1;c!==null;e+=1){if(e>=da)return!1;if(Aa.has(c)||n&&c===Ra)return!0;if(r.has(c))return o(c,e),i()>=0;r.add(c);let t=c;if(!s(t,()=>{if(!a(16))return!1;let n=Wa(t);if(!n)return no(t,void 0,e,i,a,o);for(let r of Reflect.ownKeys(t)){let i=Object.getOwnPropertyDescriptor(t,r);if(!i)return!1;if(!qa(i,n.descriptors.get(r),n.functionPrototype)){if(!a(typeof r==`string`?r.length*2+8:8)||!(`value`in i))return!1;typeof r==`symbol`&&o(r,e+1),o(i.value,e+1)}}return i()>=0}))return!1;c=Object.getPrototypeOf(t)}return!0}var io=32,ao=32,oo=8,so=16,co=131072;function lo(e,t){let n=0,r=0,i=new WeakSet,a=new Set,o=new Set,s=new Map,c,l=()=>t-n,u=e=>!Number.isSafeInteger(e)||e<0?(n=t+1,!1):(n+=e,c?c.bytes+=e:r+=e,n<=t),d=e=>{c?c.edges.add(e):o.add(e)},f=(e,t)=>{d(e);let n={bytes:0,edges:new Set};s.set(e,n);let r=c;c=n;try{return t()}finally{c=r}},p=e=>{if(a.has(e)){d(e),u(8);return}a.add(e),f(e,()=>{if(!va)return!1;let t=Reflect.apply(va,e,[]);return u(8+(t?.length??0)*2)})||(n=t+1)},m=(e,r,a=!1)=>{if(!(n>t)){if(typeof e==`string`){u(e.length*2);return}if(typeof e==`symbol`){p(e);return}if(typeof e==`function`){n=t+1;return}if(typeof e!=`object`||!e){u(8);return}if(Fa?.(e)){n=t+1;return}if(r>=da){n=t+1;return}if(i.has(e)){d(e),u(8);return}i.add(e),f(e,()=>{if(!u(16))return!1;let o=$a(e,m,r);return!ro(e,r,a,i,l,u,m,f)||o!==void 0&&!u(o.bytes)||!eo(e,o?.kind,(e,i)=>u(i)?(m(e,r+1),n<=t):!1)?!1:no(e,o?.kind,r,l,u,m)})||(n=t+1)}};try{m(e,0)}catch{return}return n<=t?{scalarBytes:r,roots:o,nodes:s}:void 0}function uo(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function fo(e,t){return e.bytes+ao+e.edges.size*oo+t*so}function po(e){return io+e.scalarBytes+e.roots.size*oo}function mo(e,t,n,r){let i=new Set,a=[...e];for(;a.length;){if(--r.remaining,r.remaining<0)return;let e=a.pop();if(i.has(e))continue;let o=t.get(e)??n.get(e);if(!o)return;i.add(e);for(let e of o.edges)a.push(e)}return i}function ho(e,t,n,r,i){let a=r.get(e);if(a)return i&&(a.node=i),a;let o=i??t.nodes.get(e)??n.get(e);if(!o)return;let s={node:o,ownerDelta:0};return r.set(e,s),s}function go(e,t,n,r,i){let a=new Set([e]);for(let[e,o]of t.nodes){if(--i.remaining,i.remaining<0)return;let s=n.get(e);if(!s)continue;let c=!uo(s.edges,o.edges);if((s.bytes!==o.bytes||c)&&ho(e,t,n,r,o),c)for(let e of s.owners){if(--i.remaining,i.remaining<0)return;a.add(e)}}return a}function _o(e,t,n,r,i,a){for(let o of e.identities){if(--a.remaining,a.remaining<0)return!1;if(!t.has(o)){let e=ho(o,n,r,i);if(!e)return!1;--e.ownerDelta}}for(let o of t){if(--a.remaining,a.remaining<0)return!1;if(!e.identities.has(o)){let e=ho(o,n,r,i);if(!e)return!1;e.ownerDelta+=1}}return!0}function vo(e,t,n,r,i,a){let o=new Map;for(let s of n){let n=mo(s===e?t.roots:s.roots,t.nodes,r,a);if(!n||!_o(s,n,t,r,i,a))return;o.set(s,n)}return o}function yo(e,t,n,r,i,a){let o=e-(r?0:po(t))+po(n);for(let[e,t]of i){let n=a.get(e),r=(n?.owners.size??0)+t.ownerDelta;if(r<0)return;n&&(o-=fo(n,n.owners.size)),r&&(o+=fo(t.node,r))}return Number.isSafeInteger(o)&&o>=0&&o<=la?o:void 0}function bo(e,t,n){for(let[n,r]of t){let t=e.get(n);(t?.owners.size??0)+r.ownerDelta&&(t?(t.bytes=r.node.bytes,t.edges=r.node.edges):e.set(n,{bytes:r.node.bytes,edges:r.node.edges,owners:new Set}))}for(let[t,r]of n){for(let n of t.identities)r.has(n)||e.get(n)?.owners.delete(t);for(let n of r)t.identities.has(n)||e.get(n).owners.add(t);t.identities=r}for(let n of t.keys())e.get(n)?.owners.size===0&&e.delete(n)}function xo(){let e=new Map,t=0,n=(n,r,i)=>{let a={remaining:co},o=new Map,s=go(n,r,e,o,a);if(!s)return!1;let c=vo(n,r,s,e,o,a);if(!c)return!1;let l=yo(t,n,r,i,o,e);return l!==void 0&&(bo(e,o,c),n.scalarBytes=r.scalarBytes,n.roots=r.roots,t=l,!0)};return{retain(e){let t={scalarBytes:0,roots:new Set,identities:new Set};return n(t,e,!0)?t:void 0},refresh(e,t){return n(e,t,!1)},release:n=>{t-=po(n);for(let r of n.identities){let i=e.get(r);i?.owners.delete(n)&&(t-=so,i.owners.size===0&&(t-=fo(i,0),e.delete(r)))}n.identities.clear()},clear(){e.clear(),t=0}}}var So=class{constructor(){Li.add(this),this.controller=new AbortController,Ri.set(this,void 0),zi.set(this,()=>void 0),Bi.set(this,()=>void 0),Vi.set(this,void 0),Hi.set(this,()=>void 0),Ui.set(this,()=>void 0),Wi.set(this,Object.create(null)),Gi.set(this,[]),Ki.set(this,new WeakMap),qi.set(this,new Set),Ji.set(this,new Set),Yi.set(this,0),Xi.set(this,!1),Zi.set(this,!1),Qi.set(this,!1),$i.set(this,!1),ea.set(this,void 0),t(this,Ri,new Promise((e,n)=>{t(this,zi,e,`f`),t(this,Bi,n,`f`)}),`f`),t(this,Vi,new Promise((e,n)=>{t(this,Hi,e,`f`),t(this,Ui,n,`f`)}),`f`),n(this,Ri,`f`).catch(()=>void 0),n(this,Vi,`f`).catch(()=>void 0)}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(e=>{t=!0,n(this,Li,`m`,oa).call(this,e)}).then(()=>{if(!t){try{this._emitFinal()}catch(e){n(this,Li,`m`,oa).call(this,e);return}this._emit(`end`)}})},0)}_connected(){this.ended||(n(this,zi,`f`).call(this),this._emit(`connect`))}get ended(){return n(this,Xi,`f`)}get errored(){return n(this,Zi,`f`)}get aborted(){return n(this,Qi,`f`)}abort(){this.controller.abort()}_userAbortError(){let e=new c;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){n(this,Li,`m`,ta).call(this,e);return}if(n(this,Gi,`f`).some(t=>t.signal===e))return;let t=()=>n(this,Li,`m`,ta).call(this,e);e.addEventListener(`abort`,t,{once:!0}),n(this,Gi,`f`).push({signal:e,listener:t})}on(e,t){var r;return((r=n(this,Wi,`f`))[e]||(r[e]=[])).push({listener:t}),this}off(e,t){let r=n(this,Wi,`f`)[e];if(!r)return this;let i=n(this,Ki,`f`).get(t);if(i?.event===e&&!i.registration.removed&&!i.registration.detached)return n(this,Li,`m`,ia).call(this,e,i.registration),this;let a=r.findIndex(e=>!e.removed&&e.listener===t);return a!==-1&&r.splice(a,1),this}once(e,t){var r;return((r=n(this,Wi,`f`))[e]||(r[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((r,i)=>{t(this,$i,!0,`f`);let a=t=>{this.off(e,o),i(t)},o=(...t)=>{e!==`error`&&this.off(`error`,a),r(t.length>1?t:t[0])};e!==`error`&&n(this,Li,`m`,ra).call(this,`error`,a),n(this,Li,`m`,ra).call(this,e,o)})}events(e){return this._createIterator(t=>{let n=(...e)=>{ma.add(e);try{t(e)}finally{ma.delete(e)}};return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!==`error`,rejectOnAbort:e!==`abort`})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:r=!0,onReturn:i}={}){let a=Za(),s=Za(),c=Za(),l=xo(),u=this.ended,d,f=!1,p=()=>void 0,m=()=>({value:void 0,done:!0}),h=()=>{for(;c.length;)c.dequeue().resolve(m())},g=()=>{d&&!f&&c.length&&(f=!0,c.dequeue().reject(d))},_=()=>{p(),this.off(`end`,w),t&&this.off(`error`,S),r&&this.off(`abort`,S)},v=e=>{e.active=!1,e.check&&=(n(this,Ji,`f`).delete(e.check),void 0)},y=(e=!1)=>{if(e){for(;s.length;)v(s.dequeue());a.clear(),l.clear()}let t=new o(`Event stream iterator buffer limit exceeded (${ca} events or ${la} bytes); consume events as they arrive.`);try{n(this,Li,`m`,oa).call(this,t)}finally{this.controller.abort()}return t},b=(e,t)=>{if(!t.active||n(this,Xi,`f`))return;let r=lo(e,la);(!r||!l.refresh(t.retention,r))&&y(!0)},x=e=>{if(u)return;let t=c.dequeue();if(t)t.resolve({value:e,done:!1});else{if(a.length>=ca){y();return}let t=lo(e,la),r=t&&l.retain(t);if(!r){y();return}if(typeof e==`object`&&e&&ma.has(e)){let t=e;for(let e=0;e<t.length;e+=1){let n=t[e];typeof n==`string`&&(t[e]=pa(fa(n)))}}let i={retention:r,active:!0,check:void 0};a.enqueue(e),s.enqueue(i);let o=()=>{i.check=void 0,b(e,i)};i.check=o,n(this,Ji,`f`).add(o)}},S=e=>{d=e,a.length||g()},C=()=>{if(d)return;let e=n(this,ea,`f`);e&&(e.kind===`error`?t:r)&&(d=e.error)},w=()=>{u=!0,C(),_(),a.length||(g(),h())};return u||(p=e(x),this.on(`end`,w),t&&this.on(`error`,S),r&&this.on(`abort`,S)),{next:()=>{if(a.length){let e=a.dequeue(),t=s.dequeue();v(t);let n=lo(e,la);if(!n||!l.refresh(t.retention,n)){let e=y(!0);return f=!0,Promise.reject(e)}return l.release(t.retention),Promise.resolve({value:e,done:!1})}return(u||this.ended)&&C(),d&&!f?(f=!0,Promise.reject(d)):u?Promise.resolve(m()):new Promise((e,t)=>{c.enqueue({resolve:e,reject:t})})},return:()=>{for(u=!0,f=!0;s.length;)v(s.dequeue());return a.clear(),l.clear(),_(),h(),i&&(this.done().catch(()=>void 0),i()),Promise.resolve(m())},[Symbol.asyncIterator](){return this}}}async done(){t(this,$i,!0,`f`),await n(this,Vi,`f`)}_hasListeners(e){return!!n(this,Wi,`f`)[e]?.some(e=>!e.removed)}_emit(e,...r){if(n(this,Xi,`f`))return;e===`end`&&(n(this,Li,`m`,na).call(this),t(this,Xi,!0,`f`),n(this,Hi,`f`).call(this));let i=n(this,Wi,`f`)[e],a,o=!1;try{if(i){n(this,Wi,`f`)[e]=i.filter(e=>(e.once&&(e.detached=!0),!e.once&&!e.removed)),t(this,Yi,n(this,Yi,`f`)+1,`f`);try{for(let e of i)if(!e.removed){let{listener:t}=e;t(...r)}}finally{if(t(this,Yi,n(this,Yi,`f`)-1,`f`),n(this,Yi,`f`)===0){n(this,Li,`m`,aa).call(this);for(let e of n(this,Ji,`f`))n(this,Ji,`f`).delete(e),n(this,Xi,`f`)||e()}}}}catch(e){a=e,o=!0}try{n(this,Li,`m`,sa).call(this,e,r,!!i?.length)}catch(e){o||=(a=e,!0)}if(o)throw a}_emitFinal(){}};Ri=new WeakMap,zi=new WeakMap,Bi=new WeakMap,Vi=new WeakMap,Hi=new WeakMap,Ui=new WeakMap,Wi=new WeakMap,Gi=new WeakMap,Ki=new WeakMap,qi=new WeakMap,Ji=new WeakMap,Yi=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Qi=new WeakMap,$i=new WeakMap,ea=new WeakMap,Li=new WeakSet,ta=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},na=function(){for(let{signal:e,listener:t}of n(this,Gi,`f`).splice(0))e.removeEventListener(`abort`,t)},ra=function(e,t){let r=n(this,Wi,`f`)[e],i=r?.length??0;this.once(e,t);let a=n(this,Wi,`f`)[e],[o]=a?.slice(-1)??[];(r===void 0||a===r)&&a?.length===i+1&&o?.listener===t&&o.once&&n(this,Ki,`f`).set(t,{event:e,registration:o})},ia=function(e,t){t.removed||(t.removed=!0,n(this,Ki,`f`).delete(t.listener),n(this,qi,`f`).add(e),n(this,Yi,`f`)===0&&n(this,Li,`m`,aa).call(this))},aa=function(){for(let e of n(this,qi,`f`)){let t=e,r=n(this,Wi,`f`)[t];r&&(n(this,Wi,`f`)[t]=r.filter(e=>!e.removed))}n(this,qi,`f`).clear()},oa=function(e){if(t(this,Zi,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=this._userAbortError()),e instanceof c)return t(this,Qi,!0,`f`),this._emit(`abort`,e);if(e instanceof o)return this._emit(`error`,e);if(e instanceof Error){let t=new o(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new o(String(e)))},sa=function(e,r,i){if(e===`abort`){let e=r[0];t(this,ea,n(this,ea,`f`)??{kind:`abort`,error:e},`f`),!n(this,$i,`f`)&&!i&&Promise.reject(e),n(this,Bi,`f`).call(this,e),n(this,Ui,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=r[0];t(this,ea,n(this,ea,`f`)??{kind:`error`,error:e},`f`),!n(this,$i,`f`)&&!i&&Promise.reject(e),n(this,Bi,`f`).call(this,e),n(this,Ui,`f`).call(this,e),this._emit(`end`)}};function Co(e){return typeof e.parse==`function`}var V,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po,Fo=10;function Io(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||=`call_${r()}`}function Lo(e){if(!Fi(e))return e;let t={role:`assistant`};return e.audio!=null&&(t.audio={id:e.audio.id}),e.content!==void 0&&(t.content=e.content),e.function_call!=null&&(t.function_call=e.function_call),e.name!==void 0&&(t.name=e.name),e.refusal!=null&&(t.refusal=e.refusal),e.tool_calls!==void 0&&(t.tool_calls=e.tool_calls.map(e=>e.type===`custom`?{id:e.id,type:e.type,custom:{input:e.custom.input,name:e.custom.name}}:{id:e.id,type:e.type,function:{arguments:e.function.arguments,name:e.function.name}})),t}var Ro=class extends So{constructor(){super(...arguments),V.add(this),this._chatCompletions=[],To.set(this,!1),Eo.set(this,!1),this.messages=[]}_addChatCompletion(e){t(this,To,!this.controller.signal.aborted,`f`),Io(e),this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,t=!0,n=!0){if(n&&!(`content`in e)&&(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Ii(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Fi(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new o(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),n(this,V,`m`,Do).call(this)}async finalMessage(){return await this.done(),n(this,V,`m`,Oo).call(this)}async finalFunctionToolCall(){return await this.done(),n(this,V,`m`,ko).call(this)}async finalFunctionToolCallResult(){return await this.done(),n(this,V,`m`,Ao).call(this)}async totalUsage(){return await this.done(),n(this,V,`m`,jo).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){n(this,Eo,`f`)&&n(this,V,`m`,Mo).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=n(this,V,`m`,Oo).call(this);t&&this._emit(`finalMessage`,t);let r=n(this,V,`m`,Do).call(this);r&&this._emit(`finalContent`,r);let i=n(this,V,`m`,ko).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=n(this,V,`m`,Ao).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,n(this,V,`m`,jo).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),n(wo,wo,`m`,No).call(wo,t);let i=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ki(i,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,r,i,a){let s=`tool`,{tool_choice:c=`auto`,stream:l,toolContext:u,...d}=r,f=u,p=typeof c!=`string`&&c.type===`function`&&c?.function?.name,{maxChatCompletions:m=Fo,afterCompletion:h}=a||{},g=async e=>{h!=null&&(t(this,Eo,!0,`f`),await h(e,i),n(this,V,`m`,Mo).call(this))},_=r.tools.map(e=>{if(Di(e)){if(!e.$callback)throw new o("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}),v=Object.create(null);for(let e of _)e.type===`function`&&(v[e.function.name||e.function.function.name]=e.function);let y=`tools`in r?_.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 r.messages)this._addMessage(e,!1,!1);let b=!1,x=async e=>{let t=b;if(b=!1,e.type!==`function`)return{message:void 0,functionCalled:!1};let r=e.id,{name:a,arguments:o}=e.function,c=v[a];if(!c){let e=`Invalid tool_call: ${JSON.stringify(a)}. Available options are: ${Object.keys(v).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:s,tool_call_id:r,content:e},functionCalled:!1}}if(p&&p!==a){let e=`Invalid tool_call: ${JSON.stringify(a)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:s,tool_call_id:r,content:e},functionCalled:!1}}let l;if(Co(c)){let e;try{e=await c.parse(o)}catch(e){if(this.controller.signal.aborted)throw this._userAbortError();let t=e instanceof Error?e.message:String(e);return{message:{role:s,tool_call_id:r,content:t},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{l=await c.function(e,i,f)}catch(e){throw this.controller.signal.aborted&&Object.is(e,this.controller.signal.reason)?this._userAbortError():e}}else{if(this.controller.signal.aborted&&!t)throw this._userAbortError();try{l=await c.function(o,i,f)}catch(e){throw this.controller.signal.aborted&&Object.is(e,this.controller.signal.reason)?this._userAbortError():e}}let u=n(wo,wo,`m`,Po).call(wo,l);return{message:{role:s,tool_call_id:r,content:u},functionCalled:!0}};for(let t=0;t<m;++t){let t=await this._createChatCompletion(e,{...d,tool_choice:c,tools:y,messages:this.messages.map(Lo)},a);b=this.controller.signal.aborted&&n(this,To,`f`);let i=t.choices[0]?.message;if(!i)throw new o(`missing message in ChatCompletion response`);if(!i.tool_calls?.length){await g(t);return}if(p||r.parallel_tool_calls===!1)for(let e of i.tool_calls){let n=await x(e);if(n.message&&this._addMessage(n.message),this.controller.signal.aborted)throw this._userAbortError();if(p&&n.functionCalled){await g(t);return}}else{let e=await Promise.allSettled(i.tool_calls.map(x));if(!this.controller.signal.aborted){for(let t of e)if(t.status===`rejected`)throw t.reason}for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await g(t)}}};wo=Ro,To=new WeakMap,Eo=new WeakMap,V=new WeakSet,Do=function(){return n(this,V,`m`,Oo).call(this).content??null},Oo=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Fi(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new o(`stream ended without producing a ChatCompletionMessage with role=assistant`)},ko=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Fi(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},Ao=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ii(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},jo=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Mo=function(){if(this.controller.signal.aborted)throw this._userAbortError()},No=function(e){if(e.n!=null&&e.n>1)throw new o(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},Po=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var zo=class e extends Ro{static runTools(t,n,r){let i=new e,a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0,n=!0){super._addMessage(e,t,n),t&&Fi(e)&&e.content&&this._emit(`content`,e.content)}},H={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},Bo=class extends Error{},Vo=class extends Error{};function Ho(e,t=H.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Uo(e.trim(),t)}var Uo=(e,t)=>{let n=e.length,r=0,i=e=>{throw new Bo(`${e} at position ${r}`)},a=e=>{throw new Vo(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||H.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||H.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||H.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||H.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||H.MINUS_INFINITY&t&&n-r>1&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||H.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)===`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(H.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&H.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(H.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(H.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(H.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&H.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(H.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r===n&&!(H.NUM&t)&&i(`Unterminated number literal`);let s=e.substring(o,r);try{return JSON.parse(s)}catch{s===`-`&&H.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(s.substring(0,s.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
8
+ \r `.includes(e[r]);)r++};return o()},Wo=e=>Ho(e,H.ALL^H.NUM),U,W,Go,Ko,qo,G,Jo,Yo,Xo,Zo,Qo,$o,es,ts,ns,rs;function is(e){try{return Wo(e)}catch(t){if(t instanceof Vo||t instanceof SyntaxError)return Ei({type:`json_schema`,$parseRaw:void 0},e);throw t}}var as=`chat.completion.chunk.message:`;function os(e,t,n){let r={type:`message`,message:t,...n?{tool_call_ids:n}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${as}${JSON.stringify(r)}`}}function ss(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(as)}function cs(e){return`type`in e?e:JSON.parse(e.object.slice(30))}var ls=128,us=128,ds=16777216,fs=65536,ps=128,ms=67108864,hs=1024;function gs(){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 _s(e,t,n,r){if(t.fragments>=fs)throw new o(`Chat completion stream exceeded its structured JSON fragment limit`);let i=0,{depth:a,escaped:s,has_non_whitespace:c,in_string:l}=e,u=!1,d=!0;for(let f of n){let n=i,p=f.codePointAt(0);if(d&&e.pending_high_surrogate&&p>=56320&&p<=57343?i+=1:i+=p<=127?1:p<=2047?2:p<=65535?3:4,d=!1,t.bytes+i>ds)throw new o(`Chat completion stream exceeded its structured JSON byte limit`);if(r&&r.work+i>ms)throw r.work+=n,new o(`Chat completion stream exceeded its structured JSON parse-work limit`);if(f!==` `&&f!==`
9
+ `&&f!==`\r`&&f!==` `&&(c=!0),l){s?s=!1:f===`\\`?s=!0:f===`"`&&(l=!1,u||=a===0);continue}if(f===`"`)l=!0;else if(f===`{`||f===`[`){if(a+=1,a>ps)throw new o(`Chat completion stream exceeded its structured JSON nesting depth limit`)}else(f===`}`||f===`]`)&&a>0&&(--a,u||=a===0)}if(e.bytes+=i,e.fragments+=1,e.depth=a,e.escaped=s,e.has_non_whitespace=c,e.in_string=l,n.length>0){let t=n.codePointAt(n.length-1)??0;e.pending_high_surrogate=t>=55296&&t<=56319}if(t.bytes+=i,t.fragments+=1,r&&(r.work+=i),!c||i===0)return!1;let f=Math.max(hs,Math.floor(e.last_parsed_bytes/2));return!(e.bytes>hs&&!u&&e.bytes-e.last_parsed_bytes<f)}function vs(e,t){return t.work+e.bytes>ms?!1:(t.work+=e.bytes,e.work+=e.bytes,e.last_parsed_bytes=e.bytes,!0)}function ys(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n){let n=Object.getPrototypeOf(e);for(let e=0;n!==null;e+=1){if(e>=ps||Object.getOwnPropertyDescriptor(n,t))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);n=Object.getPrototypeOf(n)}return}if(!(`value`in n)||typeof n.value!=`string`&&n.value!==null&&n.value!==void 0)throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);return n.value}function bs(e){let t=Object.getOwnPropertyDescriptor(e,`message`);if(!t||!(`value`in t)||typeof t.value!=`object`||t.value===null)throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);return t.value}function xs(e,t,n,r){let i=Object.getOwnPropertyDescriptor(e,t);if(!i){let n=Object.getPrototypeOf(e);for(let e=0;n!==null;e+=1){if(e>=ps||Object.getOwnPropertyDescriptor(n,t))throw new o(`Chat completion stream contains an unsafe snapshot ${r} collection`);n=Object.getPrototypeOf(n)}return}if(!(`value`in i)||!Array.isArray(i.value))throw new o(`Chat completion stream contains an unsafe snapshot ${r} collection`);let a=Object.getOwnPropertyDescriptor(i.value,`length`);if(!a||!(`value`in a)||!Number.isSafeInteger(a.value)||a.value>n)throw new o(`Chat completion stream exceeded its snapshot ${r} limit`);return i.value}function Ss(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(n){if(!(`value`in n))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);return n.value}}function Cs(e,t,n,r){let i=Object.getOwnPropertyDescriptor(e,`length`),a=i&&`value`in i?i.value:void 0;if(typeof a!=`number`||!Number.isSafeInteger(a)||a<0||a>t)throw new o(`Chat completion stream exceeded its snapshot ${n} limit`);let s=[];s.length=a;for(let t=0;t<a;t+=1){let n=Object.getOwnPropertyDescriptor(e,t);if(n){if(!(`value`in n))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);s[t]=r(n.value,t)}}return s}function ws(e,t,n){let r=gs(),i=t??{bytes:0,fragments:0,work:0};if(_s(r,i,e,n),!vs(r,i))throw new o(`Chat completion stream exceeded its structured JSON parse-work limit`);return e}function Ts(e){let t=Object.getOwnPropertyDescriptor(e,`type`),n=Object.getOwnPropertyDescriptor(e,`function`);if(!t||!(`value`in t)||t.value!==`function`||!n||!(`value`in n)||typeof n.value!=`object`||n.value===null)return;let r=Object.getOwnPropertyDescriptor(n.value,`name`);if(r&&`value`in r&&typeof r.value==`string`&&r.value.length!==0)return{type:`function`,name:r.value}}function Es(e,t){let n=Ts(e);if(!n||n.name!==t.name||n.type!==t.type)throw new o(`Chat completion stream contains a changed tool call identity`)}function Ds(e,t){return Object.prototype.propertyIsEnumerable.call(t,`__proto__`)&&!E(e,`__proto__`)&&Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(e,t)}function Os(e,t=[]){let n=Object.getOwnPropertyDescriptors(e);for(let r of t){let t=n[r];(t||r in e)&&(n[r]={value:t&&`value`in t?t.value:Reflect.get(e,r,e),enumerable:t?.enumerable??!1,configurable:t?.configurable??!0,writable:t&&`writable`in t?t.writable:!1})}return Object.create(Object.getPrototypeOf(e),n)}function ks(e){let t=Os(e);if(e.tools){let n=[],r=Object.getOwnPropertyDescriptor(e.tools,`length`),i=r&&`value`in r?r.value:void 0,a=typeof i==`number`&&Number.isSafeInteger(i)&&i>=0?Math.min(i,us):0;for(let t=0;t<a;t+=1){let r=Object.getOwnPropertyDescriptor(e.tools,String(t));if(!r||!(`value`in r)){n.length=t+1;continue}let i=r.value,a=Os(i,[`type`,`$brand`,`$parseRaw`,`$callback`,`function`]),o=Object.getOwnPropertyDescriptors(a);if(Ci(a)){let e=o.function;o.function={...e&&`value`in e?e:{configurable:!0,enumerable:!0,writable:!0},value:Os(a.function,[`name`,`strict`])}}n[t]=Object.create(Object.getPrototypeOf(i),o)}t.tools=n}return e.response_format&&(t.response_format=Os(e.response_format,[`type`,`$brand`,`$parseRaw`])),t}var As=4096,js=JSON.stringify,Ms=1048576,Ns=64,Ps=Symbol(`omitted serialized parser value`),K=Symbol(`unsafe serialized parser value`);function Fs(e,t){let n=new WeakSet,r=e=>!Number.isSafeInteger(e)||e<0||t.bytes+e>Ms?!1:(t.bytes+=e,!0),i=(e,a)=>{if(a>Ns||t.nodes>=As)return K;if(t.nodes+=1,e===void 0||typeof e==`function`||typeof e==`symbol`)return Ps;if(typeof e==`bigint`)return K;if(e===null||typeof e==`boolean`||typeof e==`number`){let t=js(e);return typeof t==`string`&&r(t.length)?t:K}if(typeof e==`string`)return r(e.length*6+2)?js(e):K;if(typeof e!=`object`||n.has(e))return K;let o=Array.isArray(e),s=Object.getPrototypeOf(e);if(o&&s!==Array.prototype||!o&&s!==null&&s!==Object.prototype)return K;for(let t=e;t!==null;t=Object.getPrototypeOf(t)){let e=Object.getOwnPropertyDescriptor(t,`toJSON`);if(e){if(!(`value`in e)||typeof e.value==`function`)return K;break}}n.add(e);try{if(!r(2))return K;if(o){let n=Object.getOwnPropertyDescriptor(e,`length`),o=n&&`value`in n?n.value:void 0;if(typeof o!=`number`||!Number.isSafeInteger(o)||o<0||o>As-t.nodes)return K;let s=[];for(let n=0;n<o;n+=1){let o=String(n),c=Object.getOwnPropertyDescriptor(e,o);if(!c){if(Object.getOwnPropertyDescriptor(Array.prototype,o)||Object.getOwnPropertyDescriptor(Object.prototype,o)||(t.nodes+=1,!r(4)))return K;s.push(`null`);continue}if(!(`value`in c))return K;let l=i(c.value,a+1);if(l===K)return l;s.push(l===Ps?`null`:l)}return`[${s.join(`,`)}]`}let n=Reflect.ownKeys(e);if(n.length>As-t.nodes)return K;let s=[];for(let t of n){if(typeof t!=`string`)continue;let n=Object.getOwnPropertyDescriptor(e,t);if(!n)return K;if(n.enumerable){if(!(`value`in n))return K;s.push([t,n.value])}}s.sort(([e],[t])=>e===t?0:e<t?-1:1);let c=[];for(let[e,t]of s){let n=i(t,a+1);if(n===K)return n;if(n!==Ps){if(!r(e.length*6+3))return K;c.push(`${js(e)}:${n}`)}}return`{${c.join(`,`)}}`}finally{n.delete(e)}};try{let t=i(e,0);return typeof t==`string`?t:void 0}catch{return}}function Is(e,t,n,r){let i=Object.getOwnPropertyDescriptor(t,`$parseRaw`),a=Object.getOwnPropertyDescriptor(n,r);if(!i||!(`value`in i)||typeof i.value!=`function`||!a||!(`value`in a))return;let o=Fs(a.value,{nodes:0,bytes:0});o!==void 0&&e.set(t,o)}function Ls(e,t,n,r,i){let a=t&&e.get(t),o=Object.getOwnPropertyDescriptor(n,r);return a!==void 0&&o!==void 0&&`value`in o&&Fs(i,{nodes:0,bytes:0})===a}function Rs(e,t){return e&&`value`in e?{...e,value:t}:{configurable:!0,enumerable:!0,writable:!0,value:t}}function zs(e,t,n){for(let r of n){let n=e[r];(n||r in t)&&(e[r]=n&&`value`in n?{...n,value:void 0}:{configurable:n?.configurable??!0,enumerable:n?.enumerable??!1,writable:!1,value:void 0})}}function Bs(e){let t=e.source??{type:e.type,...e.type===`function`?{function:{}}:{}},n=Object.getOwnPropertyDescriptors(t);if(n.type=Rs(n.type,e.type),e.type!==`function`||!e.function)return n.function&&=Rs(n.function,void 0),zs(n,t,[`$brand`,`$parseRaw`,`$callback`]),Object.create(Object.getPrototypeOf(t),n);let r=n.function,i=r&&`value`in r&&typeof r.value==`object`&&r.value!==null?r.value:{},a=Object.getOwnPropertyDescriptors(i);return a.name=Rs(a.name,e.function.name),a.strict=Rs(a.strict,e.function.strict),n.function=Rs(r,Object.create(Object.getPrototypeOf(i),a)),e.function.schemaMatches||zs(n,t,[`$brand`,`$parseRaw`,`$callback`]),Object.create(Object.getPrototypeOf(t),n)}function Vs(e){let t=e.source??{type:e.type},n=Object.getOwnPropertyDescriptors(t);return n.type=Rs(n.type,e.type),(e.type!==`json_schema`||!e.source||!e.schemaMatches)&&zs(n,t,[`$brand`,`$parseRaw`]),Object.create(Object.getPrototypeOf(t),n)}function Hs(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n||!(`value`in n))return;let{value:r}=n;return typeof r==`object`&&r?r:void 0}function Us(e,t,n){let r=new WeakMap,i=new WeakMap;if(e.tools)for(let n=0;n<e.tools.length&&n<us;n+=1){let a=Hs(e.tools,String(n)),o=t.tools?.[n];if(a&&o){r.set(a,o);let e=Hs(o,`function`);e&&Is(i,o,e,`parameters`)}}t.response_format&&Is(i,t.response_format,t.response_format,`json_schema`);let a,o,s,c,l=[],u=new WeakMap,d=new Map,f=new WeakMap;return _t(e,{value(n,p,m){if(!a&&p===``&&typeof m==`object`&&m){a=m,o=void 0,s=void 0,c=void 0,l=[],u=new WeakMap,d=new Map,f=new WeakMap;return}if(n===a&&p===`response_format`){typeof m==`object`&&m&&(s=m,c={source:Hs(n,p)===e.response_format?t.response_format:void 0,schemaMatches:!1});return}if(n===a&&p===`tools`)return Array.isArray(m)?(o=new Proxy(m,{get(e,t){let n=Reflect.get(e,t,e);if(typeof t==`string`){let e=Number(t);Number.isSafeInteger(e)&&e>=0&&e<us&&String(e)===t&&d.set(e,typeof n==`object`&&n?n:void 0)}return n}}),o):void 0;if(n===o){let e=Number(p);if(!Number.isSafeInteger(e)||e<0||e>=us||typeof m!=`object`||!m)return;let t=d.get(e),n={source:t?r.get(t):void 0};l[e]=n,u.set(m,n);return}let h=u.get(n);if(h){if(p===`type`&&typeof m==`string`)h.type=m;else if(p===`function`&&typeof m==`object`&&m){let e={source:h.source,schemaMatches:!1};h.function=e,f.set(m,e)}return}if(n===s&&c){p===`type`&&typeof m==`string`?c.type=m:p===`json_schema`&&(c.schemaMatches=Ls(i,c.source,n,p,m));return}let g=f.get(n);g&&(p===`name`&&typeof m==`string`?g.name=m:p===`strict`&&typeof m==`boolean`?g.strict=m:p===`parameters`&&(g.schemaMatches=Ls(i,g.source,n,p,m)))},complete(){if(!a)return;let e=Os(t);if(o){let t=[];for(let e=0;e<l.length;e+=1){let n=l[e];n&&(t[e]=Bs(n))}e.tools=t}else delete e.tools;c?e.response_format=Vs(c):delete e.response_format,n(e),a=void 0,o=void 0,s=void 0,c=void 0,l=[],u=new WeakMap,d=new Map,f=new WeakMap}})}var Ws=class e extends Ro{constructor(e){super(),U.add(this),W.set(this,void 0),Go.set(this,!1),Ko.set(this,void 0),qo.set(this,void 0),G.set(this,void 0),Jo.set(this,void 0),Yo.set(this,void 0),t(this,W,e,`f`),t(this,Ko,new Set,`f`),t(this,qo,[],`f`),t(this,Jo,!1,`f`);let n=e?.tools,r=n&&Object.getOwnPropertyDescriptor(n,`length`),i=r&&`value`in r?r.value:void 0;if(n&&typeof i==`number`&&Number.isSafeInteger(i)&&i>=0)for(let e=0;e<Math.min(i,us);e+=1){let r=Object.getOwnPropertyDescriptor(n,String(e));if(!r||!(`value`in r))continue;let i=r.value;if(Ci(i)&&(Di(i)||i.function.strict===!0)){t(this,Jo,!0,`f`);break}}t(this,Yo,{bytes:0,fragments:0,work:0},`f`)}get currentChatCompletionSnapshot(){return n(this,G,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}_runTools(e,n,r,i){return t(this,Go,!0,`f`),super._runTools(e,n,r,i)}async _createChatCompletion(e,r,i){this._listenForAbort(i?.signal);let a={...r,stream:!0};t(this,W,a,`f`),n(this,U,`m`,Xo).call(this);let o=ks(a);t(this,W,o,`f`),t(this,Jo,o.tools?.some(e=>Ci(e)&&(Di(e)||e.function.strict===!0))??!1,`f`);let s=a.tools||a.response_format?Us(a,o,e=>{t(this,W,e,`f`),t(this,Jo,e.tools?.some(e=>Ci(e)&&(Di(e)||e.function.strict===!0))??!1,`f`)}):void 0,c=await e.chat.completions.create(a,{...i,signal:this.controller.signal}).finally(s);this._connected();for await(let e of c)n(this,U,`m`,Qo).call(this,e);if(c.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(n(this,U,`m`,ns).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),n(this,U,`m`,Xo).call(this),this._connected();let r=Ze.fromReadableStream(e,this.controller),i;for await(let e of r){if(`error`in e&&E(e,`error`)&&typeof e.error==`object`&&e.error!==null)throw new s(void 0,e.error,void 0,void 0);if(ss(e)){let t=cs(e);if(n(this,G,`f`)){let e=n(this,G,`f`).choices[0]?.message.tool_calls;for(let[n,r]of t.tool_call_ids?.entries()??[]){let t=e?.[n];t&&r&&(t.id=r)}this._addChatCompletion(n(this,U,`m`,ns).call(this)),i=void 0}this._addMessage(t.message);continue}let t=e;i&&t.id&&i!==t.id&&this._addChatCompletion(n(this,U,`m`,ns).call(this)),n(this,U,`m`,Qo).call(this,t),t.id&&(i=t.id)}if(r.controller.signal?.aborted)throw this._userAbortError();if(n(this,G,`f`))return this._addChatCompletion(n(this,U,`m`,ns).call(this));let a=this._chatCompletions[this._chatCompletions.length-1];if(a)return a;throw new o(`request ended without sending any chunks`)}[(W=new WeakMap,Go=new WeakMap,Ko=new WeakMap,qo=new WeakMap,G=new WeakMap,Jo=new WeakMap,Yo=new WeakMap,U=new WeakSet,Xo=function(){this.ended||(t(this,Ko,new Set,`f`),t(this,G,void 0,`f`),t(this,Yo,{bytes:0,fragments:0,work:0},`f`))},Zo=function(e){let t=n(this,qo,`f`)[e.index];return t||(t={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},n(this,qo,`f`)[e.index]=t,t)},Qo=function(e){if(this.ended)return;let t=new WeakMap,r=n(this,U,`m`,rs).call(this,e,t);this._emit(`chunk`,e,r);for(let i of e.choices){let e=t.get(i),a=r.choices[e?.index??i.index],s=e?.tool_calls??[],{delta:c}=i,l=Ti(n(this,W,`f`)?.response_format),u=l||n(this,Jo,`f`),d=u?bs(a):a.message,f=u?ys(d,`refusal`):d.refusal,p=!f&&l?ys(d,`content`):d.content;c?.content!=null&&d.role===`assistant`&&p&&(this._emit(`content`,c.content,p),this._emit(`content.delta`,{delta:c.content,snapshot:p,parsed:d.parsed})),c?.refusal!=null&&d.role===`assistant`&&f&&this._emit(`refusal.delta`,{delta:c.refusal,snapshot:f}),i.logprobs?.content!=null&&d.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:i.logprobs?.content,snapshot:a.logprobs?.content??[]}),i.logprobs?.refusal!=null&&d.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:i.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});let m=n(this,U,`m`,Zo).call(this,a);a.finish_reason&&(n(this,U,`m`,es).call(this,a),m.current_tool_call_index!=null&&n(this,U,`m`,$o).call(this,a,m.current_tool_call_index));for(let e of s)m.current_tool_call_index!==e.index&&(n(this,U,`m`,es).call(this,a),m.current_tool_call_index!=null&&n(this,U,`m`,$o).call(this,a,m.current_tool_call_index)),m.current_tool_call_index=e.index;for(let e of s){let t=d.tool_calls?.[e.index];if(t?.type){if(t.type===`function`){let n=m.tool_call_identities.get(e.index),r;if(n?.parseable){let e=ys(t.function,`arguments`);if(typeof e!=`string`)throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);r=e}else r=t.function.arguments;this._emit(`tool_calls.function.arguments.delta`,{name:t.function.name,index:e.index,arguments:r,parsed_arguments:t.function.parsed_arguments,arguments_delta:e.arguments_delta})}else t.type}}}},$o=function(e,t){let r=n(this,U,`m`,Zo).call(this,e);if(r.done_tool_calls.has(t))return;let i=(n(this,Jo,`f`)?bs(e):e.message).tool_calls?.[t];if(!i)throw Error(`no tool call snapshot`);let a=r.tool_call_identities.get(t);if(a&&Es(i,a),!i.type)throw Error("tool call snapshot missing `type`");if(i.type===`function`){let a=n(this,W,`f`)?.tools?.find(e=>Ci(e)&&e.function.name===i.function.name),s=null,c=Di(a)||a?.function.strict===!0,l;if(c){n(this,G,`f`)&&n(this,U,`m`,ts).call(this,n(this,G,`f`));let e=ys(i.function,`arguments`);if(typeof e!=`string`)throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);l=e}else l=i.function.arguments;Di(a)?s=a.$parseRaw(ws(l)):a?.function.strict&&(s=Ei({type:`json_schema`,$parseRaw:void 0},ws(l))),e.finish_reason&&r.done_tool_calls.add(t),this._emit(`tool_calls.function.arguments.done`,{name:i.function.name,index:t,arguments:l,parsed_arguments:s})}else i.type},es=function(e){let t=n(this,U,`m`,Zo).call(this,e),r=Ti(n(this,W,`f`)?.response_format),i=r||n(this,Jo,`f`),a=i?bs(e):e.message,o=i?ys(a,`refusal`):a.refusal,s=!o&&r,c=s?ys(a,`content`):a.content;c!=null&&(c!==``||!o&&!a.tool_calls?.length&&!a.function_call)&&!t.content_done&&(s&&n(this,G,`f`)&&n(this,U,`m`,ts).call(this,n(this,G,`f`)),t.content_done=!0,this._emit(`content.done`,{content:c,parsed:o?null:Ei(n(this,W,`f`)?.response_format,s?ws(c):c)})),o&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:o})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},ts=function(e){let t={bytes:0,fragments:0,work:0},r=Ti(n(this,W,`f`)?.response_format),i=new WeakMap,a=xs(e,`choices`,ls,`choice`);if(!a)throw new o(`Chat completion stream contains an unsafe snapshot choice collection`);for(let e=0;e<a.length;e+=1){let s=Ss(a,e);if(!s)continue;let c=bs(s),l=ys(c,`refusal`),u=ys(c,`content`),d=new Map,f=xs(c,`tool_calls`,us,`tool-call`);i.set(s,Object.freeze({message:c,content:u,refusal:l,toolCallCollection:f,toolCalls:d}));let p=n(this,qo,`f`)[s.index];r&&!l&&typeof u==`string`&&ws(u,t,n(this,Yo,`f`));for(let[e,t]of p?.tool_call_identities??[]){let n=f&&Ss(f,e);if(!n)throw new o(`Chat completion stream contains a changed tool call identity`);Es(n,t)}if(n(this,Jo,`f`))for(let e=0;e<(f?.length??0);e+=1){let r=Ss(f,e);if(!r)continue;let i=Ts(r);if(!i){let e=Object.getOwnPropertyDescriptor(r,`type`);if(e&&!(`value`in e))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);if(e?.value!==`function`)continue;let t=Object.getOwnPropertyDescriptor(r,`function`);if(t&&!(`value`in t))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);if(t&&typeof t.value==`object`&&t.value!==null){let e=Object.getOwnPropertyDescriptor(t.value,`name`);if(e&&!(`value`in e))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`)}continue}if(!Mi(n(this,W,`f`),{type:i.type,function:{name:i.name}}))continue;let a=Object.getOwnPropertyDescriptor(r,`function`);if(!a||!(`value`in a))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);let s=a.value,c=ys(s,`arguments`);if(typeof c!=`string`)throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);ws(c,t,n(this,Yo,`f`)),d.set(e,Object.freeze({tool:r,function:s,type:i.type,name:i.name,arguments:c}))}}return i},ns=function(){if(this.ended)throw new o(`stream has ended, this shouldn't happen`);let e=n(this,G,`f`);if(!e)throw new o(`request ended without sending any chunks`);let r=n(this,U,`m`,ts).call(this,e),i=n(this,Ko,`f`);return t(this,Ko,new Set,`f`),t(this,G,void 0,`f`),t(this,qo,[],`f`),Gs(e,n(this,W,`f`),i,r)},rs=function(e,r){var i,a,s,c,l;let u=n(this,G,`f`),{choices:d,obfuscation:f,...p}=e;if(u)e.id&&Ds(u,p);else{let e={...p,choices:[]};t(this,G,e,`f`),u=e}let m=n(this,W,`f`)?.n,h=typeof m==`number`&&Number.isSafeInteger(m)&&m>0?Math.min(m,ls):ls;for(let t of e.choices){let{delta:e,finish_reason:d,index:f,logprobs:p=null,...m}=t,g=[];if(r.set(t,Object.freeze({index:f,tool_calls:g})),!Number.isSafeInteger(f)||f<0||f>=h)throw new o(`Chat completion stream contains an invalid choice index: ${f}`);let _=u.choices[f];if(!_){let e={finish_reason:d,index:f,message:{},logprobs:null,...m};u.choices[f]=e,_=e}if((Ti(n(this,W,`f`)?.response_format)||n(this,Jo,`f`))&&ys(bs(_),`refusal`),p){if(_.logprobs){let{content:e,refusal:t,...n}=p;Ds(_.logprobs,n),e&&((i=_.logprobs).content??(i.content=[]),_.logprobs.content.push(...e)),t&&((a=_.logprobs).refusal??(a.refusal=[]),_.logprobs.refusal.push(...t))}else _.logprobs={...p},p.content&&(_.logprobs.content=[...p.content]),p.refusal&&(_.logprobs.refusal=[...p.refusal])}if(d&&(_.finish_reason=d,n(this,W,`f`)&&(n(this,Go,`f`)||Ni(n(this,W,`f`))))){if(d===`length`)throw new y;if(d===`content_filter`)throw new b}if(Ds(_,m),!e){Object.freeze(g);continue}n(this,Ko,`f`).delete(f);let{audio:v,content:x,refusal:S,function_call:C,role:w,...ee}=e,{tool_calls:T,...te}=ee,ne=E(ee,`tool_calls`)?T:e.tool_calls;if(Ds(_.message,te),v?.expires_at!=null&&v.id==null&&v.data==null&&v.transcript==null&&x==null&&S==null&&C==null&&w==null&&ne==null&&Object.keys(te).length===0&&n(this,Ko,`f`).add(f),S&&(_.message.refusal=(_.message.refusal||``)+S),w&&(_.message.role=w),v){let e=(s=_.message).audio??(s.audio={});v.id!=null&&(e.id=v.id),v.data!=null&&(e.data=(e.data??``)+v.data),v.transcript!=null&&(e.transcript=(e.transcript??``)+v.transcript),v.expires_at!=null&&(e.expires_at=v.expires_at)}if(C&&(_.message.function_call?(C.name&&(_.message.function_call.name=C.name),C.arguments&&((c=_.message.function_call).arguments??(c.arguments=``),_.message.function_call.arguments+=C.arguments)):_.message.function_call=C),x!=null){if(!_.message.refusal&&Ti(n(this,W,`f`)?.response_format)){let e=n(this,U,`m`,Zo).call(this,_),t=e.content_parse_state??=gs(),r=_s(t,n(this,Yo,`f`),x);_.message.content=(ys(_.message,`content`)||``)+x,t.has_non_whitespace?r&&vs(t,n(this,Yo,`f`))?(n(this,U,`m`,ts).call(this,u),_.message.parsed=is(ws(_.message.content))):x.length>0&&(_.message.parsed=null):_.message.parsed=null}else _.message.content=(_.message.content||``)+x}if(ne){let e=(l=_.message).tool_calls??(l.tool_calls=[]);for(let t of ne){let{index:r,id:i,type:a,function:s,custom:c,...l}=t;if(!Number.isSafeInteger(r)||r<0||r>=us)throw new o(`Chat completion stream contains an invalid tool call index: ${r}`);let d=``,f=e[r]??(e[r]={}),p=s?.name,m=n(this,Jo,`f`)?n(this,U,`m`,Zo).call(this,_):void 0,h=m?.tool_call_identities.get(r);if(h&&(Es(f,h),a!==void 0&&a!==h.type||p!==void 0&&p!==h.name))throw new o(`Chat completion stream contains a changed tool call identity`);if(Ds(f,l),i&&(f.id=i),a&&(f.type=a),c){let e=f.custom??={name:c.name??``,input:``};c.name&&(e.name=c.name),c.input&&(e.input+=c.input)}if(s){let e=f.function??={name:p??``,arguments:``};if(p&&(e.name=p),m&&!h){let e=Ts(f),t=e&&n(this,W,`f`)?.tools?.find(t=>Ci(t)&&t.function.name===e.name);if(e&&(h={...e,parseable:t!==void 0&&Mi(n(this,W,`f`),{type:e.type,function:{name:e.name}})},m.tool_call_identities.set(r,h),!h.parseable)){let e=m.tool_call_parse_states.get(r);e&&(n(this,Yo,`f`).bytes-=e.bytes,n(this,Yo,`f`).fragments-=e.fragments,n(this,Yo,`f`).work-=e.work,m.tool_call_parse_states.delete(r))}}let t=s.arguments;if(t!=null){if(d=t,m&&h?.parseable!==!1){let i=m.tool_call_parse_states.get(r);i||(i=gs(),m.tool_call_parse_states.set(r,i));let a=_s(i,n(this,Yo,`f`),t),s=ys(e,`arguments`);if(typeof s!=`string`)throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);e.arguments=s+t,a&&h?.parseable===!0&&vs(i,n(this,Yo,`f`))?(n(this,U,`m`,ts).call(this,u),e.parsed_arguments=is(ws(e.arguments))):t.length>0&&E(e,`parsed_arguments`)&&(e.parsed_arguments=void 0)}else e.arguments+=t}}g.push(Object.freeze({index:r,arguments_delta:d}))}}Object.freeze(g)}return u},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`chunk`,t),()=>this.off(`chunk`,t)},{onReturn:()=>this.abort()})}toReadableStream(){return new Ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Gs(e,t,n,i){let{id:a,choices:s,created:c,model:l,system_fingerprint:u,...d}=e;return Oi({...d,id:a,choices:Cs(s,ls,`choice`,e=>{let a=i.get(e);if(!a)throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`);let{message:s,finish_reason:c,index:l,logprobs:u,...d}=new Proxy(e,{get(e,t,n){return t===`message`?a.message:Reflect.get(e,t,n)}}),f=new Proxy(s,{get(e,t,n){return t===`content`?a.content:t===`refusal`?a.refusal:t===`tool_calls`?a.toolCallCollection:Reflect.get(e,t,n)}}),{content:p=null,function_call:m,tool_calls:h,audio:g,..._}=f,v=c??(n.has(l)&&Ks(g)?`stop`:null);if(!v)throw new o(`missing finish_reason for choice ${l}`);let y=g?{audio:g}:{},b=f.role;if(!b)throw new o(`missing role for choice ${l}`);if(m){let{arguments:e,name:t}=m;if(e==null)throw new o(`missing function_call.arguments for choice ${l}`);if(!t)throw new o(`missing function_call.name for choice ${l}`);return{...d,message:{...y,content:p,function_call:{arguments:e,name:t},role:b,refusal:f.refusal??null},finish_reason:v,index:l,logprobs:u}}return h?{...d,index:l,finish_reason:v,logprobs:u,message:{..._,...y,role:b,content:p,refusal:f.refusal??null,tool_calls:Cs(h,us,`tool-call`,(e,n)=>{let i=a.toolCalls.get(n);if(!i){let n=Ts(e);if(n&&Mi(t,{type:n.type,function:{name:n.name}}))throw new o(`Chat completion stream contains an unsafe structured JSON snapshot`)}if(i&&i.tool!==e)throw new o(`Chat completion stream contains a changed tool call identity`);let s=i&&new Proxy(i.function,{get(e,t,n){return t===`arguments`?i.arguments:t===`name`?i.name:Reflect.get(e,t,n)}}),c=i&&s?new Proxy(e,{get(e,t,n){return t===`type`?i.type:t===`function`?s:Reflect.get(e,t,n)}}):e;if(c.type==null)throw new o(`missing choices[${l}].tool_calls[${n}].type`);if(c.type===`custom`){let{custom:e,type:t,id:i,...a}=c,{input:s=``,name:u,...d}=e||{};if(u==null)throw new o(`missing choices[${l}].tool_calls[${n}].custom.name`);return{...a,id:i||`call_${r()}`,type:t,custom:{...d,name:u,input:s}}}let{function:u,type:d,id:f,...p}=c,{arguments:m,name:h,...g}=u||{};if(h==null)throw new o(`missing choices[${l}].tool_calls[${n}].function.name`);if(m==null)throw new o(`missing choices[${l}].tool_calls[${n}].function.arguments`);return{...p,id:f||`call_${r()}`,type:d,function:{...g,name:h,arguments:m}}})}}:{...d,message:{..._,...y,content:p,role:b,refusal:f.refusal??null},finish_reason:v,index:l,logprobs:u}}),created:c,model:l,object:`chat.completion`,...u?{system_fingerprint:u}:{}},t)}function Ks(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}var qs=class e extends Ws{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e,t,n=this._createIterator(n=>{let r=t=>{e=t,n(t)},i=r=>{if(Fi(r)){t=r.tool_calls?.map(e=>e.id);return}if(Ii(r)){if(!e)throw new o(`cannot serialize a tool message before receiving any chunks`);n(os(e,r,t)),t=void 0}};return this.on(`chunk`,r),this.on(`message`,i),()=>{this.off(`chunk`,r),this.off(`message`,i)}},{onReturn:()=>this.abort()});return new Ze(()=>n,this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}};function Js(e,t){return Promise.resolve(e).then(t)}var Ys=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Xs(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Ys.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Ys.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Zs=class extends z{constructor(){super(...arguments),this.messages=new Si(this._client)}create(e,t){return this._client.post(`/chat/completions`,Js(t,t=>({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/chat/completions/${e}`,Js(t,e=>({...e,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(B`/chat/completions/${e}`,Js(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=Xs(e,[`after`,`limit`,`metadata`,`model`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/chat/completions`,N,Js(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/chat/completions/${e}`,Js(t,e=>({...e,__security:{bearerAuth:!0}})))}parse(e,t){return Pi(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:`chat.completions.parse`}})._thenUnwrap(t=>ki(t,e))}runTools(e,t){return e.stream?qs.runTools(this._client,e,t):zo.runTools(this._client,e,t)}stream(e,t){return Ws.createChatCompletion(this._client,e,t)}};Zs.Messages=Si;var Qs=class extends z{constructor(){super(...arguments),this.completions=new Zs(this._client)}};Qs.Completions=Zs;function $s(e,t){return Promise.resolve(e).then(t)}var ec=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function tc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>ec.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ec.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var nc=class extends z{create(e,t){return this._client.post(`/organization/admin_api_keys`,$s(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(B`/organization/admin_api_keys/${e}`,$s(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=tc(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/admin_api_keys`,N,$s(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/admin_api_keys/${e}`,$s(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function rc(e,t){return Promise.resolve(e).then(t)}var ic=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ac(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>ic.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ic.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var oc=class extends z{list(e={},t){let n=ac(e,[`actor_emails`,`actor_ids`,`after`,`before`,`effective_at`,`event_types`,`limit`,`project_ids`,`resource_ids`,`tenant_only`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/audit_logs`,P,rc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}};function sc(e,t){return Promise.resolve(e).then(t)}var cc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function lc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>cc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!cc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var uc=class extends z{create(e,t){return this._client.post(`/organization/certificates`,sc(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t={},n){let r=lc(t,[`include`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.get(B`/organization/certificates/${e}`,sc(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/certificates/${e}`,sc(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=lc(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/certificates`,P,sc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/certificates/${e}`,sc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,Kt,sc(t,t=>({body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})))}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,Kt,sc(t,t=>({body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})))}};function dc(e,t){return Promise.resolve(e).then(t)}var fc=class extends z{retrieve(e){return this._client.get(`/organization/data_retention`,dc(e,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t){return this._client.post(`/organization/data_retention`,dc(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}};function pc(e,t){return Promise.resolve(e).then(t)}var mc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function hc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>mc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!mc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var gc=class extends z{create(e,t){return this._client.post(`/organization/external_storage`,pc(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(B`/organization/external_storage/${e}`,pc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=hc(e,[`after`,`limit`,`order`,`project_id`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/external_storage`,N,pc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/external_storage/${e}`,pc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}validate(e,t){return this._client.post(B`/organization/external_storage/${e}/validate`,pc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function _c(e,t){return Promise.resolve(e).then(t)}var vc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function yc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>vc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!vc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var bc=class extends z{create(e,t){return this._client.post(`/organization/invites`,_c(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(B`/organization/invites/${e}`,_c(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=yc(e,[`after`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/invites`,P,_c(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/invites/${e}`,_c(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function xc(e,t){return Promise.resolve(e).then(t)}var Sc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Cc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Sc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Sc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var wc=class extends z{create(e,t){return this._client.post(`/organization/roles`,xc(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(B`/organization/roles/${e}`,xc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/roles/${e}`,xc(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Cc(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/roles`,qt,xc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/roles/${e}`,xc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function Tc(e,t){return Promise.resolve(e).then(t)}var Ec=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Dc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Ec.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Ec.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Oc=class extends z{create(e,t){return this._client.post(`/organization/spend_alerts`,Tc(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(B`/organization/spend_alerts/${e}`,Tc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/spend_alerts/${e}`,Tc(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Dc(e,[`after`,`before`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/spend_alerts`,P,Tc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/spend_alerts/${e}`,Tc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function kc(e,t){return Promise.resolve(e).then(t)}var Ac=class extends z{retrieve(e){return this._client.get(`/organization/spend_limit`,kc(e,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t){return this._client.post(`/organization/spend_limit`,kc(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e){return this._client.delete(`/organization/spend_limit`,kc(e,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function jc(e,t){return Promise.resolve(e).then(t)}var Mc=class extends z{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}completions(e,t){return this._client.get(`/organization/usage/completions`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}costs(e,t){return this._client.get(`/organization/costs`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}images(e,t){return this._client.get(`/organization/usage/images`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}moderations(e,t){return this._client.get(`/organization/usage/moderations`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,jc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}};function Nc(e,t){return Promise.resolve(e).then(t)}var Pc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Fc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Pc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Pc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Ic=class extends z{create(e,t,n){return this._client.post(B`/organization/groups/${e}/roles`,Nc(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(B`/organization/groups/${r}/roles/${e}`,Nc(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=Fc(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/groups/${e}/roles`,qt,Nc(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{group_id:r}=t;return this._client.delete(B`/organization/groups/${r}/roles/${e}`,Nc(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function Lc(e,t){return Promise.resolve(e).then(t)}var Rc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function zc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Rc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Rc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Bc=class extends z{create(e,t,n){return this._client.post(B`/organization/groups/${e}/users`,Lc(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(B`/organization/groups/${r}/users/${e}`,Lc(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=zc(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/groups/${e}/users`,qt,Lc(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{group_id:r}=t;return this._client.delete(B`/organization/groups/${r}/users/${e}`,Lc(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function Vc(e,t){return Promise.resolve(e).then(t)}var Hc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Uc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Hc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Hc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Wc=class extends z{constructor(){super(...arguments),this.users=new Bc(this._client),this.roles=new Ic(this._client)}create(e,t){return this._client.post(`/organization/groups`,Vc(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(B`/organization/groups/${e}`,Vc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/groups/${e}`,Vc(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Uc(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/groups`,qt,Vc(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/groups/${e}`,Vc(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};Wc.Users=Bc,Wc.Roles=Ic;function Gc(e,t){return Promise.resolve(e).then(t)}var Kc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function qc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Kc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Kc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Jc=class extends z{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/api_keys/${e}`,Gc(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=qc(t,[`after`,`limit`,`owner_project_access`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/api_keys`,P,Gc(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/api_keys/${e}`,Gc(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function Yc(e,t){return Promise.resolve(e).then(t)}var Xc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Zc(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Xc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Xc.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Qc=class extends z{list(e,t={},n){let r=Zc(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/certificates`,P,Yc(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}activate(e,t,n){return this._client.getAPIList(B`/organization/projects/${e}/certificates/activate`,Kt,Yc(n,e=>({body:t,method:`post`,...e,__security:{adminAPIKeyAuth:!0}})))}deactivate(e,t,n){return this._client.getAPIList(B`/organization/projects/${e}/certificates/deactivate`,Kt,Yc(n,e=>({body:t,method:`post`,...e,__security:{adminAPIKeyAuth:!0}})))}};function $c(e,t){return Promise.resolve(e).then(t)}var el=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/data_retention`,$c(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/projects/${e}/data_retention`,$c(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}};function tl(e,t){return Promise.resolve(e).then(t)}var nl=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/hosted_tool_permissions`,tl(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/projects/${e}/hosted_tool_permissions`,tl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}};function rl(e,t){return Promise.resolve(e).then(t)}var il=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/model_permissions`,rl(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/projects/${e}/model_permissions`,rl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/projects/${e}/model_permissions`,rl(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function al(e,t){return Promise.resolve(e).then(t)}var ol=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function sl(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>ol.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ol.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var cl=class extends z{listRateLimits(e,t={},n){let r=sl(t,[`after`,`before`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/rate_limits`,P,al(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/rate_limits/${e}`,al(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}};function ll(e,t){return Promise.resolve(e).then(t)}var ul=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function dl(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>ul.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ul.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var fl=class extends z{create(e,t,n){return this._client.post(B`/projects/${e}/roles`,ll(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/projects/${r}/roles/${e}`,ll(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/projects/${r}/roles/${e}`,ll(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=dl(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/projects/${e}/roles`,qt,ll(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/projects/${r}/roles/${e}`,ll(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function pl(e,t){return Promise.resolve(e).then(t)}var ml=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function hl(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>ml.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ml.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var gl=class extends z{create(e,t,n){return this._client.post(B`/organization/projects/${e}/spend_alerts`,pl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/spend_alerts/${e}`,pl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/spend_alerts/${e}`,pl(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=hl(t,[`after`,`before`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/spend_alerts`,P,pl(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/spend_alerts/${e}`,pl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function _l(e,t){return Promise.resolve(e).then(t)}var vl=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/spend_limit`,_l(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/projects/${e}/spend_limit`,_l(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/projects/${e}/spend_limit`,_l(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function yl(e,t){return Promise.resolve(e).then(t)}var bl=class extends z{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/projects/${r}/groups/${e}/roles`,yl(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(B`/projects/${r}/groups/${i}/roles/${e}`,yl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(B`/projects/${r}/groups/${e}/roles`,qt,yl(n,e=>({query:i,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(B`/projects/${r}/groups/${i}/roles/${e}`,yl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function xl(e,t){return Promise.resolve(e).then(t)}var Sl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Cl(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Sl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Sl.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var wl=class extends z{constructor(){super(...arguments),this.roles=new bl(this._client)}create(e,t,n){return this._client.post(B`/organization/projects/${e}/groups`,xl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(B`/organization/projects/${r}/groups/${e}`,xl(n,e=>({query:i,...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=Cl(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/groups`,qt,xl(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/groups/${e}`,xl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};wl.Roles=bl;function Tl(e,t){return Promise.resolve(e).then(t)}var El=class extends z{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/service_accounts/${e}/api_keys`,Tl(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}};function Dl(e,t){return Promise.resolve(e).then(t)}var Ol=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function kl(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Ol.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Ol.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Al=class extends z{constructor(){super(...arguments),this.apiKeys=new El(this._client)}create(e,t,n){return this._client.post(B`/organization/projects/${e}/service_accounts`,Dl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/service_accounts/${e}`,Dl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/service_accounts/${e}`,Dl(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=kl(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/service_accounts`,P,Dl(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/service_accounts/${e}`,Dl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};Al.APIKeys=El;function jl(e,t){return Promise.resolve(e).then(t)}var Ml=class extends z{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/projects/${r}/users/${e}/roles`,jl(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(B`/projects/${r}/users/${i}/roles/${e}`,jl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(B`/projects/${r}/users/${e}/roles`,qt,jl(n,e=>({query:i,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(B`/projects/${r}/users/${i}/roles/${e}`,jl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function Nl(e,t){return Promise.resolve(e).then(t)}var Pl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Fl(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Pl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Pl.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Il=class extends z{constructor(){super(...arguments),this.roles=new Ml(this._client)}create(e,t,n){return this._client.post(B`/organization/projects/${e}/users`,Nl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/users/${e}`,Nl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/users/${e}`,Nl(n,e=>({body:i,...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=Fl(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/users`,P,Nl(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/users/${e}`,Nl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};Il.Roles=Ml;function Ll(e,t){return Promise.resolve(e).then(t)}var Rl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function zl(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Rl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Rl.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Bl=class extends z{constructor(){super(...arguments),this.users=new Il(this._client),this.serviceAccounts=new Al(this._client),this.apiKeys=new Jc(this._client),this.rateLimits=new cl(this._client),this.modelPermissions=new il(this._client),this.hostedToolPermissions=new nl(this._client),this.groups=new wl(this._client),this.roles=new fl(this._client),this.dataRetention=new el(this._client),this.spendLimit=new vl(this._client),this.spendAlerts=new gl(this._client),this.certificates=new Qc(this._client)}create(e,t){return this._client.post(`/organization/projects`,Ll(t,t=>({body:e,...t,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(B`/organization/projects/${e}`,Ll(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/projects/${e}`,Ll(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=zl(e,[`after`,`include_archived`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/projects`,P,Ll(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}archive(e,t){return this._client.post(B`/organization/projects/${e}/archive`,Ll(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};Bl.Users=Il,Bl.ServiceAccounts=Al,Bl.APIKeys=Jc,Bl.RateLimits=cl,Bl.ModelPermissions=il,Bl.HostedToolPermissions=nl,Bl.Groups=wl,Bl.Roles=fl,Bl.DataRetention=el,Bl.SpendLimit=vl,Bl.SpendAlerts=gl,Bl.Certificates=Qc;function Vl(e,t){return Promise.resolve(e).then(t)}var Hl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Ul(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Hl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Hl.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Wl=class extends z{create(e,t,n){return this._client.post(B`/organization/users/${e}/roles`,Vl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(B`/organization/users/${r}/roles/${e}`,Vl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=Ul(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/users/${e}/roles`,qt,Vl(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{user_id:r}=t;return this._client.delete(B`/organization/users/${r}/roles/${e}`,Vl(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};function Gl(e,t){return Promise.resolve(e).then(t)}var Kl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ql(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Kl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Kl.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Jl=class extends z{constructor(){super(...arguments),this.roles=new Wl(this._client)}retrieve(e,t){return this._client.get(B`/organization/users/${e}`,Gl(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(B`/organization/users/${e}`,Gl(n,e=>({body:t,...e,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=ql(e,[`after`,`emails`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/users`,P,Gl(t,t=>({query:e,...t,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(B`/organization/users/${e}`,Gl(t,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}};Jl.Roles=Wl;var Yl=class extends z{constructor(){super(...arguments),this.auditLogs=new oc(this._client),this.adminAPIKeys=new nc(this._client),this.usage=new Mc(this._client),this.invites=new bc(this._client),this.users=new Jl(this._client),this.groups=new Wc(this._client),this.roles=new wc(this._client),this.dataRetention=new fc(this._client),this.externalStorage=new gc(this._client),this.spendLimit=new Ac(this._client),this.spendAlerts=new Oc(this._client),this.certificates=new uc(this._client),this.projects=new Bl(this._client)}};Yl.AuditLogs=oc,Yl.AdminAPIKeys=nc,Yl.Usage=Mc,Yl.Invites=bc,Yl.Users=Jl,Yl.Groups=Wc,Yl.Roles=wc,Yl.DataRetention=fc,Yl.ExternalStorage=gc,Yl.SpendLimit=Ac,Yl.SpendAlerts=Oc,Yl.Certificates=uc,Yl.Projects=Bl;var Xl=class extends z{constructor(){super(...arguments),this.organization=new Yl(this._client)}};Xl.Organization=Yl;function Zl(e,t){return Promise.resolve(e).then(t)}var Ql=class extends z{create(e,t){return this._client.post(`/audio/speech`,Zl(t,t=>({body:e,...t,headers:F([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function $l(e,t){return Promise.resolve(e).then(t)}var eu=class extends z{create(e,t){return this._client.post(`/audio/transcriptions`,$l(t,t=>Vr({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client)))}};function tu(e,t){return Promise.resolve(e).then(t)}var nu=class extends z{create(e,t){return this._client.post(`/audio/translations`,tu(t,t=>Vr({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client)))}},ru=class extends z{constructor(){super(...arguments),this.transcriptions=new eu(this._client),this.translations=new nu(this._client),this.speech=new Ql(this._client)}};ru.Transcriptions=eu,ru.Translations=nu,ru.Speech=Ql;function iu(e,t){return Promise.resolve(e).then(t)}var au=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ou(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>au.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!au.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var su=class extends z{create(e,t){return this._client.post(`/batches`,iu(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/batches/${e}`,iu(t,e=>({...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=ou(e,[`after`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/batches`,N,iu(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(B`/batches/${e}/cancel`,iu(t,e=>({...e,__security:{bearerAuth:!0}})))}};function cu(e,t){return Promise.resolve(e).then(t)}var lu=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function uu(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>lu.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!lu.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var du=class extends z{create(e,t){return this._client.post(`/assistants`,cu(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/assistants/${e}`,cu(t,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(B`/assistants/${e}`,cu(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=uu(e,[`after`,`before`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/assistants`,N,cu(t,t=>({query:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/assistants/${e}`,cu(t,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}},fu=class extends z{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},pu=class extends z{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},mu=class extends z{constructor(){super(...arguments),this.sessions=new fu(this._client),this.transcriptionSessions=new pu(this._client)}};mu.Sessions=fu,mu.TranscriptionSessions=pu;var hu=class extends o{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 gu(e){let t=e.split(`/`),n=t[2]??``;if(!e.startsWith(`/workspace/`)||e.includes(`\\`)||e.includes(`\0`)||t.slice(1).some(e=>e===``||e===`.`||e===`..`)||n===`.codex`||n===`.managed-agents`||n.startsWith(`.managed-agents-`)||e===`/workspace/outputs`)throw new o(`Agent files require a non-reserved absolute file path inside /workspace`)}function _u(e,t){let n=Object.entries(e),r=F([t.headers]);if(n.length>1&&(r.values.has(`idempotency-key`)||!r.nulls.has(`idempotency-key`)&&t?.idempotencyKey!==void 0))throw new o(`Do not reuse an Idempotency-Key across multiple file uploads`);let i=new Set(n.map(([e])=>e));for(let[e]of n){gu(e);for(let t=e.lastIndexOf(`/`);t>0;t=e.lastIndexOf(`/`,t-1))if(i.has(e.slice(0,t)))throw new o(`Agent file destinations conflict`)}return n}async function vu(e,t,n){let r={...n},i=F([e._options.defaultHeaders,r.headers]);r.headers=i;let a=_u(t,r);a.length>1&&i.nulls.add(`idempotency-key`);let o={files:[],uploadedFiles:[]};try{for(let[t,n]of a){let i=await e.files.create({file:n,purpose:`user_data`},r);o.uploadedFiles.push(i),o.files.push({type:`file_id`,file_id:i.id,path:t})}return o}catch(e){throw new hu(o.uploadedFiles,e)}}async function yu(e,t,n,r,i){let a=await vu(e,{[r.path]:r.file},i),[s]=a.files,[c]=a.uploadedFiles;if(!s||!c)throw new o(`Missing prepared agent file`);try{return{uploadedFile:c,environmentFile:await t.create(n,s,i)}}catch(e){throw new hu(a.uploadedFiles,e)}}function bu(e,t){return Promise.resolve(e).then(t)}var xu=class extends z{prepare(e,t){return vu(this._client,e,t)}upload(e,t,n){return yu(this._client,this,e,t,n)}create(e,t,n){return this._client.post(B`/agents/environments/${e}/files`,bu(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){return this._client.getAPIList(B`/agents/environments/${e}/files`,Jt,bu(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function Su(e,t){return Promise.resolve(e).then(t)}var Cu=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function wu(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Cu.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Cu.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Tu=class extends z{create(e={},t){return this._client.post(`/agents/environments/templates`,Su(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/agents/environments/templates/${e}`,Su(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(B`/agents/environments/templates/${e}`,Su(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=wu(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/agents/environments/templates`,N,Su(t,t=>({query:e,...t,headers:F([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/agents/environments/templates/${e}`,Su(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function Eu(e,t){return Promise.resolve(e).then(t)}var Du=class extends z{constructor(){super(...arguments),this.files=new xu(this._client),this.templates=new Tu(this._client)}retrieve(e,t){return this._client.get(B`/agents/environments/${e}`,Eu(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};Du.Files=xu,Du.Templates=Tu;var Ou,ku,Au,ju,Mu=class{constructor(){Ou.set(this,void 0),ku.set(this,!1),Au.set(this,new Set),ju.set(this,new Set)}accept(e){if(n(this,Au,`f`).has(e.event_id))return!1;if(n(this,Au,`f`).size===1024){let e=n(this,Au,`f`).values().next();e.done||n(this,Au,`f`).delete(e.value)}return n(this,Au,`f`).add(e.event_id),e.type===`agent.session.turn.created`&&e.turn.subagent_id===null&&n(this,Ou,`f`)===void 0&&t(this,Ou,e.turn_id,`f`),(e.type===`agent.session.turn.completed`||e.type===`agent.session.turn.failed`||e.type===`agent.session.turn.cancelled`)&&n(this,Ou,`f`)!==void 0&&e.turn_id===n(this,Ou,`f`)&&t(this,ku,!0,`f`),!0}terminal(e){return e.type===`agent.session.failed`||e.type===`agent.session.idle`&&n(this,ku,`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(!n(this,ju,`f`).has(r))return n(this,ju,`f`).add(r),t}};Ou=new WeakMap,ku=new WeakMap,Au=new WeakMap,ju=new WeakMap;function Nu(e){return e.content.map(e=>e.type===`output_text`?e.text:``).join(``)}var Pu=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(Nu).join(``)}},Fu=class extends Pu{constructor(e,t){super(e.turn,e.messages),this.raw_result=e,this.output_parsed=t}},Iu,Lu=class extends o{constructor(e){super(`The completed agent output could not be parsed`),this.name=`AgentOutputParseError`,Iu.set(this,void 0),t(this,Iu,e,`f`)}get raw_result(){return n(this,Iu,`f`)}};Iu=new WeakMap;function Ru(e,t){try{if(!t)return e;let n;for(let r of e.messages)for(let e of r.content)if(e.type===`output_text`){let r=t.$parseRaw(e.text);n??={value:r}}if(!n)throw new Lu(e);return new Fu(e,n.value)}catch{throw new Lu(e)}}function zu(e,t){let n=e&&Object.getOwnPropertyDescriptor(e,t);return n?.enumerable&&`value`in n?n.value:void 0}function Bu(e){if(!e)return;let t=Object.getOwnPropertyDescriptor(e,`$parseRaw`);if(!t||!(`value`in t)||typeof t.value!=`function`)return;let n=zu(e,`schema`);if(zu(e,`type`)!==`json_schema`||!n)throw new o(`Typed agent formats require own enumerable type and schema data properties`);let r=t.value;return{type:`json_schema`,schema:n,$parseRaw:t=>r.call(e,t)}}function Vu(e,t,n=e=>e){let r=Object.getOwnPropertyDescriptor(e,t);if(!r?.enumerable)return e;let i=n(e[t]);return`value`in r&&i===r.value?e:Object.create(Object.getPrototypeOf(e),{...Object.getOwnPropertyDescriptors(e),[t]:{value:i,enumerable:!0,configurable:r.configurable,writable:!0}})}function Hu(e,t){let n=Vu(e,`agent`,e=>e&&Vu(e,`text`,e=>e&&Vu(e,`format`))),r=zu(n,`agent`),i=zu(r,`text`),a=Bu(zu(i,`format`));if(!a)return{body:n,options:t};let s=structuredClone(a.schema);for(let e of[n,r,i])if(e&&`toJSON`in e)throw new o(`Typed agent requests cannot customize body, agent, or text serialization`);let c={...t};if(zu(c,`body`)!==void 0)throw new o(`Typed agent requests cannot override the body in request options`);return delete c.body,{options:c,body:{...n,agent:{...r,text:{...i,format:{type:`json_schema`,schema:s}}}},format:a}}async function Uu(e,t){return Ru(await e,t)}var Wu=class extends o{constructor(e,t,n,r,i=[],a){super(`Could not collect the agent turn result: ${e}`),this.name=`AgentTurnResultError`,this.reason=e,this.session_id=t,this.turn=n,this.messages=r,this.required_actions=i,this.cause=a}get turn_id(){return this.turn?.id}},Gu,Ku,qu,Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd=class{constructor(e){Gu.add(this),Ku.set(this,void 0),qu.set(this,void 0),Ju.set(this,new Map),Yu.set(this,[]),Xu.set(this,!1),Zu.set(this,!1),Qu.set(this,!1),t(this,Ku,e,`f`)}accept(e){if(this.ready)return;`session`in e&&(t(this,Ku,n(this,Ku,`f`)??e.session.id,`f`),t(this,Yu,structuredClone(e.session.required_actions??[]),`f`),t(this,Xu,n(this,Xu,`f`)||e.type===`agent.session.failed`,`f`),t(this,Qu,n(this,Qu,`f`)||e.type===`agent.session.idle`&&n(this,Zu,`f`),`f`)),e.type===`agent.session.turn.created`&&e.turn.subagent_id===null&&!n(this,qu,`f`)&&(t(this,qu,structuredClone(e.turn),`f`),t(this,Ku,e.turn.session_id,`f`));let r=`turn_id`in e?e.turn_id:void 0;`item`in e&&(r=e.item.turn_id),n(this,qu,`f`)&&r===n(this,qu,`f`).id&&n(this,Gu,`m`,$u).call(this,e)}error(e,t){return new Wu(e,n(this,Ku,`f`),n(this,qu,`f`),n(this,Gu,`m`,td).call(this),n(this,Yu,`f`),t)}checkAction(e){if(n(this,Xu,`f`)||n(this,qu,`f`)?.status===`failed`)throw this.error(`failed`);if(n(this,qu,`f`)?.status===`cancelled`)throw this.error(`cancelled`);if(n(this,Yu,`f`).some(t=>t.type!==`function_call`||!e(t.name)))throw this.error(`requires_action`)}get ready(){return n(this,Zu,`f`)&&n(this,Qu,`f`)}release(){n(this,Ju,`f`).clear(),t(this,Yu,[],`f`)}finish(){if(this.checkAction(()=>this.ready),!n(this,Zu,`f`)||n(this,qu,`f`)?.status!==`completed`||!n(this,Qu,`f`))throw this.error(`observation`);return new Pu(n(this,qu,`f`),n(this,Gu,`m`,td).call(this))}};Ku=new WeakMap,qu=new WeakMap,Ju=new WeakMap,Yu=new WeakMap,Xu=new WeakMap,Zu=new WeakMap,Qu=new WeakMap,Gu=new WeakSet,$u=function(e){`turn`in e&&(t(this,qu,structuredClone(e.turn),`f`),t(this,Zu,n(this,Zu,`f`)||e.type===`agent.session.turn.completed`||e.type===`agent.session.turn.failed`||e.type===`agent.session.turn.cancelled`,`f`)),n(this,Gu,`m`,ed).call(this,e)},ed=function(e){e.type!==`agent.session.turn.item.done`||e.item.type!==`message`||e.item.status!==`completed`||e.item.phase===`commentary`||n(this,Ju,`f`).has(e.item.id)||n(this,Ju,`f`).set(e.item.id,{index:e.output_index,message:structuredClone(e.item)})},td=function(){return[...n(this,Ju,`f`).values()].sort((e,t)=>e.index-t.index).map(({message:e})=>e)};var rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd=class{constructor(e,n=()=>!1,r,i){rd.add(this),id.set(this,void 0),ad.set(this,!1),od.set(this,!1),sd.set(this,!1),cd.set(this,void 0),ld.set(this,void 0),ud.set(this,void 0),dd.set(this,void 0),fd.set(this,void 0),t(this,ud,e,`f`),t(this,dd,i,`f`),t(this,fd,n,`f`),this.collector=new nd(r)}enable(){if(!n(this,od,`f`)&&n(this,sd,`f`))throw new o(`Call withResultCollection() before consuming events, or call finalResult() on a fresh stream.`);t(this,od,!0,`f`)}iterate(){if(n(this,id,`f`))throw new o(`An agent result stream can only be consumed once`);return t(this,id,n(this,rd,`m`,pd).call(this),`f`)}finalResult(){return t(this,ld,n(this,ld,`f`)??n(this,rd,`m`,md).call(this),`f`)}};id=new WeakMap,ad=new WeakMap,od=new WeakMap,sd=new WeakMap,cd=new WeakMap,ld=new WeakMap,ud=new WeakMap,dd=new WeakMap,fd=new WeakMap,rd=new WeakSet,pd=async function*(){let e=n(this,ud,`f`).call(this),r=!1;try{for(;;){let i=await e.next();if(i.done){r=!0;return}n(this,od,`f`)?this.collector.accept(i.value):t(this,sd,!0,`f`),yield i.value}}catch(e){throw n(this,od,`f`)&&t(this,cd,e,`f`),e}finally{t(this,ad,!0,`f`),r||await e.return?.()}},md=async function(){this.enable();try{let e=n(this,id,`f`)??this.iterate();for(;!n(this,ad,`f`)&&!this.collector.ready&&(this.collector.checkAction(n(this,fd,`f`)),!(await e.next()).done););if(n(this,cd,`f`)!==void 0&&!this.collector.ready)throw n(this,cd,`f`);if(!this.collector.ready&&n(this,dd,`f`)?.aborted)throw this.collector.error(`observation`,n(this,dd,`f`).reason);return this.collector.finish()}catch(e){throw e instanceof Wu?e:this.collector.error(`observation`,e)}finally{try{await n(this,id,`f`)?.return()}finally{this.collector.release()}}};function gd(e){if(!D(e))return!1;let t=e,n;if(t.type===`input_text`)n=`text`;else if(t.type===`input_image`)n=`image_url`;else return!1;return E(t,`type`)&&E(t,n)&&typeof t[n]==`string`}var q,_d,vd,yd,bd,xd,Sd,Cd,wd,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd;function Id(e){if(e===null)return null;if(typeof e==`string`||Array.isArray(e)&&e.every(gd))return e;throw new o(`Tool output must be text, content, a JSON object, or null`)}function Ld(e,t){let n=D(t)?JSON.stringify(t):t,r=JSON.stringify(n);if(r===void 0)throw new o(`Tool output must be JSON serializable`);return{type:`agent.session.input.tool_result`,turn_id:e.turn_id,call_id:e.call_id,success:!0,output:Id(typeof n==`string`?n:JSON.parse(r))}}async function Rd(e){try{await e?.body?.cancel()}catch{}}var zd=class{constructor(e,i,a,s){q.add(this),this.controller=new AbortController,_d.set(this,!1),vd.set(this,void 0),yd.set(this,void 0),bd.set(this,void 0),xd.set(this,void 0),Sd.set(this,void 0),Cd.set(this,!1),wd.set(this,void 0),Td.set(this,void 0),Ed.set(this,void 0),Dd.set(this,void 0),Od.set(this,void 0),kd.set(this,void 0);let c=typeof a.input==`string`?[{role:`user`,content:[{type:`input_text`,text:a.input}]}]:a.input;if(a.input.length===0)throw new o(`input must not be empty`);if(t(this,vd,Bu(a.outputFormat),`f`),a.outputFormat&&!n(this,vd,`f`))throw new o(`outputFormat must have its own parser function`);t(this,wd,e,`f`),t(this,Td,i,`f`),t(this,Ed,{type:`agent.session.input.message`,input:c},`f`),t(this,Dd,new Map(Object.entries(a.toolHandlers??{})),`f`);let l=F([s?.headers]);t(this,Od,l.nulls.has(`idempotency-key`)?void 0:l.values.get(`idempotency-key`)??a.idempotencyKey??s?.idempotencyKey??r(),`f`),l.values.delete(`idempotency-key`),l.nulls.delete(`idempotency-key`);let{idempotencyKey:u,...d}=s??{};t(this,kd,{...d,headers:l},`f`),t(this,bd,new hd(()=>n(this,q,`m`,Ad).call(this),e=>n(this,Dd,`f`).has(e),i),`f`)}abort(e){this.controller.abort(e),n(this,xd,`f`)?.controller.abort(this.controller.signal.reason),n(this,Cd,`f`)||Rd(n(this,Sd,`f`))}[(_d=new WeakMap,vd=new WeakMap,yd=new WeakMap,bd=new WeakMap,xd=new WeakMap,Sd=new WeakMap,Cd=new WeakMap,wd=new WeakMap,Td=new WeakMap,Ed=new WeakMap,Dd=new WeakMap,Od=new WeakMap,kd=new WeakMap,q=new WeakSet,Symbol.asyncIterator)](){if(n(this,_d,`f`))throw new o(`An AgentSessionStream can only be consumed once`);return t(this,_d,!0,`f`),n(this,bd,`f`).iterate()}withResultCollection(){return n(this,bd,`f`).enable(),this}finalResult(){return t(this,yd,n(this,yd,`f`)??Uu(n(this,bd,`f`).finalResult(),n(this,vd,`f`)),`f`)}};Ad=async function*(){let e=n(this,kd,`f`).signal,r=()=>this.abort(e?.aborted?e.reason:this.controller.signal.reason);e?.addEventListener(`abort`,r,{once:!0}),this.controller.signal.addEventListener(`abort`,r,{once:!0});let i={...n(this,kd,`f`),signal:this.controller.signal},a=new Mu;try{if(e?.aborted&&this.abort(e.reason),n(this,q,`m`,Md).call(this),(await n(this,wd,`f`).retrieve(n(this,Td,`f`),i)).status!==`idle`)throw new o(`sessions.stream requires an idle session; use sessions.events.stream for active sessions`);let r=await n(this,wd,`f`).events.stream(n(this,Td,`f`),i).withResponse();t(this,xd,r.data,`f`),t(this,Sd,r.response,`f`),n(this,q,`m`,Md).call(this),await n(this,wd,`f`).events.create(n(this,Td,`f`),{events:[n(this,Ed,`f`)],...n(this,Od,`f`)===void 0?{}:{"Idempotency-Key":n(this,Od,`f`)}},{...i,headers:F([i.headers,{"Idempotency-Key":n(this,Od,`f`)??null}])}),n(this,q,`m`,Md).call(this),t(this,Cd,!0,`f`);for await(let e of n(this,xd,`f`)){if(n(this,q,`m`,Md).call(this),!a.accept(e))continue;let t=a.terminal(e),r=a.call(e),o=r&&n(this,Dd,`f`).get(r.name),s=r&&o?structuredClone(r):void 0;if(t&&n(this,xd,`f`).controller.abort(),yield e,t)return;if(n(this,q,`m`,Md).call(this),!s||!o)continue;let c=await n(this,q,`m`,jd).call(this,s,o);n(this,q,`m`,Md).call(this),await n(this,q,`m`,Fd).call(this,c,i)}throw n(this,q,`m`,Md).call(this),new o(`Session event stream ended before the turn reached idle or failed`)}finally{e?.removeEventListener(`abort`,r),this.controller.signal.removeEventListener(`abort`,r),this.abort()}},jd=async function(e,t){try{let r=typeof e.arguments==`string`?JSON.parse(e.arguments):e.arguments;if(!D(r))throw new o(`Function arguments must be a JSON object`);return Ld(e,await n(this,q,`m`,Pd).call(this,()=>t(r)))}catch{return n(this,q,`m`,Md).call(this),{type:`agent.session.input.tool_result`,turn_id:e.turn_id,call_id:e.call_id,success:!1,error:`Tool handler failed.`}}},Md=function(){if(this.controller.signal.aborted)throw n(this,q,`m`,Nd).call(this)},Nd=function(){let e=new c;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e},Pd=async function(e){let t,r=new Promise((e,r)=>{t=()=>r(n(this,q,`m`,Nd).call(this)),this.controller.signal.addEventListener(`abort`,t,{once:!0})});try{return n(this,q,`m`,Md).call(this),await Promise.race([(async()=>await e())(),r])}finally{t&&this.controller.signal.removeEventListener(`abort`,t)}},Fd=async function e(t,i,a=r(),o=0){n(this,q,`m`,Md).call(this);try{await n(this,wd,`f`).events.create(n(this,Td,`f`),{events:[t],"Idempotency-Key":a},i)}catch(r){let s=[100,300,600][o];if(s===void 0||!(r instanceof d)||r.code!==`invalid_request_error`||!r.error||!(`message`in r.error)||r.error.message!==`Unknown pending tool call: ${t.call_id}`)throw r;let c;try{await n(this,q,`m`,Pd).call(this,()=>new Promise(e=>{c=setTimeout(e,s)}))}finally{c!==void 0&&clearTimeout(c)}await n(this,q,`m`,e).call(this,t,i,a,o+1)}};function Bd(e,t){let n;e.__betaTransformIterator(t=>(n=new hd(t,void 0,void 0,e.controller.signal),()=>n.iterate()));let r,i=Object.assign(e,{finalResult:()=>r??=Uu(n.finalResult(),t),withResultCollection:()=>(n.enable(),i)});return i}async function*Vd(e){let t;for(;;){let n=await e(t);if(yield*n.data,!n.has_more)return;let r=n.body,i=n.data[n.data.length-1],a=D(r)&&typeof r.last_id==`string`?r.last_id:i?.id;if(!a||a===t)throw new o(`Agent pagination cannot advance to the next page`);t=a}}var Hd,Ud,Wd,Gd=class{constructor(e,n){Hd.set(this,void 0),Ud.set(this,void 0),Wd.set(this,void 0),t(this,Hd,e,`f`),t(this,Ud,n.session_id,`f`),t(this,Wd,n.turn_id,`f`)}async retrieve(e,t){let r;for await(let i of Vd(e=>n(this,Hd,`f`).list(n(this,Ud,`f`),{},{...t,query:{...t?.query,after:e,environment_id:void 0}})))if(i.session_id===n(this,Ud,`f`)&&i.turn_id===n(this,Wd,`f`)&&i.path===e){if(r)throw new o(`Multiple artifacts match this result and path`);r=i}if(!r)throw new o(`No artifact matches this result and path`);return r}async content(e,t){let r=await this.retrieve(e,t);return n(this,Hd,`f`).content(r.id,{session_id:n(this,Ud,`f`)},t)}async download(e,t){let{path:r,to:i}=e,a=await this.retrieve(r,t),s=await n(this,Hd,`f`).content(a.id,{session_id:n(this,Ud,`f`)},t);if(!s.body)throw new o(`Artifact response has no content stream`);try{await s.body.pipeTo(i,t?.signal?{signal:t.signal}:{})}catch(e){try{await s.body.cancel()}catch{}throw e}return a}};Hd=new WeakMap,Ud=new WeakMap,Wd=new WeakMap;function Kd(e,t){return Promise.resolve(e).then(t)}var qd=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Jd(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>qd.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!qd.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Yd=class extends z{forResult(e){return new Gd(this,e)}retrieve(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/artifacts/${e}`,Kd(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let r=Jd(t,[`after`,`environment_id`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/artifacts`,N,Kd(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{session_id:r}=t;return this._client.delete(B`/agents/sessions/${r}/artifacts/${e}`,Kd(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}content(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/artifacts/${e}/content`,Kd(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`,Accept:`application/octet-stream`},e?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function Xd(e,t){return Promise.resolve(e).then(t)}var Zd=class extends z{create(e,t,n){let{"Idempotency-Key":r,...i}=t;return this._client.post(B`/agents/sessions/${e}/events`,Xd(n,e=>({body:i,...e,headers:F([{"OpenAI-Beta":`agents=v1`,Accept:`*/*`,...r==null?void 0:{"Idempotency-Key":r}},e?.headers]),__security:{bearerAuth:!0}})))}stream(e,t){return this._client.get(B`/agents/sessions/${e}/events`,Xd(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`,Accept:`text/event-stream`},e?.headers]),stream:!0,__security:{bearerAuth:!0}})))}};function Qd(e,t){return Promise.resolve(e).then(t)}var $d=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ef(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>$d.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!$d.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var tf=class extends z{list(e,t={},n){let r=ef(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/items`,N,Qd(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function nf(e,t){return Promise.resolve(e).then(t)}var rf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function af(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>rf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!rf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var of=class extends z{list(e,t={},n){let r=af(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/traces`,N,nf(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function sf(e,t){return Promise.resolve(e).then(t)}var cf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function lf(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>cf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!cf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var uf=class extends z{retrieve(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/turns/${e}`,sf(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let r=lf(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/turns`,N,sf(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function df(e,t){return Promise.resolve(e).then(t)}var ff=class extends z{list(e,t,n){let{session_id:r,...i}=t;return this._client.getAPIList(B`/agents/sessions/${r}/subagents/${e}/items`,N,df(n,e=>({query:i,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function pf(e,t){return Promise.resolve(e).then(t)}var mf=class extends z{list(e,t,n){let{session_id:r,subagent_id:i,...a}=t;return this._client.getAPIList(B`/agents/sessions/${r}/subagents/${i}/turns/${e}/items`,N,pf(n,e=>({query:a,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function hf(e,t){return Promise.resolve(e).then(t)}var gf=class extends z{constructor(){super(...arguments),this.items=new mf(this._client)}retrieve(e,t,n){let{session_id:r,subagent_id:i}=t;return this._client.get(B`/agents/sessions/${r}/subagents/${i}/turns/${e}`,hf(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t,n){let{session_id:r,...i}=t;return this._client.getAPIList(B`/agents/sessions/${r}/subagents/${e}/turns`,N,hf(n,e=>({query:i,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};gf.Items=mf;function _f(e,t){return Promise.resolve(e).then(t)}var vf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function yf(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>vf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!vf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var bf=class extends z{constructor(){super(...arguments),this.items=new ff(this._client),this.turns=new gf(this._client)}retrieve(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/subagents/${e}`,_f(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let r=yf(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/subagents`,N,_f(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};bf.Items=ff,bf.Turns=gf;function xf(e,t){return Promise.resolve(e).then(t)}var Sf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Cf(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Sf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Sf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var wf=class extends z{constructor(){super(...arguments),this.subagents=new bf(this._client),this.artifacts=new Yd(this._client),this.items=new tf(this._client),this.events=new Zd(this._client),this.traces=new of(this._client),this.turns=new uf(this._client)}stream(e,t,n){return new zd(this,e,t,n)}create(e,t){let n=Hu(e,t);return this._client.post(`/agents/sessions`,xf(n.options,e=>({body:n.body,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),stream:n.body.stream??!1,__security:{bearerAuth:!0}})))._thenUnwrap((e,{options:t})=>t.stream?Bd(e,n.format):e)}retrieve(e,t){return this._client.get(B`/agents/sessions/${e}`,xf(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(B`/agents/sessions/${e}`,xf(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Cf(e,[`after`,`agent_id`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/agents/sessions`,N,xf(t,t=>({query:e,...t,headers:F([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/agents/sessions/${e}`,xf(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};wf.Subagents=bf,wf.Artifacts=Yd,wf.Items=tf,wf.Events=Zd,wf.Traces=of,wf.Turns=uf;function Tf(e,t){return Promise.resolve(e).then(t)}var Ef=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Df(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Ef.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Ef.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Of=class extends z{create(e,t,n){return this._client.post(B`/vaults/${e}/credentials`,Tf(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{vault_id:r}=t;return this._client.get(B`/vaults/${r}/credentials/${e}`,Tf(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{vault_id:r,...i}=t;return this._client.post(B`/vaults/${r}/credentials/${e}`,Tf(n,e=>({body:i,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let r=Df(t,[`after`,`limit`,`order`,`status`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/vaults/${e}/credentials`,N,Tf(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{vault_id:r}=t;return this._client.delete(B`/vaults/${r}/credentials/${e}`,Tf(n,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function kf(e,t){return Promise.resolve(e).then(t)}var Af=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function jf(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Af.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Af.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Mf=class extends z{constructor(){super(...arguments),this.credentials=new Of(this._client)}create(e={},t){return this._client.post(`/vaults`,kf(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/vaults/${e}`,kf(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=jf(e,[`after`,`limit`,`order`,`status`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/vaults`,N,kf(t,t=>({query:e,...t,headers:F([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/vaults/${e}`,kf(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};Mf.Credentials=Of;function Nf(e,t){return Promise.resolve(e).then(t)}var Pf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Ff(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Pf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Pf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var If=class extends z{constructor(){super(...arguments),this.environments=new Du(this._client),this.vaults=new Mf(this._client),this.sessions=new wf(this._client)}create(e,t){return this._client.post(`/agents`,Nf(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/agents/${e}`,Nf(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(B`/agents/${e}`,Nf(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Ff(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/agents`,N,Nf(t,t=>({query:e,...t,headers:F([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/agents/${e}`,Nf(t,e=>({...e,headers:F([{"OpenAI-Beta":`agents=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};If.Environments=Du,If.Vaults=Mf,If.Sessions=wf;function Lf(e,t){return Promise.resolve(e).then(t)}var Rf=class extends z{create(e,t){return this._client.post(`/chatkit/sessions`,Lf(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(B`/chatkit/sessions/${e}/cancel`,Lf(t,e=>({...e,headers:F([{"OpenAI-Beta":`chatkit_beta=v1`},e?.headers]),__security:{bearerAuth:!0}})))}};function zf(e,t){return Promise.resolve(e).then(t)}var Bf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Vf(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Bf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Bf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Hf=class extends z{retrieve(e,t){return this._client.get(B`/chatkit/threads/${e}`,zf(t,e=>({...e,headers:F([{"OpenAI-Beta":`chatkit_beta=v1`},e?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Vf(e,[`after`,`before`,`limit`,`order`,`user`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/chatkit/threads`,P,zf(t,t=>({query:e,...t,headers:F([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/chatkit/threads/${e}`,zf(t,e=>({...e,headers:F([{"OpenAI-Beta":`chatkit_beta=v1`},e?.headers]),__security:{bearerAuth:!0}})))}listItems(e,t={},n){let r=Vf(t,[`after`,`before`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/chatkit/threads/${e}/items`,P,zf(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`chatkit_beta=v1`},e?.headers]),__security:{bearerAuth:!0}})))}},Uf=class extends z{constructor(){super(...arguments),this.sessions=new Rf(this._client),this.threads=new Hf(this._client)}};Uf.Sessions=Rf,Uf.Threads=Hf;function Wf(e,t){return Promise.resolve(e).then(t)}var Gf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Kf(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Gf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Gf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var qf=class extends z{list(e,t={},n){let r=Kf(t,[`after`,`betas`,`include`,`limit`,`order`],n);r!==void 0&&(n=r,t={}),t=t;let{betas:i,...a}=t??{};return this._client.getAPIList(B`/responses/${e}/input_items?beta=true`,N,Wf(n,e=>({query:a,...e,headers:F([{...i?.toString()==null?void 0:{"openai-beta":i?.toString()}},e?.headers]),__security:{bearerAuth:!0}})))}};function Jf(e,t){return Promise.resolve(e).then(t)}var Yf=class extends z{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,Jf(t,e=>({body:r,...e,headers:F([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},e?.headers]),__security:{bearerAuth:!0}})))}};function Xf(e,t){return Promise.resolve(e).then(t)}var Zf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Qf(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Zf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Zf.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var $f=class extends z{constructor(){super(...arguments),this.inputItems=new qf(this._client),this.inputTokens=new Yf(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,Xf(t,t=>({body:r,...t,headers:F([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})))}retrieve(e,t={},n){let r=Qf(t,[`betas`,`include`,`include_obfuscation`,`starting_after`,`stream`],n);r!==void 0&&(n=r,t={}),t=t;let{betas:i,...a}=t??{};return this._client.get(B`/responses/${e}?beta=true`,Xf(n,e=>({query:a,...e,headers:F([{...i?.toString()==null?void 0:{"openai-beta":i?.toString()}},e?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})))}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(B`/responses/${e}?beta=true`,Xf(n,e=>({...e,headers:F([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},e?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(B`/responses/${e}/cancel?beta=true`,Xf(n,e=>({...e,headers:F([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},e?.headers]),__security:{bearerAuth:!0}})))}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,Xf(t,e=>({body:r,...e,headers:F([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},e?.headers]),__security:{bearerAuth:!0}})))}};$f.InputItems=qf,$f.InputTokens=Yf;function ep(e,t){return Promise.resolve(e).then(t)}var tp=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function np(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>tp.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!tp.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var rp=class extends z{create(e,t,n){return this._client.post(B`/threads/${e}/messages`,ep(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(B`/threads/${r}/messages/${e}`,ep(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(B`/threads/${r}/messages/${e}`,ep(n,e=>({body:i,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let r=np(t,[`after`,`before`,`limit`,`order`,`run_id`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/threads/${e}/messages`,N,ep(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(B`/threads/${r}/messages/${e}`,ep(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}};function ip(e,t){return Promise.resolve(e).then(t)}var ap=class extends z{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(B`/threads/${r}/runs/${i}/steps/${e}`,ip(n,e=>({query:a,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(B`/threads/${r}/runs/${e}/steps`,N,ip(n,e=>({query:i,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}},op=e=>{if(globalThis.Buffer!==void 0){let t=globalThis.Buffer.from(e,`base64`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof atob<`u`){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}throw new o("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},sp=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);if(t.length%Float32Array.BYTES_PER_ELEMENT!==0)throw RangeError(`Invalid base64-encoded float32 array: byte length must be a multiple of 4`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},cp=e=>{try{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0}catch{return}},lp=1024,up=65536;function dp(e){switch(e){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 e;default:return`unknown`}}var fp=new WeakMap,pp=new WeakSet;function mp(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function hp(e){for(let[t,n]of e.arrays)n.cacheable&&!pp.has(t)?fp.set(t,{length:n.length,ownEntryCount:n.ownEntryCount}):fp.delete(t)}function gp(e){return typeof e==`string`||typeof e==`number`}function _p(e,t){return t.every(gp)&&e.every(gp)}function vp(e){let t=0;for(let n of Object.keys(e)){let r=Number(n);Number.isSafeInteger(r)&&r>=0&&r<e.length&&String(r)===n&&(t+=1)}return t}function yp(e,t,n){return t?n?.length===e.length?n.ownEntryCount:vp(e):0}function bp(e,t,n){let{index:r}=e;if(t===`array`&&r==null)throw Error("Expected array delta entry to have an `index` property");if(t===`array`&&typeof r!=`number`)throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(r)||r<0||r>=n+lp||r>=up)throw new o(`Assistant stream delta contains an invalid ${t} index: ${typeof r==`number`?r:`unknown`}`);return r}function xp(e,t,n,r,i){let a=r.arrays.get(e);if(!a){let t=r.cacheArrays&&!pp.has(e),n=t?fp.get(e):void 0;a={baselineLength:e.length,cacheable:t,enforceSparseHoleBudget:t,entries:new Map,length:e.length,ownEntryCount:yp(e,t,n)},r.arrays.set(e,a)}for(let s of t){if(!D(s))throw Error(`Expected array delta entry to be an object but got an invalid value`);let t=bp(s,n,a.baselineLength),c;a.entries.has(t)?c=a.entries.get(t):E(e,t)?(c=e[t],c??a.entries.set(t,s)):(a.entries.set(t,s),a.ownEntryCount+=1);let l=Math.max(a.length,t+1);if(a.enforceSparseHoleBudget&&l-a.ownEntryCount>lp)throw new o(`Assistant stream delta contains an invalid ${n} index: ${t}`);D(c)&&i(c,s,r),a.length=l}}function Sp(e,t,n){let r=n.records.get(e);for(let[i,a]of Object.entries(t)){if(i===`index`||i===`type`)continue;let t;if(r?.has(i)?t=r.get(i):E(e,i)&&(t=e[i]),t==null){r||(r=new Map,n.records.set(e,r)),r.set(i,a);continue}D(t)&&D(a)?Sp(t,a,n):Array.isArray(t)&&Array.isArray(a)&&!_p(t,a)&&xp(t,a,`array`,n,Sp)}}function Cp(e){return(D(e)||Array.isArray(e))&&pp.has(e)}function wp(e){if(!(!D(e)&&!Array.isArray(e)||pp.has(e))){pp.add(e),Array.isArray(e)&&fp.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n&&`value`in n&&wp(n.value)}}}function Tp(e,t,n){pp.has(e)&&wp(n),Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function Ep(e){let{index:t}=e;if(t==null)throw Error("Expected array delta entry to have an `index` property");if(typeof t!=`number`)throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return t}function Dp(e,t,n){if(_p(e,t)){e.push(...t),fp.delete(e);return}for(let r of t){if(!D(r))throw Error(`Expected array delta entry to be an object but got an invalid value`);let t=Ep(r);if(E(e,t)){let i=e[t];i==null?(pp.has(e)&&wp(r),e[t]=r):e[t]=n(i,r)}else Tp(e,t,r)}}function Op(e,t){let n=pp.has(e);for(let[r,i]of Object.entries(t)){if(r===`__proto__`||r===`constructor`||r===`prototype`)throw new o(`Assistant stream delta contains an unsafe property: ${r}`);if(!E(e,r)){n&&wp(i),e[r]=i;continue}let t=e[r];if(t==null){n&&wp(i),e[r]=i;continue}if(r===`index`||r===`type`){e[r]=i;continue}if(typeof t==`string`&&typeof i==`string`)t+=i;else if(typeof t==`number`&&typeof i==`number`)t+=i;else if(D(t)&&D(i))t=Op(t,i);else if(Array.isArray(t)&&Array.isArray(i)){Dp(t,i,Op);continue}else throw TypeError(`Unhandled record type: ${dp(r)}`);e[r]=t}return e}function kp(e){if(D(e)||Array.isArray(e))for(let[t,n]of Object.entries(e)){if(t===`__proto__`||t===`constructor`||t===`prototype`)throw new o(`Assistant stream delta contains an unsafe property: ${t}`);kp(n)}}function Ap(e,t,n=!1){kp(t);let r=e,i=t,a=mp(n&&!Cp(e));return Sp(r,i,a),Op(r,i),hp(a),e}function jp(e,t,n,r=!0){kp(t);let i=mp(r&&!Cp(e));return xp(e,t,n,i,Sp),()=>hp(i)}var J,Mp,Np,Pp,Fp,Ip,Y,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,X,em,tm,nm,rm,im;function am(e){let t=Object.getOwnPropertyDescriptor(e,`event`),n=Object.getOwnPropertyDescriptor(e,`data`),r=Reflect.get(e,`event`,e),i=Reflect.get(e,`data`,e),a=i;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 e=Object.getOwnPropertyDescriptor(i,`id`);if(e&&`value`in e&&i.id!==e.value){let t=e.value;a=new Proxy(i,{get(e,n){return n===`id`?t:Reflect.get(e,n,e)}})}}return{event:Object.freeze({event:r,data:a}),exposedEvent:t!==void 0&&`value`in t&&t.value===r&&n!==void 0&&`value`in n&&n.value===i&&a===i?e:{event:r,data:a}}}var om=class e extends So{constructor(){super(...arguments),J.add(this),Mp.set(this,Object.create(null)),Np.set(this,new Map),Pp.set(this,void 0),Fp.set(this,Object.create(null)),Ip.set(this,new Map),Y.set(this,void 0),Lp.set(this,void 0),Rp.set(this,void 0),zp.set(this,void 0),Bp.set(this,void 0),Vp.set(this,void 0),Hp.set(this,void 0),Up.set(this,void 0),Wp.set(this,void 0),Gp.set(this,void 0)}[(Mp=new WeakMap,Np=new WeakMap,Pp=new WeakMap,Fp=new WeakMap,Ip=new WeakMap,Y=new WeakMap,Lp=new WeakMap,Rp=new WeakMap,zp=new WeakMap,Bp=new WeakMap,Vp=new WeakMap,Hp=new WeakMap,Up=new WeakMap,Wp=new WeakMap,Gp=new WeakMap,J=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(structuredClone(t));return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}static fromReadableStream(t){let n=new e;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=Ze.fromReadableStream(e,this.controller);for await(let e of r)n(this,J,`m`,Kp).call(this,e);if(r.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,qp).call(this))}toReadableStream(){return new Ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runToolAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}async _createToolAssistantStream(e,t,r,i){this._listenForAbort(i?.signal);let a={...r,stream:!0},o=await e.submitToolOutputs(t,a,{...i,signal:this.controller.signal});this._connected();for await(let e of o)n(this,J,`m`,Kp).call(this,e);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,qp).call(this))}static createThreadAssistantStream(t,n,r){let i=new e;return i._run(()=>i._threadAssistantStream(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static createAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}currentEvent(){return wp(n(this,Up,`f`)),n(this,Up,`f`)}currentRun(){return wp(n(this,Wp,`f`)),n(this,Wp,`f`)}currentMessageSnapshot(){return wp(n(this,Y,`f`)),n(this,Y,`f`)}currentRunStepSnapshot(){return wp(n(this,Gp,`f`)),n(this,Gp,`f`)}async finalRunSteps(){return await this.done(),Object.values(n(this,Mp,`f`))}async finalMessages(){return await this.done(),Object.values(n(this,Fp,`f`))}async finalRun(){if(await this.done(),!n(this,Rp,`f`))throw Error(`Final run was not received.`);return n(this,Rp,`f`)}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let i={...t,stream:!0},a=await e.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)n(this,J,`m`,Kp).call(this,e);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,qp).call(this))}async _createAssistantStream(e,t,r,i){this._listenForAbort(i?.signal);let a={...r,stream:!0},o=await e.create(t,a,{...i,signal:this.controller.signal});this._connected();for await(let e of o)n(this,J,`m`,Kp).call(this,e);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,qp).call(this))}static accumulateDelta(e,t){return Ap(e,t)}_addRun(e){return n(this,J,`m`,X).call(this,`run`,e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};Kp=function(e){if(this.ended)return;let{event:r,exposedEvent:i}=am(e),a,c,l,u;switch(r.event){case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:a=n(this,J,`m`,Xp).call(this,r),c=r.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`:l=n(this,J,`m`,Jp).call(this,r),u=r.data}switch(t(this,Up,i,`f`),n(this,J,`m`,em).call(this,i),a!==void 0&&c!==void 0&&n(this,J,`m`,Zp).call(this,c,a),l!==void 0&&u!==void 0&&n(this,J,`m`,Yp).call(this,u,l),l===void 0&&n(this,Pp,`f`)!==void 0&&n(this,Gp,`f`)&&n(this,J,`m`,Yp).call(this,n(this,Gp,`f`),n(this,Pp,`f`)),r.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`:n(this,J,`m`,im).call(this,r);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(l===void 0)throw new o(`Received assistant run-step event without a canonical run-step ID`);let e=n(this,Mp,`f`)[l];e&&n(this,J,`m`,Yp).call(this,e,l),n(this,J,`m`,$p).call(this,r,l),n(this,J,`m`,Yp).call(this,r.data,l);let t=n(this,Mp,`f`)[l];t&&n(this,J,`m`,Yp).call(this,t,l);break}case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:if(a!==void 0&&n(this,Y,`f`)&&n(this,J,`m`,Zp).call(this,n(this,Y,`f`),a),n(this,J,`m`,Qp).call(this,r),a!==void 0){n(this,J,`m`,Zp).call(this,r.data,a);let e=n(this,Fp,`f`)[a];e&&n(this,J,`m`,Zp).call(this,e,a)}break;case`error`:throw new s(void 0,r.data,void 0,void 0)}},qp=function(){if(this.ended)throw new o(`stream has ended, this shouldn't happen`);if(!n(this,Rp,`f`))throw Error(`Final run has not been received`);return n(this,Rp,`f`)},Jp=function(e){let r=Object.getOwnPropertyDescriptor(e.data,`id`),i=r&&`value`in r?r.value:void 0;if(typeof i!=`string`||i.length===0)throw new o(`Received assistant run-step event with an invalid run-step ID`);if(e.event===`thread.run.step.delta`){let t=e.data.delta;if(t&&E(t,`id`))throw new o(`Run-step deltas must not contain an id field`)}if(e.event===`thread.run.step.created`){if(n(this,Pp,`f`)!==void 0)throw new o(`Received run-step creation for "${i}" before the active run step "${n(this,Pp,`f`)}" reached a terminal state`);if(E(n(this,Mp,`f`),i)||n(this,Np,`f`).has(i))throw new o(`Received run-step creation for run step "${i}", which has already been created`);return t(this,Pp,i,`f`),n(this,Np,`f`).set(i,i),i}if(n(this,Pp,`f`)!==void 0){if(i!==n(this,Pp,`f`))throw new o(`Received ${e.event} for run step "${i}", which does not match the active run step "${n(this,Pp,`f`)}"`);return i}if(e.event===`thread.run.step.delta`)throw E(n(this,Mp,`f`),i)?new o(`Received run-step delta for "${i}" with no active run step`):new o(`Received a RunStepDelta before creation of a snapshot`);if(E(n(this,Mp,`f`),i)||n(this,Np,`f`).has(i))throw new o(`Received run-step event for run step "${i}", which has already been created`);return n(this,Np,`f`).set(i,i),e.event===`thread.run.step.in_progress`&&t(this,Pp,i,`f`),i},Yp=function(e,t){let r=Object.getOwnPropertyDescriptor(e,`id`),i=r&&`value`in r?r.value:void 0;if(typeof i!=`string`||i.length===0)throw new o(`Received assistant run-step event with an invalid run-step ID`);let a=n(this,Np,`f`).get(i);if(a!==void 0&&a!==t)throw new o(`Received run-step creation for run step "${i}", which has already been created`);n(this,Np,`f`).set(i,t)},Xp=function(e){let r=Object.getOwnPropertyDescriptor(e.data,`id`),i=r&&`value`in r?r.value:void 0;if(typeof i!=`string`||i.length===0)throw new o(`Received assistant message event with an invalid message ID`);if(e.event===`thread.message.created`){if(n(this,Y,`f`))throw new o(`Received message creation for "${i}" before the active message "${n(this,Lp,`f`)}" reached a terminal state`);if(E(n(this,Fp,`f`),i)||n(this,Ip,`f`).has(i))throw new o(`Received message creation for message "${i}", which has already been created`);return t(this,Lp,i,`f`),n(this,Ip,`f`).set(i,i),i}if(!n(this,Y,`f`))throw e.event===`thread.message.delta`?new o(`Received a delta with no existing snapshot (there should be one from message creation)`):new o(`Received thread message event with no existing snapshot`);if(i!==n(this,Lp,`f`))throw new o(`Received ${e.event} for message "${i}", which does not match the active message "${n(this,Lp,`f`)}"`);return i},Zp=function(e,t){let r=Object.getOwnPropertyDescriptor(e,`id`),i=r&&`value`in r?r.value:void 0;if(typeof i!=`string`||i.length===0)throw new o(`Received assistant message event with an invalid message ID`);let a=n(this,Ip,`f`).get(i);if(a!==void 0&&a!==t)throw new o(`Received message creation for message "${i}", which has already been created`);n(this,Ip,`f`).set(i,t)},Qp=function(e){let[r,i]=n(this,J,`m`,nm).call(this,e,n(this,Y,`f`));if(t(this,Y,r,`f`),!n(this,Lp,`f`))throw new o(`Received thread message event with no active message ID`);n(this,Fp,`f`)[n(this,Lp,`f`)]=r;for(let e of i){let t=r.content[e.index];t?.type===`text`&&n(this,J,`m`,X).call(this,`textCreated`,t.text)}switch(e.event){case`thread.message.created`:t(this,zp,void 0,`f`),t(this,Bp,void 0,`f`),n(this,J,`m`,X).call(this,`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(n(this,J,`m`,X).call(this,`messageDelta`,e.data.delta,r),e.data.delta.content)for(let i of e.data.delta.content){if(i.type===`text`&&i.text){let e=i.text,t=r.content[i.index];if(t&&t.type===`text`)n(this,J,`m`,X).call(this,`textDelta`,e,t.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(i.index!==n(this,zp,`f`)){if(n(this,Bp,`f`))switch(n(this,Bp,`f`).type){case`text`:n(this,J,`m`,X).call(this,`textDone`,n(this,Bp,`f`).text,n(this,Y,`f`));break;case`image_file`:n(this,J,`m`,X).call(this,`imageFileDone`,n(this,Bp,`f`).image_file,n(this,Y,`f`))}t(this,zp,i.index,`f`)}t(this,Bp,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(n(this,zp,`f`)!==void 0){let t=e.data.content[n(this,zp,`f`)];if(t)switch(t.type){case`image_file`:n(this,J,`m`,X).call(this,`imageFileDone`,t.image_file,n(this,Y,`f`));break;case`text`:n(this,J,`m`,X).call(this,`textDone`,t.text,n(this,Y,`f`))}}n(this,Y,`f`)&&n(this,J,`m`,X).call(this,`messageDone`,e.data),t(this,zp,void 0,`f`),t(this,Bp,void 0,`f`),t(this,Y,void 0,`f`),t(this,Lp,void 0,`f`)}},$p=function(e,r){let i=n(this,J,`m`,tm).call(this,e,r);switch(t(this,Gp,i,`f`),e.event){case`thread.run.step.created`:t(this,Vp,void 0,`f`),t(this,Hp,void 0,`f`),n(this,J,`m`,X).call(this,`runStepCreated`,e.data);break;case`thread.run.step.delta`:{let r=e.data.delta;if(r.step_details&&r.step_details.type===`tool_calls`&&r.step_details.tool_calls&&i.step_details.type===`tool_calls`)for(let e of r.step_details.tool_calls)e.index===n(this,Vp,`f`)?n(this,J,`m`,X).call(this,`toolCallDelta`,e,i.step_details.tool_calls[e.index]):(n(this,Hp,`f`)&&n(this,J,`m`,X).call(this,`toolCallDone`,n(this,Hp,`f`)),t(this,Vp,e.index,`f`),t(this,Hp,i.step_details.tool_calls[e.index],`f`),n(this,Hp,`f`)&&n(this,J,`m`,X).call(this,`toolCallCreated`,n(this,Hp,`f`)));n(this,J,`m`,X).call(this,`runStepDelta`,e.data.delta,i);break}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:t(this,Gp,void 0,`f`),t(this,Pp,void 0,`f`),e.data.step_details.type===`tool_calls`&&n(this,Hp,`f`)&&n(this,J,`m`,X).call(this,`toolCallDone`,n(this,Hp,`f`)),n(this,J,`m`,X).call(this,`runStepDone`,e.data,i),t(this,Vp,void 0,`f`),t(this,Hp,void 0,`f`)}},X=function(e,...t){if(this._hasListeners(e))for(let e of t)wp(e);this._emit(e,...t)},em=function(e){n(this,J,`m`,X).call(this,`event`,e)},tm=function(e,t){switch(e.event){case`thread.run.step.created`:return n(this,Mp,`f`)[t]=e.data,e.data;case`thread.run.step.delta`:{let r=n(this,Mp,`f`)[t];if(!r)throw Error(`Received a RunStepDelta before creation of a snapshot`);let i=e.data.delta;if(i){if(E(i,`id`))throw new o(`Run-step deltas must not contain an id field`);let e=Ap(r,i,!0);n(this,Mp,`f`)[t]=e}return n(this,Mp,`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`:n(this,Mp,`f`)[t]=e.data}if(n(this,Mp,`f`)[t])return n(this,Mp,`f`)[t];throw Error(`No snapshot available`)},nm=function(e,t){let r=[];switch(e.event){case`thread.message.created`:return[e.data,r];case`thread.message.delta`:{if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let i=e.data;if(i.delta.content){kp(i.delta);let e=!Cp(t),a=jp(t.content,i.delta.content,`content`,e);for(let a of i.delta.content)if(E(t.content,a.index)){let r=t.content[a.index];t.content[a.index]=n(this,J,`m`,rm).call(this,a,r,e)}else Tp(t.content,a.index,a),r.push(a);a()}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 Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},rm=function(e,t,n){return Ap(t,e,n)},im=function(e){switch(t(this,Wp,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`:t(this,Rp,e.data,`f`),n(this,Hp,`f`)&&n(this,J,`m`,X).call(this,`toolCallDone`,n(this,Hp,`f`)),t(this,Vp,void 0,`f`),t(this,Hp,void 0,`f`)}};function sm(e,t){return new Promise((n,r)=>{let i,a,o=!1,s=e=>{try{t.removeEventListener(`abort`,e)}catch{}},l=()=>{if(i!==void 0&&(clearTimeout(i),i=void 0),a){let e=a;a=void 0,s(e)}},u=()=>{if(!o){o=!0,l();try{let e=new c;Object.defineProperty(e,"cause",{value:t.reason,writable:!0,configurable:!0}),r(e)}catch(e){r(e)}}};if(t.aborted){u();return}i=setTimeout(()=>{o||(o=!0,l(),n())},e),a=u;try{t.addEventListener(`abort`,u,{once:!0}),o?s(u):t.aborted&&u()}catch(e){o?s(u):(o=!0,l(),r(e))}})}async function cm(e,t,n,r){let i=F([r?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:o}=await e(i).withResponse(),{status:s}=a;if(t.includes(s)){let e=5e3,t=r?.pollIntervalMs;if(t||t===0)e=t;else{let t=o.headers.get(`openai-poll-after-ms`);if(t){let n=Number.parseInt(t);Number.isNaN(n)||(e=n)}}let n=r&&Object.prototype.propertyIsEnumerable.call(r,`signal`)?r.signal:void 0;await(n?sm(e,n):oe(e))}else if(n.includes(s))return a}}function lm(e,t,n,r){return cm(i=>e.retrieve(t,n,{...r,headers:{...r?.headers,...i}}),[`queued`,`in_progress`,`cancelling`],[`requires_action`,`incomplete`,`cancelled`,`completed`,`failed`,`expired`],r)}function um(e,t){return Promise.resolve(e).then(t)}var dm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function fm(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>dm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!dm.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var pm=class extends z{constructor(){super(...arguments),this.steps=new ap(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(B`/threads/${e}/runs`,um(n,e=>({query:{include:r},body:i,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(B`/threads/${r}/runs/${e}`,um(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(B`/threads/${r}/runs/${e}`,um(n,e=>({body:i,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let r=fm(t,[`after`,`before`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/threads/${e}/runs`,N,um(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(B`/threads/${r}/runs/${e}/cancel`,um(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return om.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){return await lm(this,e,t,n)}stream(e,t,n){return om.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(B`/threads/${r}/runs/${e}/submit_tool_outputs`,um(n,e=>({body:i,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})))}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return om.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};pm.Steps=ap;function mm(e,t){return Promise.resolve(e).then(t)}var hm=class extends z{constructor(){super(...arguments),this.runs=new pm(this._client),this.messages=new rp(this._client)}create(e={},t){return this._client.post(`/threads`,mm(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/threads/${e}`,mm(t,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(B`/threads/${e}`,mm(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/threads/${e}`,mm(t,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}createAndRun(e,t){return this._client.post(`/threads/runs`,mm(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})))}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return om.createThreadAssistantStream(e,this._client.beta.threads,t)}};hm.Runs=pm,hm.Messages=rp;var gm=class extends z{constructor(){super(...arguments),this.realtime=new mu(this._client),this.agents=new If(this._client),this.responses=new $f(this._client),this.chatkit=new Uf(this._client),this.assistants=new du(this._client),this.threads=new hm(this._client)}};gm.Realtime=mu,gm.Agents=If,gm.Responses=$f,gm.ChatKit=Uf,gm.Assistants=du,gm.Threads=hm;function _m(e,t){return Promise.resolve(e).then(t)}var vm=class extends z{create(e,t){return this._client.post(`/completions`,_m(t,t=>({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})))}};function ym(e,t){return Promise.resolve(e).then(t)}var bm=class extends z{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(B`/containers/${r}/files/${e}/content`,ym(n,e=>({...e,headers:F([{Accept:`application/binary`},e?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function xm(e,t){return Promise.resolve(e).then(t)}var Sm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Cm(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Sm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Sm.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var wm=class extends z{constructor(){super(...arguments),this.content=new bm(this._client)}create(e,t,n){return this._client.post(B`/containers/${e}/files`,xm(n,e=>Br({body:t,...e,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(B`/containers/${r}/files/${e}`,xm(n,e=>({...e,__security:{bearerAuth:!0}})))}list(e,t={},n){let r=Cm(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/containers/${e}/files`,N,xm(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}delete(e,t,n){let{container_id:r}=t;return this._client.delete(B`/containers/${r}/files/${e}`,xm(n,e=>({...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}};wm.Content=bm;function Tm(e,t){return Promise.resolve(e).then(t)}var Em=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Dm(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Em.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Em.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Om=class extends z{constructor(){super(...arguments),this.files=new wm(this._client)}create(e,t){return this._client.post(`/containers`,Tm(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/containers/${e}`,Tm(t,e=>({...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=Dm(e,[`after`,`limit`,`name`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/containers`,N,Tm(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/containers/${e}`,Tm(t,e=>({...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}};Om.Files=wm;function km(e,t){return Promise.resolve(e).then(t)}var Am=class extends z{create(e,t){return this._client.post(`/content_provenance_checks`,km(t,t=>Vr({body:e,...t,__security:{bearerAuth:!0}},this._client)))}};function jm(e,t){return Promise.resolve(e).then(t)}var Mm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Nm(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Mm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Mm.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Pm=class extends z{create(e,t,n){let{include:r,...i}=t;return this._client.post(B`/conversations/${e}/items`,jm(n,e=>({query:{include:r},body:i,...e,__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(B`/conversations/${r}/items/${e}`,jm(n,e=>({query:i,...e,__security:{bearerAuth:!0}})))}list(e,t={},n){let r=Nm(t,[`after`,`include`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/conversations/${e}/items`,P,jm(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(B`/conversations/${r}/items/${e}`,jm(n,e=>({...e,__security:{bearerAuth:!0}})))}};function Fm(e,t){return Promise.resolve(e).then(t)}var Im=class extends z{constructor(){super(...arguments),this.items=new Pm(this._client)}create(e={},t){return this._client.post(`/conversations`,Fm(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/conversations/${e}`,Fm(t,e=>({...e,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(B`/conversations/${e}`,Fm(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/conversations/${e}`,Fm(t,e=>({...e,__security:{bearerAuth:!0}})))}};Im.Items=Pm;function Lm(e,t,n){let r=!!t.encoding_format,i=r?t.encoding_format:`base64`;r&&j(e).debug(`embeddings/user defined encoding_format:`,t.encoding_format);let a={body:{...t,encoding_format:i},...n,__security:{bearerAuth:!0}},o=e.post(`/embeddings`,a);return r?o:(j(e).debug(`embeddings/decoding base64 embeddings from base64`),o._thenUnwrap(e=>{let t=e?.data;if(t!==void 0){if(!Array.isArray(t))throw TypeError(`Expected embeddings response data to be an array`);let{length:e}=t;for(let n=0;n<e;n+=1)if(n in t){let e=t[n],{embedding:r}=e;if(Array.isArray(r))continue;e.embedding=sp(r)}}return e}))}var Rm=class extends z{create(e,t){return Lm(this._client,e,t)}};function zm(e,t){return Promise.resolve(e).then(t)}var Bm=class extends z{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(B`/evals/${r}/runs/${i}/output_items/${e}`,zm(n,e=>({...e,__security:{bearerAuth:!0}})))}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(B`/evals/${r}/runs/${e}/output_items`,N,zm(n,e=>({query:i,...e,__security:{bearerAuth:!0}})))}};function Vm(e,t){return Promise.resolve(e).then(t)}var Hm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Um(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Hm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Hm.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Wm=class extends z{constructor(){super(...arguments),this.outputItems=new Bm(this._client)}create(e,t,n){return this._client.post(B`/evals/${e}/runs`,Vm(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(B`/evals/${r}/runs/${e}`,Vm(n,e=>({...e,__security:{bearerAuth:!0}})))}list(e,t={},n){let r=Um(t,[`after`,`limit`,`order`,`status`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/evals/${e}/runs`,N,Vm(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(B`/evals/${r}/runs/${e}`,Vm(n,e=>({...e,__security:{bearerAuth:!0}})))}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(B`/evals/${r}/runs/${e}/cancel`,Vm(n,e=>({...e,__security:{bearerAuth:!0}})))}};Wm.OutputItems=Bm;function Gm(e,t){return Promise.resolve(e).then(t)}var Km=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function qm(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Km.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Km.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var Jm=class extends z{constructor(){super(...arguments),this.runs=new Wm(this._client)}create(e,t){return this._client.post(`/evals`,Gm(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/evals/${e}`,Gm(t,e=>({...e,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(B`/evals/${e}`,Gm(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=qm(e,[`after`,`limit`,`order`,`order_by`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/evals`,N,Gm(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/evals/${e}`,Gm(t,e=>({...e,__security:{bearerAuth:!0}})))}};Jm.Runs=Wm;async function Ym(e,t,n,r){let i=new Set([`processed`,`error`,`deleted`]),a=performance.now(),o=await e.retrieve(t);for(;!o.status||!i.has(o.status);)if(await oe(n),o=await e.retrieve(t),performance.now()-a>r)throw new u({message:`Giving up on waiting for file ${t} to finish processing after ${r} milliseconds.`});return o}function Xm(e,t){return Promise.resolve(e).then(t)}var Zm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Qm(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>Zm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Zm.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var $m=class extends z{create(e,t){return this._client.post(`/files`,Xm(t,t=>Vr({body:e,...t,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(B`/files/${e}`,Xm(t,e=>({...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=Qm(e,[`after`,`limit`,`order`,`purpose`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/files`,N,Xm(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/files/${e}`,Xm(t,e=>({...e,__security:{bearerAuth:!0}})))}content(e,t){return this._client.get(B`/files/${e}/content`,Xm(t,e=>({...e,headers:F([{Accept:`application/binary`},e?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){return await Ym(this,e,t,n)}},eh=class extends z{};function th(e,t){return Promise.resolve(e).then(t)}var nh=class extends z{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,th(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,th(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}},rh=class extends z{constructor(){super(...arguments),this.graders=new nh(this._client)}};rh.Graders=nh;function ih(e,t){return Promise.resolve(e).then(t)}var ah=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function oh(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>ah.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ah.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var sh=class extends z{create(e,t,n){return this._client.getAPIList(B`/fine_tuning/checkpoints/${e}/permissions`,Kt,ih(n,e=>({body:t,method:`post`,...e,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t={},n){let r=oh(t,[`after`,`limit`,`order`,`project_id`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.get(B`/fine_tuning/checkpoints/${e}/permissions`,ih(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let r=oh(t,[`after`,`limit`,`order`,`project_id`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/fine_tuning/checkpoints/${e}/permissions`,P,ih(n,e=>({query:t,...e,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(B`/fine_tuning/checkpoints/${r}/permissions/${e}`,ih(n,e=>({...e,__security:{adminAPIKeyAuth:!0}})))}},ch=class extends z{constructor(){super(...arguments),this.permissions=new sh(this._client)}};ch.Permissions=sh;function lh(e,t){return Promise.resolve(e).then(t)}var uh=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function dh(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>uh.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!uh.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var fh=class extends z{list(e,t={},n){let r=dh(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/fine_tuning/jobs/${e}/checkpoints`,N,lh(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}};function ph(e,t){return Promise.resolve(e).then(t)}var mh=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function hh(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>mh.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!mh.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var gh=class extends z{constructor(){super(...arguments),this.checkpoints=new fh(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,ph(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/fine_tuning/jobs/${e}`,ph(t,e=>({...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=hh(e,[`after`,`limit`,`metadata`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/fine_tuning/jobs`,N,ph(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(B`/fine_tuning/jobs/${e}/cancel`,ph(t,e=>({...e,__security:{bearerAuth:!0}})))}listEvents(e,t={},n){let r=hh(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/fine_tuning/jobs/${e}/events`,N,ph(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}pause(e,t){return this._client.post(B`/fine_tuning/jobs/${e}/pause`,ph(t,e=>({...e,__security:{bearerAuth:!0}})))}resume(e,t){return this._client.post(B`/fine_tuning/jobs/${e}/resume`,ph(t,e=>({...e,__security:{bearerAuth:!0}})))}};gh.Checkpoints=fh;var _h=class extends z{constructor(){super(...arguments),this.methods=new eh(this._client),this.jobs=new gh(this._client),this.checkpoints=new ch(this._client),this.alpha=new rh(this._client)}};_h.Methods=eh,_h.Jobs=gh,_h.Checkpoints=ch,_h.Alpha=rh;var vh=class extends z{},yh=class extends z{constructor(){super(...arguments),this.graderModels=new vh(this._client)}};yh.GraderModels=vh;function bh(e,t){return Promise.resolve(e).then(t)}var xh=class extends z{createVariation(e,t){return this._client.post(`/images/variations`,bh(t,t=>Vr({body:e,...t,__security:{bearerAuth:!0}},this._client)))}edit(e,t){return this._client.post(`/images/edits`,bh(t,t=>Vr({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client)))}generate(e,t){return this._client.post(`/images/generations`,bh(t,t=>({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})))}};function Sh(e,t){return Promise.resolve(e).then(t)}var Ch=class extends z{accept(e,t,n){return this._client.post(B`/live/sessions/${e}/accept`,Sh(n,e=>({body:t,...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}downloadRecording(e,t){return this._client.get(B`/live/sessions/${e}/content`,Sh(t,e=>({...e,headers:F([{Accept:`application/binary`},e?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}fork(e,t,n){return this._client.post(B`/live/sessions/${e}/fork`,Sh(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}hangup(e,t){return this._client.post(B`/live/sessions/${e}/hangup`,Sh(t,e=>({...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}refer(e,t,n){return this._client.post(B`/live/sessions/${e}/refer`,Sh(n,e=>({body:t,...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}reject(e,t,n){return this._client.post(B`/live/sessions/${e}/reject`,Sh(n,e=>({body:t,...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}},wh=class extends z{},Th=class extends z{};function Eh(e,t){return Promise.resolve(e).then(t)}var Dh=class extends z{constructor(){super(...arguments),this.sideband=new Th(this._client),this.forks=new wh(this._client),this.sessions=new Ch(this._client)}create(e,t){return this._client.post(`/live/sessions`,Eh(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}};Dh.Sideband=Th,Dh.Forks=wh,Dh.Sessions=Ch;function Oh(e,t){return Promise.resolve(e).then(t)}var kh=class extends z{retrieve(e,t){return this._client.get(B`/models/${e}`,Oh(t,e=>({...e,__security:{bearerAuth:!0}})))}list(e){return this._client.getAPIList(`/models`,Kt,Oh(e,e=>({...e,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/models/${e}`,Oh(t,e=>({...e,__security:{bearerAuth:!0}})))}};function Ah(e,t){return Promise.resolve(e).then(t)}var jh=class extends z{create(e,t){return this._client.post(`/moderations`,Ah(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}};async function Mh(e,t,n,r=null){if(e.body===null||typeof e.body!=`object`||Array.isArray(e.body))throw TypeError(`Multipart request body must be an object`);let i=Object.fromEntries(Object.entries(e.body).filter(([,e])=>e!==void 0));if(r!==null&&Object.keys(i).length===1&&Object.prototype.hasOwnProperty.call(i,r)){let t=i[r];if(typeof t!=`string`)throw TypeError(`Raw multipart alternative must be a string`);return{...e,body:t,headers:F([e.headers,{"content-type":n[r].content_type}])}}let a=[];for(let[e,t]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let n=i[e],r=t.json?JSON.stringify(n):n;if(typeof r!=`string`)throw TypeError(`Multipart field ${e} must encode as a string`);a.push([e,Nr([r],``,{type:t.content_type})]),delete i[e]}let o=(await Vr({...e,body:i},t)).body;if(!(o instanceof FormData))throw await o.cancel(),TypeError(`Unexpected streaming upload in typed multipart request body`);for(let[e,t]of a)o.append(e,t,``);return{...e,body:o,headers:F([e.headers,{"content-type":null}])}}function Nh(e,t){return Promise.resolve(e).then(t)}var Ph=class extends z{create(e,t){return this._client.post(`/realtime/calls`,Nh(t,t=>Mh({body:e,...t,headers:F([{Accept:`application/sdp`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:`application/sdp`,json:!1},session:{content_type:`application/json`,json:!0}},`sdp`)))}accept(e,t,n){return this._client.post(B`/realtime/calls/${e}/accept`,Nh(n,e=>({body:t,...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}hangup(e,t){return this._client.post(B`/realtime/calls/${e}/hangup`,Nh(t,e=>({...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}refer(e,t,n){return this._client.post(B`/realtime/calls/${e}/refer`,Nh(n,e=>({body:t,...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}reject(e,t={},n){return this._client.post(B`/realtime/calls/${e}/reject`,Nh(n,e=>({body:t,...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}};function Fh(e,t){return Promise.resolve(e).then(t)}var Ih=class extends z{create(e,t){return this._client.post(`/realtime/client_secrets`,Fh(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}};function Lh(e,t){return Promise.resolve(e).then(t)}var Rh=class extends z{create(e,t){return this._client.post(`/realtime/translations/client_secrets`,Lh(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}},zh=class extends z{constructor(){super(...arguments),this.clientSecrets=new Rh(this._client)}};zh.ClientSecrets=Rh;var Bh=class extends z{constructor(){super(...arguments),this.clientSecrets=new Ih(this._client),this.calls=new Ph(this._client),this.translations=new zh(this._client)}};Bh.ClientSecrets=Ih,Bh.Calls=Ph,Bh.Translations=zh;function Vh(e,t){if(!t||!Wh(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return Jh(e,t)&&Yh(t),t}return Hh(e,t)}function Hh(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?qh(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?Uh(t,e.text):null}:e);return{...e,content:r}}return e}),i={...e,output:r};return Jh(e,i)&&Yh(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function Uh(e,t){return Ei(e.text?.format,t)}function Wh(e){return Ti(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>Gh(e)||e.type===`function`&&e.strict===!0||e.type===`namespace`&&e.tools.some(e=>e.type===`function`&&(Gh(e)||e.strict===!0)))}function Gh(e){return e?.$brand===`auto-parseable-tool`}function Kh(e,t,n){for(let r of e)if(n==null){if(r.type===`function`&&r.name===t)return r}else if(r.type===`namespace`&&r.name===n)return r.tools.find(e=>e.type===`function`&&e.name===t)}function qh(e,t){let n=Kh(e.tools??[],t.name,t.namespace),r=null;return Gh(n)?r=n.$parseRaw(t.arguments):n?.strict&&(r=Ei({type:`json_schema`,$parseRaw:void 0},t.arguments)),{...t,parsed_arguments:r}}function Jh(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function Yh(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var Xh=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw RangeError(`missing output at index ${e}`);let n=this.capacity+e,r=t-(this.values[n]??0);if(r!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+r,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,r=0;for(;t<n;)t%2==1&&(r+=this.values[t]??0,t+=1),n%2==1&&(--n,r+=this.values[n]??0),t=Math.floor(t/2),n=Math.floor(n/2);return r}grow(){let e=this.capacity;this.capacity*=2;let t=Array.from({length:this.capacity*2},()=>0);for(let n=0;n<this.size;n+=1)t[this.capacity+n]=this.values[e+n]??0;for(let e=this.capacity-1;e>0;--e)t[e]=(t[e*2]??0)+(t[e*2+1]??0);this.values=t}};function Zh(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Xh}}function Qh(e,t){if(t.type!==`message`)return``;let n=``;for(let e of t.content)e.type===`output_text`&&(n+=e.text);return e.outputTextLengths.set(t,n.length),n}function $h(e,t){if(e.deferOutputText){e.canonicalSnapshot=void 0;return}if(e.canonicalSnapshot===t)return;let n=new Xh,r=``;for(let i of t.output){let t=Qh(e,i);r+=t,n.append(t.length)}t.output_text=r,e.outputTextIndex=n,e.canonicalSnapshot=t}function eg(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new Xh;let n=structuredClone(t);return!Object.getOwnPropertyDescriptor(n,`output_text`)||n.output_text===null||n.output_text===void 0?$h(e,n):n.output.length===0&&n.output_text===``&&(e.canonicalSnapshot=n),n}function tg(e,t,n,r,i){if(e.deferOutputText)return;let a=e.outputTextLengths.get(t);if(a!==void 0){let o=a-r.length+i.length;e.outputTextLengths.set(t,o),e.outputTextIndex.update(n,o)}}function ng(e,t,n){if(t.length===0){e.output_text+=n;return}e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+n}function rg(e,t,n,r){if(n===void 0||t?.type!==`message`)return 0;if(n<t.content.length-n-1){let e=0;for(let r=0;r<n;r+=1){let n=t.content[r];n?.type===`output_text`&&(e+=n.text.length)}return e}let i=0;for(let e=n+1;e<t.content.length;e+=1){let n=t.content[e];n?.type===`output_text`&&(i+=n.text.length)}return(e.outputTextLengths.get(t)??Qh(e,t).length)-i-r.length}function ig(e,t,n,r,i,a){if(r===i)return;if(e.deferOutputText){e.outputTextDirty=!0;return}let o=t.output[n];if(n===t.output.length-1&&(a===void 0||o?.type===`message`&&a===o.content.length-1)){ng(t,r,i);return}let s=rg(e,o,a,i),c=e.outputTextIndex.prefixSum(n)+s;if(c+r.length===t.output_text.length){ng(t,r,i);return}t.output_text=t.output_text.slice(0,c)+i+t.output_text.slice(c+r.length)}var ag=new WeakMap;function og(e,t,n,r=!1){if(!Array.isArray(e)||!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!r||t in e:!E(e,t)))throw new o(`missing ${n} at index ${t}`)}function sg(e,t,n){if(t!==e.length)throw new o(`missing ${n} at index ${t}`);og(e,t,n,!0)}function Z(e,t){og(e.output,t,`output`);let n=e.output[t];if(!n)throw new o(`missing output at index ${t}`);return n}function cg(e){return e.type===`function_call`||e.type===`custom_tool_call`||e.type===`shell_call`||e.type===`shell_call_output`}function lg(e,t){if(!E(e,`type`)||typeof e.type!=`string`)throw new o(`expected an own output item type for ${t}`);let n=e.type===`function_call`||e.type===`custom_tool_call`,r=[];if(E(e,`id`)){if(typeof e.id!=`string`||e.id.length===0)throw new o(`expected a non-empty output item id for ${t}`);r.push(`id:${e.id}`)}else if(!n)throw new o(`expected a non-empty output item id for ${t}`);if(cg(e)){if(!E(e,`call_id`)||typeof e.call_id!=`string`||e.call_id.length===0)throw new o(`expected a non-empty output item call_id for ${t}`);r.push(`call:${e.type}:${e.call_id}`)}return r}function ug(e,t){for(let n of t)if(e.has(n))throw new o(`duplicate output item identity '${n}'`)}function dg(e,t){ug(e,t);for(let n of t)e.add(n)}function fg(e){let t={snapshot:e,output:e.output,length:e.output.length,identities:new Set};for(let n=0;n<e.output.length;n+=1){let r=Z(e,n);dg(t.identities,lg(r,`response snapshot`))}return t}function pg(e,t){let n=ag.get(e);if(n&&n.snapshot===t&&n.output===t.output&&n.length===t.output.length)return n;let r=fg(t);return ag.set(e,r),r}function mg(e,t){let n=Zh(),r=eg(n,t),i=fg(r);return e.canonicalSnapshot=n.canonicalSnapshot,e.outputTextLengths=n.outputTextLengths,e.outputTextIndex=n.outputTextIndex,ag.set(e,i),r}var hg={"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 gg(e){return e.type===`response.content_part.added`||e.type===`response.content_part.done`?e.part.type===`reasoning_text`?`reasoning`:`message`:hg[e.type]}function _g(e,t){let n=Z(t,e.output_index),r=e.item;if(lg(n,e.type),lg(r,e.type),!E(r,`type`)||n.type!==r.type)throw new o(`expected output item type '${n.type}', got '${r.type}'`);let i=E(n,`id`)?n.id:void 0,a=E(r,`id`)?r.id:void 0;if(i!==a)throw new o(`expected output item id '${i}', got '${a}'`);if(cg(n)&&cg(r)&&n.call_id!==r.call_id)throw new o(`expected output item call_id '${n.call_id}', got '${r.call_id}'`)}function vg(e,t,n){if(e.type===`response.output_item.done`){_g(e,t);return}if(n&&(e.type===`response.shell_call_command.added`||e.type===`response.shell_call_command.delta`||e.type===`response.shell_call_command.done`)){let n=Z(t,e.output_index);if(!E(n,`type`)||n.type!==`shell_call`)throw new o(`expected output item type 'shell_call', got '${n.type}'`);return}if(e.type!==`response.content_part.added`&&e.type!==`response.content_part.done`&&!E(hg,e.type))return;let r=e;if(!E(e,`item_id`)||typeof r.item_id!=`string`||r.item_id.length===0)throw new o(`expected a non-empty item_id for ${e.type}`);let i=Z(t,r.output_index),a=E(i,`id`)?i.id:void 0;if(a!==r.item_id)throw new o(`expected item_id '${a}', got '${r.item_id}'`);let s=gg(r);if(i.type!==s)throw new o(`expected output item type '${s}', got '${i.type}'`)}function yg(e,t){og(e,t,`content`);let n=e[t];if(!n)throw new o(`missing content at index ${t}`);return n}function bg(e,t,n){let r=e.output.find(e=>e.type===`shell_call`&&e.call_id===t.call_id);for(r?og(r.action.commands,n,`command`):og(t.output,n,`content`,!0);t.output.length<=n;)t.output.push({stdout:``,stderr:``,outcome:{type:`exit`,exit_code:0}});return yg(t.output,n)}function xg(e){return new Set(e)}var Sg=xg(`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`.split(`,`));function Cg(e){throw new o(`Unhandled response stream event: unknown`)}var wg=[`item_id`,`output_index`,`content_index`,`annotation_index`,`command_index`,`summary_index`];function Tg(e){let t;try{t=Object.getOwnPropertyDescriptor(e,`type`)}catch{return Cg(e)}let n=t?.value;if(typeof n!=`string`||!Sg.has(n))return Cg(e);let r=new Map([[`type`,n]]);if(n===`response.output_item.added`||n===`response.output_item.done`||n===`response.content_part.added`||n===`response.content_part.done`||n===`response.shell_call_command.added`||n===`response.shell_call_command.delta`||n===`response.shell_call_command.done`||E(hg,n))try{for(let t of wg){let n=Object.getOwnPropertyDescriptor(e,t);r.set(t,n?e[t]:void 0)}n===`response.output_item.done`?r.set(`item`,structuredClone(e.item)):(n===`response.content_part.added`||n===`response.content_part.done`)&&r.set(`part`,structuredClone(e.part))}catch{return Cg(e)}return new Proxy(e,{get(e,t){return r.has(t)?r.get(t):Reflect.get(e,t,e)}})}function Eg(e,t,n){switch(e.type){case`response.output_item.added`:{sg(t.output,e.output_index,`output`);let r=pg(n,t),i=structuredClone(e.item),a=lg(i,e.type);ug(r.identities,a),i.type===`message`&&$h(n,t),t.output.push(i),dg(r.identities,a),r.length=t.output.length;let o=Qh(n,i);return n.canonicalSnapshot===t&&n.outputTextIndex.append(o.length),o&&(n.deferOutputText?n.outputTextDirty=!0:t.output_text+=o),!0}case`response.output_item.done`:{let r=Z(t,e.output_index),i=Qh(n,r),a=e.item;(r.type===`message`||a.type===`message`)&&$h(n,t),t.output[e.output_index]=a;let o=Qh(n,a);return n.canonicalSnapshot===t&&n.outputTextIndex.update(e.output_index,o.length),ig(n,t,e.output_index,i,o),!0}default:return!1}}function Dg(e,t,n){switch(e.type){case`response.content_part.added`:{let r=Z(t,e.output_index),{type:i}=r,{part:a}=e;if(i===`message`&&a.type!==`reasoning_text`){sg(r.content,e.content_index,`content`);let i=a;i.type===`output_text`&&$h(n,t),r.content.push(i),i.type===`output_text`&&(tg(n,r,e.output_index,``,i.text),ig(n,t,e.output_index,``,i.text,e.content_index))}else if(i===`reasoning`&&a.type===`reasoning_text`){let t=r.content??[];sg(t,e.content_index,`content`),r.content||=t,t.push(a)}return!0}default:return!1}}function Og(e,t,n){switch(e.type){case`response.content_part.done`:{let r=Z(t,e.output_index),{part:i}=e;if(r.type===`message`&&i.type!==`reasoning_text`){let a=yg(r.content,e.content_index),o=a.type===`output_text`?a.text:``,s=i;(a.type===`output_text`||s.type===`output_text`)&&$h(n,t),r.content[e.content_index]=s;let c=s.type===`output_text`?s.text:``;tg(n,r,e.output_index,o,c),ig(n,t,e.output_index,o,c,e.content_index)}else if(r.type===`reasoning`&&i.type===`reasoning_text`){let{content:t}=r;if(!t)throw new o(`missing content at index ${e.content_index}`);yg(t,e.content_index),t[e.content_index]=i}return!0}default:return!1}}function kg(e){return D(e)&&typeof e.token==`string`&&typeof e.logprob==`number`&&Array.isArray(e.bytes)&&e.bytes.every(e=>typeof e==`number`)}function Ag(e){return Array.isArray(e)&&e.every(e=>kg(e)&&`top_logprobs`in e&&Array.isArray(e.top_logprobs)&&e.top_logprobs.every(kg))}function jg(e,t){let n=structuredClone(t.logprobs);if(Ag(n)){if(t.type===`response.output_text.done`)(n.length>0||Array.isArray(e.logprobs)&&e.logprobs.length>0)&&(e.logprobs=n);else if(n.length>0){Array.isArray(e.logprobs)||(e.logprobs=[]);for(let t of n)e.logprobs.push(t)}}}function Mg(e,t,n){switch(e.type){case`response.output_text.delta`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=yg(r.content,e.content_index);if(i.type!==`output_text`)throw new o(`expected content to be 'output_text', got ${i.type}`);jg(i,e);let a=i.text;$h(n,t),i.text=a+e.delta,tg(n,r,e.output_index,a,i.text),e.output_index===t.output.length-1&&e.content_index===r.content.length-1?n.deferOutputText?e.delta!==``&&(n.outputTextDirty=!0):t.output_text+=e.delta:ig(n,t,e.output_index,a,i.text,e.content_index)}return!0}case`response.output_text.done`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=yg(r.content,e.content_index);if(i.type!==`output_text`)throw new o(`expected content to be 'output_text', got ${i.type}`);jg(i,e);let a=i.text;$h(n,t),i.text=e.text,tg(n,r,e.output_index,a,e.text),ig(n,t,e.output_index,a,e.text,e.content_index)}return!0}case`response.output_text.annotation.added`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=yg(n.content,e.content_index);if(t.type!==`output_text`)throw new o(`expected content to be 'output_text', got ${t.type}`);og(t.annotations,e.annotation_index,`annotation`,!0),t.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function Ng(e,t){switch(e.type){case`response.refusal.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=yg(n.content,e.content_index);if(t.type!==`refusal`)throw new o(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}return!0}case`response.refusal.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=yg(n.content,e.content_index);if(t.type!==`refusal`)throw new o(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}return!0}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments+=e.delta),!0}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments=e.arguments),!0}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input+=e.delta),!0}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input=e.input),!0}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments+=e.delta),!0}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments=e.arguments),!0}default:return!1}}function Pg(e,t){switch(e.type){case`response.shell_call_command.added`:case`response.shell_call_command.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call`){let t=e.type===`response.shell_call_command.added`;og(n.action.commands,e.command_index,`command`,t),n.action.commands[e.command_index]=e.command}return!0}case`response.shell_call_command.delta`:{let n=Z(t,e.output_index);return n.type===`shell_call`&&(og(n.action.commands,e.command_index,`command`),n.action.commands[e.command_index]+=e.delta),!0}case`response.shell_call_output_content.delta`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=bg(t,n,e.command_index);r.stdout+=e.delta.stdout??``,r.stderr+=e.delta.stderr??``}return!0}case`response.shell_call_output_content.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=yg(e.output,0);bg(t,n,e.command_index),n.output[e.command_index]=structuredClone(r)}return!0}default:return!1}}function Fg(e,t){switch(e.type){case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new o(`missing content at index ${e.content_index}`);let t=yg(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new o(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}return!0}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new o(`missing content at index ${e.content_index}`);let t=yg(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new o(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}return!0}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(sg(n.summary,e.summary_index,`content`),n.summary.push(structuredClone(e.part))),!0}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(yg(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part)),!0}case`response.reasoning_summary_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=yg(n.summary,e.summary_index);t.text+=e.delta}return!0}case`response.reasoning_summary_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=yg(n.summary,e.summary_index);t.text=e.text}return!0}default:return!1}}function Ig(e,t){switch(e.type){case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta),!0}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=e.code),!0}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`in_progress`),!0}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`interpreting`),!0}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`completed`),!0}default:return!1}}function Lg(e,t){switch(e.type){case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`in_progress`),!0}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`searching`),!0}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`completed`),!0}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`in_progress`),!0}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`searching`),!0}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`completed`),!0}default:return!1}}function Rg(e,t){switch(e.type){case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`in_progress`),!0}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`generating`),!0}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`completed`),!0}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`in_progress`),!0}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`completed`),!0}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`failed`),!0}default:return!1}}function zg(e){switch(e.type){case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:return!0;default:return!1}}function Bg(e){switch(e.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 Vg(){return Zh()}function Hg(e,t,n,r){return vg(e,t,r),!!(Eg(e,t,n)||Dg(e,t,n)||Og(e,t,n)||Mg(e,t,n)||Ng(e,t)||Pg(e,t)||Fg(e,t)||Ig(e,t)||Lg(e,t)||Rg(e,t)||Bg(e))}function Ug(e,t,n,r=!1,i){let a=Tg(e);if(i&&a.type!==`keepalive`&&i(a),!t){if(a.type!==`response.created`)throw new o(`When snapshot hasn't been set yet, expected 'response.created' event, got ${a.type}`);return mg(n,a.response)}return Hg(a,t,n,r)?t:zg(a)?mg(n,a.response):Cg(a)}var Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,Qg=class e extends So{constructor(e){super(),Wg.add(this),Gg.set(this,void 0),Kg.set(this,void 0),qg.set(this,void 0),Jg.set(this,Vg()),t(this,Gg,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}async _createOrRetrieveResponse(e,t,r){this._listenForAbort(r?.signal),n(this,Wg,`m`,Yg).call(this);let i,a=null;`response_id`in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let e of i)n(this,Wg,`m`,Xg).call(this,e,a);if(i.controller.signal?.aborted)throw this._userAbortError();return n(this,Wg,`m`,Zg).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),n(this,Wg,`m`,Yg).call(this),this._connected();let r=Ze.fromReadableStream(e,this.controller);for await(let e of r)n(this,Wg,`m`,Xg).call(this,e,null);if(r.controller.signal?.aborted)throw this._userAbortError();return n(this,Wg,`m`,Zg).call(this)}[(Gg=new WeakMap,Kg=new WeakMap,qg=new WeakMap,Jg=new WeakMap,Wg=new WeakSet,Yg=function(){this.ended||(t(this,Kg,void 0,`f`),t(this,Jg,Vg(),`f`))},Xg=function(e,r){if(this.ended)return;let i=(e,t)=>{(r==null||t.sequence_number>r)&&this._emit(e,t)};if(e.type===`error`)throw new s(void 0,`error`in e&&typeof e.error==`object`&&e.error!==null?e.error:e,e.message,void 0);let a=e,c=Ug(e,n(this,Kg,`f`),n(this,Jg,`f`),!0,e=>{a=e});switch(t(this,Kg,c,`f`),i(`event`,e),a.type){case`response.output_text.delta`:{let e=c.output[a.output_index];if(!e)throw new o(`missing output at index ${a.output_index}`);if(e.type===`message`){let t=e.content[a.content_index];if(!t)throw new o(`missing content at index ${a.content_index}`);if(t.type!==`output_text`)throw new o(`expected content to be 'output_text', got ${t.type}`);i(`response.output_text.delta`,{...a,type:a.type,item_id:a.item_id,output_index:a.output_index,content_index:a.content_index,snapshot:t.text})}break}case`response.function_call_arguments.delta`:{let e=c.output[a.output_index];if(!e)throw new o(`missing output at index ${a.output_index}`);e.type===`function_call`&&i(`response.function_call_arguments.delta`,{...a,type:a.type,item_id:a.item_id,output_index:a.output_index,snapshot:e.arguments});break}default:i(a.type,e)}},Zg=function(){if(this.ended)throw new o(`stream has ended, this shouldn't happen`);let e=n(this,Kg,`f`);if(!e)throw new o(`request ended without sending any events`);t(this,Kg,void 0,`f`),t(this,Jg,Vg(),`f`);let r=$g(e,n(this,Gg,`f`));return t(this,qg,r,`f`),r},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=n(this,qg,`f`);if(!e)throw new o(`stream ended without producing a Response`);return e}};function $g(e,t){return Vh(e,t)}function e_(e,t){return Promise.resolve(e).then(t)}var t_=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function n_(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>t_.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!t_.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var r_=class extends z{list(e,t={},n){let r=n_(t,[`after`,`include`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/responses/${e}/input_items`,N,e_(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}};function i_(e,t){return Promise.resolve(e).then(t)}var a_=class extends z{count(e={},t){return this._client.post(`/responses/input_tokens`,i_(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}};function o_(e,t){return Promise.resolve(e).then(t)}var s_=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function c_(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>s_.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!s_.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var l_=class extends z{constructor(){super(...arguments),this.inputItems=new r_(this._client),this.inputTokens=new a_(this._client)}create(e,t){return this._client.post(`/responses`,o_(t,t=>({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})))._thenUnwrap(e=>(`object`in e&&e.object===`response`&&Yh(e),e))}retrieve(e,t={},n){let r=c_(t,[`include`,`include_obfuscation`,`starting_after`,`stream`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.get(B`/responses/${e}`,o_(n,e=>({query:t,...e,stream:t?.stream??!1,__security:{bearerAuth:!0}})))._thenUnwrap(e=>(`object`in e&&e.object===`response`&&Yh(e),e))}delete(e,t){return this._client.delete(B`/responses/${e}`,o_(t,e=>({...e,headers:F([{Accept:`*/*`},e?.headers]),__security:{bearerAuth:!0}})))}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>Hh(t,e))}stream(e,t){return Qg.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(B`/responses/${e}/cancel`,o_(t,e=>({...e,__security:{bearerAuth:!0}})))}compact(e,t){return this._client.post(`/responses/compact`,o_(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}};l_.InputItems=r_,l_.InputTokens=a_;function u_(e,t){return Promise.resolve(e).then(t)}var d_=class extends z{retrieve(e,t){return this._client.get(B`/safety/alerts/${e}`,u_(t,e=>({...e,__security:{bearerAuth:!0}})))}};function f_(e,t){return Promise.resolve(e).then(t)}var p_=class extends z{retrieve(e,t){return this._client.get(B`/safety/cases/${e}`,f_(t,e=>({...e,__security:{bearerAuth:!0}})))}},m_=class extends z{constructor(){super(...arguments),this.cases=new p_(this._client),this.alerts=new d_(this._client)}};m_.Cases=p_,m_.Alerts=d_;function h_(e,t){return Promise.resolve(e).then(t)}var g_=class extends z{retrieve(e,t){return this._client.get(B`/skills/${e}/content`,h_(t,e=>({...e,headers:F([{Accept:`application/binary`},e?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function __(e,t){return Promise.resolve(e).then(t)}var v_=class extends z{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(B`/skills/${r}/versions/${e}/content`,__(n,e=>({...e,headers:F([{Accept:`application/binary`},e?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function y_(e,t){return Promise.resolve(e).then(t)}var b_=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function x_(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>b_.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!b_.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var S_=class extends z{constructor(){super(...arguments),this.content=new v_(this._client)}create(e,t={},n){return this._client.post(B`/skills/${e}/versions`,Br({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(B`/skills/${r}/versions/${e}`,y_(n,e=>({...e,__security:{bearerAuth:!0}})))}list(e,t={},n){let r=x_(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/skills/${e}/versions`,N,y_(n,e=>({query:t,...e,__security:{bearerAuth:!0}})))}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(B`/skills/${r}/versions/${e}`,y_(n,e=>({...e,__security:{bearerAuth:!0}})))}};S_.Content=v_;function C_(e,t){return Promise.resolve(e).then(t)}var w_=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function T_(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>w_.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!w_.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var E_=class extends z{constructor(){super(...arguments),this.content=new g_(this._client),this.versions=new S_(this._client)}create(e={},t){return this._client.post(`/skills`,Br({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(B`/skills/${e}`,C_(t,e=>({...e,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(B`/skills/${e}`,C_(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=T_(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/skills`,N,C_(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/skills/${e}`,C_(t,e=>({...e,__security:{bearerAuth:!0}})))}};E_.Content=g_,E_.Versions=S_;function D_(e,t){return Promise.resolve(e).then(t)}var O_=class extends z{create(e,t,n){return this._client.post(B`/uploads/${e}/parts`,D_(n,e=>Vr({body:t,...e,__security:{bearerAuth:!0}},this._client)))}};function k_(e,t){return Promise.resolve(e).then(t)}var A_=class extends z{constructor(){super(...arguments),this.parts=new O_(this._client)}create(e,t){return this._client.post(`/uploads`,k_(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(B`/uploads/${e}/cancel`,k_(t,e=>({...e,__security:{bearerAuth:!0}})))}complete(e,t,n){return this._client.post(B`/uploads/${e}/complete`,k_(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}};A_.Parts=O_;function j_(e,t,n,r){return cm(i=>e.retrieve(n,{vector_store_id:t},{...r,headers:i}),[`in_progress`],[`failed`,`cancelled`,`completed`],r)}function M_(e,t,n,r){return cm(i=>e.retrieve(n,{vector_store_id:t},{...r,headers:i}),[`in_progress`],[`failed`,`cancelled`,`completed`],r)}var N_=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length)throw Object.defineProperty(Error(`${n.length} promise(s) failed`),"rejections",{configurable:!0,value:n.map(({reason:e})=>e),writable:!0});let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r};async function P_(e,t,n,r,i,a){if(r==null||r.length===0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=a?.maxConcurrency??5,s=Math.min(o,r.length);if(s===0)throw RangeError(`maxConcurrency must be greater than 0`);let c=r.values(),l=[...i];async function u(e){for(let n of e){let e=await t.files.create({file:n,purpose:`assistants`},a);l.push(e.id)}}let d=[];d.length=s;for(let e=0;e<d.length;e+=1)d[e]=u(c);return await N_(d),await e.createAndPoll(n,{file_ids:l},a)}function F_(e,t){return Promise.resolve(e).then(t)}var I_=class extends z{create(e,t,n){return this._client.post(B`/vector_stores/${e}/file_batches`,F_(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(B`/vector_stores/${r}/file_batches/${e}`,F_(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(B`/vector_stores/${r}/file_batches/${e}/cancel`,F_(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(B`/vector_stores/${r}/file_batches/${e}/files`,N,F_(n,e=>({query:i,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}async poll(e,t,n){return await M_(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){return await P_(this,this._client,e,t,n,r)}};function L_(e,t){return Promise.resolve(e).then(t)}var R_=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function z_(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>R_.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!R_.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var B_=class extends z{create(e,t,n){return this._client.post(B`/vector_stores/${e}/files`,L_(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(B`/vector_stores/${r}/files/${e}`,L_(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(B`/vector_stores/${r}/files/${e}`,L_(n,e=>({body:i,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let r=z_(t,[`after`,`before`,`filter`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/vector_stores/${e}/files`,N,L_(n,e=>({query:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(B`/vector_stores/${r}/files/${e}`,L_(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){return await j_(this,e,t,n)}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(B`/vector_stores/${r}/files/${e}/content`,Kt,L_(n,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}};function V_(e,t){return Promise.resolve(e).then(t)}var H_=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function U_(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>H_.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!H_.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var W_=class extends z{constructor(){super(...arguments),this.files=new B_(this._client),this.fileBatches=new I_(this._client)}create(e,t){return this._client.post(`/vector_stores`,V_(t,t=>({body:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/vector_stores/${e}`,V_(t,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(B`/vector_stores/${e}`,V_(n,e=>({body:t,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=U_(e,[`after`,`before`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/vector_stores`,N,V_(t,t=>({query:e,...t,headers:F([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/vector_stores/${e}`,V_(t,e=>({...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}search(e,t,n){return this._client.getAPIList(B`/vector_stores/${e}/search`,Kt,V_(n,e=>({body:t,method:`post`,...e,headers:F([{"OpenAI-Beta":`assistants=v2`},e?.headers]),__security:{bearerAuth:!0}})))}};W_.Files=B_,W_.FileBatches=I_;function G_(e,t){return Promise.resolve(e).then(t)}var K_=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function q_(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>K_.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!K_.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var J_=class extends z{create(e,t){return this._client.post(`/videos`,G_(t,t=>Vr({body:e,...t,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(B`/videos/${e}`,G_(t,e=>({...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=q_(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/videos`,P,G_(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/videos/${e}`,G_(t,e=>({...e,__security:{bearerAuth:!0}})))}createCharacter(e,t){return this._client.post(`/videos/characters`,G_(t,t=>Vr({body:e,...t,__security:{bearerAuth:!0}},this._client)))}downloadContent(e,t={},n){let r=q_(t,[`variant`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.get(B`/videos/${e}/content`,G_(n,e=>({query:t,...e,headers:F([{Accept:`application/binary`},e?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}edit(e,t){return this._client.post(`/videos/edits`,G_(t,t=>Vr({body:e,...t,__security:{bearerAuth:!0}},this._client)))}extend(e,t){return this._client.post(`/videos/extensions`,G_(t,t=>Vr({body:e,...t,__security:{bearerAuth:!0}},this._client)))}getCharacter(e,t){return this._client.get(B`/videos/characters/${e}`,G_(t,e=>({...e,__security:{bearerAuth:!0}})))}remix(e,t,n){return this._client.post(B`/videos/${e}/remix`,G_(n,e=>Br({body:t,...e,__security:{bearerAuth:!0}},this._client)))}},Y_=32,X_=32;function Z_(e){return e.split(` `,33).length>Y_}function*Q_(e){let t=0;for(;t<=e.length;){let n=e.indexOf(` `,t),r=e.slice(t,n===-1?void 0:n);if(yield r.startsWith(`v1,`)?r.slice(3):r,n===-1)break;t=n+1}}function $_(e){try{let t=op(e);return t.byteLength===X_?t:void 0}catch{return}}function ev(e){for(let t of Q_(e)){let e=$_(t);if(e)return e}}function tv(e,t,n){let r=n;for(let n of Q_(e)){let e=$_(n);if(!e)continue;let i=0;for(let[n,r]of e.entries())i|=r^(t[n]??0);i===0&&(r=e)}return r}async function nv(e,t,n,r,i,a){let o=Number.parseInt(n,10);if(Number.isNaN(o))throw new x(`Invalid webhook timestamp format`);let s=Math.floor(Date.now()/1e3);if(s-o>a)throw new x(`Webhook timestamp is too old`);if(o>s+a)throw new x(`Webhook timestamp is too new`);let c=Z_(t),l=c?ev(t):void 0;if(c&&!l)throw new x(`The given webhook signature does not match the expected signature`);let u=Uint8Array.from(i.startsWith(`whsec_`)?op(i.slice(6)):xe(i)),d=r?`${r}.${n}.${e}`:`${n}.${e}`,f=Uint8Array.from(xe(d)),p=await crypto.subtle.importKey(`raw`,u,{name:`HMAC`,hash:`SHA-256`},!1,c?[`sign`,`verify`]:[`verify`]);if(c&&l){let e=tv(t,new Uint8Array(await crypto.subtle.sign(`HMAC`,p,f)),l);try{if(await crypto.subtle.verify(`HMAC`,p,Uint8Array.from(e),f))return}catch{}throw new x(`The given webhook signature does not match the expected signature`)}for(let e of Q_(t))try{let t=Uint8Array.from(op(e));if(await crypto.subtle.verify(`HMAC`,p,t,f))return}catch{}throw new x(`The given webhook signature does not match the expected signature`)}function rv(e,t){return Promise.resolve(e).then(t)}var iv=class extends z{list(e){return this._client.get(`/webhook_event_types`,rv(e,e=>({...e,__security:{bearerAuth:!0}})))}},av,ov,sv;function cv(e,t){return Promise.resolve(e).then(t)}var lv=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function uv(e,t,n){if(typeof e!=`object`||!e)return;let r=Object.entries(Object.getOwnPropertyDescriptors(e)).filter(([,e])=>e.enumerable&&(!(`value`in e)||e.value!==void 0)),i=r.map(([e])=>e);if(i.some(e=>lv.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!lv.has(e)||t.includes(e)))throw TypeError(`Query parameters and request options must be passed as separate arguments.`);if(i.some(e=>![`headers`,`maxRetries`,`timeout`,`signal`,`idempotencyKey`,`query`].includes(e)))throw TypeError(`Pass transport overrides in the explicit request options argument.`);return Object.fromEntries(r.map(([t,n])=>`value`in n?[t,n.value]:[t,n.get?Reflect.apply(n.get,e,[]):void 0]))}}var dv=class extends z{constructor(){super(...arguments),av.add(this),this.eventTypes=new iv(this._client)}create(e,t){return this._client.post(`/webhook_endpoints`,cv(t,t=>({body:e,...t,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(B`/webhook_endpoints/${e}`,cv(t,e=>({...e,__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(B`/webhook_endpoints/${e}`,cv(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}list(e={},t){let n=uv(e,[`after`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/webhook_endpoints`,N,cv(t,t=>({query:e,...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(B`/webhook_endpoints/${e}`,cv(t,e=>({...e,__security:{bearerAuth:!0}})))}rotateSecret(e,t={},n){return this._client.post(B`/webhook_endpoints/${e}/rotate_secret`,cv(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}test(e,t,n){return this._client.post(B`/webhook_endpoints/${e}/test`,cv(n,e=>({body:t,...e,__security:{bearerAuth:!0}})))}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,i=300){if(typeof crypto>`u`||typeof crypto.subtle?.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");n(this,av,`m`,ov).call(this,r);let a=F([t]).values,o=n(this,av,`m`,sv).call(this,a,`webhook-signature`),s=n(this,av,`m`,sv).call(this,a,`webhook-timestamp`),c=n(this,av,`m`,sv).call(this,a,`webhook-id`);if(Z_(o)&&typeof crypto.subtle.sign!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");return await nv(e,o,s,c,r,i)}};av=new WeakSet,ov=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},sv=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n},dv.EventTypes=iv;var fv=Symbol.for(`openai.privateBedrockClient`);function pv(e,t){let n=new URL(e),r=new URL(t),i=n.origin,a=r.origin;if(n.protocol!==`http:`&&n.protocol!==`https:`||r.protocol!==`http:`&&r.protocol!==`https:`||a!==i)throw new o(`Bedrock request origin \`${a}\` does not match the configured base URL origin \`${i}\`.`)}function mv(e){if(/^[\t ]|[\t ]$/.test(e))throw TypeError(`Bedrock bearer credential contains an invalid HTTP header value.`);for(let t of e){let e=t.codePointAt(0)??0;if(e<32&&e!==9||e===127||e>255)throw TypeError(`Bedrock bearer credential contains an invalid HTTP header value.`)}}var hv=Symbol.for(`openai.realtimeAPIKeyCacheContext`),gv;function _v(e){let t=e[hv]?.getStore();return t?.client===e?t:void 0}function vv(e,t){return t!==null&&fv in e&&mv(t),t}async function yv(e,t=!1){let n,r={client:e,commit:()=>n===void 0?e.apiKey:n},i=e=>{n=e},a=()=>e._callApiKey(i),o=e[hv]??gv;t&&o&&!e[hv]&&Object.defineProperty(e,hv,{value:o});let s=await(o?o.run(t?r:void 0,a):a());return{apiKey:n===void 0?e.apiKey:n,isProvider:s,commit:()=>{let t=r.providerKey!==void 0&&n!==void 0&&n!==r.providerKey?vv(e,n):void 0,i=r.commit();return t===void 0?vv(e,i):t}}}function bv(e,t,n){let r=new Map(Object.entries(t).map(([e,t])=>[e.toLowerCase(),t]));for(let e of n)r.delete(e);for(let[t,n]of Object.entries(e.headers??{}))r.set(t,n);return{...e,headers:Object.fromEntries(r)}}var xv=new WeakMap,Sv=Symbol.for(`openai.node.providerDefinitions.v1`),Cv=globalThis,wv=Cv[Sv],Tv=wv??new WeakMap;wv||Object.defineProperty(Cv,Sv,{value:Tv});function Ev(e){let t=Tv.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var Dv,Ov,kv,Q,Av,jv,Mv,Nv,Pv,Fv,Iv,Lv,Rv,zv;function Bv(){if(ct())return!0;let e=globalThis;return typeof e.WorkerGlobalScope==`function`&&e instanceof e.WorkerGlobalScope&&typeof e.WorkerNavigator==`function`&&e.navigator instanceof e.WorkerNavigator&&typeof e.navigator?.userAgent==`string`&&e.navigator.userAgent!==`Cloudflare-Workers`&&e.process?.versions?.node===void 0&&e.Deno===void 0&&e.Bun===void 0&&e.EdgeRuntime===void 0&&e.WebSocketPair===void 0}var Vv=`workload-identity-auth`,Hv=Symbol(`inheritedDataResidencySelection`),$=class{constructor(e={}){Dv.add(this),kv.set(this,void 0),Q.set(this,void 0),Av.set(this,void 0),jv.set(this,void 0),Mv.set(this,!1),Nv.set(this,new WeakMap),this._apiKeyInvocation=0,this._lastCachedAPIKeyInvocation=0,this.completions=new vm(this),this.chat=new Qs(this),this.embeddings=new Rm(this),this.files=new $m(this),this.images=new xh(this),this.contentProvenanceChecks=new Am(this),this.audio=new ru(this),this.moderations=new jh(this),this.models=new kh(this),this.fineTuning=new _h(this),this.graders=new yh(this),this.vectorStores=new W_(this),this.safety=new m_(this),this.webhooks=new dv(this),this.beta=new gm(this),this.batches=new su(this),this.uploads=new A_(this),this.admin=new Xl(this),this.responses=new l_(this),this.live=new Dh(this),this.realtime=new Bh(this),this.conversations=new Im(this),this.evals=new Jm(this),this.containers=new Om(this),this.skills=new E_(this),this.videos=new J_(this);let{credential:r,options:i}=Er(e);e=i;let a=zt(e),s=e.provider,{baseURL:c=s?null:cp(`OPENAI_BASE_URL`),dataResidency:l,[Hv]:u=!1,apiKey:d=s?null:cp(`OPENAI_API_KEY`)??null,adminAPIKey:f=s?null:cp(`OPENAI_ADMIN_KEY`)??null,organization:p=s?null:cp(`OPENAI_ORG_ID`)??null,project:m=s?null:cp(`OPENAI_PROJECT_ID`)??null,webhookSecret:h=cp(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:g,x509Transport:_,credential:v,...y}=e;if(s){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`x509Transport`,`baseURL`,`dataResidency`].filter(t=>(t===`workloadIdentity`?g:e[t])!=null);if(t.length)throw new o(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let b=xr(g)?{x509:g,legacy:void 0}:{x509:void 0,legacy:g},x=b.x509,S=x!==void 0,C=s?Ev(s):void 0,w={apiKey:d,adminAPIKey:f,organization:p,project:m,webhookSecret:h,workloadIdentity:g,x509Transport:_,provider:s,...y,baseURL:C?.baseURL??a??(c||(S?`https://mtls.api.openai.com/v1`:`https://api.openai.com/v1`))};if(_&&!S)throw new o(`An X.509 transport requires an X.509 workload identity.`);if(S){if(a!==void 0||u)throw new o(`X.509 workload identity does not support data residency selection.`);if(e.fetch!==void 0)throw new o(`X.509 workload identity does not support a custom fetch implementation.`);if(ln(w.baseURL),Cr(w.fetchOptions),this.fetchWithAuth!==Ov.prototype.fetchWithAuth||this.fetchWithTimeout!==Ov.prototype.fetchWithTimeout)throw new o(`X.509 workload identity does not support overridden fetch dispatch hooks.`)}if(d&&g)throw new o("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!C&&!d&&!f&&!g)throw new o("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!w.dangerouslyAllowBrowser&&Bv())throw new o(`It looks like you're running in a browser-like environment.
10
+
11
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
12
+ If you understand the risks and have appropriate mitigations in place,
13
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
14
+
15
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
16
+
17
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
18
+ `);this.baseURL=w.baseURL,t(this,Mv,a!==void 0||u,`f`),this.timeout=w.timeout??Ov.DEFAULT_TIMEOUT,this.logger=n(this,Dv,`m`,zv).call(this,w.logger??console);let ee=`warn`;this.logLevel=ee,this.logLevel=Pe(w.logLevel,`ClientOptions.logLevel`,this)??Pe(cp(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??ee,this.fetchOptions=w.fetchOptions,this.maxRetries=n(this,Dv,`m`,Iv).call(this,w.maxRetries),this.fetch=w.fetch??he(),t(this,kv,vt,`f`);let T=s||r?void 0:cp(`OPENAI_CUSTOM_HEADERS`);if(T){let e={};for(let t of T.split(`
19
+ `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}w.defaultHeaders=F([e,w.defaultHeaders])}if(this._options=w,this._provider=C,x){let e=new Tr(x,_,p,m);this._workloadIdentityAuth=e,t(this,Q,e,`f`),t(this,Av,r,`f`),t(this,jv,e.fetch(),`f`),this.fetch=n(this,jv,`f`),Bn(this)}else b.legacy&&(this._workloadIdentityAuth=new cn(b.legacy,this.fetch));this.apiKey=typeof d==`string`?d:null,this.adminAPIKey=f,this.organization=p,this.project=m,this.webhookSecret=h}withOptions(e){let r=zt(e),i=n(this,Q,`f`),a={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:n(this,Q,`f`)?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:i?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:o,provider:s}=kr(a,e,n(this,Av,`f`),i!==void 0);r!==void 0&&delete a.baseURL;let c={...a,...e,credential:o,provider:s,[Hv]:n(this,Mv,`f`)&&r===void 0&&!E(e,`baseURL`)&&e.credential===void 0&&!s},l=new this.constructor(c);return s&&new URL(l.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(l._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),l.fetchOptions=e.fetchOptions,l.fetch=e.fetch??he(),l.organization=e.organization??null,l.project=e.project??null),n(this,Q,`f`)&&n(l,Q,`f`)&&this.baseURL===l.baseURL&&n(this,Q,`f`).matches(n(l,Q,`f`))&&(l._workloadIdentityAuth=n(this,Q,`f`),t(l,Q,n(this,Q,`f`),`f`),t(l,jv,n(this,jv,`f`),`f`)),l}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e,t){let n=xv.get(this);if(n?.baseHeaders)return bv({headers:n.baseHeaders},e,n.removedHeaders??new Set).headers;let r=F([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]);r.nulls.forEach(e=>(t??n?.removedHeaders)?.add(e));let i=Object.fromEntries(r.values);return n&&(n.baseHeaders={...i}),i}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return(n(this,Q,`f`)??this._workloadIdentityAuth)instanceof Tr&&t.adminAPIKeyAuth&&this.adminAPIKey!==null?await this.adminAPIKeyAuth(e):F([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=n(this,Q,`f`)??this._workloadIdentityAuth;if(t){if(t instanceof Tr){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==Ov.prototype.fetchWithAuth||this.fetchWithTimeout!==Ov.prototype.fetchWithTimeout))throw new o(`X.509 workload identity does not support overridden fetch dispatch hooks.`);let n=t.headerSnapshots();if(!Tr.shouldAuthenticate(e,n.defaultHeaders,n.requestHeaders))return}return F([{Authorization:`Bearer ${t instanceof Tr?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken()}`}])}let{apiKey:r}=await yv(this);if(r!=null)return F([{Authorization:`Bearer ${r}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return F([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Lt(e)}getUserAgent(){return`${this.constructor.name}/JS ${st}`}defaultIdempotencyKey(){return`stainless-node-retry-${r()}`}makeStatusError(e,t,n,r){let i=t&&typeof t==`object`&&t.error==null?{error:t}:t;return s.generate(e,i,n,r)}_hasApiKeyProvider(){return typeof this._options.apiKey==`function`}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;let t=this._options.apiKey;if(typeof t!=`function`)return e?.(this.apiKey),!1;let n=_v(this),r=++this._apiKeyInvocation,i;try{i=await t()}catch(e){throw e instanceof o?e:new o(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof i!=`string`||!i)throw new o(`Expected 'apiKey' function argument to return a string but it returned ${i}`);let a=i,s=()=>{if(e&&vv(this,a),r<this._lastCachedAPIKeyInvocation)return a;this.apiKey=a;let t=e?this.apiKey:a;return this._lastCachedAPIKeyInvocation=r,t};n&&(n.providerKey=a,n.commit=s);let c=n?vv(this,a):s();return e?.(c),!0}buildURL(e,t,r){let i=!n(this,Dv,`m`,Fv).call(this)&&r||this.baseURL,a,o={},s;if(ee(e))a=new URL(e);else if(i.includes(`?`)){let t=new URL(i);s=new URLSearchParams(t.search),o=Object.fromEntries(s),t.search=``,t.hash=``,a=new URL(t.toString()+(t.pathname.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e))}else a=new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e));let c=this.defaultQuery(),l=Object.fromEntries(a.searchParams),u;if((!re(o)||!re(c)||!re(l))&&(u={...l,...c,...t},t={...o,...u}),typeof t==`object`&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t),s&&u)){let e=new Set,t=new Set;for(let n of s.keys())e.has(n)&&!E(u,n)&&t.add(n),e.add(n);if(t.size){let e=new URLSearchParams;for(let[n,r]of a.searchParams)t.has(n)||e.append(n,r);for(let[n,r]of s)t.has(n)&&e.append(n,r);a.search=e.toString()}}return a.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){let r=n(this,Q,`f`)??this._workloadIdentityAuth,i=r instanceof Tr?Promise.resolve(e).then(e=>r.runRequest(()=>this.makeRequest(e,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(i)}responsePromise(e,t=(e,t)=>this.parseResponseWithTimeout(e,t)){let r=new Ht(this,e,(e,r)=>{let i=n(this,Nv,`f`).get(r.controller)?.continueRequest;return i?i(()=>t(e,r)):t(e,r)});return r.withResponse=async()=>{let t=await r,{response:n}=await e;return{data:t,response:n,request_id:n.headers.get(`x-request-id`)}},r._thenUnwrap=n=>this.responsePromise(e,async(e,r)=>ot(n(await t(e,r),r),r.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 it(e,t);for(;;){let r=n(this,Nv,`f`).get(t.controller),i=r?.timeout??t.options.timeout??this.timeout,a=r?.authentication,s=a?t.controller.signal:t.options.signal,d=()=>a&&s?this._makeUserAbortError(s):new c,f;try{f=a?.remainingTimeout(t.options,i)??Math.max(0,t.startTime+i-Date.now())}catch(e){let n=s?.aborted?d():void 0;throw t.controller.abort(),ye(t.response.body).catch(()=>void 0),n??e}let p,m,h=!1;try{if(s?.aborted&&r?.helperMethod!==`runTools`)throw d();let n=new Promise((e,n)=>{p=setTimeout(()=>{h=!0,t.controller.abort(),n(new u)},f),s&&(m=()=>{h||n(d())},s.addEventListener(`abort`,m,{once:!0}))});return await Promise.race([it(e,t),n])}catch(e){if(s?.aborted&&!h)throw d();if(!h)throw a&&e instanceof SyntaxError?SyntaxError(`X.509 workload identity API response contains invalid JSON.`):a&&!(e instanceof o)?new l({message:`X.509 workload identity API response body could not be read.`}):e;let n=r?.retriesRemaining??0;if(!n||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 u;p!==void 0&&clearTimeout(p),m&&s?.removeEventListener(`abort`,m),m=void 0;let i=await this.retryRequest(t.options,n,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,i)}finally{p!==void 0&&clearTimeout(p),m&&s?.removeEventListener(`abort`,m)}}}async readX509ResponseError(e,t,n,r,i){let a=new AbortController,o=r.signal,s=!1,c=()=>a.abort(o.reason);o.addEventListener(`abort`,c,{once:!0}),o.aborted&&c();try{let r=i.remainingTimeout(t,n),s=i.waitForRetry(r,a.signal).then(()=>{throw new u}),c=await Promise.race([e.text().catch(()=>`X.509 workload identity API response body could not be read.`),s]);if(o.aborted)throw this._makeUserAbortError(o);return c}catch(t){throw t instanceof u&&(s=!o.aborted,r.abort(),ye(e.body).catch(()=>void 0)),o.aborted&&!s?this._makeUserAbortError(o):t}finally{o.removeEventListener(`abort`,c),a.abort()}}async makeRequest(e,t,r){let o=await e,s=n(this,Dv,`m`,Iv).call(this,o.maxRetries??this.maxRetries);t=t==null?s:Math.min(n(this,Dv,`m`,Iv).call(this,t),s);let c=n(this,Q,`f`);c?.beginRequestPreparation(),await this.prepareOptions(o),c?.beginRequestPlanning();let d;try{let e=await this.buildRequest(o,{retryCount:s-t});if(d={req:e.req,url:e.url,timeout:e.timeout},c){ie(`timeout`,d.timeout),c.authorizePlannedRequest(d.url,d.req,d.timeout),Tr.isStreamingRequestBody(d.req.body)&&(o.__metadata={...o.__metadata,hasStreamingBody:!0}),await this.prepareRequest(d.req,{url:d.url,options:o}),await this._provider?.prepareRequest?.(d.req,{url:d.url,options:o}),c.beginRequestPlanning(),c.authorizePlannedRequest(d.url,d.req,d.timeout,!0),Tr.isStreamingRequestBody(d.req.body)&&(o.__metadata={...o.__metadata,hasStreamingBody:!0});let e=c.requestSnapshot().signal;if(e?.aborted||d.req.signal?.aborted)throw this._makeUserAbortError(e?.aborted?e:d.req.signal);c.setEffectiveSignal(d.req.signal||e?Wv(d.req.signal??e,e).signal:void 0),c.beginRequestNetwork();let t=o.__security??{bearerAuth:!0},n=await this.authHeaders(o,t),r=c.headerSnapshots(),i=F([r.defaultHeaders,r.requestHeaders]);for(let[e,t]of n?.values??[])!i.nulls.has(e)&&!d.req.headers.has(e)&&d.req.headers.set(e,t);this.validateHeaders(F([i,d.req.headers]),t)}}catch(e){if(c?.retireRequestBody(),c&&t&&!o.__metadata?.hasStreamingBody&&Tr.isRetryableFailure(e))return await this.retryRequest(o,t,r??`x509-token-exchange`,Tr.retryHeaders(e));throw e}let{req:f,url:p}=d,m=c?Math.min(d.timeout,c.requestSnapshot().timeout):d.timeout;c?.bindRequest(o,f,this.adminAPIKey);let h=o.__metadata?.hasStreamingBody===!0;c||(await this.prepareRequest(f,{url:p,options:o}),await this._provider?.prepareRequest?.(f,{url:p,options:o})),c?.adoptRequestHeaders(f),c&&Tr.isStreamingRequestBody(f.body)&&(h=!0);let g=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),_=r===void 0?``:`, retryOf: ${r}`,v=c?.requestStartedAt(o)??Date.now();if(this.logLevel===`debug`){let e=typeof f.body==`string`?{type:`string`,length:f.body.length}:f.body;j(this).debug(`[${g}] sending request`,We({retryOfRequestLogID:r,method:o.method,url:p,options:c?{body:e,...c.requestSnapshot()}:{...o,body:e},headers:f.headers}))}let y=c?c.requestSnapshot().signal:o.signal;if(y?.aborted||f.signal?.aborted)throw this._makeUserAbortError(y?.aborted?y:f.signal);let b=o.__security??{bearerAuth:!0},x=c||this.fetchWithTimeout===Ov.prototype.fetchWithTimeout?Wv(f.signal??(c?y:void 0),c?y:void 0):new AbortController,w=c?.remainingTimeout(o,m)??m,ee=c?Ov.prototype.fetchWithAuth:this.fetchWithAuth;c?.releaseRequestBody(f.body);let T=await ee.call(this,p,f,w,x,b).catch(a),te=Date.now();if(T instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(y?.aborted||f.signal?.aborted)throw this._makeUserAbortError(y?.aborted?y:f.signal);let n=i(T)||/timed? ?out/i.test(String(T)+(`cause`in T?String(T.cause):``));if(t&&!h&&(!c||Ln(T)))return j(this).info(`[${g}] connection ${n?`timed out`:`failed`} - ${e}`),j(this).debug(`[${g}] connection ${n?`timed out`:`failed`} (${e})`,We({retryOfRequestLogID:r,url:p,durationMs:te-v,message:c?`X.509 workload identity API connection failed.`:T.message})),this.retryRequest(o,t,r??g,void 0,f.signal);let a=h?`error; streaming body cannot be retried`:`error; no more retries left`;if(j(this).info(`[${g}] connection ${n?`timed out`:`failed`} - ${a}`),j(this).debug(`[${g}] connection ${n?`timed out`:`failed`} (${a})`,We({retryOfRequestLogID:r,url:p,durationMs:te-v,message:c?`X.509 workload identity API connection failed.`:T.message})),T instanceof S||T instanceof C)throw T;if(n){let e=`cause`in T?T.cause:void 0,t=typeof e==`object`&&e&&`code`in e&&e.code===`UND_ERR_HEADERS_TIMEOUT`?new u({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 u;throw c?new u:Object.assign(t,{cause:T})}throw c?new l({message:`X.509 workload identity API connection failed.`}):new l({message:Gv(T),cause:T})}let ne=`[${g}${_}${[...T.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${f.method} ${Ue(p)} ${T.ok?`succeeded`:`failed`} with status ${T.status} in ${te-v}ms`;if(!T.ok){let e=T.status===401&&c&&b.bearerAuth&&c.usedWorkloadToken(o);if(e&&c.invalidateToken(),T.status===401&&(c||this._workloadIdentityAuth)&&b.bearerAuth&&(!c||c.usedWorkloadToken(o))&&(!c||t>0)&&!h&&!o.__metadata?.workloadIdentityTokenRefreshed){c?ye(T.body).catch(()=>void 0):(await ye(T.body),this._workloadIdentityAuth?.invalidateToken());let e={...o,__metadata:{...o.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(e,c?t-1:t,r??g)}let n=e&&o.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(T);if(t&&n&&!h){let e=`retrying, ${t} attempts remaining`;return c?ye(T.body).catch(()=>void 0):await ye(T.body),j(this).info(`${ne} - ${e}`),j(this).debug(`[${g}] response error (${e})`,We({retryOfRequestLogID:r,url:T.url,status:T.status,headers:T.headers,durationMs:te-v})),this.retryRequest(o,t,r??g,T.headers,f.signal)}let i=n?h?`error; streaming body cannot be retried`:`error; no more retries left`:`error; not retryable`;j(this).info(`${ne} - ${i}`);let s=c?await this.readX509ResponseError(T,o,m,x,c):await T.text().catch(e=>a(e).message),l=ae(s),u=l?void 0:s;throw j(this).debug(`[${g}] response error (${i})`,We({retryOfRequestLogID:r,url:T.url,status:T.status,headers:T.headers,message:u,durationMs:Date.now()-v})),this.makeStatusError(T.status,l,u,T.headers)}j(this).info(ne),j(this).debug(`[${g}] response start`,We({retryOfRequestLogID:r,url:T.url,status:T.status,headers:T.headers,durationMs:te-v}));let re=c?.continuation();return c?.releaseRequestCredentials(),n(this,Nv,`f`).set(x,{timeout:m,retriesRemaining:t,hasStreamingBody:h,...c?{authentication:c}:{},helperMethod:o.__metadata?.helperMethod,...re?{continueRequest:re}:{}}),{response:T,options:o,controller:x,requestSignal:f.signal,requestLogID:g,retryOfRequestLogID:r,startTime:v}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let r=n(this,Q,`f`)??this._workloadIdentityAuth,i=r instanceof Tr?Promise.resolve(t).then(e=>r.runRequest(()=>this.makeRequest(e,null,void 0),this)):this.makeRequest(t,null,void 0),a=new Gt(this,i,e),o=this.responsePromise(i,async(t,n)=>{let r=await this.parseResponseWithTimeout(t,n);return new e(t,n.response,r,n.options)});return a.then=o.then.bind(o),a.catch=o.catch.bind(o),a.finally=o.finally.bind(o),a.withResponse=o.withResponse.bind(o),a._thenUnwrap=o._thenUnwrap.bind(o),a}async fetchWithAuth(e,t,r,i,a={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!n(this,jv,`f`)&&a.bearerAuth){let e=t.headers;if(e.get(`Authorization`)===`Bearer ${Vv}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await(n(this,jv,`f`)?Ov.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,r,i)}async fetchWithTimeout(e,t,r,i){let{signal:a,method:o,...s}=t||{},c=this._makeAbort(i),l=!!a&&Uv.get(i)===a,u=a&&!l?me(a,c,i.signal):void 0,d=setTimeout(c,r),f=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body==`object`&&s.body!==null&&Symbol.asyncIterator in s.body,p={signal:i.signal,...f?{duplex:`half`}:{},method:`GET`,...s};o&&(p.method=o.toUpperCase());try{let t=await(n(this,jv,`f`)??this.fetch).call(void 0,e,p);return u&&pe(t.body??t,c,i.signal),t}catch(e){throw u?.(),e}finally{clearTimeout(d)}}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,i,a=e.signal){let o,s=i?.get(`retry-after-ms`);if(s){let e=parseFloat(s);Number.isNaN(e)||(o=e)}let c=i?.get(`retry-after`);if(c&&o===void 0){let e=parseFloat(c);o=Number.isNaN(e)?Date.parse(c)-Date.now():e*1e3}if(o===void 0||!Number.isFinite(o)||o<0||o>6e4){let r=n(this,Dv,`m`,Iv).call(this,e.maxRetries??this.maxRetries);o=this.calculateDefaultRetryTimeoutMillis(t,r)}let l=n(this,Q,`f`);if(l){let t=l.remainingTimeout(e,l.requestSnapshot().timeout);if(o>=t)throw new u}if(l)await l.waitForRetry(o,l.effectiveSignal());else{let t=a===e.signal?[a]:[a,e.signal];try{await oe(o,...t)}catch(e){let n=t.find(e=>e?.aborted);throw n?this._makeUserAbortError(n):e}}return this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){if(n(this,Q,`f`)&&!n(this,Q,`f`).inRequest(this)){let r=n(this,Q,`f`);return await r.runRequest(async()=>{let n=await Ov.prototype.buildRequest.call(this,e,{retryCount:t});return r.releaseRequestBody(n.req.body),n},this)}let r={...e},i=n(this,Q,`f`),a=i?.snapshotTenant(this.organization,this.project),o=i?.snapshotHeaders(this._options.defaultHeaders,r.headers);o&&(r.headers=o.requestHeaders);let s=i?wr(this.fetchOptions):void 0,c=i?wr(r.fetchOptions):void 0,{method:l,path:u,query:d,defaultBaseURL:f}=r,p=this.buildURL(u,d,f);i?.snapshotAPIURL(p);let m=`timeout`in r;if(m&&ie(`timeout`,r.timeout),r.timeout=r.timeout??this.timeout,i&&c&&i.snapshotRequest(r.signal,r.timeout,c),i){let e=i.requestSnapshot();r.timeout=e.timeout,e.signal===void 0?delete r.signal:r.signal=e.signal}let h=this._provider||i?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),{bodyHeaders:g,body:_,isStreamingBody:v}=this.buildBody({options:r});return v&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},i?.ownRequestBody(_,r.body)),{req:{method:l,headers:await this.buildHeaders({options:e,method:l,bodyHeaders:g,authenticationHeaders:h,retryCount:t,x509Headers:o,x509Timeout:m?r.timeout:void 0,x509Tenant:a}),...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:`half`},..._&&{body:_},...(i?s:this.fetchOptions)??{},...(i?c:r.fetchOptions)??{}},url:p,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,authenticationHeaders:i,retryCount:a,x509Headers:o,x509Timeout:s,x509Tenant:c}){let l={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),l[this.idempotencyHeader]=e.idempotencyKey);let u=e.__metadata?.helperMethod,d=o?s:e.timeout,f=F([l,{Accept:`application/json`,...Bv()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(a),...d?{"X-Stainless-Timeout":String(Math.trunc(d/1e3))}:{},...ht(),...typeof u==`string`?{"X-Stainless-Helper-Method":u}:{},"OpenAI-Organization":c?c.organization:this.organization,"OpenAI-Project":c?c.project:this.project},n(this,Q,`f`)&&!n(this,Q,`f`).isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):i,o?.defaultHeaders??this._options.defaultHeaders,r,o?.requestHeaders??e.headers]);return!this._provider&&!n(this,Q,`f`)?.isPlanningRequest()&&this.validateHeaders(f,e.__security??{bearerAuth:!0}),f.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new c;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?{...n(this,kv,`f`).call(this,{body:t,headers:F([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let i=F([r]),a=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,o=!a&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&i.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||a?{bodyHeaders:void 0,body:t,isStreamingBody:!o}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:_e(t),isStreamingBody:!0}:typeof t==`object`&&i.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...n(this,kv,`f`).call(this,{body:t,headers:i}),isStreamingBody:!1}}};Ov=$,kv=new WeakMap,Q=new WeakMap,Av=new WeakMap,jv=new WeakMap,Mv=new WeakMap,Nv=new WeakMap,Dv=new WeakSet,Fv=function(){return n(this,Mv,`f`)||this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},Iv=function(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0?e:2},Lv=function(e){let t=e.replace(/[^a-z0-9]/gi,``).toLowerCase();return/authorization|authentication|cookie|session|signature|assertion|connectionstring|devicecode|codeverifier|accountkey|mtlskey|proxyauth|(?:api|access|secret|private|security|refresh|id|bearer|aws|azure|openai|admin|client|proxy|auth)[a-z0-9]*(?:key|token|secret|password|passwd|pwd|credential|auth)|^(?:auth|key|sig|sas|jwt|bearer|pfx|p12)$|(?:sid|token|secret|password|passwd|pwd|credential|passphrase|apikey|accesskey|privatekey|username)s?$/.test(t)},Rv=function(e,t){let r=4096,i=e=>e.replace(/((?:[a-z][a-z0-9+.-]*:)?\/\/)([^/\s?#]*@)(?=[^/\s?#]+)/gi,`$1[REDACTED]@`).replace(/(^|[\s(=])([^/\s]+:[^/\s]*@)(?=[^/\s@]+)/gi,`$1[REDACTED]@`).replace(/(^|[\s,;])([a-z][a-z0-9_-]*)(\s*:\s*)([^\r\n,;]+)/gi,(e,t,r,i)=>n(this,Dv,`m`,Lv).call(this,r)?`${t}${r}${i}[REDACTED]`:e).replace(/(^|[?&#;])([^=&;\s?#/]+)=([^&;\s#]+)/g,(e,t,r)=>{let i=r;try{i=globalThis.decodeURIComponent(r)}catch{}return n(this,Dv,`m`,Lv).call(this,i)?`${t}${r}=[REDACTED]`:e}),a=e=>{try{return globalThis.String.prototype.valueOf.call(e)}catch{return}},o=e=>{let t=a(e);if(t!==void 0)return n(this,Dv,`m`,Lv).call(this,t);try{return e instanceof globalThis.String}catch{return!0}},s=[],c=[],l,u=(e,t)=>{try{return{descriptor:globalThis.Object.getOwnPropertyDescriptor(e,t),failed:!1}}catch{return{descriptor:void 0,failed:!0}}},d=(e,t,n)=>{if(t>64||s.length>=r){n(`[REDACTED]`);return}s.push({value:e,depth:t,assign:n})};d(e,0,e=>{l=e});for(let e=0;e<s.length;e+=1){let{value:l,depth:f,assign:p}=s[e];if(typeof l==`string`){p(i(l));continue}if(typeof l==`function`||typeof l==`symbol`){p(`[REDACTED]`);continue}if(typeof l!=`object`||!l){p(l);continue}let m=t.get(l);if(m!==void 0){p(m);continue}try{let e=a(l);if(e!==void 0){let n=new globalThis.String(i(e));t.set(l,n),p(n);continue}if(l instanceof globalThis.String){t.set(l,`[REDACTED]`),p(`[REDACTED]`);continue}let s=globalThis.Headers;if(typeof s==`function`&&l instanceof s){let e=new s;t.set(l,e),p(e),s.prototype.forEach.call(l,(t,r)=>{e.set(r,n(this,Dv,`m`,Lv).call(this,r)?`[REDACTED]`:i(t))});continue}if(l instanceof URL){let e=new URL(URL.prototype.toString.call(l));t.set(l,e),p(e),e.username&&=`[REDACTED]`,e.password&&=`[REDACTED]`;for(let[t]of e.searchParams)n(this,Dv,`m`,Lv).call(this,t)&&e.searchParams.set(t,`[REDACTED]`);e.hash&&=i(e.hash);continue}if(Array.isArray(l)){let e=u(l,`length`);if(e.failed||!e.descriptor||!(`value`in e.descriptor)||typeof e.descriptor.value!=`number`){t.set(l,`[REDACTED]`),p(`[REDACTED]`);continue}let n=[];t.set(l,n),p(n);let i=Math.min(e.descriptor.value,r),a=u(l,`0`),s=!a.failed&&a.descriptor&&`value`in a.descriptor?a.descriptor.value:void 0;for(let e=0;e<i;e+=1){let t=e===0?a:u(l,`${e}`);if(t.failed){n[e]=`[REDACTED]`;continue}let r=t.descriptor;if(r?.enumerable){if(e===1&&(a.failed||a.descriptor&&!(`value`in a.descriptor)||o(s))){n[e]=`[REDACTED]`;continue}if(!(`value`in r)){n[e]=`[REDACTED]`;continue}d(r.value,f+1,t=>{n[e]=t})}}n.length=i,e.descriptor.value>i&&(n[i]=`[REDACTED]`);continue}if(l instanceof globalThis.Map){let e=new globalThis.Map,n=[];c.push({map:e,entries:n}),t.set(l,e),p(e),globalThis.Map.prototype.forEach.call(l,(e,t)=>{let r=[`[REDACTED]`,`[REDACTED]`];n.push(r),d(t,f+1,e=>{typeof e!=`function`&&typeof e!=`symbol`&&!(typeof t==`object`&&t&&e===t)&&(r[0]=e)}),!o(t)&&d(e,f+1,e=>{r[1]=e})});continue}if(l instanceof globalThis.Set){let e=new globalThis.Set;t.set(l,e),p(e),globalThis.Set.prototype.forEach.call(l,t=>{d(t,f+1,t=>{e.add(t)})});continue}if(l instanceof globalThis.Date){p(new globalThis.Date(globalThis.Date.prototype.getTime.call(l)));continue}let m=globalThis.ReadableStream;if(typeof m==`function`&&l instanceof m||l instanceof globalThis.ArrayBuffer||globalThis.ArrayBuffer.isView(l)){t.set(l,`[REDACTED]`),p(`[REDACTED]`);continue}let h;try{h=globalThis.Reflect.ownKeys(l)}catch{t.set(l,`[REDACTED]`),p(`[REDACTED]`);continue}let g={};t.set(l,g),p(g);for(let e of h){if(typeof e!=`string`)continue;let t=u(l,e);if(t.failed){g[e]=`[REDACTED]`;continue}let r=t.descriptor;if(r?.enumerable){if(n(this,Dv,`m`,Lv).call(this,e)){g[e]=`[REDACTED]`;continue}if(!(`value`in r)){g[e]=`[REDACTED]`;continue}d(r.value,f+1,t=>{g[e]=t})}}}catch{t.set(l,`[REDACTED]`),p(`[REDACTED]`)}}for(let{map:e,entries:t}of c)for(let[n,r]of t)e.set(n,r);return l},zv=function(e){if(n(Ov,Ov,`f`,Pv).has(e))return e;let t=new globalThis.Proxy(Object.create(null),{get:(t,r)=>{let i=globalThis.Reflect.get(e,r,e);return typeof i==`function`?typeof r!=`string`||![`debug`,`info`,`warn`,`error`,`trace`,`log`].includes(r)?i.bind(e):(...t)=>{let r=new WeakMap;return globalThis.Reflect.apply(i,e,t.map(e=>n(this,Dv,`m`,Rv).call(this,e,r)))}:i},set:(t,n,r)=>globalThis.Reflect.set(e,n,r,e)});return n(Ov,Ov,`f`,Pv).add(t),t},Pv={value:new globalThis.WeakSet},$.OpenAI=Ov,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=o,$.APIError=s,$.APIConnectionError=l,$.APIConnectionTimeoutError=u,$.APIUserAbortError=c,$.NotFoundError=m,$.ConflictError=h,$.RateLimitError=_,$.BadRequestError=d,$.AuthenticationError=f,$.InternalServerError=v,$.PermissionDeniedError=p,$.UnprocessableEntityError=g,$.InvalidWebhookSignatureError=x,$.toFile=mi,$.toStreamingFile=jr,$.Completions=vm,$.Chat=Qs,$.Embeddings=Rm,$.Files=$m,$.Images=xh,$.ContentProvenanceChecks=Am,$.Audio=ru,$.Moderations=jh,$.Models=kh,$.FineTuning=_h,$.Graders=yh,$.VectorStores=W_,$.Safety=m_,$.Webhooks=dv,$.Beta=gm,$.Batches=su,$.Uploads=A_,$.Admin=Xl,$.Responses=l_,$.Live=Dh,$.Realtime=Bh,$.Conversations=Im,$.Evals=Jm,$.Containers=Om,$.Skills=E_,$.Videos=J_,$.ConversationCursorPage=P,$.CursorPage=N,$.NextCursorPage=qt,$.Page=Kt,$.TokenPage=Jt;var Uv=new WeakMap;function Wv(e,t){let n=new AbortController;if(!e)return n;let r=globalThis.AbortSignal;if(typeof r?.any!=`function`||!(e instanceof r))return n;try{let i=[n.signal,e];t&&t!==e&&i.push(t);let a=r.any(i);Object.defineProperty(n,"signal",{value:a,configurable:!0}),Uv.set(n,e)}catch{}return n}function Gv(e){if(Kv(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function Kv(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var qv=class extends ${constructor({baseURL:e=cp(`OPENAI_BASE_URL`),apiKey:t=cp(`AZURE_OPENAI_API_KEY`),apiVersion:n=cp(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:s,dataResidency:c,...l}={}){if(Bt(c,`AzureOpenAI`),!n)throw new o(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof a==`function`&&(s??=!0),!a&&!t)throw new o("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new o("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(l.defaultQuery={...l.defaultQuery,"api-version":n},!e){if(r||=process.env.AZURE_OPENAI_ENDPOINT,!r)throw new o("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let t=r.length;for(;t>0&&r[t-1]===`/`;)t--;e=`${r.slice(0,t)}/openai`}else if(r)throw new o(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...l,...s===void 0?{}:{dangerouslyAllowBrowser:s}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};return E(e,`endpoint`)&&e.endpoint!==void 0&&!E(e,`baseURL`)&&(t.baseURL=void 0),super.withOptions(t)}async buildRequest(e,t={}){if(Yv.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!D(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!Jv(this.baseURL)&&(e.path=B`/deployments/${t}`+e.path)}let n=await super.buildRequest(e,t);return n.req.headers.has(`api-key`)&&(n.req.redirect=`manual`),n}async fetchWithAuth(e,t,n,r,i){return new Headers(t.headers).has(`api-key`)&&(t.redirect=`manual`),super.fetchWithAuth(e,t,n,r,i)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?F([{"api-key":this.apiKey}]):super.authHeaders(e,n)}};function Jv(e){try{return new URL(e).pathname.split(`/`).includes(`deployments`)}catch{return!1}}var Yv=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]),Xv;function Zv(e){let t=e?.trim();if(!t)throw new o("Must provide one of the `baseURL` or `awsRegion` arguments, or set the `AWS_BEDROCK_BASE_URL`, `AWS_REGION`, or `AWS_DEFAULT_REGION` environment variable.");if(!/^[a-z]{2,8}(?:-[a-z0-9]+)+-\d+$/u.test(t))throw new o("The Bedrock AWS `region` is invalid. Use a standard AWS region such as `us-east-1`.");return`https://bedrock-mantle.${t}.api.aws/openai/v1`}function Qv(e){let t=new URL(e),n=t.pathname.match(/\/responses(?:\/.*)?$/);return n?.index!==void 0&&(t.pathname=t.pathname.slice(0,n.index)||`/`),t.toString().replace(/\/$/,``)}function $v(e){return Object.getOwnPropertyDescriptor(e,`output_text`)||Yh(e),e}function ey(e){let t=e.stream.bind(e);return e.stream=((e,n)=>{let r=t(e,n),i=r.finalResponse.bind(r);return r.finalResponse=async()=>$v(await i()),r}),e}var ty=class extends ${constructor({baseURL:e=cp(`AWS_BEDROCK_BASE_URL`),apiKey:t,awsRegion:n=cp(`AWS_REGION`)??cp(`AWS_DEFAULT_REGION`),bedrockTokenProvider:r,adminAPIKey:i,workloadIdentity:a,x509Transport:s,dataResidency:c,...l}={}){if(Bt(c,`BedrockOpenAI`),i||a||s)throw new o(`BedrockOpenAI only supports Bedrock bearer token authentication.`);if(t===void 0&&!r&&(t=cp(`AWS_BEARER_TOKEN_BEDROCK`)??null),typeof t==`function`)throw new o("Pass refreshable Bedrock credentials via `bedrockTokenProvider`, not `apiKey`.");if(t&&r)throw new o("The `apiKey` and `bedrockTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(!t&&!r)throw new o("Missing credentials. Please pass an `apiKey` or `bedrockTokenProvider`, or set the `AWS_BEARER_TOKEN_BEDROCK` environment variable.");let u=e?.trim()?e:Zv(n);super({apiKey:r??t,adminAPIKey:null,baseURL:Qv(u),...l}),this[Xv]=!0;let d=this.apiKey;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,get(){return d!==null&&mv(d),d},set(e){d=e}});let f=this.baseURL,p=f;Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!1,get(){return p},set(e){pv(f,e),p=e}}),this.bedrockTokenProvider=r,this.responses=ey(new l_(this))}async prepareOptions(e){let t=this._options.baseURL??this.baseURL;pv(t,this.buildURL(e.path,null,e.defaultBaseURL)),await super.prepareOptions(e),pv(t,this.buildURL(e.path,null,e.defaultBaseURL))}async prepareRequest(e,t){pv(this._options.baseURL??this.baseURL,t.url),await super.prepareRequest(e,t),pv(this._options.baseURL??this.baseURL,this.buildURL(t.options.path,null,t.options.defaultBaseURL)),e.redirect=`manual`}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};if(n.bearerAuth||n.adminAPIKeyAuth){pv(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL));let{apiKey:t}=await yv(this);if(pv(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL)),t===null)return;mv(t);try{return F([{Authorization:`Bearer ${t}`}])}catch(e){throw e instanceof TypeError?TypeError(`Bedrock bearer credential contains an invalid HTTP header value.`):e}}return super.authHeaders(e,n)}withOptions(e){let t=e.apiKey===void 0?e.bedrockTokenProvider??this.bedrockTokenProvider:void 0;return super.withOptions({...e,...t?{apiKey:void 0,bedrockTokenProvider:t}:{}})}};Xv=fv,exports.APIConnectionError=l,exports.APIConnectionTimeoutError=u,exports.APIError=s,exports.APIPromise=Ht,exports.APIUserAbortError=c,exports.AuthenticationError=f,exports.AzureOpenAI=qv,exports.BadRequestError=d,exports.BedrockOpenAI=ty,exports.ConflictError=h,exports.InternalServerError=v,exports.InvalidWebhookSignatureError=x,exports.NotFoundError=m,exports.OAuthError=S,exports.OpenAI=$,exports.default=$,exports.OpenAIError=o,exports.PagePromise=Gt,exports.PermissionDeniedError=p,exports.RateLimitError=_,exports.SubjectTokenProviderError=C,exports.UnprocessableEntityError=g,exports.toFile=mi,exports.toStreamingFile=jr;