drizzle-cube 0.9.4 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/dist/adapters/ActivityGridChart.config-BXelP_3e.cjs +1 -0
  2. package/dist/adapters/ActivityGridChart.config-BjOOT9bc.js +2 -0
  3. package/dist/adapters/AreaChart.config-B9PiH7Kt.js +2 -0
  4. package/dist/adapters/AreaChart.config-Bv39EDi8.cjs +1 -0
  5. package/dist/adapters/BarChart.config-CU-XGdDO.cjs +1 -0
  6. package/dist/adapters/BarChart.config-D9OIP1uN.js +2 -0
  7. package/dist/adapters/BoxPlotChart.config-C3cLagI6.js +2 -0
  8. package/dist/adapters/BoxPlotChart.config-CMwswa9H.cjs +1 -0
  9. package/dist/adapters/BubbleChart.config--rvyga9s.js +2 -0
  10. package/dist/adapters/BubbleChart.config-DOCLeg91.cjs +1 -0
  11. package/dist/adapters/CandlestickChart.config-B8h__isO.cjs +1 -0
  12. package/dist/adapters/CandlestickChart.config-DPzi-8B_.js +2 -0
  13. package/dist/adapters/DataTable.config-Dn2PyQdy.cjs +1 -0
  14. package/dist/adapters/DataTable.config-wtCGsLPw.js +2 -0
  15. package/dist/adapters/DotStripChart.config-BFshbpk0.cjs +1 -0
  16. package/dist/adapters/DotStripChart.config-c-tbauT6.js +2 -0
  17. package/dist/adapters/FunnelChart.config-CZYDI4k-.js +2 -0
  18. package/dist/adapters/FunnelChart.config-Dc2pIfJy.cjs +1 -0
  19. package/dist/adapters/GaugeChart.config-C9LYrKB1.cjs +1 -0
  20. package/dist/adapters/GaugeChart.config-DD73ueqk.js +2 -0
  21. package/dist/adapters/HeatMapChart.config-5DgOpgpV.js +2 -0
  22. package/dist/adapters/HeatMapChart.config-BZgQ255E.cjs +1 -0
  23. package/dist/adapters/KpiDelta.config-BEB3XqML.cjs +1 -0
  24. package/dist/adapters/KpiDelta.config-DeRkPIxD.js +2 -0
  25. package/dist/adapters/KpiNumber.config-CxpTAKzR.cjs +1 -0
  26. package/dist/adapters/KpiNumber.config-DM1dRQL-.js +2 -0
  27. package/dist/adapters/KpiText.config-Dt59uikm.js +2 -0
  28. package/dist/adapters/KpiText.config-Dt_pW6mK.cjs +1 -0
  29. package/dist/adapters/LineChart.config-YeXia1kV.cjs +1 -0
  30. package/dist/adapters/LineChart.config-jX2ulNmq.js +2 -0
  31. package/dist/adapters/MarkdownChart.config-BAXU79ec.js +2 -0
  32. package/dist/adapters/MarkdownChart.config-BP6_9ET2.cjs +1 -0
  33. package/dist/adapters/MeasureProfileChart.config-BW2gdPaM.cjs +1 -0
  34. package/dist/adapters/MeasureProfileChart.config-CSxeKHnS.js +2 -0
  35. package/dist/adapters/PieChart.config-Ci3ZPY9U.cjs +1 -0
  36. package/dist/adapters/PieChart.config-DtCSYlvx.js +2 -0
  37. package/dist/adapters/ProportionBarChart.config-B71wPMKX.js +2 -0
  38. package/dist/adapters/ProportionBarChart.config-Bihgdn8v.cjs +1 -0
  39. package/dist/adapters/RadarChart.config-CC8jIJ78.js +2 -0
  40. package/dist/adapters/RadarChart.config-D7dCuKRM.cjs +1 -0
  41. package/dist/adapters/RadialBarChart.config-DC2nQk5q.js +2 -0
  42. package/dist/adapters/RadialBarChart.config-Dumbvnj1.cjs +1 -0
  43. package/dist/adapters/RecordsTable.config-BRqLDmY3.cjs +1 -0
  44. package/dist/adapters/RecordsTable.config-D1wlIO1v.js +2 -0
  45. package/dist/adapters/RetentionCombinedChart.config-DejP7Hcc.cjs +1 -0
  46. package/dist/adapters/RetentionCombinedChart.config-yDEDWwJt.js +2 -0
  47. package/dist/adapters/RetentionHeatmap.config-BSqTkHB8.cjs +1 -0
  48. package/dist/adapters/RetentionHeatmap.config-GRJjblsW.js +2 -0
  49. package/dist/adapters/SankeyChart.config-9b1eT_2V.js +2 -0
  50. package/dist/adapters/SankeyChart.config-n8ro9EZU.cjs +1 -0
  51. package/dist/adapters/ScatterChart.config-BHqhTxPV.cjs +1 -0
  52. package/dist/adapters/ScatterChart.config-Bub2V8Ge.js +2 -0
  53. package/dist/adapters/SunburstChart.config-CxG0NFqN.js +2 -0
  54. package/dist/adapters/SunburstChart.config-PmN9LEb5.cjs +1 -0
  55. package/dist/adapters/TreeMapChart.config-D2S3rG6P.js +2 -0
  56. package/dist/adapters/TreeMapChart.config-TC4dciRa.cjs +1 -0
  57. package/dist/adapters/WaterfallChart.config-BirJq5VE.cjs +1 -0
  58. package/dist/adapters/WaterfallChart.config-DYMzte7F.js +2 -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-DXfEc3Gg.cjs → handler-CP-6A8X3.cjs} +2 -2
  64. package/dist/adapters/{handler-BM5qe8yt.js → handler-mwSVmP0z.js} +30 -30
  65. package/dist/adapters/hono/index.cjs +1 -1
  66. package/dist/adapters/hono/index.js +1 -1
  67. package/dist/adapters/nextjs/index.cjs +1 -1
  68. package/dist/adapters/nextjs/index.js +1 -1
  69. package/dist/adapters/{openai-4uH2LLR4.cjs → openai-B82IDfp4.cjs} +1 -1
  70. package/dist/{server/openai-CgiNtz4I.js → adapters/openai-BKDrN7u0.js} +1 -1
  71. package/dist/adapters/openai-BaNGQmmK.cjs +19 -0
  72. package/dist/adapters/{openai-CjhgJRPV.js → openai-CeNMQU8r.js} +3312 -2509
  73. package/dist/client/charts.js +2 -2
  74. package/dist/client/chunks/{DashboardEditModal-DyweH8_q.js → DashboardEditModal-3_odkGXU.js} +899 -842
  75. package/dist/client/chunks/DashboardEditModal-3_odkGXU.js.map +1 -0
  76. package/dist/client/chunks/{RecordsTable-B4FqKr9E.js → RecordsTable-zy4EWyWx.js} +2 -2
  77. package/dist/client/chunks/{RecordsTable-B4FqKr9E.js.map → RecordsTable-zy4EWyWx.js.map} +1 -1
  78. package/dist/client/chunks/{analysis-builder-CL8WUtUY.js → analysis-builder-UhPaVPsn.js} +7 -7
  79. package/dist/client/chunks/{analysis-builder-CL8WUtUY.js.map → analysis-builder-UhPaVPsn.js.map} +1 -1
  80. package/dist/client/chunks/{analysis-builder-shared-CuKa4wqd.js → analysis-builder-shared-DS_eJnM8.js} +6 -6
  81. package/dist/client/chunks/{analysis-builder-shared-CuKa4wqd.js.map → analysis-builder-shared-DS_eJnM8.js.map} +1 -1
  82. package/dist/client/chunks/{chart-data-table-xLM9byGS.js → chart-data-table-DkkQtuY6.js} +2 -3
  83. package/dist/client/chunks/chart-data-table-DkkQtuY6.js.map +1 -0
  84. package/dist/client/chunks/{chart-kpi-delta-CDU8rcmS.js → chart-kpi-delta-Cih5Vh_Z.js} +2 -2
  85. package/dist/client/chunks/{chart-kpi-delta-CDU8rcmS.js.map → chart-kpi-delta-Cih5Vh_Z.js.map} +1 -1
  86. package/dist/client/chunks/{chart-kpi-number-BnoXaY00.js → chart-kpi-number-Z5zpxeKR.js} +3 -3
  87. package/dist/client/chunks/{chart-kpi-number-BnoXaY00.js.map → chart-kpi-number-Z5zpxeKR.js.map} +1 -1
  88. package/dist/client/chunks/{chart-kpi-text-5S_G6DFl.js → chart-kpi-text-glMTySe4.js} +2 -2
  89. package/dist/client/chunks/{chart-kpi-text-5S_G6DFl.js.map → chart-kpi-text-glMTySe4.js.map} +1 -1
  90. package/dist/client/chunks/{charts-loader-C9PPgWxv.js → charts-loader-DuV9kYN8.js} +7 -7
  91. package/dist/client/chunks/{charts-loader-C9PPgWxv.js.map → charts-loader-DuV9kYN8.js.map} +1 -1
  92. package/dist/client/chunks/{schema-visualization-4Vi5vrFa.js → schema-visualization-DIn9gy5O.js} +2 -2
  93. package/dist/client/chunks/{schema-visualization-4Vi5vrFa.js.map → schema-visualization-DIn9gy5O.js.map} +1 -1
  94. package/dist/client/chunks/{useDirtyStateTracking-olnTnFb1.js → useDirtyStateTracking-giMoYB90.js} +2 -2
  95. package/dist/client/chunks/{useDirtyStateTracking-olnTnFb1.js.map → useDirtyStateTracking-giMoYB90.js.map} +1 -1
  96. package/dist/client/chunks/{useExplainAI-DlZ22fsT.js → useExplainAI-CpFZbdn-.js} +4 -4
  97. package/dist/client/chunks/{useExplainAI-DlZ22fsT.js.map → useExplainAI-CpFZbdn-.js.map} +1 -1
  98. package/dist/client/chunks/{vendor-DYXrJcMx.js → vendor-wyAsikWW.js} +2 -2
  99. package/dist/client/chunks/{vendor-DYXrJcMx.js.map → vendor-wyAsikWW.js.map} +1 -1
  100. package/dist/client/components.js +1 -1
  101. package/dist/client/hooks.js +3 -3
  102. package/dist/client/icons.js +1 -1
  103. package/dist/client/index.js +7 -7
  104. package/dist/client/providers.js +1 -1
  105. package/dist/client/schema.js +1 -1
  106. package/dist/client/utils.js +2 -2
  107. package/dist/client-bundle-stats.html +1 -1
  108. package/dist/server/index.cjs +1 -1
  109. package/dist/server/index.js +1 -1
  110. package/dist/server/openai-Cxii1K2N.cjs +19 -0
  111. package/dist/server/{openai-DJbxudVD.cjs → openai-DC2ye24o.cjs} +1 -1
  112. package/dist/{adapters/openai-xpb8URhX.js → server/openai-Jt2WUOXm.js} +1 -1
  113. package/dist/server/{openai-BISsKb5q.js → openai-aLi6lmJs.js} +3312 -2509
  114. package/package.json +2 -2
  115. package/dist/adapters/ActivityGridChart.config-5Dw4ikvc.cjs +0 -1
  116. package/dist/adapters/ActivityGridChart.config-kf_mi0WP.js +0 -2
  117. package/dist/adapters/AreaChart.config-BZ6R4fa-.js +0 -2
  118. package/dist/adapters/AreaChart.config-CNKWBlma.cjs +0 -1
  119. package/dist/adapters/BarChart.config-DH8FeanY.cjs +0 -1
  120. package/dist/adapters/BarChart.config-DvNsHkbz.js +0 -2
  121. package/dist/adapters/BoxPlotChart.config-CSUdgbS3.js +0 -2
  122. package/dist/adapters/BoxPlotChart.config-DIkF7bNu.cjs +0 -1
  123. package/dist/adapters/BubbleChart.config-Cikl7Bjb.cjs +0 -1
  124. package/dist/adapters/BubbleChart.config-D34u-Hlu.js +0 -2
  125. package/dist/adapters/CandlestickChart.config-CW7oM2j2.js +0 -2
  126. package/dist/adapters/CandlestickChart.config-sZ4T7z6E.cjs +0 -1
  127. package/dist/adapters/DataTable.config-Dt3RTa86.cjs +0 -1
  128. package/dist/adapters/DataTable.config-b2Ps3QCD.js +0 -2
  129. package/dist/adapters/DotStripChart.config-1xHVgdbM.cjs +0 -1
  130. package/dist/adapters/DotStripChart.config-CXPdK6mj.js +0 -2
  131. package/dist/adapters/FunnelChart.config-DoQ6DoI6.cjs +0 -1
  132. package/dist/adapters/FunnelChart.config-TBJ8wc5T.js +0 -2
  133. package/dist/adapters/GaugeChart.config-BH1voNKO.cjs +0 -1
  134. package/dist/adapters/GaugeChart.config-BXZOfLvb.js +0 -2
  135. package/dist/adapters/HeatMapChart.config-BrJhG4sD.js +0 -2
  136. package/dist/adapters/HeatMapChart.config-DQyOyT8-.cjs +0 -1
  137. package/dist/adapters/KpiDelta.config-B7zqzeE4.js +0 -2
  138. package/dist/adapters/KpiDelta.config-PwxW3cY6.cjs +0 -1
  139. package/dist/adapters/KpiNumber.config-Cx8cFl8G.cjs +0 -1
  140. package/dist/adapters/KpiNumber.config-PfuS6HY8.js +0 -2
  141. package/dist/adapters/KpiText.config-BAGxU8eA.cjs +0 -1
  142. package/dist/adapters/KpiText.config-hpoBkwuU.js +0 -2
  143. package/dist/adapters/LineChart.config-CsUVse0Q.cjs +0 -1
  144. package/dist/adapters/LineChart.config-PnIgjyxG.js +0 -2
  145. package/dist/adapters/MarkdownChart.config-BnKKOYz7.js +0 -2
  146. package/dist/adapters/MarkdownChart.config-CvZ6e5Pm.cjs +0 -1
  147. package/dist/adapters/MeasureProfileChart.config-BAKjdSaE.js +0 -2
  148. package/dist/adapters/MeasureProfileChart.config-zTYarMOX.cjs +0 -1
  149. package/dist/adapters/PieChart.config-B5DWuB7p.cjs +0 -1
  150. package/dist/adapters/PieChart.config-DRJ-TEHx.js +0 -2
  151. package/dist/adapters/ProportionBarChart.config-CkWlUXVL.js +0 -2
  152. package/dist/adapters/ProportionBarChart.config-j5hZGdiK.cjs +0 -1
  153. package/dist/adapters/RadarChart.config-BGdcb-vd.js +0 -2
  154. package/dist/adapters/RadarChart.config-COjDDQIQ.cjs +0 -1
  155. package/dist/adapters/RadialBarChart.config-Bn6WyAZJ.cjs +0 -1
  156. package/dist/adapters/RadialBarChart.config-CKtx2iHt.js +0 -2
  157. package/dist/adapters/RecordsTable.config-BoyiHRTW.cjs +0 -1
  158. package/dist/adapters/RecordsTable.config-DIaOnBzA.js +0 -2
  159. package/dist/adapters/RetentionCombinedChart.config-COijZvyV.js +0 -2
  160. package/dist/adapters/RetentionCombinedChart.config-Dqn8yDyE.cjs +0 -1
  161. package/dist/adapters/RetentionHeatmap.config-Dg81G--t.cjs +0 -1
  162. package/dist/adapters/RetentionHeatmap.config-KBahnEBw.js +0 -2
  163. package/dist/adapters/SankeyChart.config-CU5cIUfw.cjs +0 -1
  164. package/dist/adapters/SankeyChart.config-e2PoqHK4.js +0 -2
  165. package/dist/adapters/ScatterChart.config-CFalq9dc.cjs +0 -1
  166. package/dist/adapters/ScatterChart.config-Cu87WDER.js +0 -2
  167. package/dist/adapters/SunburstChart.config-Cl3xYxse.cjs +0 -1
  168. package/dist/adapters/SunburstChart.config-XKWhwuJc.js +0 -2
  169. package/dist/adapters/TreeMapChart.config-CwPjwIMi.js +0 -2
  170. package/dist/adapters/TreeMapChart.config-DeDuzwj-.cjs +0 -1
  171. package/dist/adapters/WaterfallChart.config-CQyfg1cz.js +0 -2
  172. package/dist/adapters/WaterfallChart.config-Cr3XZuwl.cjs +0 -1
  173. package/dist/adapters/openai-BoLyuR1l.cjs +0 -19
  174. package/dist/client/chunks/DashboardEditModal-DyweH8_q.js.map +0 -1
  175. package/dist/client/chunks/chart-data-table-xLM9byGS.js.map +0 -1
  176. package/dist/server/openai-D1PmqQem.cjs +0 -19
@@ -1,19 +0,0 @@
1
- const e=require("./utils-iMkgJr10.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 ie(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ae=(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},oe=e=>{try{return JSON.parse(e)}catch{return}},se=(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()}),ce=globalThis,le=typeof ce.FinalizationRegistry==`function`?new ce.FinalizationRegistry(e=>{try{e()}catch{}}):void 0,ue=new WeakMap,de=new WeakMap;function fe(e,t,n){let r=de.get(e);if(!r){let t=new Set,i=()=>{de.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}),de.set(e,r)}let i=r;return i.callbacks.add(t),()=>{i.callbacks.delete(t),n.unregister(t),i.callbacks.size===0&&(de.get(e)===i&&de.delete(e),e.removeEventListener(`abort`,i.abort))}}function pe(e,t,n){e.addEventListener(`abort`,()=>t.deref()?.delete(n),{once:!0})}function me(e,t,n){if(typeof ce.WeakRef==`function`&&le&&!n.aborted){let r=ue.get(e);r||(r=new Set,ue.set(e,r)),r.add(t),pe(n,new ce.WeakRef(r),t)}}function he(e,t,n){if(e.aborted)return t(),()=>{};if(typeof ce.WeakRef!=`function`||!le)return e.addEventListener(`abort`,t,{once:!0}),()=>e.removeEventListener(`abort`,t);let r=new ce.WeakRef(t),i=fe(e,r,le);return le.register(t,i,r),me(n,t,n),i}function ge(){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 _e(...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 ve(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return _e({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ye(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 be(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 xe;function Se(e){let t;return(xe??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Ce;function we(e){let t;return(Ce??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var Te,D,O,k,Ee,De,Oe,ke=65536,Ae=class{constructor(){Te.add(this),D.set(this,void 0),O.set(this,void 0),k.set(this,void 0),Ee.set(this,void 0),De.set(this,void 0),t(this,D,new Uint8Array,`f`),t(this,O,0,`f`),t(this,k,0,`f`),t(this,Ee,0,`f`),t(this,De,!1,`f`)}decode(e){if(e==null)return[];let r;if(r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?Se(e):e,r.length===0||n(this,De,`f`)&&(t(this,De,!1,`f`),r[0]===10&&(r=r.subarray(1)),r.length===0))return[];n(this,Te,`m`,Oe).call(this,r);let i=[],a;for(;(a=je(n(this,D,`f`),n(this,Ee,`f`),n(this,k,`f`)))!=null;){let e=we(n(this,D,`f`).subarray(n(this,O,`f`),a.preceding));i.push(e),t(this,O,a.index,`f`),a.carriage&&(n(this,O,`f`)<n(this,k,`f`)&&n(this,D,`f`)[n(this,O,`f`)]===10?t(this,O,n(this,O,`f`)+1,`f`):n(this,O,`f`)===n(this,k,`f`)&&t(this,De,!0,`f`)),t(this,Ee,n(this,O,`f`),`f`)}if(t(this,Ee,n(this,k,`f`),`f`),n(this,O,`f`)===n(this,k,`f`))t(this,O,0,`f`),t(this,k,0,`f`),t(this,Ee,0,`f`),n(this,D,`f`).length>ke&&t(this,D,new Uint8Array,`f`);else if(i.length>0&&n(this,D,`f`).length>ke){let e=n(this,k,`f`)-n(this,O,`f`);if(e<=ke||n(this,D,`f`).length>e*4){let r=e<=ke?Math.min(Math.max(e*2,256),ke):e*2,i=new Uint8Array(r);i.set(n(this,D,`f`).subarray(n(this,O,`f`),n(this,k,`f`))),t(this,D,i,`f`),t(this,O,0,`f`),t(this,k,e,`f`),t(this,Ee,e,`f`)}}return i}flush(){return t(this,De,!1,`f`),n(this,O,`f`)===n(this,k,`f`)?[]:this.decode(`
2
- `)}};D=new WeakMap,O=new WeakMap,k=new WeakMap,Ee=new WeakMap,De=new WeakMap,Te=new WeakSet,Oe=function(e){if(n(this,k,`f`)+e.length>n(this,D,`f`).length){let r=n(this,k,`f`)-n(this,O,`f`);if(n(this,O,`f`)>=n(this,D,`f`).length/2&&r+e.length<=n(this,D,`f`).length)n(this,D,`f`).copyWithin(0,n(this,O,`f`),n(this,k,`f`));else{let i=Math.max(n(this,D,`f`).length*2,r+e.length,256),a=new Uint8Array(i);a.set(n(this,D,`f`).subarray(n(this,O,`f`),n(this,k,`f`))),t(this,D,a,`f`)}t(this,Ee,n(this,Ee,`f`)-n(this,O,`f`),`f`),t(this,k,r,`f`),t(this,O,0,`f`)}n(this,D,`f`).set(e,n(this,k,`f`)),t(this,k,n(this,k,`f`)+e.length,`f`)},Ae.NEWLINE_CHARS=new Set([`
3
- `,`\r`]),Ae.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function je(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 Me(e){for(let t=0;t<e.length-1;t++){let n=Ne(e,t);if(n>0){let r=t+n,i=Ne(e,r);if(i>0)return r+i}}return-1}function Ne(e,t){return e[t]===10?1:e[t]===13?e[t+1]===10?2:1:0}var Pe={off:0,error:200,warn:300,info:400,debug:500},Fe=(e,t,n)=>{if(e){if(E(Pe,e))return e;A(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Pe))}`)}};function Ie(){}function Le(e,t,n){return!t||Pe[e]>Pe[n]?Ie:t[e].bind(t)}var Re={error:Ie,warn:Ie,info:Ie,debug:Ie},ze=new WeakMap;function A(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Re;let r=ze.get(t);if(r&&r[0]===n)return r[1];let i={error:Le(`error`,t,n),warn:Le(`warn`,t,n),info:Le(`info`,t,n),debug:Le(`debug`,t,n)};return ze.set(t,[n,i]),i}var Be=new Set([`apikey`,`accesstoken`,`refreshtoken`,`sessiontoken`,`sessionid`,`idtoken`,`authtoken`,`authorization`,`token`,`password`,`clientsecret`,`signingsecret`,`xamzsecuritytoken`,`xamzsignature`,`xamzcredential`]);function Ve(e){let t=e.toLowerCase().replace(/[-_]/gu,``);return Be.has(t)||Be.has(t.replace(/^x/u,``))}var He=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 Ue(e){return He.has(e.toLowerCase().replace(/_/gu,`-`))||Ve(e)}function We(e){let t=new URL(e);t.username=``,t.password=``,t.hash=``;for(let e of t.searchParams.keys())Ve(e)&&t.searchParams.set(e,`***`);return t.href}var Ge=e=>{if(e.options){if(e.options={...e.options},delete e.options.headers,e.options.path){let t=e.options.path,n=new URL(We(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,Ve(e)?`***`:t])))}return e.url&&=We(e.url),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,Ue(e)?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e},Ke,qe,Je,Ye;function Xe(e){return!(e instanceof s)&&i(e)}function Ze(){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 Qe=class e{constructor(e,n,r){Ke.add(this),qe.set(this,void 0),Je.set(this,!1),this.iterator=e,this.controller=n,t(this,qe,r,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,c=r?A(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=et(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||Xe(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 Ae,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)}[(qe=new WeakMap,Je=new WeakMap,Ke=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){let{controller:r}=this,i=Ze(),a=Ze(),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,Ke,`m`,Ye).call(this,o,r)),{value:void 0,done:!0})}),c=i=>{let a=new e(()=>s(i),r,n(this,qe,`f`));return t(a,Je,!0,`f`),a};return[c(i),c(a)]}toReadableStream(){let{controller:e}=this,t,r,i=()=>r??=n(this,Ke,`m`,Ye).call(this,t,e);return _e({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=Se(JSON.stringify(n)+`
4
- `);e.enqueue(i)}catch(t){e.error(t),i().catch(()=>void 0)}},cancel:i})}};Ye=async function(e,t){let r=e.return;r&&(n(this,Je,`f`)||t.abort(),await Reflect.apply(r,e,[]))};function $e(e,t){let n=typeof e.getReader==`function`?e.getReader():void 0,r=n?{next:()=>n.read(),return:()=>n.cancel()}:ye(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*et(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 rt,r=new Ae,{signal:a}=t,s=$e(e.body,a),c=!1;try{s.start();for await(let e of nt(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 tt=3;async function*nt(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`?Se(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=Me(t.subarray(i,r)))!==-1;)o+=i,yield t.slice(n,o),n=o,i=n;i=Math.max(n,r-tt)}r>n&&(yield t.slice(n,r))}var rt=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]=it(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 it(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.slice(0,n),t,e.slice(n+t.length)]}async function at(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o,s=await(async()=>{if(t.options.stream)return A(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):Qe.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,st(t,n)}return await n.text()})().catch(e=>{throw ot(e,t.controller.signal)});return e.logLevel===`debug`&&A(e).debug(`[${r}] response parsed`,Ge({retryOfRequestLogID:i,url:n.url,status:n.status,body:o===void 0?s:{type:`json`,length:o},durationMs:Date.now()-a})),s}function ot(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 st(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 ct=`7.20.0`,lt=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function ut(){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 dt=()=>{let e=ut();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ct,"X-Stainless-OS":mt(Deno.build.os),"X-Stainless-Arch":pt(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":ct,"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":ct,"X-Stainless-OS":mt(globalThis.process.platform??`unknown`),"X-Stainless-Arch":pt(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=ft();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ct,"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":ct,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function ft(){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 pt=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,mt=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`),ht,gt=()=>ht??=dt(),_t=new WeakMap;function vt(e,t){let n=_t.get(e);return n||(n=new Set,_t.set(e,n)),n.add(t),()=>{let n=_t.get(e);n&&(n.delete(t),n.size===0&&_t.delete(e))}}var yt=({headers:e,body:t})=>{let n=typeof t==`object`&&t?_t.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}},bt=`RFC3986`,xt=String,St={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:xt},Ct,wt=(e,t)=>{let n=Ct??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return Ct=n,n(e,t)},Tt=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Et=1024,Dt=(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/Et)+1)*Et,a.length);t<a.length&&a.codePointAt(t-1)>65535&&(t+=1);let n=a.length>=Et?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]=Tt[t];continue}if(t<2048){r[r.length]=Tt[192|t>>6]+Tt[128|t&63];continue}if(t<55296||t>=57344){r[r.length]=Tt[224|t>>12]+Tt[128|t>>6&63]+Tt[128|t&63];continue}e+=1,t=65536+((t&1023)<<10|n.charCodeAt(e)&1023),r[r.length]=Tt[240|t>>18]+Tt[128|t>>12&63]+Tt[128|t>>6&63]+Tt[128|t&63]}o+=r.join(``),e=t}return o};function Ot(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function kt(e,t){if(T(e)){let n=[];for(let r of e)n.push(t(r));return n}return t(e)}var At={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},jt=function(e,t){Array.prototype.push.apply(e,T(t)?t:[t])},Mt,j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:Dt,encodeValuesOnly:!1,format:bt,formatter:xt,indices:!1,serializeDate(e){return(Mt??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Nt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Pt={};function Ft(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(Pt))!==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(Pt)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&T(v)&&(v=kt(v,e=>e instanceof Date?f?.(e):e)),v===null){if(a)return c&&!h?c(t,j.encoder,g,`key`,p):t;v=``}if(Nt(v)||Ot(v)){if(c){let e=h?t:c(t,j.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,j.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let S=[];if(v===void 0)return S;let C;if(n===`comma`&&T(v))h&&c&&(v=kt(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([[Pt,_]]);jt(S,Ft(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 It(e=j){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||j.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=bt;if(e.format!==void 0){if(!wt(St,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=St[n],i=j.filter;(typeof e.filter==`function`||T(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in At?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:j.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o;return o=e.allowDots===void 0?e.encodeDotInKeys?!0:j.allowDots:!!e.allowDots,{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:j.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?j.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:j.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:j.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:j.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:j.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:j.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:j.strictNullHandling}}function Lt(e,t={}){let n=e,r=It(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=At[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||jt(o,Ft(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 Rt(e){return Lt(e,{arrayFormat:`brackets`})}var zt=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 Bt(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=zt.get(e.dataResidency);if(t===void 0)throw new o("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return t}function Vt(e,t){if(e!=null)throw new o(`${t} does not support \`dataResidency\`.`)}var Ht,Ut=class e extends Promise{constructor(e,n,r=at){super(e=>{e(null)}),this.responsePromise=n,this.parseResponse=r,Ht.set(this,void 0),t(this,Ht,e,`f`)}_thenUnwrap(t){return new e(n(this,Ht,`f`),this.responsePromise,async(e,n)=>st(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,Ht,`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)}};Ht=new WeakMap;var Wt,Gt=class{constructor(e,n,r,i){Wt.set(this,void 0),t(this,Wt,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,Wt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Wt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Kt=class extends Ut{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await at(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},qt=class extends Gt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},M=class extends Gt{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}},N=class extends Gt{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}},Jt=class extends Gt{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}},Yt=class extends Gt{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}},Xt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},Zt=`urn:ietf:params:oauth:grant-type:token-exchange`,Qt=.5;function $t(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 en(e,t,n){let r=(n??1200)*1e3;return e-Math.min(r,t*1e3*Qt)}var tn=Response.prototype,nn=tn.arrayBuffer;function rn(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 an(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 on(e){return new TextDecoder(`utf-8`,{ignoreBOM:typeof globalThis.Bun?.version==`string`}).decode(e)}async function sn(e){let t,n=null;for(let r=0,i=e;i!==null&&r<16&&i!==tn;i=Object.getPrototypeOf(i),r+=1){rn(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`&&an(i,n)){t=a;break}return r.value.call(e)}let r=t===void 0?on(await nn.call(e)):await t.call(e);try{return JSON.parse(r)}catch{throw SyntaxError(`Token exchange response contains invalid JSON`)}}function cn(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 ln=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??ge()}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:Zt,subject_token:await this.config.provider.getToken(),subject_token_type:Xt[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 sn(r),a=typeof i==`object`&&i&&`access_token`in i?i.access_token:void 0;if(typeof a!=`string`||a.trim().length===0||cn(a))throw new o(`Token exchange response missing 'access_token' field`);let c=i.expires_in??3600,l=$t(c,n);return this.tokenGeneration===e&&(this.cachedToken={token:a,expiresAt:l,refreshAt:en(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 un(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(Ve(e))throw new o(`X.509 workload identity cannot send conflicting query authentication credentials.`);return t}var dn=Symbol(`brand.privateNullableHeaders`),fn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*pn(e){if(!e)return;if(dn 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 P=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of pn(r)){if(!fn.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{[dn]:!0,values:t,nulls:n}},mn=e.ot({findRegisteredX509Transport:()=>xn,findX509Credential:()=>Mn,findX509OAuthError:()=>An,isApprovedX509Client:()=>On,isRetryableX509IssuerError:()=>En,isTransientX509ConnectionError:()=>wn,markApprovedX509Client:()=>Dn,markRetryableX509IssuerError:()=>Tn,markTransientX509ConnectionError:()=>Cn,rememberRegisteredX509Transport:()=>Sn,rememberX509Credential:()=>jn,rememberX509OAuthError:()=>kn}),hn=new WeakMap,gn=new WeakSet,_n=new WeakSet,vn=new WeakSet,yn=new WeakMap,bn=new WeakMap,xn=WeakMap.prototype.get.bind(hn),Sn=WeakMap.prototype.set.bind(hn),Cn=WeakSet.prototype.add.bind(gn),wn=WeakSet.prototype.has.bind(gn),Tn=WeakSet.prototype.add.bind(_n),En=WeakSet.prototype.has.bind(_n),Dn=WeakSet.prototype.add.bind(vn),On=WeakSet.prototype.has.bind(vn),kn=WeakMap.prototype.set.bind(yn),An=WeakMap.prototype.get.bind(yn),jn=WeakMap.prototype.set.bind(bn),Mn=WeakMap.prototype.get.bind(bn),Nn=e.at(((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)}})),Pn=e.st(Nn(),1),{findRegisteredX509Transport:Fn,rememberRegisteredX509Transport:In,markTransientX509ConnectionError:Ln,isTransientX509ConnectionError:Rn,markRetryableX509IssuerError:zn,isRetryableX509IssuerError:Bn,markApprovedX509Client:Vn,isApprovedX509Client:Hn,rememberX509OAuthError:Un,findX509OAuthError:Wn,rememberX509Credential:Gn,findX509Credential:Kn}=typeof Pn.findRegisteredX509Transport==`function`?Pn:mn;function qn(e){if(!e||typeof e!=`object`)throw new o(`X.509 workload identity requires an approved X.509 transport capability.`);let t=Fn(e);if(!t)throw new o(`X.509 workload identity requires an approved X.509 transport capability.`);return t}var F,I,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`&&Ue(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(F.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,qn(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!P([t,n]).nulls.has(`authorization`)}snapshotHeaders(e,t){let r=n(this,F,`m`,R).call(this);return r.defaultHeaders??=P([e]),r.requestHeaders??=P([t]),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:t}=n(this,F,`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,F,`m`,R).call(this);return r.tenant={organization:e,project:t},r.tenant}tenantSnapshot(){let{tenant:e}=n(this,F,`m`,R).call(this);if(!e)throw new o(`X.509 workload identity requires snapshotted tenant selectors.`);return e}snapshotAPIURL(e){un(e),n(this,F,`m`,R).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=n(this,F,`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,F,`m`,R).call(this)).request??(i.request={signal:e,timeout:t,fetchOptions:r})}requestSnapshot(){let{request:e}=n(this,F,`m`,R).call(this);if(!e)throw new o(`X.509 workload identity requires snapshotted request settings.`);return e}beginRequestPreparation(){let e=n(this,F,`m`,R).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){n(this,F,`m`,R).call(this).phase=`planning`}beginRequestNetwork(){let e=n(this,F,`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,F,`m`,R).call(this).phase===`planning`}authorizePlannedRequest(e,t,r,i=!1){let a=n(this,F,`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,F,`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,F,`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,F,`m`,R).call(this),t=e.materializedBody;delete e.materializedBody,t&&n(I,I,`m`,ir).call(I,t)}releaseRequestBody(e){let t=n(this,F,`m`,R).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?n(this,F,`m`,R).call(this).effectiveSignal=e:delete n(this,F,`m`,R).call(this).effectiveSignal}effectiveSignal(){let e=n(this,F,`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,F,`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,F,`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&&(Rn(e)||Bn(e))}static retryHeaders(e){if(!e||typeof e!=`object`||!Bn(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,F,`m`,dr).call(this,t);let i=e?n(this,F,`m`,R).call(this):void 0,a=n(this,tr,`f`);if(a&&performance.now()<a.refreshAt&&Date.now()<a.wallRefreshAt)return n(I,I,`m`,ar).call(I,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,F,`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(I,I,`m`,ar).call(I,i,t)}catch(r){return await n(this,F,`m`,or).call(this,r,l,a,i,e,t)}finally{u.dispose(),s(),--l.waiters,n(this,F,`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,F,`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,F,`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,F,`m`,fr).call(this,t),vr(t)}fetch(){return async(e,t={})=>{let r=un(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)}}};I=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,F=new WeakSet,ir=async function(e){try{await be(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,F,`m`,sr).call(this,e,r,i);if(c!==void 0)return c;if(e&&typeof e==`object`&&!(e instanceof S)){let t=Wn(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||!I.isRetryableFailure(e))return;let i=I.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(I,I,`m`,ar).call(I,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,F,`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.`);un(e.apiURL);let t=P([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(Ue(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=Kn(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=ve($r(i,a,t,r));return{...e,body:o,headers:P([{"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 Se(`--${t}\r\n`),yield Se(`Content-Disposition: form-data; name="${si(i)}"; filename="${si(e)}"\r\nContent-Type: ${o}\r\n\r\n`),yield*oi(ai(a))}else yield Se(`--${t}\r\n`),yield Se(`Content-Disposition: form-data; name="${si(i)}"\r\n\r\n${String(a)}`);yield Se(`\r
6
- `)}yield Se(`--${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 Se(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 ye(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(ve(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),yi=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function bi(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=>yi.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!yi.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 xi=class extends z{list(e,t={},n){let r=bi(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/chat/completions/${e}/messages`,M,{query:t,...n,__security:{bearerAuth:!0}})}};function Si(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Ci(e){return e?.$brand===`auto-parseable-response-format`}function wi(e){return Ci(e)||e?.type===`json_schema`}function Ti(e,t){if(!wi(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 Ei(e){return e?.$brand===`auto-parseable-tool`}function Di(e,t){return!t||!Mi(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}}))}:Oi(e,t)}function Oi(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=>Ai(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)?ki(t,e.message.content):null}}});return{...e,choices:n}}function ki(e,t){return Ti(e.response_format,t)}function Ai(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=>Si(e)&&e.function?.name===t.function.name),r=null;return Ei(n)?r=n.$parseRaw(t.function.arguments):n?.function.strict&&(r=Ti({type:`json_schema`,$parseRaw:void 0},t.function.arguments)),{...t,function:{...t.function,parsed_arguments:r}}}function ji(e,t){if(!e||!(`tools`in e)||!e.tools||t.type!==`function`)return!1;let n=e.tools?.find(e=>Si(e)&&e.function?.name===t.function?.name);return Si(n)&&(Ei(n)||n?.function.strict||!1)}function Mi(e){return wi(e.response_format)?!0:e.tools?.some(e=>Ei(e)||e.type===`function`&&e.function.strict===!0)??!1}function Ni(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 Pi=e=>e?.role===`assistant`,Fi=e=>e?.role===`tool`,Ii,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=4096,ca=8388608,la=4096,ua=256,da=JSON.stringify,fa=JSON.parse,pa=new WeakSet,ma=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`buffer`)?.get,ha=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`length`)?.get,ga=Object.getOwnPropertyDescriptor(DataView.prototype,`buffer`)?.get,_a=Object.getOwnPropertyDescriptor(Symbol.prototype,`description`)?.get,va=Date.prototype.getTime,ya=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,`byteLength`)?.get,ba=typeof SharedArrayBuffer==`function`?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,`byteLength`)?.get:void 0,xa=Object.getOwnPropertyDescriptor(Error(`native stack descriptor`),`stack`),Sa=Function.prototype.toString,Ca=Object.prototype.toString,wa=Object.getOwnPropertyDescriptor(Error,`isError`),Ta=wa&&`value`in wa&&typeof wa.value==`function`?wa.value:void 0,Ea=Sa.call(Error),Da=Sa.call(Date),Oa=Sa.call(Function),ka=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]),Aa=new Set,ja=new Map,Ma=new WeakMap;function Na(){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 Pa=Na();function Fa(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;ka.add(t.value);let n=Sa.call(e);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n)&&t.configurable===!1&&t.writable===!1){Aa.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)}ja.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])Fa(e);for(let e of[`SharedArrayBuffer`,`AggregateError`,`Float16Array`,`BigInt64Array`,`BigUint64Array`,`Blob`,`File`,`Headers`]){let t=Object.getOwnPropertyDescriptor(globalThis,e);t&&`value`in t&&Fa(t.value)}var Ia=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`constructor`);Ia&&`value`in Ia&&Fa(Ia.value),typeof Buffer==`function`&&Fa(Buffer);var La=(()=>{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}})(),Ra=Map.prototype.entries,za=Set.prototype.values,Ba=typeof Headers==`function`?Object.getOwnPropertyDescriptor(Headers.prototype,`entries`):void 0,Va=Ba&&`value`in Ba&&typeof Ba.value==`function`?Ba.value:void 0,Ha=new Set([`ArrayBuffer`,`SharedArrayBuffer`,`Blob`,`File`,`Map`,`Date`,`Set`,`Headers`]);function Ua(e){let t=Object.getOwnPropertyDescriptor(e,`constructor`);if(!t||!(`value`in t)||typeof t.value!=`function`)return;let n=t.value,r=Sa.call(n),i=ja.get(r);if(!Aa.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 Wa(e){return ka.has(e)||Ua(e)!==void 0}function Ga(e,t,n){if(t===void 0)return e===void 0;if(typeof e!=`function`||typeof t!=`function`)return!1;let r=Sa.call(t);if(Sa.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=Ua(i);return a!==void 0&&Sa.call(a.constructor)===Oa}function Ka(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`?Ga(e.value,t.value,n):t.value!==null&&typeof t.value==`object`?!1:Object.is(e.value,t.value):!1:Ga(e.get,t.get,n)&&Ga(e.set,t.set,n)}function qa(e){if(Ta)return Ta.call(Error,e);let t=e;for(let e=0;t!==null&&e<ua;e+=1){if(Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))return!1;t=Object.getPrototypeOf(t)}return t===null&&Ca.call(e)===`[object Error]`}function Ja(e,t){if(typeof t.get!=`function`||typeof t.set!=`function`)return;let n=Object.getPrototypeOf(e);for(let e=0;n!==null&&e<ua;e+=1){let e=Object.getOwnPropertyDescriptor(n,`constructor`);if(e&&`value`in e&&typeof e.value==`function`){let r=e.value;if(Sa.call(r)===Ea&&Wa(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 Ya(e,t){if(!qa(e))return!1;if(xa&&!(`value`in xa)&&typeof xa.get==`function`&&Object.prototype.isPrototypeOf.call(Error.prototype,e)&&t.get===xa.get&&t.set===xa.set)return!0;let n=Ja(e,t);if(!n)return!1;let r=Ma.get(n.prototype);if(!r){let e=Reflect.construct(n.constructor,[]);if(typeof e!=`object`||!e||!qa(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;Ma.set(n.prototype,r)}return t.get===r.get&&t.set===r.set}function Xa(){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 Za(e){let t=Object.getPrototypeOf(e);for(let e=0;t!==null&&e<ua;e+=1){if(t===Date.prototype)return`Date`;if(!ka.has(t)){let e=Object.getOwnPropertyDescriptor(t,`constructor`);if(e&&`value`in e&&typeof e.value==`function`&&Sa.call(e.value)===Da&&Ua(t))return`Date`}let e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);if(e&&`value`in e&&typeof e.value==`string`&&Ha.has(e.value))return e.value;t=Object.getPrototypeOf(t)}}function Qa(e,t,n){if(ArrayBuffer.isView(e)){let r,i=`typed-array`;try{r=ma?.call(e)}catch{i=`data-view`,r=ga?.call(e)}return typeof r!=`object`||!r?{bytes:1/0,kind:i}:(t(r,n+1),{bytes:0,kind:i})}let r=Za(e);if(!r)return;let i;switch(r){case`ArrayBuffer`:i=ya;break;case`SharedArrayBuffer`:i=ba;break;case`Blob`:case`File`:return{bytes:1/0,kind:`blob`};case`Map`:return{bytes:0,kind:`map`};case`Date`:return Reflect.apply(va,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 $a(e,t,n){if(t===`map`){for(let[t,r]of Ra.call(e))if(!n(t,8)||!n(r,8))return!1}if(t===`set`){for(let t of za.call(e))if(!n(t,8))return!1}if(t===`headers`){if(!Va)return!1;for(let[t,r]of Va.call(e))if(!n(t,8)||!n(r,8))return!1}return!0}function eo(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=ha?.call(e);if(!(typeof r!=`number`||!Number.isSafeInteger(r)||r<0||r>la))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 to(e,t,n,r,i,a){let o=eo(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`&&Ya(e,o))continue;return!1}a(o.value,n+1,t===`blob`)}return!0}function no(e,t,n,r,i,a,o,s){let c=Object.getPrototypeOf(e);for(let e=t+1;c!==null;e+=1){if(e>=ua)return!1;if(ka.has(c)||n&&c===La)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=Ua(t);if(!n)return to(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(!Ka(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 ro=32,io=32,ao=8,oo=16,so=131072;function co(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(!_a)return!1;let t=Reflect.apply(_a,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(Pa?.(e)){n=t+1;return}if(r>=ua){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=Qa(e,m,r);return!no(e,r,a,i,l,u,m,f)||o!==void 0&&!u(o.bytes)||!$a(e,o?.kind,(e,i)=>u(i)?(m(e,r+1),n<=t):!1)?!1:to(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 lo(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function uo(e,t){return e.bytes+io+e.edges.size*ao+t*oo}function fo(e){return ro+e.scalarBytes+e.roots.size*ao}function po(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 mo(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 ho(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=!lo(s.edges,o.edges);if((s.bytes!==o.bytes||c)&&mo(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 go(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=mo(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=mo(o,n,r,i);if(!e)return!1;e.ownerDelta+=1}}return!0}function _o(e,t,n,r,i,a){let o=new Map;for(let s of n){let n=po(s===e?t.roots:s.roots,t.nodes,r,a);if(!n||!go(s,n,t,r,i,a))return;o.set(s,n)}return o}function vo(e,t,n,r,i,a){let o=e-(r?0:fo(t))+fo(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-=uo(n,n.owners.size)),r&&(o+=uo(t.node,r))}return Number.isSafeInteger(o)&&o>=0&&o<=ca?o:void 0}function yo(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 bo(){let e=new Map,t=0,n=(n,r,i)=>{let a={remaining:so},o=new Map,s=ho(n,r,e,o,a);if(!s)return!1;let c=_o(n,r,s,e,o,a);if(!c)return!1;let l=vo(t,n,r,i,o,e);return l!==void 0&&(yo(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-=fo(n);for(let r of n.identities){let i=e.get(r);i?.owners.delete(n)&&(t-=oo,i.owners.size===0&&(t-=uo(i,0),e.delete(r)))}n.identities.clear()},clear(){e.clear(),t=0}}}var xo=class{constructor(){Ii.add(this),this.controller=new AbortController,Li.set(this,void 0),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,Object.create(null)),Wi.set(this,[]),Gi.set(this,new WeakMap),Ki.set(this,new Set),qi.set(this,new Set),Ji.set(this,0),Yi.set(this,!1),Xi.set(this,!1),Zi.set(this,!1),Qi.set(this,!1),$i.set(this,void 0),t(this,Li,new Promise((e,n)=>{t(this,Ri,e,`f`),t(this,zi,n,`f`)}),`f`),t(this,Bi,new Promise((e,n)=>{t(this,Vi,e,`f`),t(this,Hi,n,`f`)}),`f`),n(this,Li,`f`).catch(()=>void 0),n(this,Bi,`f`).catch(()=>void 0)}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(e=>{t=!0,n(this,Ii,`m`,aa).call(this,e)}).then(()=>{if(!t){try{this._emitFinal()}catch(e){n(this,Ii,`m`,aa).call(this,e);return}this._emit(`end`)}})},0)}_connected(){this.ended||(n(this,Ri,`f`).call(this),this._emit(`connect`))}get ended(){return n(this,Yi,`f`)}get errored(){return n(this,Xi,`f`)}get aborted(){return n(this,Zi,`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,Ii,`m`,ea).call(this,e);return}if(n(this,Wi,`f`).some(t=>t.signal===e))return;let t=()=>n(this,Ii,`m`,ea).call(this,e);e.addEventListener(`abort`,t,{once:!0}),n(this,Wi,`f`).push({signal:e,listener:t})}on(e,t){var r;return((r=n(this,Ui,`f`))[e]||(r[e]=[])).push({listener:t}),this}off(e,t){let r=n(this,Ui,`f`)[e];if(!r)return this;let i=n(this,Gi,`f`).get(t);if(i?.event===e&&!i.registration.removed&&!i.registration.detached)return n(this,Ii,`m`,ra).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,Ui,`f`))[e]||(r[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((r,i)=>{t(this,Qi,!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,Ii,`m`,na).call(this,`error`,a),n(this,Ii,`m`,na).call(this,e,o)})}events(e){return this._createIterator(t=>{let n=(...e)=>{pa.add(e);try{t(e)}finally{pa.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=Xa(),s=Xa(),c=Xa(),l=bo(),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,qi,`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 (${sa} events or ${ca} bytes); consume events as they arrive.`);try{n(this,Ii,`m`,aa).call(this,t)}finally{this.controller.abort()}return t},b=(e,t)=>{if(!t.active||n(this,Yi,`f`))return;let r=co(e,ca);(!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>=sa){y();return}let t=co(e,ca),r=t&&l.retain(t);if(!r){y();return}if(typeof e==`object`&&e&&pa.has(e)){let t=e;for(let e=0;e<t.length;e+=1){let n=t[e];typeof n==`string`&&(t[e]=fa(da(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,qi,`f`).add(o)}},S=e=>{d=e,a.length||g()},C=()=>{if(d)return;let e=n(this,$i,`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=co(e,ca);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,Qi,!0,`f`),await n(this,Bi,`f`)}_hasListeners(e){return!!n(this,Ui,`f`)[e]?.some(e=>!e.removed)}_emit(e,...r){if(n(this,Yi,`f`))return;e===`end`&&(n(this,Ii,`m`,ta).call(this),t(this,Yi,!0,`f`),n(this,Vi,`f`).call(this));let i=n(this,Ui,`f`)[e],a,o=!1;try{if(i){n(this,Ui,`f`)[e]=i.filter(e=>(e.once&&(e.detached=!0),!e.once&&!e.removed)),t(this,Ji,n(this,Ji,`f`)+1,`f`);try{for(let e of i)if(!e.removed){let{listener:t}=e;t(...r)}}finally{if(t(this,Ji,n(this,Ji,`f`)-1,`f`),n(this,Ji,`f`)===0){n(this,Ii,`m`,ia).call(this);for(let e of n(this,qi,`f`))n(this,qi,`f`).delete(e),n(this,Yi,`f`)||e()}}}}catch(e){a=e,o=!0}try{n(this,Ii,`m`,oa).call(this,e,r,!!i?.length)}catch(e){o||=(a=e,!0)}if(o)throw a}_emitFinal(){}};Li=new WeakMap,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,Ii=new WeakSet,ea=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},ta=function(){for(let{signal:e,listener:t}of n(this,Wi,`f`).splice(0))e.removeEventListener(`abort`,t)},na=function(e,t){let r=n(this,Ui,`f`)[e],i=r?.length??0;this.once(e,t);let a=n(this,Ui,`f`)[e],[o]=a?.slice(-1)??[];(r===void 0||a===r)&&a?.length===i+1&&o?.listener===t&&o.once&&n(this,Gi,`f`).set(t,{event:e,registration:o})},ra=function(e,t){t.removed||(t.removed=!0,n(this,Gi,`f`).delete(t.listener),n(this,Ki,`f`).add(e),n(this,Ji,`f`)===0&&n(this,Ii,`m`,ia).call(this))},ia=function(){for(let e of n(this,Ki,`f`)){let t=e,r=n(this,Ui,`f`)[t];r&&(n(this,Ui,`f`)[t]=r.filter(e=>!e.removed))}n(this,Ki,`f`).clear()},aa=function(e){if(t(this,Xi,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=this._userAbortError()),e instanceof c)return t(this,Zi,!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)))},oa=function(e,r,i){if(e===`abort`){let e=r[0];t(this,$i,n(this,$i,`f`)??{kind:`abort`,error:e},`f`),!n(this,Qi,`f`)&&!i&&Promise.reject(e),n(this,zi,`f`).call(this,e),n(this,Hi,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=r[0];t(this,$i,n(this,$i,`f`)??{kind:`error`,error:e},`f`),!n(this,Qi,`f`)&&!i&&Promise.reject(e),n(this,zi,`f`).call(this,e),n(this,Hi,`f`).call(this,e),this._emit(`end`)}};function So(e){return typeof e.parse==`function`}var V,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po=10;function Fo(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||=`call_${r()}`}function Io(e){if(!Pi(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 Lo=class extends xo{constructor(){super(...arguments),V.add(this),this._chatCompletions=[],wo.set(this,!1),To.set(this,!1),this.messages=[]}_addChatCompletion(e){t(this,wo,!this.controller.signal.aborted,`f`),Fo(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),Fi(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Pi(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`,Eo).call(this)}async finalMessage(){return await this.done(),n(this,V,`m`,Do).call(this)}async finalFunctionToolCall(){return await this.done(),n(this,V,`m`,Oo).call(this)}async finalFunctionToolCallResult(){return await this.done(),n(this,V,`m`,ko).call(this)}async totalUsage(){return await this.done(),n(this,V,`m`,Ao).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){n(this,To,`f`)&&n(this,V,`m`,jo).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=n(this,V,`m`,Do).call(this);t&&this._emit(`finalMessage`,t);let r=n(this,V,`m`,Eo).call(this);r&&this._emit(`finalContent`,r);let i=n(this,V,`m`,Oo).call(this);i&&this._emit(`finalFunctionToolCall`,i);let a=n(this,V,`m`,ko).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,n(this,V,`m`,Ao).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),n(Co,Co,`m`,Mo).call(Co,t);let i=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Oi(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=Po,afterCompletion:h}=a||{},g=async e=>{h!=null&&(t(this,To,!0,`f`),await h(e,i),n(this,V,`m`,jo).call(this))},_=r.tools.map(e=>{if(Ei(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(So(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(Co,Co,`m`,No).call(Co,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(Io)},a);b=this.controller.signal.aborted&&n(this,wo,`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)}}};Co=Lo,wo=new WeakMap,To=new WeakMap,V=new WeakSet,Eo=function(){return n(this,V,`m`,Do).call(this).content??null},Do=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Pi(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new o(`stream ended without producing a ChatCompletionMessage with role=assistant`)},Oo=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Pi(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}}},ko=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Fi(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}},Ao=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},jo=function(){if(this.controller.signal.aborted)throw this._userAbortError()},Mo=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.`)},No=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var Ro=class e extends Lo{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&&Pi(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},zo=class extends Error{},Bo=class extends Error{};function Vo(e,t=H.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Ho(e.trim(),t)}var Ho=(e,t)=>{let n=e.length,r=0,i=e=>{throw new zo(`${e} at position ${r}`)},a=e=>{throw new Bo(`${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()},Uo=e=>Vo(e,H.ALL^H.NUM),U,W,Wo,Go,Ko,qo,Jo,Yo,Xo,Zo,Qo,$o,es,ts,ns,rs;function is(e){try{return Uo(e)}catch(t){if(t instanceof Bo||t instanceof SyntaxError)return Ti({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(Si(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`),G=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 G;if(t.nodes+=1,e===void 0||typeof e==`function`||typeof e==`symbol`)return Ps;if(typeof e==`bigint`)return G;if(e===null||typeof e==`boolean`||typeof e==`number`){let t=js(e);return typeof t==`string`&&r(t.length)?t:G}if(typeof e==`string`)return r(e.length*6+2)?js(e):G;if(typeof e!=`object`||n.has(e))return G;let o=Array.isArray(e),s=Object.getPrototypeOf(e);if(o&&s!==Array.prototype||!o&&s!==null&&s!==Object.prototype)return G;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 G;break}}n.add(e);try{if(!r(2))return G;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 G;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 G;s.push(`null`);continue}if(!(`value`in c))return G;let l=i(c.value,a+1);if(l===G)return l;s.push(l===Ps?`null`:l)}return`[${s.join(`,`)}]`}let n=Reflect.ownKeys(e);if(n.length>As-t.nodes)return G;let s=[];for(let t of n){if(typeof t!=`string`)continue;let n=Object.getOwnPropertyDescriptor(e,t);if(!n)return G;if(n.enumerable){if(!(`value`in n))return G;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===G)return n;if(n!==Ps){if(!r(e.length*6+3))return G;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 vt(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 Lo{constructor(e){super(),U.add(this),W.set(this,void 0),Wo.set(this,!1),Go.set(this,void 0),Ko.set(this,void 0),qo.set(this,void 0),Jo.set(this,void 0),Yo.set(this,void 0),t(this,W,e,`f`),t(this,Go,new Set,`f`),t(this,Ko,[],`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(Si(i)&&(Ei(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,qo,`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,Wo,!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=>Si(e)&&(Ei(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=>Si(e)&&(Ei(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=Qe.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,qo,`f`)){let e=n(this,qo,`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,qo,`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,Wo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,qo=new WeakMap,Jo=new WeakMap,Yo=new WeakMap,U=new WeakSet,Xo=function(){this.ended||(t(this,Go,new Set,`f`),t(this,qo,void 0,`f`),t(this,Yo,{bytes:0,fragments:0,work:0},`f`))},Zo=function(e){let t=n(this,Ko,`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,Ko,`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=wi(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=>Si(e)&&e.function.name===i.function.name),s=null,c=Ei(a)||a?.function.strict===!0,l;if(c){n(this,qo,`f`)&&n(this,U,`m`,ts).call(this,n(this,qo,`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;Ei(a)?s=a.$parseRaw(ws(l)):a?.function.strict&&(s=Ti({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=wi(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,qo,`f`)&&n(this,U,`m`,ts).call(this,n(this,qo,`f`)),t.content_done=!0,this._emit(`content.done`,{content:c,parsed:o?null:Ti(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=wi(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,Ko,`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(!ji(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,qo,`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,Go,`f`);return t(this,Go,new Set,`f`),t(this,qo,void 0,`f`),t(this,Ko,[],`f`),Gs(e,n(this,W,`f`),i,r)},rs=function(e,r){var i,a,s,c,l;let u=n(this,qo,`f`),{choices:d,obfuscation:f,...p}=e;if(u)e.id&&Ds(u,p);else{let e={...p,choices:[]};t(this,qo,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((wi(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,Wo,`f`)||Mi(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,Go,`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,Go,`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&&wi(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=>Si(t)&&t.function.name===e.name);if(e&&(h={...e,parseable:t!==void 0&&ji(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 Qe(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 Di({...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&&ji(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(Pi(r)){t=r.tool_calls?.map(e=>e.id);return}if(Fi(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 Qe(()=>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}},Js=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Ys(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=>Js.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Js.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 Xs=class extends z{constructor(){super(...arguments),this.messages=new xi(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(B`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){let n=Ys(e,[`after`,`limit`,`metadata`,`model`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/chat/completions`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Ni(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:`chat.completions.parse`}})._thenUnwrap(t=>Oi(t,e))}runTools(e,t){return e.stream?qs.runTools(this._client,e,t):Ro.runTools(this._client,e,t)}stream(e,t){return Ws.createChatCompletion(this._client,e,t)}};Xs.Messages=xi;var Zs=class extends z{constructor(){super(...arguments),this.completions=new Xs(this._client)}};Zs.Completions=Xs;var Qs=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function $s(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=>Qs.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Qs.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 ec=class extends z{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(B`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=$s(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/admin_api_keys`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},tc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function nc(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=>tc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!tc.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 rc=class extends z{list(e={},t){let n=nc(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`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},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{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){let r=ac(t,[`include`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.get(B`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=ac(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/certificates`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,qt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,qt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},sc=class extends z{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},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/external_storage`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(B`/organization/external_storage/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=lc(e,[`after`,`limit`,`order`,`project_id`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/external_storage`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/external_storage/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}validate(e,t){return this._client.post(B`/organization/external_storage/${e}/validate`,{...t,__security:{adminAPIKeyAuth:!0}})}},dc=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=>dc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!dc.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 pc=class extends z{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(B`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=fc(e,[`after`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/invites`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},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/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(B`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=hc(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/roles`,Jt,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},_c=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function vc(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=>_c.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!_c.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 yc=class extends z{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(B`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=vc(e,[`after`,`before`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/spend_alerts`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},bc=class extends z{retrieve(e){return this._client.get(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/spend_limit`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}},xc=class extends z{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},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,n){return this._client.post(B`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(B`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=Cc(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/groups/${e}/roles`,Jt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(B`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Tc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Ec(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=>Tc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Tc.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 Dc=class extends z{create(e,t,n){return this._client.post(B`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(B`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=Ec(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/groups/${e}/users`,Jt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(B`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Oc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function kc(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=>Oc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Oc.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 Ac=class extends z{constructor(){super(...arguments),this.users=new Dc(this._client),this.roles=new wc(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(B`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=kc(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/groups`,Jt,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Ac.Users=Dc,Ac.Roles=wc;var jc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Mc(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=>jc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!jc.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{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=Mc(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`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},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{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/projects/${e}/certificates`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(B`/organization/projects/${e}/certificates/activate`,qt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(B`/organization/projects/${e}/certificates/deactivate`,qt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},Lc=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},Rc=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},zc=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},Bc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Vc(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=>Bc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Bc.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 Hc=class extends z{listRateLimits(e,t={},n){let r=Vc(t,[`after`,`before`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/rate_limits`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},Uc=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Wc(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=>Uc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Uc.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,n){return this._client.post(B`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=Wc(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/projects/${e}/roles`,Jt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},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{create(e,t,n){return this._client.post(B`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=qc(t,[`after`,`before`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/spend_alerts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Yc=class extends z{retrieve(e,t){return this._client.get(B`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}},Xc=class extends z{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(B`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(B`/projects/${r}/groups/${e}/roles`,Jt,{query:i,...n,__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}`,{...n,__security:{adminAPIKeyAuth:!0}})}},Zc=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=>Zc.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Zc.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 $c=class extends z{constructor(){super(...arguments),this.roles=new Xc(this._client)}create(e,t,n){return this._client.post(B`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(B`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=Qc(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/groups`,Jt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};$c.Roles=Xc;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`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},tl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function nl(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=>tl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!tl.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 rl=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`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=nl(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/service_accounts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};rl.APIKeys=el;var il=class extends z{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(B`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(B`/projects/${r}/users/${e}/roles`,Jt,{query:i,...n,__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}`,{...n,__security:{adminAPIKeyAuth:!0}})}},al=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ol(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=>al.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!al.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 sl=class extends z{constructor(){super(...arguments),this.roles=new il(this._client)}create(e,t,n){return this._client.post(B`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(B`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(B`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=ol(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/projects/${e}/users`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(B`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};sl.Roles=il;var cl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ll(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=>cl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!cl.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 ul=class extends z{constructor(){super(...arguments),this.users=new sl(this._client),this.serviceAccounts=new rl(this._client),this.apiKeys=new Nc(this._client),this.rateLimits=new Hc(this._client),this.modelPermissions=new zc(this._client),this.hostedToolPermissions=new Rc(this._client),this.groups=new $c(this._client),this.roles=new Gc(this._client),this.dataRetention=new Lc(this._client),this.spendLimit=new Yc(this._client),this.spendAlerts=new Jc(this._client),this.certificates=new Ic(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(B`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=ll(e,[`after`,`include_archived`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/projects`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(B`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};ul.Users=sl,ul.ServiceAccounts=rl,ul.APIKeys=Nc,ul.RateLimits=Hc,ul.ModelPermissions=zc,ul.HostedToolPermissions=Rc,ul.Groups=$c,ul.Roles=Gc,ul.DataRetention=Lc,ul.SpendLimit=Yc,ul.SpendAlerts=Jc,ul.Certificates=Ic;var dl=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=>dl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!dl.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 pl=class extends z{create(e,t,n){return this._client.post(B`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(B`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=fl(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/organization/users/${e}/roles`,Jt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(B`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},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{constructor(){super(...arguments),this.roles=new pl(this._client)}retrieve(e,t){return this._client.get(B`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(B`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){let n=hl(e,[`after`,`emails`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/organization/users`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(B`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};gl.Roles=pl;var _l=class extends z{constructor(){super(...arguments),this.externalStorage=new uc(this._client),this.auditLogs=new rc(this._client),this.adminAPIKeys=new ec(this._client),this.usage=new xc(this._client),this.invites=new pc(this._client),this.users=new gl(this._client),this.groups=new Ac(this._client),this.roles=new gc(this._client),this.dataRetention=new sc(this._client),this.spendLimit=new bc(this._client),this.spendAlerts=new yc(this._client),this.certificates=new oc(this._client),this.projects=new ul(this._client)}};_l.ExternalStorage=uc,_l.AuditLogs=rc,_l.AdminAPIKeys=ec,_l.Usage=xc,_l.Invites=pc,_l.Users=gl,_l.Groups=Ac,_l.Roles=gc,_l.DataRetention=sc,_l.SpendLimit=bc,_l.SpendAlerts=yc,_l.Certificates=oc,_l.Projects=ul;var vl=class extends z{constructor(){super(...arguments),this.organization=new _l(this._client)}};vl.Organization=_l;var yl=class extends z{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:P([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},bl=class extends z{create(e,t){return this._client.post(`/audio/transcriptions`,Vr({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},xl=class extends z{create(e,t){return this._client.post(`/audio/translations`,Vr({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Sl=class extends z{constructor(){super(...arguments),this.transcriptions=new bl(this._client),this.translations=new xl(this._client),this.speech=new yl(this._client)}};Sl.Transcriptions=bl,Sl.Translations=xl,Sl.Speech=yl;var Cl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function wl(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=>Cl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Cl.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 Tl=class extends z{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){let n=wl(e,[`after`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/batches`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(B`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},El=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=>El.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!El.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 Ol=class extends z{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(B`/assistants/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){let n=Dl(e,[`after`,`before`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/assistants`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},kl=class extends z{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Al=class extends z{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},jl=class extends z{constructor(){super(...arguments),this.sessions=new kl(this._client),this.transcriptionSessions=new Al(this._client)}};jl.Sessions=kl,jl.TranscriptionSessions=Al;var Ml=class extends z{create(e,t,n){return this._client.post(B`/agents/environments/${e}/files`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(B`/agents/environments/${e}/files`,Yt,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Nl=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Pl(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=>Nl.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Nl.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){return this._client.post(`/agents/environments/templates`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/agents/environments/templates/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(B`/agents/environments/templates/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){let n=Pl(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/agents/environments/templates`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/agents/environments/templates/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}},Il=class extends z{constructor(){super(...arguments),this.files=new Ml(this._client),this.templates=new Fl(this._client)}retrieve(e,t){return this._client.get(B`/agents/environments/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};Il.Files=Ml,Il.Templates=Fl;var Ll,Rl,zl,Bl,Vl=class{constructor(){Ll.set(this,void 0),Rl.set(this,!1),zl.set(this,new Set),Bl.set(this,new Set)}accept(e){if(n(this,zl,`f`).has(e.event_id))return!1;if(n(this,zl,`f`).size===1024){let e=n(this,zl,`f`).values().next();e.done||n(this,zl,`f`).delete(e.value)}return n(this,zl,`f`).add(e.event_id),e.type===`agent.session.turn.created`&&e.turn.subagent_id===null&&n(this,Ll,`f`)===void 0&&t(this,Ll,e.turn_id,`f`),(e.type===`agent.session.turn.completed`||e.type===`agent.session.turn.failed`||e.type===`agent.session.turn.cancelled`)&&n(this,Ll,`f`)!==void 0&&e.turn_id===n(this,Ll,`f`)&&t(this,Rl,!0,`f`),!0}terminal(e){return e.type===`agent.session.failed`||e.type===`agent.session.idle`&&n(this,Rl,`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,Bl,`f`).has(r))return n(this,Bl,`f`).add(r),t}};Ll=new WeakMap,Rl=new WeakMap,zl=new WeakMap,Bl=new WeakMap;var K,Hl,Ul,Wl,Gl,Kl,ql,Jl,Yl,Xl,Zl,Ql,$l,eu,tu,nu,ru;function iu(e){if(!ie(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`}function au(e){if(e===null)return null;if(typeof e==`string`||Array.isArray(e)&&e.every(iu))return e;throw new o(`Tool output must be text, content, a JSON object, or null`)}function ou(e,t){let n=ie(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:au(typeof n==`string`?n:JSON.parse(r))}}async function su(e){try{await e?.body?.cancel()}catch{}}var cu=class{constructor(e,n,i,a){K.add(this),this.controller=new AbortController,Hl.set(this,!1),Ul.set(this,void 0),Wl.set(this,void 0),Gl.set(this,!1),Kl.set(this,void 0),ql.set(this,void 0),Jl.set(this,void 0),Yl.set(this,void 0),Xl.set(this,void 0),Zl.set(this,void 0);let s=typeof i.input==`string`?[{role:`user`,content:[{type:`input_text`,text:i.input}]}]:i.input;if(i.input.length===0)throw new o(`input must not be empty`);t(this,Kl,e,`f`),t(this,ql,n,`f`),t(this,Jl,{type:`agent.session.input.message`,input:s},`f`),t(this,Yl,new Map(Object.entries(i.toolHandlers??{})),`f`);let c=P([a?.headers]);t(this,Xl,c.nulls.has(`idempotency-key`)?void 0:c.values.get(`idempotency-key`)??i.idempotencyKey??a?.idempotencyKey??r(),`f`),c.values.delete(`idempotency-key`),c.nulls.delete(`idempotency-key`);let{idempotencyKey:l,...u}=a??{};t(this,Zl,{...u,headers:c},`f`)}abort(e){this.controller.abort(e),n(this,Ul,`f`)?.controller.abort(this.controller.signal.reason),n(this,Gl,`f`)||su(n(this,Wl,`f`))}[(Hl=new WeakMap,Ul=new WeakMap,Wl=new WeakMap,Gl=new WeakMap,Kl=new WeakMap,ql=new WeakMap,Jl=new WeakMap,Yl=new WeakMap,Xl=new WeakMap,Zl=new WeakMap,K=new WeakSet,Symbol.asyncIterator)](){if(n(this,Hl,`f`))throw new o(`An AgentSessionStream can only be consumed once`);return t(this,Hl,!0,`f`),n(this,K,`m`,Ql).call(this)}};Ql=async function*(){let e=n(this,Zl,`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,Zl,`f`),signal:this.controller.signal},a=new Vl;try{if(e?.aborted&&this.abort(e.reason),n(this,K,`m`,eu).call(this),(await n(this,Kl,`f`).retrieve(n(this,ql,`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,Kl,`f`).events.stream(n(this,ql,`f`),i).withResponse();t(this,Ul,r.data,`f`),t(this,Wl,r.response,`f`),n(this,K,`m`,eu).call(this),await n(this,Kl,`f`).events.create(n(this,ql,`f`),{events:[n(this,Jl,`f`)],...n(this,Xl,`f`)===void 0?{}:{"Idempotency-Key":n(this,Xl,`f`)}},{...i,headers:P([i.headers,{"Idempotency-Key":n(this,Xl,`f`)??null}])}),n(this,K,`m`,eu).call(this),t(this,Gl,!0,`f`);for await(let e of n(this,Ul,`f`)){if(n(this,K,`m`,eu).call(this),!a.accept(e))continue;let t=a.terminal(e),r=a.call(e),o=r&&n(this,Yl,`f`).get(r.name),s=r&&o?structuredClone(r):void 0;if(t&&n(this,Ul,`f`).controller.abort(),yield e,t)return;if(n(this,K,`m`,eu).call(this),!s||!o)continue;let c=await n(this,K,`m`,$l).call(this,s,o);n(this,K,`m`,eu).call(this),await n(this,K,`m`,ru).call(this,c,i)}throw n(this,K,`m`,eu).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()}},$l=async function(e,t){try{let r=typeof e.arguments==`string`?JSON.parse(e.arguments):e.arguments;if(!ie(r))throw new o(`Function arguments must be a JSON object`);return ou(e,await n(this,K,`m`,nu).call(this,()=>t(r)))}catch{return n(this,K,`m`,eu).call(this),{type:`agent.session.input.tool_result`,turn_id:e.turn_id,call_id:e.call_id,success:!1,error:`Tool handler failed.`}}},eu=function(){if(this.controller.signal.aborted)throw n(this,K,`m`,tu).call(this)},tu=function(){let e=new c;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e},nu=async function(e){let t,r=new Promise((e,r)=>{t=()=>r(n(this,K,`m`,tu).call(this)),this.controller.signal.addEventListener(`abort`,t,{once:!0})});try{return n(this,K,`m`,eu).call(this),await Promise.race([(async()=>await e())(),r])}finally{t&&this.controller.signal.removeEventListener(`abort`,t)}},ru=async function e(t,i,a=r(),o=0){n(this,K,`m`,eu).call(this);try{await n(this,Kl,`f`).events.create(n(this,ql,`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,K,`m`,nu).call(this,()=>new Promise(e=>{c=setTimeout(e,s)}))}finally{c!==void 0&&clearTimeout(c)}await n(this,K,`m`,e).call(this,t,i,a,o+1)}};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{retrieve(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/artifacts/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){let r=uu(t,[`after`,`environment_id`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/artifacts`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{session_id:r}=t;return this._client.delete(B`/agents/sessions/${r}/artifacts/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}content(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/artifacts/${e}/content`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`,Accept:`application/octet-stream`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},fu=class extends z{create(e,t,n){let{"Idempotency-Key":r,...i}=t;return this._client.post(B`/agents/sessions/${e}/events`,{body:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`,Accept:`*/*`,...r==null?void 0:{"Idempotency-Key":r}},n?.headers]),__security:{bearerAuth:!0}})}stream(e,t){return this._client.get(B`/agents/sessions/${e}/events`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`,Accept:`text/event-stream`},t?.headers]),stream:!0,__security:{bearerAuth:!0}})}},pu=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function mu(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=>pu.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!pu.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 hu=class extends z{list(e,t={},n){let r=mu(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/items`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},gu=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=>gu.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!gu.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 vu=class extends z{retrieve(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/turns/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){let r=_u(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/turns`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},yu=class extends z{list(e,t,n){let{session_id:r,...i}=t;return this._client.getAPIList(B`/agents/sessions/${r}/subagents/${e}/items`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},bu=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`,M,{query:a,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},xu=class extends z{constructor(){super(...arguments),this.items=new bu(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}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.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`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}};xu.Items=bu;var Su=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Cu(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=>Su.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Su.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 wu=class extends z{constructor(){super(...arguments),this.items=new yu(this._client),this.turns=new xu(this._client)}retrieve(e,t,n){let{session_id:r}=t;return this._client.get(B`/agents/sessions/${r}/subagents/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){let r=Cu(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/agents/sessions/${e}/subagents`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}};wu.Items=yu,wu.Turns=xu;var Tu=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Eu(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=>Tu.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Tu.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{constructor(){super(...arguments),this.subagents=new wu(this._client),this.artifacts=new du(this._client),this.items=new hu(this._client),this.events=new fu(this._client),this.turns=new vu(this._client)}stream(e,t,n){return new cu(this,e,t,n)}create(e,t){return this._client.post(`/agents/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/agents/sessions/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(B`/agents/sessions/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){let n=Eu(e,[`after`,`agent_id`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/agents/sessions`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/agents/sessions/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};Du.Subagents=wu,Du.Artifacts=du,Du.Items=hu,Du.Events=fu,Du.Turns=vu;var Ou=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ku(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=>Ou.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Ou.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 Au=class extends z{create(e,t,n){return this._client.post(B`/vaults/${e}/credentials`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vault_id:r}=t;return this._client.get(B`/vaults/${r}/credentials/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vault_id:r,...i}=t;return this._client.post(B`/vaults/${r}/credentials/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){let r=ku(t,[`after`,`limit`,`order`,`status`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/vaults/${e}/credentials`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vault_id:r}=t;return this._client.delete(B`/vaults/${r}/credentials/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},ju=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Mu(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=>ju.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ju.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 Nu=class extends z{constructor(){super(...arguments),this.credentials=new Au(this._client)}create(e={},t){return this._client.post(`/vaults`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/vaults/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){let n=Mu(e,[`after`,`limit`,`order`,`status`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/vaults`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/vaults/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};Nu.Credentials=Au;var Pu=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Fu(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=>Pu.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Pu.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 Iu=class extends z{constructor(){super(...arguments),this.environments=new Il(this._client),this.vaults=new Nu(this._client),this.sessions=new Du(this._client)}create(e,t){return this._client.post(`/agents`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/agents/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(B`/agents/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){let n=Fu(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/agents`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/agents/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};Iu.Environments=Il,Iu.Vaults=Nu,Iu.Sessions=Du;var Lu=class extends z{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(B`/chatkit/sessions/${e}/cancel`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},Ru=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function zu(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=>Ru.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Ru.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 Bu=class extends z{retrieve(e,t){return this._client.get(B`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){let n=zu(e,[`after`,`before`,`limit`,`order`,`user`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/chatkit/threads`,N,{query:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){let r=zu(t,[`after`,`before`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/chatkit/threads/${e}/items`,N,{query:t,...n,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Vu=class extends z{constructor(){super(...arguments),this.sessions=new Lu(this._client),this.threads=new Bu(this._client)}};Vu.Sessions=Lu,Vu.Threads=Bu;var Hu=class extends z{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(B`/responses/${e}/input_items?beta=true`,M,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}},Uu=class extends z{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},Wu=class extends z{constructor(){super(...arguments),this.inputItems=new Hu(this._client),this.inputTokens=new Uu(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(B`/responses/${e}?beta=true`,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(B`/responses/${e}?beta=true`,{...n,headers:P([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(B`/responses/${e}/cancel?beta=true`,{...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}};Wu.InputItems=Hu,Wu.InputTokens=Uu;var Gu=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Ku(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=>Gu.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Gu.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 qu=class extends z{create(e,t,n){return this._client.post(B`/threads/${e}/messages`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(B`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(B`/threads/${r}/messages/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){let r=Ku(t,[`after`,`before`,`limit`,`order`,`run_id`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/threads/${e}/messages`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(B`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Ju=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}`,{query:a,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(B`/threads/${r}/runs/${e}/steps`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Yu=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")},Xu=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))}},q=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}},Zu=1024,Qu=65536;function $u(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 ed=new WeakMap,td=new WeakSet;function nd(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function rd(e){for(let[t,n]of e.arrays)n.cacheable&&!td.has(t)?ed.set(t,{length:n.length,ownEntryCount:n.ownEntryCount}):ed.delete(t)}function id(e){return typeof e==`string`||typeof e==`number`}function ad(e,t){return t.every(id)&&e.every(id)}function od(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 sd(e,t,n){return t?n?.length===e.length?n.ownEntryCount:od(e):0}function cd(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+Zu||r>=Qu)throw new o(`Assistant stream delta contains an invalid ${t} index: ${typeof r==`number`?r:`unknown`}`);return r}function ld(e,t,n,r,i){let a=r.arrays.get(e);if(!a){let t=r.cacheArrays&&!td.has(e),n=t?ed.get(e):void 0;a={baselineLength:e.length,cacheable:t,enforceSparseHoleBudget:t,entries:new Map,length:e.length,ownEntryCount:sd(e,t,n)},r.arrays.set(e,a)}for(let s of t){if(!ie(s))throw Error(`Expected array delta entry to be an object but got an invalid value`);let t=cd(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>Zu)throw new o(`Assistant stream delta contains an invalid ${n} index: ${t}`);ie(c)&&i(c,s,r),a.length=l}}function ud(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}ie(t)&&ie(a)?ud(t,a,n):Array.isArray(t)&&Array.isArray(a)&&!ad(t,a)&&ld(t,a,`array`,n,ud)}}function dd(e){return(ie(e)||Array.isArray(e))&&td.has(e)}function fd(e){if(!(!ie(e)&&!Array.isArray(e)||td.has(e))){td.add(e),Array.isArray(e)&&ed.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n&&`value`in n&&fd(n.value)}}}function pd(e,t,n){td.has(e)&&fd(n),Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function md(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 hd(e,t,n){if(ad(e,t)){e.push(...t),ed.delete(e);return}for(let r of t){if(!ie(r))throw Error(`Expected array delta entry to be an object but got an invalid value`);let t=md(r);if(E(e,t)){let i=e[t];i==null?(td.has(e)&&fd(r),e[t]=r):e[t]=n(i,r)}else pd(e,t,r)}}function gd(e,t){let n=td.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&&fd(i),e[r]=i;continue}let t=e[r];if(t==null){n&&fd(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(ie(t)&&ie(i))t=gd(t,i);else if(Array.isArray(t)&&Array.isArray(i)){hd(t,i,gd);continue}else throw TypeError(`Unhandled record type: ${$u(r)}`);e[r]=t}return e}function _d(e){if(ie(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}`);_d(n)}}function vd(e,t,n=!1){_d(t);let r=e,i=t,a=nd(n&&!dd(e));return ud(r,i,a),gd(r,i),rd(a),e}function yd(e,t,n,r=!0){_d(t);let i=nd(r&&!dd(e));return ld(e,t,n,i,ud),()=>rd(i)}var J,bd,xd,Sd,Cd,wd,Y,Td,Ed,Dd,Od,kd,Ad,jd,Md,Nd,Pd,Fd,Id,Ld,Rd,zd,Bd,Vd,X,Hd,Ud,Wd,Gd,Kd;function qd(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 Jd=class e extends xo{constructor(){super(...arguments),J.add(this),bd.set(this,Object.create(null)),xd.set(this,new Map),Sd.set(this,void 0),Cd.set(this,Object.create(null)),wd.set(this,new Map),Y.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),Ad.set(this,void 0),jd.set(this,void 0),Md.set(this,void 0),Nd.set(this,void 0)}[(bd=new WeakMap,xd=new WeakMap,Sd=new WeakMap,Cd=new WeakMap,wd=new WeakMap,Y=new WeakMap,Td=new WeakMap,Ed=new WeakMap,Dd=new WeakMap,Od=new WeakMap,kd=new WeakMap,Ad=new WeakMap,jd=new WeakMap,Md=new WeakMap,Nd=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=Qe.fromReadableStream(e,this.controller);for await(let e of r)n(this,J,`m`,Pd).call(this,e);if(r.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,Fd).call(this))}toReadableStream(){return new Qe(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`,Pd).call(this,e);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,Fd).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 fd(n(this,jd,`f`)),n(this,jd,`f`)}currentRun(){return fd(n(this,Md,`f`)),n(this,Md,`f`)}currentMessageSnapshot(){return fd(n(this,Y,`f`)),n(this,Y,`f`)}currentRunStepSnapshot(){return fd(n(this,Nd,`f`)),n(this,Nd,`f`)}async finalRunSteps(){return await this.done(),Object.values(n(this,bd,`f`))}async finalMessages(){return await this.done(),Object.values(n(this,Cd,`f`))}async finalRun(){if(await this.done(),!n(this,Ed,`f`))throw Error(`Final run was not received.`);return n(this,Ed,`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`,Pd).call(this,e);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,Fd).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`,Pd).call(this,e);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(n(this,J,`m`,Fd).call(this))}static accumulateDelta(e,t){return vd(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)}};Pd=function(e){if(this.ended)return;let{event:r,exposedEvent:i}=qd(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`,Rd).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`,Id).call(this,r),u=r.data}switch(t(this,jd,i,`f`),n(this,J,`m`,Hd).call(this,i),a!==void 0&&c!==void 0&&n(this,J,`m`,zd).call(this,c,a),l!==void 0&&u!==void 0&&n(this,J,`m`,Ld).call(this,u,l),l===void 0&&n(this,Sd,`f`)!==void 0&&n(this,Nd,`f`)&&n(this,J,`m`,Ld).call(this,n(this,Nd,`f`),n(this,Sd,`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`,Kd).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,bd,`f`)[l];e&&n(this,J,`m`,Ld).call(this,e,l),n(this,J,`m`,Vd).call(this,r,l),n(this,J,`m`,Ld).call(this,r.data,l);let t=n(this,bd,`f`)[l];t&&n(this,J,`m`,Ld).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`,zd).call(this,n(this,Y,`f`),a),n(this,J,`m`,Bd).call(this,r),a!==void 0){n(this,J,`m`,zd).call(this,r.data,a);let e=n(this,Cd,`f`)[a];e&&n(this,J,`m`,zd).call(this,e,a)}break;case`error`:throw new s(void 0,r.data,void 0,void 0)}},Fd=function(){if(this.ended)throw new o(`stream has ended, this shouldn't happen`);if(!n(this,Ed,`f`))throw Error(`Final run has not been received`);return n(this,Ed,`f`)},Id=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,Sd,`f`)!==void 0)throw new o(`Received run-step creation for "${i}" before the active run step "${n(this,Sd,`f`)}" reached a terminal state`);if(E(n(this,bd,`f`),i)||n(this,xd,`f`).has(i))throw new o(`Received run-step creation for run step "${i}", which has already been created`);return t(this,Sd,i,`f`),n(this,xd,`f`).set(i,i),i}if(n(this,Sd,`f`)!==void 0){if(i!==n(this,Sd,`f`))throw new o(`Received ${e.event} for run step "${i}", which does not match the active run step "${n(this,Sd,`f`)}"`);return i}if(e.event===`thread.run.step.delta`)throw E(n(this,bd,`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,bd,`f`),i)||n(this,xd,`f`).has(i))throw new o(`Received run-step event for run step "${i}", which has already been created`);return n(this,xd,`f`).set(i,i),e.event===`thread.run.step.in_progress`&&t(this,Sd,i,`f`),i},Ld=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,xd,`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,xd,`f`).set(i,t)},Rd=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,Td,`f`)}" reached a terminal state`);if(E(n(this,Cd,`f`),i)||n(this,wd,`f`).has(i))throw new o(`Received message creation for message "${i}", which has already been created`);return t(this,Td,i,`f`),n(this,wd,`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,Td,`f`))throw new o(`Received ${e.event} for message "${i}", which does not match the active message "${n(this,Td,`f`)}"`);return i},zd=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,wd,`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,wd,`f`).set(i,t)},Bd=function(e){let[r,i]=n(this,J,`m`,Wd).call(this,e,n(this,Y,`f`));if(t(this,Y,r,`f`),!n(this,Td,`f`))throw new o(`Received thread message event with no active message ID`);n(this,Cd,`f`)[n(this,Td,`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,Dd,void 0,`f`),t(this,Od,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,Dd,`f`)){if(n(this,Od,`f`))switch(n(this,Od,`f`).type){case`text`:n(this,J,`m`,X).call(this,`textDone`,n(this,Od,`f`).text,n(this,Y,`f`));break;case`image_file`:n(this,J,`m`,X).call(this,`imageFileDone`,n(this,Od,`f`).image_file,n(this,Y,`f`))}t(this,Dd,i.index,`f`)}t(this,Od,r.content[i.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(n(this,Dd,`f`)!==void 0){let t=e.data.content[n(this,Dd,`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,Dd,void 0,`f`),t(this,Od,void 0,`f`),t(this,Y,void 0,`f`),t(this,Td,void 0,`f`)}},Vd=function(e,r){let i=n(this,J,`m`,Ud).call(this,e,r);switch(t(this,Nd,i,`f`),e.event){case`thread.run.step.created`:t(this,kd,void 0,`f`),t(this,Ad,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,kd,`f`)?n(this,J,`m`,X).call(this,`toolCallDelta`,e,i.step_details.tool_calls[e.index]):(n(this,Ad,`f`)&&n(this,J,`m`,X).call(this,`toolCallDone`,n(this,Ad,`f`)),t(this,kd,e.index,`f`),t(this,Ad,i.step_details.tool_calls[e.index],`f`),n(this,Ad,`f`)&&n(this,J,`m`,X).call(this,`toolCallCreated`,n(this,Ad,`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,Nd,void 0,`f`),t(this,Sd,void 0,`f`),e.data.step_details.type===`tool_calls`&&n(this,Ad,`f`)&&n(this,J,`m`,X).call(this,`toolCallDone`,n(this,Ad,`f`)),n(this,J,`m`,X).call(this,`runStepDone`,e.data,i),t(this,kd,void 0,`f`),t(this,Ad,void 0,`f`)}},X=function(e,...t){if(this._hasListeners(e))for(let e of t)fd(e);this._emit(e,...t)},Hd=function(e){n(this,J,`m`,X).call(this,`event`,e)},Ud=function(e,t){switch(e.event){case`thread.run.step.created`:return n(this,bd,`f`)[t]=e.data,e.data;case`thread.run.step.delta`:{let r=n(this,bd,`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=vd(r,i,!0);n(this,bd,`f`)[t]=e}return n(this,bd,`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,bd,`f`)[t]=e.data}if(n(this,bd,`f`)[t])return n(this,bd,`f`)[t];throw Error(`No snapshot available`)},Wd=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){_d(i.delta);let e=!dd(t),a=yd(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`,Gd).call(this,a,r,e)}else pd(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`)},Gd=function(e,t,n){return vd(t,e,n)},Kd=function(e){switch(t(this,Md,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,Ed,e.data,`f`),n(this,Ad,`f`)&&n(this,J,`m`,X).call(this,`toolCallDone`,n(this,Ad,`f`)),t(this,kd,void 0,`f`),t(this,Ad,void 0,`f`)}};function Yd(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 Xd(e,t,n,r){let i=P([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?Yd(e,n):se(e))}else if(n.includes(s))return a}}function Zd(e,t,n,r){return Xd(i=>e.retrieve(t,n,{...r,headers:{...r?.headers,...i}}),[`queued`,`in_progress`,`cancelling`],[`requires_action`,`incomplete`,`cancelled`,`completed`,`failed`,`expired`],r)}var Qd=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function $d(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 ef=class extends z{constructor(){super(...arguments),this.steps=new Ju(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(B`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(B`/threads/${r}/runs/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(B`/threads/${r}/runs/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){let r=$d(t,[`after`,`before`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/threads/${e}/runs`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(B`/threads/${r}/runs/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Jd.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){return await Zd(this,e,t,n)}stream(e,t,n){return Jd.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`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Jd.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};ef.Steps=Ju;var tf=class extends z{constructor(){super(...arguments),this.runs=new ef(this._client),this.messages=new qu(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(B`/threads/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Jd.createThreadAssistantStream(e,this._client.beta.threads,t)}};tf.Runs=ef,tf.Messages=qu;var nf=class extends z{constructor(){super(...arguments),this.realtime=new jl(this._client),this.agents=new Iu(this._client),this.responses=new Wu(this._client),this.chatkit=new Vu(this._client),this.assistants=new Ol(this._client),this.threads=new tf(this._client)}};nf.Realtime=jl,nf.Agents=Iu,nf.Responses=Wu,nf.ChatKit=Vu,nf.Assistants=Ol,nf.Threads=tf;var rf=class extends z{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},af=class extends z{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(B`/containers/${r}/files/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},of=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function sf(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=>of.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!of.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 cf=class extends z{constructor(){super(...arguments),this.content=new af(this._client)}create(e,t,n){return this._client.post(B`/containers/${e}/files`,Br({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(B`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){let r=sf(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/containers/${e}/files`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(B`/containers/${r}/files/${e}`,{...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};cf.Content=af;var lf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function uf(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=>lf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!lf.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 df=class extends z{constructor(){super(...arguments),this.files=new cf(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){let n=uf(e,[`after`,`limit`,`name`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/containers`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/containers/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};df.Files=cf;var ff=class extends z{create(e,t){return this._client.post(`/content_provenance_checks`,Vr({body:e,...t,__security:{bearerAuth:!0}},this._client))}},pf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function mf(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 hf=class extends z{create(e,t,n){let{include:r,...i}=t;return this._client.post(B`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(B`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){let r=mf(t,[`after`,`include`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/conversations/${e}/items`,N,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(B`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},gf=class extends z{constructor(){super(...arguments),this.items=new hf(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(B`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};gf.Items=hf;function _f(e,t,n){let r=!!t.encoding_format,i=r?t.encoding_format:`base64`;r&&A(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:(A(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=Xu(r)}}return e}))}var vf=class extends z{create(e,t){return _f(this._client,e,t)}},yf=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}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(B`/evals/${r}/runs/${e}/output_items`,M,{query:i,...n,__security:{bearerAuth:!0}})}},bf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function xf(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 Sf=class extends z{constructor(){super(...arguments),this.outputItems=new yf(this._client)}create(e,t,n){return this._client.post(B`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(B`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){let r=xf(t,[`after`,`limit`,`order`,`status`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/evals/${e}/runs`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(B`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(B`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};Sf.OutputItems=yf;var Cf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function wf(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 Tf=class extends z{constructor(){super(...arguments),this.runs=new Sf(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(B`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){let n=wf(e,[`after`,`limit`,`order`,`order_by`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/evals`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Tf.Runs=Sf;async function Ef(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 se(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}var Df=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Of(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=>Df.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Df.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 kf=class extends z{create(e,t){return this._client.post(`/files`,Vr({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(B`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){let n=Of(e,[`after`,`limit`,`order`,`purpose`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/files`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(B`/files/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){return await Ef(this,e,t,n)}},Af=class extends z{},jf=class extends z{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},Mf=class extends z{constructor(){super(...arguments),this.graders=new jf(this._client)}};Mf.Graders=jf;var Nf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Pf(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=>Nf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Nf.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 Ff=class extends z{create(e,t,n){return this._client.getAPIList(B`/fine_tuning/checkpoints/${e}/permissions`,qt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){let r=Pf(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`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){let r=Pf(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`,N,{query:t,...n,__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}`,{...n,__security:{adminAPIKeyAuth:!0}})}},If=class extends z{constructor(){super(...arguments),this.permissions=new Ff(this._client)}};If.Permissions=Ff;var Lf=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Rf(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=>Lf.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Lf.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 zf=class extends z{list(e,t={},n){let r=Rf(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/fine_tuning/jobs/${e}/checkpoints`,M,{query:t,...n,__security:{bearerAuth:!0}})}},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{constructor(){super(...arguments),this.checkpoints=new zf(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){let n=Vf(e,[`after`,`limit`,`metadata`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/fine_tuning/jobs`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(B`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){let r=Vf(t,[`after`,`limit`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/fine_tuning/jobs/${e}/events`,M,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(B`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(B`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};Hf.Checkpoints=zf;var Uf=class extends z{constructor(){super(...arguments),this.methods=new Af(this._client),this.jobs=new Hf(this._client),this.checkpoints=new If(this._client),this.alpha=new Mf(this._client)}};Uf.Methods=Af,Uf.Jobs=Hf,Uf.Checkpoints=If,Uf.Alpha=Mf;var Wf=class extends z{},Gf=class extends z{constructor(){super(...arguments),this.graderModels=new Wf(this._client)}};Gf.GraderModels=Wf;var Kf=class extends z{createVariation(e,t){return this._client.post(`/images/variations`,Vr({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,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`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},qf=class extends z{accept(e,t,n){return this._client.post(B`/live/sessions/${e}/accept`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,t){return this._client.get(B`/live/sessions/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,t,n){return this._client.post(B`/live/sessions/${e}/fork`,{body:t,...n,__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(B`/live/sessions/${e}/hangup`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(B`/live/sessions/${e}/refer`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t,n){return this._client.post(B`/live/sessions/${e}/reject`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},Jf=class extends z{},Yf=class extends z{},Xf=class extends z{constructor(){super(...arguments),this.sideband=new Yf(this._client),this.forks=new Jf(this._client),this.sessions=new qf(this._client)}create(e,t){return this._client.post(`/live/sessions`,{body:e,...t,__security:{bearerAuth:!0}})}};Xf.Sideband=Yf,Xf.Forks=Jf,Xf.Sessions=qf;var Zf=class extends z{retrieve(e,t){return this._client.get(B`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,qt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},Qf=class extends z{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}};async function $f(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:P([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:P([e.headers,{"content-type":null}])}}var ep=class extends z{create(e,t){return this._client.post(`/realtime/calls`,$f({body:e,...t,headers:P([{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`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(B`/realtime/calls/${e}/hangup`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(B`/realtime/calls/${e}/refer`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(B`/realtime/calls/${e}/reject`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},tp=class extends z{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},np=class extends z{constructor(){super(...arguments),this.clientSecrets=new tp(this._client),this.calls=new ep(this._client)}};np.ClientSecrets=tp,np.Calls=ep;function rp(e,t){if(!t||!op(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 up(e,t)&&dp(t),t}return ip(e,t)}function ip(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?lp(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?ap(t,e.text):null}:e);return{...e,content:r}}return e}),i={...e,output:r};return up(e,i)&&dp(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 ap(e,t){return Ti(e.text?.format,t)}function op(e){return wi(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>sp(e)||e.type===`function`&&e.strict===!0||e.type===`namespace`&&e.tools.some(e=>e.type===`function`&&(sp(e)||e.strict===!0)))}function sp(e){return e?.$brand===`auto-parseable-tool`}function cp(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 lp(e,t){let n=cp(e.tools??[],t.name,t.namespace),r=null;return sp(n)?r=n.$parseRaw(t.arguments):n?.strict&&(r=Ti({type:`json_schema`,$parseRaw:void 0},t.arguments)),{...t,parsed_arguments:r}}function up(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function dp(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 fp=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 pp(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new fp}}function mp(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 hp(e,t){if(e.canonicalSnapshot===t)return;let n=new fp,r=``;for(let i of t.output){let t=mp(e,i);r+=t,n.append(t.length)}t.output_text=r,e.outputTextIndex=n,e.canonicalSnapshot=t}function gp(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new fp;let n=structuredClone(t);return!Object.getOwnPropertyDescriptor(n,`output_text`)||n.output_text===null||n.output_text===void 0?hp(e,n):n.output.length===0&&n.output_text===``&&(e.canonicalSnapshot=n),n}function _p(e,t,n,r,i){let a=e.outputTextLengths.get(t);if(a!==void 0){let o=a-r.length+i.length;e.outputTextLengths.set(t,o),e.outputTextIndex.update(n,o)}}function vp(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 yp(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)??mp(e,t).length)-i-r.length}function bp(e,t,n,r,i,a){if(r===i)return;let o=t.output[n];if(n===t.output.length-1&&(a===void 0||o?.type===`message`&&a===o.content.length-1)){vp(t,r,i);return}let s=yp(e,o,a,i),c=e.outputTextIndex.prefixSum(n)+s;if(c+r.length===t.output_text.length){vp(t,r,i);return}t.output_text=t.output_text.slice(0,c)+i+t.output_text.slice(c+r.length)}var xp=new WeakMap;function Sp(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 Cp(e,t,n){if(t!==e.length)throw new o(`missing ${n} at index ${t}`);Sp(e,t,n,!0)}function Z(e,t){Sp(e.output,t,`output`);let n=e.output[t];if(!n)throw new o(`missing output at index ${t}`);return n}function wp(e){return e.type===`function_call`||e.type===`custom_tool_call`||e.type===`shell_call`||e.type===`shell_call_output`}function Tp(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(wp(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 Ep(e,t){for(let n of t)if(e.has(n))throw new o(`duplicate output item identity '${n}'`)}function Dp(e,t){Ep(e,t);for(let n of t)e.add(n)}function Op(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);Dp(t.identities,Tp(r,`response snapshot`))}return t}function kp(e,t){let n=xp.get(e);if(n&&n.snapshot===t&&n.output===t.output&&n.length===t.output.length)return n;let r=Op(t);return xp.set(e,r),r}function Ap(e,t){let n=pp(),r=gp(n,t),i=Op(r);return e.canonicalSnapshot=n.canonicalSnapshot,e.outputTextLengths=n.outputTextLengths,e.outputTextIndex=n.outputTextIndex,xp.set(e,i),r}var jp={"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 Mp(e){return e.type===`response.content_part.added`||e.type===`response.content_part.done`?e.part.type===`reasoning_text`?`reasoning`:`message`:jp[e.type]}function Np(e,t){let n=Z(t,e.output_index),r=e.item;if(Tp(n,e.type),Tp(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(wp(n)&&wp(r)&&n.call_id!==r.call_id)throw new o(`expected output item call_id '${n.call_id}', got '${r.call_id}'`)}function Pp(e,t,n){if(e.type===`response.output_item.done`){Np(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(jp,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=Mp(r);if(i.type!==s)throw new o(`expected output item type '${s}', got '${i.type}'`)}function Fp(e,t){Sp(e,t,`content`);let n=e[t];if(!n)throw new o(`missing content at index ${t}`);return n}function Ip(e,t,n){let r=e.output.find(e=>e.type===`shell_call`&&e.call_id===t.call_id);for(r?Sp(r.action.commands,n,`command`):Sp(t.output,n,`content`,!0);t.output.length<=n;)t.output.push({stdout:``,stderr:``,outcome:{type:`exit`,exit_code:0}});return Fp(t.output,n)}function Lp(e){return new Set(e)}var Rp=Lp(`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 zp(e){throw new o(`Unhandled response stream event: unknown`)}var Bp=[`item_id`,`output_index`,`content_index`,`annotation_index`,`command_index`,`summary_index`];function Vp(e){let t;try{t=Object.getOwnPropertyDescriptor(e,`type`)}catch{return zp(e)}let n=t?.value;if(typeof n!=`string`||!Rp.has(n))return zp(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(jp,n))try{for(let t of Bp){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 zp(e)}return new Proxy(e,{get(e,t){return r.has(t)?r.get(t):Reflect.get(e,t,e)}})}function Hp(e,t,n){switch(e.type){case`response.output_item.added`:{Cp(t.output,e.output_index,`output`);let r=kp(n,t),i=structuredClone(e.item),a=Tp(i,e.type);Ep(r.identities,a),i.type===`message`&&hp(n,t),t.output.push(i),Dp(r.identities,a),r.length=t.output.length;let o=mp(n,i);return n.canonicalSnapshot===t&&n.outputTextIndex.append(o.length),o&&(t.output_text+=o),!0}case`response.output_item.done`:{let r=Z(t,e.output_index),i=mp(n,r),a=e.item;(r.type===`message`||a.type===`message`)&&hp(n,t),t.output[e.output_index]=a;let o=mp(n,a);return n.canonicalSnapshot===t&&n.outputTextIndex.update(e.output_index,o.length),bp(n,t,e.output_index,i,o),!0}default:return!1}}function Up(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`){Cp(r.content,e.content_index,`content`);let i=a;i.type===`output_text`&&hp(n,t),r.content.push(i),i.type===`output_text`&&(_p(n,r,e.output_index,``,i.text),bp(n,t,e.output_index,``,i.text,e.content_index))}else if(i===`reasoning`&&a.type===`reasoning_text`){let t=r.content??[];Cp(t,e.content_index,`content`),r.content||=t,t.push(a)}return!0}default:return!1}}function Wp(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=Fp(r.content,e.content_index),o=a.type===`output_text`?a.text:``,s=i;(a.type===`output_text`||s.type===`output_text`)&&hp(n,t),r.content[e.content_index]=s;let c=s.type===`output_text`?s.text:``;_p(n,r,e.output_index,o,c),bp(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}`);Fp(t,e.content_index),t[e.content_index]=i}return!0}default:return!1}}function Gp(e,t,n){switch(e.type){case`response.output_text.delta`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Fp(r.content,e.content_index);if(i.type!==`output_text`)throw new o(`expected content to be 'output_text', got ${i.type}`);let a=i.text;hp(n,t),i.text=a+e.delta,_p(n,r,e.output_index,a,i.text),e.output_index===t.output.length-1&&e.content_index===r.content.length-1?t.output_text+=e.delta:bp(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=Fp(r.content,e.content_index);if(i.type!==`output_text`)throw new o(`expected content to be 'output_text', got ${i.type}`);let a=i.text;hp(n,t),i.text=e.text,_p(n,r,e.output_index,a,e.text),bp(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=Fp(n.content,e.content_index);if(t.type!==`output_text`)throw new o(`expected content to be 'output_text', got ${t.type}`);Sp(t.annotations,e.annotation_index,`annotation`,!0),t.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function Kp(e,t){switch(e.type){case`response.refusal.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Fp(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=Fp(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 qp(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`;Sp(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`&&(Sp(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=Ip(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=Fp(e.output,0);Ip(t,n,e.command_index),n.output[e.command_index]=structuredClone(r)}return!0}default:return!1}}function Jp(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=Fp(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=Fp(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`&&(Cp(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`&&(Fp(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=Fp(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=Fp(n.summary,e.summary_index);t.text=e.text}return!0}default:return!1}}function Yp(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 Xp(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 Zp(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 Qp(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 $p(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 em(){return pp()}function tm(e,t,n,r=!1,i){let a=Vp(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 Ap(n,a.response)}return Pp(a,t,r),Hp(a,t,n)||Up(a,t,n)||Wp(a,t,n)||Gp(a,t,n)||Kp(a,t)||qp(a,t)||Jp(a,t)||Yp(a,t)||Xp(a,t)||Zp(a,t)?t:Qp(a)?Ap(n,a.response):$p(a)?t:zp(a)}var nm,rm,im,am,om,sm,cm,lm,um=class e extends xo{constructor(e){super(),nm.add(this),rm.set(this,void 0),im.set(this,void 0),am.set(this,void 0),om.set(this,em()),t(this,rm,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,nm,`m`,sm).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,nm,`m`,cm).call(this,e,a);if(i.controller.signal?.aborted)throw this._userAbortError();return n(this,nm,`m`,lm).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),n(this,nm,`m`,sm).call(this),this._connected();let r=Qe.fromReadableStream(e,this.controller);for await(let e of r)n(this,nm,`m`,cm).call(this,e,null);if(r.controller.signal?.aborted)throw this._userAbortError();return n(this,nm,`m`,lm).call(this)}[(rm=new WeakMap,im=new WeakMap,am=new WeakMap,om=new WeakMap,nm=new WeakSet,sm=function(){this.ended||(t(this,im,void 0,`f`),t(this,om,em(),`f`))},cm=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=tm(e,n(this,im,`f`),n(this,om,`f`),!0,e=>{a=e});switch(t(this,im,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)}},lm=function(){if(this.ended)throw new o(`stream has ended, this shouldn't happen`);let e=n(this,im,`f`);if(!e)throw new o(`request ended without sending any events`);t(this,im,void 0,`f`),t(this,om,em(),`f`);let r=dm(e,n(this,rm,`f`));return t(this,am,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,am,`f`);if(!e)throw new o(`stream ended without producing a Response`);return e}};function dm(e,t){return rp(e,t)}var fm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function pm(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=>fm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!fm.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 mm=class extends z{list(e,t={},n){let r=pm(t,[`after`,`include`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/responses/${e}/input_items`,M,{query:t,...n,__security:{bearerAuth:!0}})}},hm=class extends z{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},gm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function _m(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=>gm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!gm.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 vm=class extends z{constructor(){super(...arguments),this.inputItems=new mm(this._client),this.inputTokens=new hm(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&dp(e),e))}retrieve(e,t={},n){let r=_m(t,[`include`,`include_obfuscation`,`starting_after`,`stream`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.get(B`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&dp(e),e))}delete(e,t){return this._client.delete(B`/responses/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>ip(t,e))}stream(e,t){return um.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(B`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};vm.InputItems=mm,vm.InputTokens=hm;var ym=class extends z{retrieve(e,t){return this._client.get(B`/safety/alerts/${e}`,{...t,__security:{bearerAuth:!0}})}},bm=class extends z{retrieve(e,t){return this._client.get(B`/safety/cases/${e}`,{...t,__security:{bearerAuth:!0}})}},xm=class extends z{constructor(){super(...arguments),this.alerts=new ym(this._client),this.cases=new bm(this._client)}};xm.Alerts=ym,xm.Cases=bm;var Sm=class extends z{retrieve(e,t){return this._client.get(B`/skills/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Cm=class extends z{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(B`/skills/${r}/versions/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},wm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Tm(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=>wm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!wm.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 Em=class extends z{constructor(){super(...arguments),this.content=new Cm(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}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){let r=Tm(t,[`after`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/skills/${e}/versions`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(B`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};Em.Content=Cm;var Dm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Om(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 km=class extends z{constructor(){super(...arguments),this.content=new Sm(this._client),this.versions=new Em(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}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(B`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){let n=Om(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/skills`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};km.Content=Sm,km.Versions=Em;var Am=class extends z{create(e,t,n){return this._client.post(B`/uploads/${e}/parts`,Vr({body:t,...n,__security:{bearerAuth:!0}},this._client))}},jm=class extends z{constructor(){super(...arguments),this.parts=new Am(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(B`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(B`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};jm.Parts=Am;function Mm(e,t,n,r){return Xd(i=>e.retrieve(n,{vector_store_id:t},{...r,headers:i}),[`in_progress`],[`failed`,`cancelled`,`completed`],r)}function Nm(e,t,n,r){return Xd(i=>e.retrieve(n,{vector_store_id:t},{...r,headers:i}),[`in_progress`],[`failed`,`cancelled`,`completed`],r)}var Pm=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 Fm(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 Pm(d),await e.createAndPoll(n,{file_ids:l},a)}var Im=class extends z{create(e,t,n){return this._client.post(B`/vector_stores/${e}/file_batches`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(B`/vector_stores/${r}/file_batches/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(B`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(B`/vector_stores/${r}/file_batches/${e}/files`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){return await Nm(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){return await Fm(this,this._client,e,t,n,r)}},Lm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Rm(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=>Lm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Lm.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 zm=class extends z{create(e,t,n){return this._client.post(B`/vector_stores/${e}/files`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(B`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(B`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){let r=Rm(t,[`after`,`before`,`filter`,`limit`,`order`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.getAPIList(B`/vector_stores/${e}/files`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(B`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){return await Mm(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`,qt,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Bm=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Vm(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=>Bm.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Bm.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 Hm=class extends z{constructor(){super(...arguments),this.files=new zm(this._client),this.fileBatches=new Im(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(B`/vector_stores/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){let n=Vm(e,[`after`,`before`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/vector_stores`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(B`/vector_stores/${e}/search`,qt,{body:t,method:`post`,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};Hm.Files=zm,Hm.FileBatches=Im;var Um=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function Wm(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=>Um.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!Um.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 Gm=class extends z{create(e,t){return this._client.post(`/videos`,Vr({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(B`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){let n=Wm(e,[`after`,`limit`,`order`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/videos`,N,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,Vr({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){let r=Wm(t,[`variant`],n);return r!==void 0&&(n=r,t={}),t=t,this._client.get(B`/videos/${e}/content`,{query:t,...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,Vr({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,Vr({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(B`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(B`/videos/${e}/remix`,Br({body:t,...n,__security:{bearerAuth:!0}},this._client))}},Km=32,qm=32;function Jm(e){return e.split(` `,33).length>Km}function*Ym(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 Xm(e){try{let t=Yu(e);return t.byteLength===qm?t:void 0}catch{return}}function Zm(e){for(let t of Ym(e)){let e=Xm(t);if(e)return e}}function Qm(e,t,n){let r=n;for(let n of Ym(e)){let e=Xm(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 $m(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=Jm(t),l=c?Zm(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_`)?Yu(i.slice(6)):Se(i)),d=r?`${r}.${n}.${e}`:`${n}.${e}`,f=Uint8Array.from(Se(d)),p=await crypto.subtle.importKey(`raw`,u,{name:`HMAC`,hash:`SHA-256`},!1,c?[`sign`,`verify`]:[`verify`]);if(c&&l){let e=Qm(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 Ym(t))try{let t=Uint8Array.from(Yu(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`)}var eh=class extends z{list(e){return this._client.get(`/webhook_event_types`,{...e,__security:{bearerAuth:!0}})}},th,nh,rh,ih=new Set([`method`,`path`,`query`,`body`,`headers`,`maxRetries`,`stream`,`timeout`,`httpAgent`,`fetchOptions`,`signal`,`idempotencyKey`,`defaultBaseURL`,`__metadata`,`__binaryRequest`,`__binaryResponse`,`__streamClass`,`__security`,`__synthesizeEventData`]);function ah(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=>ih.has(e)&&!t.includes(e))){if(n!==void 0||i.some(e=>!ih.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 oh=class extends z{constructor(){super(...arguments),th.add(this),this.eventTypes=new eh(this._client)}create(e,t){return this._client.post(`/webhook_endpoints`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(B`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(B`/webhook_endpoints/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){let n=ah(e,[`after`,`limit`],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList(`/webhook_endpoints`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(B`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}rotateSecret(e,t={},n){return this._client.post(B`/webhook_endpoints/${e}/rotate_secret`,{body:t,...n,__security:{bearerAuth:!0}})}test(e,t,n){return this._client.post(B`/webhook_endpoints/${e}/test`,{body:t,...n,__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,th,`m`,nh).call(this,r);let a=P([t]).values,o=n(this,th,`m`,rh).call(this,a,`webhook-signature`),s=n(this,th,`m`,rh).call(this,a,`webhook-timestamp`),c=n(this,th,`m`,rh).call(this,a,`webhook-id`);if(Jm(o)&&typeof crypto.subtle.sign!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");return await $m(e,o,s,c,r,i)}};th=new WeakSet,nh=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`)},rh=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},oh.EventTypes=eh;async function sh(e){let t,n=await e._callApiKey(e=>{t=e});return{apiKey:t===void 0?e.apiKey:t,isProvider:n}}var ch=Symbol.for(`openai.node.providerDefinitions.v1`),lh=globalThis,uh=lh[ch],dh=uh??new WeakMap;uh||Object.defineProperty(lh,ch,{value:dh});function fh(e){let t=dh.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var ph,mh,hh,Q,gh,_h,vh,yh,bh;function xh(){if(lt())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 Sh=`workload-identity-auth`,Ch=Symbol(`inheritedDataResidencySelection`),$=class{constructor(e={}){ph.add(this),hh.set(this,void 0),Q.set(this,void 0),gh.set(this,void 0),_h.set(this,void 0),vh.set(this,!1),yh.set(this,new WeakMap),this.completions=new rf(this),this.chat=new Zs(this),this.embeddings=new vf(this),this.files=new kf(this),this.images=new Kf(this),this.contentProvenanceChecks=new ff(this),this.audio=new Sl(this),this.moderations=new Qf(this),this.models=new Zf(this),this.fineTuning=new Uf(this),this.graders=new Gf(this),this.vectorStores=new Hm(this),this.safety=new xm(this),this.webhooks=new oh(this),this.beta=new nf(this),this.batches=new Tl(this),this.uploads=new jm(this),this.admin=new vl(this),this.responses=new vm(this),this.live=new Xf(this),this.realtime=new np(this),this.conversations=new gf(this),this.evals=new Tf(this),this.containers=new df(this),this.skills=new km(this),this.videos=new Gm(this);let{credential:r,options:i}=Er(e);e=i;let a=Bt(e),s=e.provider,{baseURL:c=s?null:q(`OPENAI_BASE_URL`),dataResidency:l,[Ch]:u=!1,apiKey:d=s?null:q(`OPENAI_API_KEY`)??null,adminAPIKey:f=s?null:q(`OPENAI_ADMIN_KEY`)??null,organization:p=s?null:q(`OPENAI_ORG_ID`)??null,project:m=s?null:q(`OPENAI_PROJECT_ID`)??null,webhookSecret:h=q(`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?fh(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(un(w.baseURL),Cr(w.fetchOptions),this.fetchWithAuth!==mh.prototype.fetchWithAuth||this.fetchWithTimeout!==mh.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&&xh())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,vh,a!==void 0||u,`f`),this.timeout=w.timeout??mh.DEFAULT_TIMEOUT,this.logger=w.logger??console;let ee=`warn`;this.logLevel=ee,this.logLevel=Fe(w.logLevel,`ClientOptions.logLevel`,this)??Fe(q(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??ee,this.fetchOptions=w.fetchOptions,this.maxRetries=w.maxRetries??2,this.fetch=w.fetch??ge(),t(this,hh,yt,`f`);let T=s||r?void 0:q(`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=P([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,gh,r,`f`),t(this,_h,e.fetch(),`f`),this.fetch=n(this,_h,`f`),Vn(this)}else b.legacy&&(this._workloadIdentityAuth=new ln(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=Bt(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,gh,`f`),i!==void 0);r!==void 0&&delete a.baseURL;let c={...a,...e,credential:o,provider:s,[Ch]:n(this,vh,`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??ge(),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,_h,n(this,_h,`f`),`f`)),l}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e){return Object.fromEntries(P([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]).values)}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw 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):P([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!==mh.prototype.fetchWithAuth||this.fetchWithTimeout!==mh.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 P([{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 sh(this);if(r!=null)return P([{Authorization:`Bearer ${r}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return P([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Rt(e)}getUserAgent(){return`${this.constructor.name}/JS ${ct}`}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;try{n=await t()}catch(e){throw e instanceof o?e:new o(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof n!=`string`||!n)throw new o(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,e?.(this.apiKey),!0}buildURL(e,t,r){let i=!n(this,ph,`m`,bh).call(this)&&r||this.baseURL,a=ee(e)?new URL(e):new URL(i+(i.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(a.searchParams);return(!re(o)||!re(s))&&(t={...s,...o,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),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 Ut(this,e,(e,r)=>{let i=n(this,yh,`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)=>st(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 at(e,t);for(;;){let r=n(this,yh,`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(),be(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([at(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(),be(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=o.maxRetries??this.maxRetries;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){ae(`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?Th(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=P([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(P([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;A(this).debug(`[${g}] sending request`,Ge({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===mh.prototype.fetchWithTimeout?Th(f.signal??(c?y:void 0),c?y:void 0):new AbortController,w=c?.remainingTimeout(o,m)??m,ee=c?mh.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||Rn(T)))return A(this).info(`[${g}] connection ${n?`timed out`:`failed`} - ${e}`),A(this).debug(`[${g}] connection ${n?`timed out`:`failed`} (${e})`,Ge({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(A(this).info(`[${g}] connection ${n?`timed out`:`failed`} - ${a}`),A(this).debug(`[${g}] connection ${n?`timed out`:`failed`} (${a})`,Ge({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:Eh(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} ${We(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?be(T.body).catch(()=>void 0):(await be(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?be(T.body).catch(()=>void 0):await be(T.body),A(this).info(`${ne} - ${e}`),A(this).debug(`[${g}] response error (${e})`,Ge({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`;A(this).info(`${ne} - ${i}`);let s=c?await this.readX509ResponseError(T,o,m,x,c):await T.text().catch(e=>a(e).message),l=oe(s),u=l?void 0:s;throw A(this).debug(`[${g}] response error (${i})`,Ge({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)}A(this).info(ne),A(this).debug(`[${g}] response start`,Ge({retryOfRequestLogID:r,url:T.url,status:T.status,headers:T.headers,durationMs:te-v}));let re=c?.continuation();return c?.releaseRequestCredentials(),n(this,yh,`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 Kt(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,_h,`f`)&&a.bearerAuth){let e=t.headers;if(e.get(`Authorization`)===`Bearer ${Sh}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await(n(this,_h,`f`)?mh.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&&wh.get(i)===a,u=a&&!l?he(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,_h,`f`)??this.fetch).call(void 0,e,p);return u&&me(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 n=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,n)}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 se(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 mh.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&&ae(`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=P([l,{Accept:`application/json`,...xh()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(a),...d?{"X-Stainless-Timeout":String(Math.trunc(d/1e3))}:{},...gt(),...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,hh,`f`).call(this,{body:t,headers:P([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let i=P([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:ve(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,hh,`f`).call(this,{body:t,headers:i}),isStreamingBody:!1}}};mh=$,hh=new WeakMap,Q=new WeakMap,gh=new WeakMap,_h=new WeakMap,vh=new WeakMap,yh=new WeakMap,ph=new WeakSet,bh=function(){return n(this,vh,`f`)||this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=mh,$.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=rf,$.Chat=Zs,$.Embeddings=vf,$.Files=kf,$.Images=Kf,$.ContentProvenanceChecks=ff,$.Audio=Sl,$.Moderations=Qf,$.Models=Zf,$.FineTuning=Uf,$.Graders=Gf,$.VectorStores=Hm,$.Safety=xm,$.Webhooks=oh,$.Beta=nf,$.Batches=Tl,$.Uploads=jm,$.Admin=vl,$.Responses=vm,$.Live=Xf,$.Realtime=np,$.Conversations=gf,$.Evals=Tf,$.Containers=df,$.Skills=km,$.Videos=Gm,$.ConversationCursorPage=N,$.CursorPage=M,$.NextCursorPage=Jt,$.Page=qt,$.TokenPage=Yt;var wh=new WeakMap;function Th(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}),wh.set(n,e)}catch{}return n}function Eh(e){if(Dh(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 Dh(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 Oh=class extends ${constructor({baseURL:e=q(`OPENAI_BASE_URL`),apiKey:t=q(`AZURE_OPENAI_API_KEY`),apiVersion:n=q(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:s,dataResidency:c,...l}={}){if(Vt(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(Ah.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!ie(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!kh(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`?P([{"api-key":this.apiKey}]):super.authHeaders(e,n)}};function kh(e){try{return new URL(e).pathname.split(`/`).includes(`deployments`)}catch{return!1}}var Ah=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]),jh=Symbol.for(`openai.privateBedrockClient`);function Mh(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 Nh(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 Ph;function Fh(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 Ih(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 Lh(e){return Object.getOwnPropertyDescriptor(e,`output_text`)||dp(e),e}function Rh(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()=>Lh(await i()),r}),e}var zh=class extends ${constructor({baseURL:e=q(`AWS_BEDROCK_BASE_URL`),apiKey:t,awsRegion:n=q(`AWS_REGION`)??q(`AWS_DEFAULT_REGION`),bedrockTokenProvider:r,adminAPIKey:i,workloadIdentity:a,x509Transport:s,dataResidency:c,...l}={}){if(Vt(c,`BedrockOpenAI`),i||a||s)throw new o(`BedrockOpenAI only supports Bedrock bearer token authentication.`);if(t===void 0&&!r&&(t=q(`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:Fh(n);super({apiKey:r??t,adminAPIKey:null,baseURL:Ih(u),...l}),this[Ph]=!0;let d=this.apiKey;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,get(){return d!==null&&Nh(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){Mh(f,e),p=e}}),this.bedrockTokenProvider=r,this.responses=Rh(new vm(this))}async prepareOptions(e){let t=this._options.baseURL??this.baseURL;Mh(t,this.buildURL(e.path,null,e.defaultBaseURL)),await super.prepareOptions(e),Mh(t,this.buildURL(e.path,null,e.defaultBaseURL))}async prepareRequest(e,t){Mh(this._options.baseURL??this.baseURL,t.url),await super.prepareRequest(e,t),Mh(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){Mh(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL));let{apiKey:t}=await sh(this);if(Mh(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL)),t===null)return;Nh(t);try{return P([{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}:{}})}};Ph=jh,exports.APIConnectionError=l,exports.APIConnectionTimeoutError=u,exports.APIError=s,exports.APIPromise=Ut,exports.APIUserAbortError=c,exports.AuthenticationError=f,exports.AzureOpenAI=Oh,exports.BadRequestError=d,exports.BedrockOpenAI=zh,exports.ConflictError=h,exports.InternalServerError=v,exports.InvalidWebhookSignatureError=x,exports.NotFoundError=m,exports.OAuthError=S,exports.OpenAI=$,exports.default=$,exports.OpenAIError=o,exports.PagePromise=Kt,exports.PermissionDeniedError=p,exports.RateLimitError=_,exports.SubjectTokenProviderError=C,exports.UnprocessableEntityError=g,exports.toFile=mi,exports.toStreamingFile=jr;