noskills 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +25 -1123
  2. package/dist/launcher.js +162 -0
  3. package/dist/noskills.js +38 -0
  4. package/package.json +31 -16
  5. package/noskills.js +0 -146
  6. package/ts/chunks/ajan-bridge-6UUIUFAV.js +0 -1
  7. package/ts/chunks/anthropic-ICVQ5GK6.js +0 -1
  8. package/ts/chunks/approve-R7MCYHCS.js +0 -1
  9. package/ts/chunks/ask-GBLFPNFX.js +0 -2
  10. package/ts/chunks/block-YEKLMXHR.js +0 -1
  11. package/ts/chunks/cancel-7NS4WM2N.js +0 -1
  12. package/ts/chunks/chunk-2CLD527I.js +0 -1
  13. package/ts/chunks/chunk-34AWV7DB.js +0 -1
  14. package/ts/chunks/chunk-3M26Y3NG.js +0 -27
  15. package/ts/chunks/chunk-3QVRJO3V.js +0 -1
  16. package/ts/chunks/chunk-5ALJRBMW.js +0 -22
  17. package/ts/chunks/chunk-5NMDE2VZ.js +0 -4
  18. package/ts/chunks/chunk-6BKTY7SA.js +0 -4
  19. package/ts/chunks/chunk-6M7PCVUR.js +0 -1
  20. package/ts/chunks/chunk-6O2RXYTM.js +0 -3
  21. package/ts/chunks/chunk-7DIQYKPL.js +0 -3
  22. package/ts/chunks/chunk-7J6R2D2K.js +0 -2
  23. package/ts/chunks/chunk-ATNTR7M5.js +0 -1
  24. package/ts/chunks/chunk-AW3XJGEP.js +0 -1
  25. package/ts/chunks/chunk-BRC46A3N.js +0 -39
  26. package/ts/chunks/chunk-C5LYQDQH.js +0 -368
  27. package/ts/chunks/chunk-CCYWFSXR.js +0 -3
  28. package/ts/chunks/chunk-CL55MNGD.js +0 -1
  29. package/ts/chunks/chunk-CSP2GUD4.js +0 -29
  30. package/ts/chunks/chunk-D2UKX2VW.js +0 -2
  31. package/ts/chunks/chunk-DGYDUGTM.js +0 -1
  32. package/ts/chunks/chunk-FB3Z7XYQ.js +0 -1
  33. package/ts/chunks/chunk-FLLYK5FU.js +0 -1
  34. package/ts/chunks/chunk-GCPGG4YB.js +0 -1
  35. package/ts/chunks/chunk-HISXAZ4Y.js +0 -1
  36. package/ts/chunks/chunk-HLDPASM6.js +0 -3
  37. package/ts/chunks/chunk-HNQA5O2S.js +0 -2
  38. package/ts/chunks/chunk-HUP7XWW6.js +0 -1
  39. package/ts/chunks/chunk-I4Z2RF7L.js +0 -31
  40. package/ts/chunks/chunk-J3XNDEMU.js +0 -4
  41. package/ts/chunks/chunk-K6FVY52W.js +0 -5
  42. package/ts/chunks/chunk-KQJGXVWX.js +0 -91
  43. package/ts/chunks/chunk-M4U4Y3XQ.js +0 -7
  44. package/ts/chunks/chunk-M6CAJL36.js +0 -1
  45. package/ts/chunks/chunk-MPHTBN7E.js +0 -1
  46. package/ts/chunks/chunk-NYIFCLEG.js +0 -1
  47. package/ts/chunks/chunk-RRDWQKZY.js +0 -1
  48. package/ts/chunks/chunk-RVNSKPFL.js +0 -1
  49. package/ts/chunks/chunk-S5F2DAAG.js +0 -5
  50. package/ts/chunks/chunk-SCYP2G2T.js +0 -3
  51. package/ts/chunks/chunk-SWP6BJR6.js +0 -147
  52. package/ts/chunks/chunk-SWRVSRYY.js +0 -5
  53. package/ts/chunks/chunk-T2X4E35X.js +0 -1
  54. package/ts/chunks/chunk-TDLTCTV4.js +0 -1
  55. package/ts/chunks/chunk-TKBGNLNV.js +0 -1
  56. package/ts/chunks/chunk-UY4YFVSW.js +0 -3
  57. package/ts/chunks/chunk-V5ZXCJPI.js +0 -2
  58. package/ts/chunks/chunk-W46BJM2F.js +0 -1
  59. package/ts/chunks/chunk-W7KQFMHV.js +0 -1
  60. package/ts/chunks/chunk-XGRZPTAD.js +0 -24
  61. package/ts/chunks/chunk-XTQFSF6C.js +0 -1
  62. package/ts/chunks/chunk-YN3SHWBR.js +0 -1
  63. package/ts/chunks/chunk-ZAY6LSJD.js +0 -2
  64. package/ts/chunks/chunk-ZGVXR3EC.js +0 -8
  65. package/ts/chunks/chunk-ZW5C5IGT.js +0 -32
  66. package/ts/chunks/claude-code-J2V5WSGZ.js +0 -1
  67. package/ts/chunks/concern-EDWQHU4H.js +0 -1
  68. package/ts/chunks/config-E7BDBHPK.js +0 -1
  69. package/ts/chunks/decision-ledger-5QXKZSV2.js +0 -1
  70. package/ts/chunks/delegate-LVQQ3GCV.js +0 -1
  71. package/ts/chunks/diagrams-2F5ZYXA7.js +0 -1
  72. package/ts/chunks/diagrams-H62JGTIS.js +0 -1
  73. package/ts/chunks/dist-3MH5UCQU.js +0 -12
  74. package/ts/chunks/done-U3TOSZIX.js +0 -1
  75. package/ts/chunks/followup-J2HJU3ZT.js +0 -1
  76. package/ts/chunks/free-73WMLMCT.js +0 -1
  77. package/ts/chunks/gemini-GA6P4M7D.js +0 -1
  78. package/ts/chunks/init-6CVDGRY2.js +0 -1
  79. package/ts/chunks/invoke-hook-2TMKWL7I.js +0 -15
  80. package/ts/chunks/kiro-BJSKSAUC.js +0 -1
  81. package/ts/chunks/learn-7Q2VWZMI.js +0 -7
  82. package/ts/chunks/ledger-XR4AHZRX.js +0 -2
  83. package/ts/chunks/list-CUQCPXZH.js +0 -1
  84. package/ts/chunks/manager-WTLJ5C2I.js +0 -3
  85. package/ts/chunks/mod-BZA5TFW7.js +0 -1
  86. package/ts/chunks/mod-RWA5ZPYH.js +0 -1
  87. package/ts/chunks/mod-X372UNSQ.js +0 -1
  88. package/ts/chunks/mod-XVE4ZWPY.js +0 -1
  89. package/ts/chunks/multipart-parser-DKDFOZKD.js +0 -2
  90. package/ts/chunks/next-CEYZSYGB.js +0 -20
  91. package/ts/chunks/node-33JV5VS3.js +0 -15
  92. package/ts/chunks/node-XYP2DQHR.js +0 -74
  93. package/ts/chunks/node-ZSGIX7K3.js +0 -1
  94. package/ts/chunks/ollama-X6OGN5BW.js +0 -1
  95. package/ts/chunks/openai-TV7KLQ2C.js +0 -1
  96. package/ts/chunks/openai-YPM2E7QS.js +0 -30
  97. package/ts/chunks/opencode-AK6WWZRF.js +0 -1
  98. package/ts/chunks/pack-EOUSZGJT.js +0 -5
  99. package/ts/chunks/plan-export-ZBINRAAS.js +0 -3
  100. package/ts/chunks/purge-GPMC5A6Y.js +0 -5
  101. package/ts/chunks/reopen-LPVNZN5I.js +0 -1
  102. package/ts/chunks/reset-RNLPXGWQ.js +0 -1
  103. package/ts/chunks/review-ZGAY5XCN.js +0 -1
  104. package/ts/chunks/rule-SNBQ4VZD.js +0 -6
  105. package/ts/chunks/run-4TDP4C7Z.js +0 -3
  106. package/ts/chunks/sdk-MEVPL5WT.js +0 -1
  107. package/ts/chunks/session-J7TSLNEH.js +0 -1
  108. package/ts/chunks/spec-3NSPFDIC.js +0 -1
  109. package/ts/chunks/src-HXQVVTGQ.js +0 -3
  110. package/ts/chunks/status-DIEA2OGR.js +0 -1
  111. package/ts/chunks/sync-HZNKILSP.js +0 -1
  112. package/ts/chunks/validate-MWHDOF2F.js +0 -1
  113. package/ts/chunks/vertexai-ARXI4AMJ.js +0 -1
  114. package/ts/chunks/watch-P6HABMAS.js +0 -7
  115. package/ts/chunks/web-BMIC3VJQ.js +0 -1
  116. package/ts/chunks/wontfix-6UKEYTVB.js +0 -1
  117. package/ts/noskills.js +0 -2
@@ -1,30 +0,0 @@
1
- import{c as Q_,d as H_,e as X_}from"./chunk-HISXAZ4Y.js";var If=Q_((G,su)=>{"use strict";if(typeof su<"u"&&su!==globalThis.module&&typeof G<"u"&&su.exports===G){Object.defineProperty(G,"__esModule",{value:!0}),G.findX509Credential=G.rememberX509Credential=G.findX509OAuthError=G.rememberX509OAuthError=G.isApprovedX509Client=G.markApprovedX509Client=G.isRetryableX509IssuerError=G.markRetryableX509IssuerError=G.isTransientX509ConnectionError=G.markTransientX509ConnectionError=G.rememberRegisteredX509Transport=G.findRegisteredX509Transport=void 0;let r=new WeakMap,e=new WeakSet,t=new WeakSet,n=new WeakSet,s=new WeakMap,i=new WeakMap;G.findRegisteredX509Transport=WeakMap.prototype.get.bind(r),G.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(r),G.markTransientX509ConnectionError=WeakSet.prototype.add.bind(e),G.isTransientX509ConnectionError=WeakSet.prototype.has.bind(e),G.markRetryableX509IssuerError=WeakSet.prototype.add.bind(t),G.isRetryableX509IssuerError=WeakSet.prototype.has.bind(t),G.markApprovedX509Client=WeakSet.prototype.add.bind(n),G.isApprovedX509Client=WeakSet.prototype.has.bind(n),G.rememberX509OAuthError=WeakMap.prototype.set.bind(s),G.findX509OAuthError=WeakMap.prototype.get.bind(s),G.rememberX509Credential=WeakMap.prototype.set.bind(i),G.findX509Credential=WeakMap.prototype.get.bind(i)}});function w(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t}function u(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var De=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return De=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function jt(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var li=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e="cause"in r,t=new Error(r.message,e?{cause:r.cause}:{});return r.stack&&(t.stack=r.stack),e&&!Object.prototype.hasOwnProperty.call(t,"cause")&&(t.cause=r.cause),r.name&&(t.name=r.name),t}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var f=class extends Error{},J=class r extends f{constructor(e,t,n,s){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let i=t;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,n){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new Je({message:n,cause:li(t)});let i=t?.error;return e===400?new bt(e,i,n,s):e===401?new tr(e,i,n,s):e===403?new rr(e,i,n,s):e===404?new nr(e,i,n,s):e===409?new sr(e,i,n,s):e===422?new or(e,i,n,s):e===429?new ir(e,i,n,s):e>=500?new ar(e,i,n,s):new r(e,i,n,s)}},Y=class extends J{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Je=class extends J{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},se=class extends Je{constructor({message:e}={}){super({message:e??"Request timed out."})}},bt=class extends J{},tr=class extends J{},rr=class extends J{},nr=class extends J{},sr=class extends J{},or=class extends J{},ir=class extends J{},ar=class extends J{},ur=class extends f{constructor(){super("Could not parse response content as the length limit was reached")}},cr=class extends f{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Fe=class extends Error{constructor(e){super(e)}},Ve=class extends J{constructor(e,t,n){let s="OAuth2 authentication error",i;if(t&&typeof t=="object"){let o=t;i=o.error;let a=o.error_description;a&&typeof a=="string"?s=a:i&&(s=i)}super(e,t,s,n),this.error_code=i}},Mr=class extends f{constructor(e,t,n){super(e),this.provider=t,this.cause=n}};var V_=/^[a-z][a-z0-9+.-]*:/i,Md=r=>V_.test(r),Oe=r=>(Oe=Array.isArray,Oe(r)),Ld=Oe;function di(r){return typeof r!="object"?{}:r??{}}function Wa(r){if(!r)return!0;for(let e in r)return!1;return!0}function P(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function L(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Uc=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new f(`${r} must be an integer`);if(e<0)throw new f(`${r} must be a positive integer`);return e};var Bd=r=>{try{return JSON.parse(r)}catch{return}};var Xn=(r,...e)=>new Promise((t,n)=>{let s=[...new Set(e.filter(p=>p!=null))],i,o=!1,a=()=>{for(let p of s)try{p.removeEventListener("abort",d)}catch{}},c=p=>{o||(o=!0,i!==void 0&&(clearTimeout(i),i=void 0),a(),p())},d=()=>{c(()=>n())};if(s.some(p=>p.aborted)){d();return}i=setTimeout(()=>{c(t)},r);for(let p of s){if(o)break;try{p.addEventListener("abort",d,{once:!0})}catch(y){c(()=>n(y))}}s.some(p=>p.aborted)&&d()});var Jn=globalThis,Ua=typeof Jn.FinalizationRegistry=="function"?new Jn.FinalizationRegistry(r=>{try{r()}catch{}}):void 0,Kd=new WeakMap,fi=new WeakMap;function G_(r,e,t){let n=fi.get(r);if(!n){let i=new Set,o=()=>{fi.delete(r);for(let a of i)t.unregister(a),a.deref()?.();i.clear()};n={callbacks:i,abort:o},r.addEventListener("abort",o,{once:!0}),fi.set(r,n)}let s=n;return s.callbacks.add(e),()=>{s.callbacks.delete(e),t.unregister(e),s.callbacks.size===0&&(fi.get(r)===s&&fi.delete(r),r.removeEventListener("abort",s.abort))}}function Y_(r,e,t){r.addEventListener("abort",()=>e.deref()?.delete(t),{once:!0})}function Qc(r,e,t){if(typeof Jn.WeakRef=="function"&&Ua&&!t.aborted){let n=Kd.get(r);n||(n=new Set,Kd.set(r,n)),n.add(e),Y_(t,new Jn.WeakRef(n),e)}}function Nd(r,e,t){if(r.aborted)return e(),()=>{};if(typeof Jn.WeakRef!="function"||!Ua)return r.addEventListener("abort",e,{once:!0}),()=>r.removeEventListener("abort",e);let n=new Jn.WeakRef(e),s=G_(r,n,Ua);return Ua.register(e,s,n),Qc(t,e,t),s}function pi(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Hc(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function hi(r,e){let t=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return Hc({start(){},async pull(n){let{done:s,value:i}=await t.next();s?n.close():n.enqueue(i)},async cancel(){await t.return?.()}},e)}function Qa(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function dt(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var Ud;function ge(r){let e;return(Ud??(e=new globalThis.TextEncoder,Ud=e.encode.bind(e)))(r)}var Qd;function Hd(r){let e;return(Qd??(e=new globalThis.TextDecoder,Qd=e.decode.bind(e)))(r)}var Xc,le,oe,ae,wt,Lr,Jd,mi=64*1024,Br=class{constructor(){Xc.add(this),le.set(this,void 0),oe.set(this,void 0),ae.set(this,void 0),wt.set(this,void 0),Lr.set(this,void 0),w(this,le,new Uint8Array,"f"),w(this,oe,0,"f"),w(this,ae,0,"f"),w(this,wt,0,"f"),w(this,Lr,!1,"f")}decode(e){if(e==null)return[];let t;if(e instanceof ArrayBuffer?t=new Uint8Array(e):typeof e=="string"?t=ge(e):t=e,t.length===0)return[];if(u(this,Lr,"f")&&(w(this,Lr,!1,"f"),t[0]===10&&(t=t.subarray(1)),t.length===0))return[];u(this,Xc,"m",Jd).call(this,t);let n=[],s;for(;(s=Z_(u(this,le,"f"),u(this,wt,"f"),u(this,ae,"f")))!=null;){let i=Hd(u(this,le,"f").subarray(u(this,oe,"f"),s.preceding));n.push(i),w(this,oe,s.index,"f"),s.carriage&&(u(this,oe,"f")<u(this,ae,"f")&&u(this,le,"f")[u(this,oe,"f")]===10?w(this,oe,u(this,oe,"f")+1,"f"):u(this,oe,"f")===u(this,ae,"f")&&w(this,Lr,!0,"f")),w(this,wt,u(this,oe,"f"),"f")}if(w(this,wt,u(this,ae,"f"),"f"),u(this,oe,"f")===u(this,ae,"f"))w(this,oe,0,"f"),w(this,ae,0,"f"),w(this,wt,0,"f"),u(this,le,"f").length>mi&&w(this,le,new Uint8Array,"f");else if(n.length>0&&u(this,le,"f").length>mi){let i=u(this,ae,"f")-u(this,oe,"f");if(i<=mi||u(this,le,"f").length>i*4){let o=i<=mi?Math.min(Math.max(i*2,256),mi):i*2,a=new Uint8Array(o);a.set(u(this,le,"f").subarray(u(this,oe,"f"),u(this,ae,"f"))),w(this,le,a,"f"),w(this,oe,0,"f"),w(this,ae,i,"f"),w(this,wt,i,"f")}}return n}flush(){return w(this,Lr,!1,"f"),u(this,oe,"f")===u(this,ae,"f")?[]:this.decode(`
2
- `)}};le=new WeakMap,oe=new WeakMap,ae=new WeakMap,wt=new WeakMap,Lr=new WeakMap,Xc=new WeakSet,Jd=function(e){if(u(this,ae,"f")+e.length>u(this,le,"f").length){let t=u(this,ae,"f")-u(this,oe,"f");if(u(this,oe,"f")>=u(this,le,"f").length/2&&t+e.length<=u(this,le,"f").length)u(this,le,"f").copyWithin(0,u(this,oe,"f"),u(this,ae,"f"));else{let n=Math.max(u(this,le,"f").length*2,t+e.length,256),s=new Uint8Array(n);s.set(u(this,le,"f").subarray(u(this,oe,"f"),u(this,ae,"f"))),w(this,le,s,"f")}w(this,wt,u(this,wt,"f")-u(this,oe,"f"),"f"),w(this,ae,t,"f"),w(this,oe,0,"f")}u(this,le,"f").set(e,u(this,ae,"f")),w(this,ae,u(this,ae,"f")+e.length,"f")};Br.NEWLINE_CHARS=new Set([`
3
- `,"\r"]);Br.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Z_(r,e,t){for(let i=e;i<t;i++){if(r[i]===10)return{preceding:i,index:i+1,carriage:!1};if(r[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Vd(r){for(let e=0;e<r.length-1;e++){let t=Xd(r,e);if(t>0){let n=e+t,s=Xd(r,n);if(s>0)return n+s}}return-1}function Xd(r,e){return r[e]===10?1:r[e]===13?r[e+1]===10?2:1:0}var Xa={off:0,error:200,warn:300,info:400,debug:500},Jc=(r,e,t)=>{if(r){if(P(Xa,r))return r;ue(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Xa))}`)}};function _i(){}function Ha(r,e,t){return!e||Xa[r]>Xa[t]?_i:e[r].bind(e)}var ey={error:_i,warn:_i,info:_i,debug:_i},Gd=new WeakMap;function ue(r){let e=r.logger,t=r.logLevel??"off";if(!e)return ey;let n=Gd.get(e);if(n&&n[0]===t)return n[1];let s={error:Ha("error",e,t),warn:Ha("warn",e,t),info:Ha("info",e,t),debug:Ha("debug",e,t)};return Gd.set(e,[t,s]),s}var Yd=new Set(["apikey","accesstoken","refreshtoken","sessiontoken","sessionid","idtoken","authtoken","authorization","token","password","clientsecret","signingsecret","sig","signature","xgoogsignature","xgoogcredential","xamzsecuritytoken","xamzsignature","xamzcredential"]);function yi(r){let e=r.toLowerCase().replace(/[-_]/gu,"");return Yd.has(e)||Yd.has(e.replace(/^x/u,""))}var ty=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 Va(r){return ty.has(r.toLowerCase().replace(/_/gu,"-"))||yi(r)}function Ja(r){let e=new URL(r);e.username="",e.password="",e.hash="";for(let t of e.searchParams.keys())yi(t)&&e.searchParams.set(t,"***");return e.href}var qt=r=>{if(r.options){if(r.options={...r.options},delete r.options.headers,r.options.path){let e=r.options.path,t=new URL(Ja(new URL(e,"https://redacted.invalid").href));r.options.path=t.origin==="https://redacted.invalid"?`${e.startsWith("/")?"/":""}${t.pathname.slice(1)}${t.search}`:t.href}r.options.query&&(r.options.query=Object.fromEntries(Object.entries(r.options.query).map(([e,t])=>[e,yi(e)?"***":t])))}return r.url&&(r.url=Ja(r.url)),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,Va(e)?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r};var Ga,Ya,Za,Vc;function ry(r){return!(r instanceof J)&&jt(r)}function Zd(){let r=[],e=0,t=!1;return{get length(){return r.length-e},get canceled(){return t},enqueue(n){t||r.push(n)},dequeue(){if(e===r.length)return;let n=r[e];return r[e]=void 0,e+=1,e===r.length?(r=[],e=0):e>=1024&&e*2>=r.length&&(r=r.slice(e),e=0),n},cancel(){t=!0,r.length=0,e=0}}}var ze=class r{constructor(e,t,n){Ga.add(this),Ya.set(this,void 0),Za.set(this,!1),this.iterator=e,this.controller=t,w(this,Ya,n,"f")}static fromSSEResponse(e,t,n,s,i="legacy"){let o=!1,a=n?ue(n):console;async function*c(){if(o)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let d=!1,p=!1,y=sy(e,t),_=y.return.bind(y);y.return=b=>(p||t.abort(),_(b));try{for await(let b of y){if(b.data==="[DONE]"){p=!0;break}let h;try{h=JSON.parse(b.data)}catch{throw a.error("Could not parse message into JSON:"),a.error("From chunk:"),new SyntaxError("Error reading response: malformed server-sent event JSON.")}if(i==="legacy"){if(b.event?.startsWith("thread.")){yield{event:b.event,data:h};continue}if(b.event==="error")throw new J(void 0,h?.error??h,void 0,e.headers);if(h&&h.error)throw new J(void 0,h.error,void 0,e.headers)}yield s?{event:b.event,data:h}:h}d=!0}catch(b){if(p||ry(b)||t.signal.aborted&&b===t.signal.reason)return;throw b}finally{d||t.abort()}}return new r(c,t,n)}static fromReadableStream(e,t,n){let s=!1;async function*i(){let a=new Br,c=e.getReader(),d=!1,p,y=()=>{p??(p=c.cancel()),p.catch(()=>{})};t.signal.addEventListener("abort",y,{once:!0});try{if(t.signal.aborted){y();return}for(;;){let{value:_,done:b}=await c.read();if(b){d=!0;break}if(t.signal.aborted)return;for(let h of a.decode(_)){if(t.signal.aborted)return;yield h}}if(t.signal.aborted)return;for(let _ of a.flush()){if(t.signal.aborted)return;yield _}}finally{t.signal.removeEventListener("abort",y),d||y(),c.releaseLock()}}async function*o(){if(s)throw new f("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let c of i())if(c){let d;try{d=JSON.parse(c)}catch(p){throw p instanceof SyntaxError?new SyntaxError("Error reading response: malformed newline-delimited JSON."):p}yield d}a=!0}catch(c){if(t.signal.aborted||jt(c))return;throw c}finally{a||t.abort()}}return new r(o,t,n)}[(Ya=new WeakMap,Za=new WeakMap,Ga=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}__betaTransformIterator(e){this.iterator=e(this.iterator.bind(this))}tee(){let{controller:e}=this,t=Zd(),n=Zd(),s=this.iterator(),i=a=>({next:()=>{if(a.canceled)return Promise.resolve({value:void 0,done:!0});if(a.length===0){let c=s.next();t.enqueue(c),n.enqueue(c)}return a.dequeue()},return:async()=>(a.canceled||(a.cancel(),t.canceled&&n.canceled&&await u(this,Ga,"m",Vc).call(this,s,e)),{value:void 0,done:!0})}),o=a=>{let c=new r(()=>i(a),e,u(this,Ya,"f"));return w(c,Za,!0,"f"),c};return[o(t),o(n)]}toReadableStream(){let{controller:e}=this,t,n,s=()=>n??(n=u(this,Ga,"m",Vc).call(this,t,e));return Hc({start:async()=>{t=this[Symbol.asyncIterator]()},async pull(i){try{let{value:o,done:a}=await t.next();if(a)return i.close();let c=ge(JSON.stringify(o)+`
4
- `);i.enqueue(c)}catch(o){i.error(o),s().catch(()=>{})}},cancel:s})}};Vc=async function(e,t){let n=e.return;n&&(u(this,Za,"f")||t.abort(),await Reflect.apply(n,e,[]))};function ny(r,e){let t=typeof r.getReader=="function"?r.getReader():void 0,n=t?{next:()=>t.read(),return:()=>t.cancel()}:Qa(r)[Symbol.asyncIterator](),s={value:void 0,done:!0},i=!1,o=!1,a,c,d=()=>new Promise(b=>{c=b}),p=()=>{if(o||i)return a;o=!0;try{a=Promise.resolve(n.return?.())}catch(b){a=Promise.reject(b)}return a.catch(()=>{}),a},y=()=>{queueMicrotask(()=>{c?.(),p()})};return{iterator:{async next(){if(e.aborted)return s;let b=d().then(()=>s);try{let h=await Promise.race([n.next(),b]);return e.aborted?s:h.done?(i=!0,s):{value:h.value,done:!1}}catch(h){if(e.aborted&&(jt(h)||h===e.reason))return s;throw h}finally{c=void 0}},async return(){let b=p();if(b&&!e.aborted){let h=d();try{e.aborted||await Promise.race([b,h])}finally{c=void 0}}return s},[Symbol.asyncIterator](){return this}},start(){e.addEventListener("abort",y,{once:!0}),e.aborted&&y()},async cleanup(b){let h;try{e.removeEventListener("abort",y)}catch(A){h=A}if(!i){let A=p();if(A&&!b&&!e.aborted)try{await A}catch(O){h??(h=O)}}if(t)try{t.releaseLock()}catch(A){h??(h=A)}if(h!==void 0&&!b&&!e.aborted)throw h}}}async function*sy(r,e){if(!r.body)throw e.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product==="ReactNative"?new f("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new f("Attempted to iterate over a response with no body");let t=new Gc,n=new Br,{signal:s}=e,i=ny(r.body,s),o=!1;try{i.start();for await(let c of iy(i.iterator)){if(s.aborted)return;for(let d of n.decode(c)){if(s.aborted)return;let p=t.decode(d);p&&(yield p)}}if(s.aborted)return;for(let c of n.flush()){if(s.aborted)return;let d=t.decode(c);d&&(yield d)}if(s.aborted)return;let a=t.flush();a&&(yield a)}catch(a){if(o=!0,!s.aborted||!jt(a)&&a!==s.reason)throw a}finally{await i.cleanup(o)}}var oy=3;async function*iy(r){let e=new Uint8Array,t=0,n=0,s=0;for await(let i of r){if(i==null)continue;let o;if(i instanceof ArrayBuffer?o=new Uint8Array(i):typeof i=="string"?o=ge(i):o=i,n+o.length>e.length){let c=n-t;if(t>=e.length/2&&c+o.length<=e.length)e.copyWithin(0,t,n);else{let d=new Uint8Array(Math.max(e.length*2,c+o.length));d.set(e.subarray(t,n)),e=d}s-=t,t=0,n=c}e.set(o,n),n+=o.length;let a;for(;(a=Vd(e.subarray(s,n)))!==-1;)a+=s,yield e.slice(t,a),t=a,s=t;s=Math.max(t,n-oy)}n>t&&(yield e.slice(t,n))}var Gc=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.slice(0,-1)),!e){if(!this.event&&!this.data.length)return null;let i={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,,n]=ay(e,":"),s=n;return s.startsWith(" ")&&(s=s.slice(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}flush(){return this.decode("")}};function ay(r,e){let t=r.indexOf(e);return t!==-1?[r.slice(0,t),e,r.slice(t+e.length)]:[r,"",""]}async function Kr(r,e){let{response:t,requestLogID:n,retryOfRequestLogID:s,startTime:i}=e,o,a=await(async()=>{if(e.options.stream)return ue(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData,e.options.__streamMode):ze.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData,e.options.__streamMode);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let d=t.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if(d?.includes("application/json")||d?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let b=await t.text();if(!b)return;let h=JSON.parse(b);return o=b.length,gi(h,t)}return await t.text()})().catch(c=>{throw uy(c,e.controller.signal)});return r.logLevel==="debug"&&ue(r).debug(`[${n}] response parsed`,qt({retryOfRequestLogID:s,url:t.url,status:t.status,body:o===void 0?a:{type:"json",length:o},durationMs:Date.now()-i})),a}function uy(r,e){if(!e.aborted||r!==e.reason||jt(r))return r;let t="This operation was aborted",n=globalThis.DOMException;return typeof n=="function"?new n(t,"AbortError"):Object.assign(new Error(t),{name:"AbortError"})}function gi(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var lr="7.54.0";var nf=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function cy(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ly=()=>{let r=cy();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lr,"X-Stainless-OS":tf(Deno.build.os),"X-Stainless-Arch":ef(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":lr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process?.version??"unknown"};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lr,"X-Stainless-OS":tf(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ef(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=dy();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":lr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function dy(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/\bEdg(?:e|A|iOS)?\b(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let s=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${s}.${i}.${o}`}}}return null}var ef=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",tf=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),rf,sf=()=>rf??(rf=ly());var bi=new WeakMap;function eu(r,e){let t=bi.get(r);return t||(t=new Set,bi.set(r,t)),t.add(e),()=>{let n=bi.get(r);n&&(n.delete(e),n.size===0&&bi.delete(r))}}var of=({headers:r,body:e})=>{let t=typeof e=="object"&&e!==null?bi.get(e):void 0,n;if(!t||t.size===0)n=JSON.stringify(e);else{let s=[...t];n=JSON.stringify(e,function(i,o){let a=o;for(let c of s){let d=c.value(this,i,a);d!==void 0&&(a=d)}return a});for(let i of s)i.complete()}return{bodyHeaders:{"content-type":"application/json"},body:n}};var Yc="RFC3986",Zc=String,el={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:Zc},af="RFC1738";var uf,cf=(r,e)=>{let t=uf??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return uf=t,t(r,e)};var At=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var tl=1024,lf=(r,e,t,n,s)=>{if(r.length===0)return r;let i=r;if(typeof r=="symbol"?i=Symbol.prototype.toString.call(r):typeof r!="string"&&(i=String(r)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,a=>"%26%23"+Number.parseInt(a.slice(2),16)+"%3B");let o="";for(let a=0;a<i.length;){let c=Math.min((Math.floor(a/tl)+1)*tl,i.length);c<i.length&&i.codePointAt(c-1)>65535&&(c+=1);let d=i.length>=tl?i.slice(a,c):i,p=[];for(let y=0;y<d.length;++y){let _=d.charCodeAt(y);if(_===45||_===46||_===95||_===126||_>=48&&_<=57||_>=65&&_<=90||_>=97&&_<=122||s===af&&(_===40||_===41)){p[p.length]=d.charAt(y);continue}if(_<128){p[p.length]=At[_];continue}if(_<2048){p[p.length]=At[192|_>>6]+At[128|_&63];continue}if(_<55296||_>=57344){p[p.length]=At[224|_>>12]+At[128|_>>6&63]+At[128|_&63];continue}y+=1,_=65536+((_&1023)<<10|d.charCodeAt(y)&1023),p[p.length]=At[240|_>>18]+At[128|_>>12&63]+At[128|_>>6&63]+At[128|_&63]}o+=p.join(""),a=c}return o};function df(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function rl(r,e){if(Oe(r)){let t=[];for(let n of r)t.push(e(n));return t}return e(r)}var pf={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat:String},hf=function(e,t){Array.prototype.push.apply(e,Oe(t)?t:[t])},ff,he={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:lf,encodeValuesOnly:!1,format:Yc,formatter:Zc,indices:!1,serializeDate(r){return(ff??(ff=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function py(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var nl={};function mf(r,e,t,n,s,i,o,a,c,d,p,y,_,b,h,A,O,E){let x=r,q=E,C=0,D=!1;for(;(q=q.get(nl))!==void 0&&!D;){let T=q.get(r);if(C+=1,T!==void 0){if(T===C)throw new RangeError("Cyclic object value");D=!0}q.get(nl)===void 0&&(C=0)}if(typeof d=="function"?x=d(e,x):x instanceof Date?x=_?.(x):t==="comma"&&Oe(x)&&(x=rl(x,T=>T instanceof Date?_?.(T):T)),x===null){if(i)return c&&!A?c(e,he.encoder,O,"key",b):e;x=""}if(py(x)||df(x)){if(c){let T=A?e:c(e,he.encoder,O,"key",b);return[h?.(T)+"="+h?.(c(x,he.encoder,O,"value",b))]}return[h?.(e)+"="+h?.(String(x))]}let R=[];if(x===void 0)return R;let v;if(t==="comma"&&Oe(x))A&&c&&(x=rl(x,c)),v=[{value:x.length>0?x.join(",")||null:void 0}];else if(Oe(d))v=d;else{let T=Object.keys(x);p&&T.sort(p),v=T}let S=a?String(e).replace(/\./g,"%2E"):String(e),j=n&&Oe(x)&&x.length===1?S+"[]":S;if(s&&Oe(x)&&x.length===0)return j+"[]";for(let T of v){let $=typeof T=="object"&&T.value!==void 0?T.value:x[T];if(o&&$===null)continue;let k=y&&a?T.replace(/\./g,"%2E"):T,z;Oe(x)?z=typeof t=="function"?t(j,k):j:z=j+(y?"."+k:"["+k+"]"),E.set(r,C);let N=new WeakMap([[nl,E]]);hf(R,mf($,z,t,n,s,i,o,a,t==="comma"&&A&&Oe(x)?null:c,d,p,y,_,b,h,A,O,N))}return R}function hy(r=he){if(r.allowEmptyArrays!==void 0&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(r.encodeDotInKeys!==void 0&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&r.encoder!==void 0&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||he.charset;if(r.charset!==void 0&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Yc;if(r.format!==void 0){if(!cf(el,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=el[t],s=he.filter;(typeof r.filter=="function"||Oe(r.filter))&&(s=r.filter);let i;if(r.arrayFormat&&r.arrayFormat in pf?i=r.arrayFormat:"indices"in r?i=r.indices?"indices":"repeat":i=he.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o;return r.allowDots===void 0?o=r.encodeDotInKeys?!0:he.allowDots:o=!!r.allowDots,{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:he.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:he.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:he.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:r.delimiter===void 0?he.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:he.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:he.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:he.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:he.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:he.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:he.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:he.strictNullHandling}}function _f(r,e={}){let t=r,n=hy(e),s,i;typeof n.filter=="function"?(i=n.filter,t=i("",t)):Oe(n.filter)&&(i=n.filter,s=i);let o=[];if(typeof t!="object"||t===null)return"";let a=pf[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);let d=new WeakMap;for(let _ of s)n.skipNulls&&t[_]===null||hf(o,mf(t[_],_,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d));let p=o.join(n.delimiter),y=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(y+=n.charset==="iso-8859-1"?"utf8=%26%2310003%3B&":"utf8=%E2%9C%93&"),p.length>0?y+p:""}function yf(r){return _f(r,{arrayFormat:"brackets"})}var _y=new Map([["global","https://api.openai.com/v1"],["us","https://us.api.openai.com/v1"],["eu","https://eu.api.openai.com/v1"],["ae","https://ae.api.openai.com/v1"],["au","https://au.api.openai.com/v1"],["in","https://in.api.openai.com/v1"],["jp","https://jp.api.openai.com/v1"]]);function sl(r){if(r.dataResidency===null||r.dataResidency===void 0)return;if(P(r,"baseURL"))throw new f("The `dataResidency` and `baseURL` options are mutually exclusive.");let e=_y.get(r.dataResidency);if(e===void 0)throw new f("Invalid `dataResidency`; expected one of: global, us, eu, ae, au, in, jp.");return e}function tu(r,e){if(r!=null)throw new f(`${e} does not support \`dataResidency\`.`)}var wi,$t=class r extends Promise{constructor(e,t,n=Kr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=n,wi.set(this,void 0),w(this,wi,e,"f")}_thenUnwrap(e){return new r(u(this,wi,"f"),this.responsePromise,async(t,n)=>gi(e(await this.parseResponse(t,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.parsedPromise=this.responsePromise.then(e=>this.parseResponse(u(this,wi,"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)}};wi=new WeakMap;var ru,Nr=class{constructor(e,t,n,s){ru.set(this,void 0),w(this,ru,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new f("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await u(this,ru,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ru=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ai=class extends $t{constructor(e,t,n){super(e,t,async(s,i)=>new n(s,i.response,await Kr(s,i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},be=class extends Nr{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},I=class extends Nr{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...di(this.options.query),after:t}}:null}},Q=class extends Nr{constructor(e,t,n,s){super(e,t,n,s),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?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...di(this.options.query),after:e}}:null}},ie=class extends Nr{constructor(e,t,n,s){super(e,t,n,s),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?!1:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...di(this.options.query),after:e}}:null}},Vn=class extends Nr{constructor(e,t,n,s){super(e,t,n,s),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?!1:this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...di(this.options.query),page:e}}:null}};var gy={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},by="urn:ietf:params:oauth:grant-type:token-exchange",wy=.5;function Ay(r,e){if(typeof r!="number"||!Number.isFinite(r)||r<=0)throw new f("Token exchange response has invalid 'expires_in' field");let t=Date.now(),n=t+r*1e3;if(!Number.isSafeInteger(n)||n<=t)throw new f("Token exchange response has invalid 'expires_in' field");let s=n-(performance.now()-e);if(s<=t)throw new f("Workload identity token expired before its exchange completed.");return s}function Ry(r,e,t){let n=(t??1200)*1e3,s=Math.min(n,e*1e3*wy);return r-s}var gf=Response.prototype,Oy=gf.arrayBuffer;function Py(r,e){let t=Object.getOwnPropertyDescriptor(e,"constructor")?.value;if(e===r||typeof t!="function"||Object.getOwnPropertyDescriptor(t,"name")?.value!=="Response"||Object.getOwnPropertyDescriptor(t,"prototype")?.value!==e)return!1;let n=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);return(n?.value==="Response"||typeof n?.get=="function")&&typeof Object.getOwnPropertyDescriptor(e,"headers")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"ok")?.get=="function"&&typeof Object.getOwnPropertyDescriptor(e,"status")?.get=="function"}function xy(r,e){if(r===e)return!0;let t=Object.getOwnPropertyDescriptor(r,"constructor")?.value;return e!==null&&Object.getPrototypeOf(e)===r&&typeof t=="function"&&Object.getOwnPropertyDescriptor(t,"name")?.value==="Body"&&Object.getOwnPropertyDescriptor(t,"prototype")?.value===r}function vy(r){let e=globalThis;return new TextDecoder("utf-8",{ignoreBOM:typeof e.Bun?.version=="string"}).decode(r)}async function Iy(r){let e,t=null;for(let s=0,i=r;i!==null&&s<16&&i!==gf;i=Object.getPrototypeOf(i),s+=1){Py(r,i)&&(t=i);let o=Object.getOwnPropertyDescriptor(i,"json");if(!o)continue;if(typeof o.value!="function")break;let a=Object.getOwnPropertyDescriptor(i,"text")?.value;if(typeof a=="function"&&xy(i,t)){e=a;break}return o.value.call(r)}let n=e===void 0?vy(await Oy.call(r)):await e.call(r);try{return JSON.parse(n)}catch{throw new SyntaxError("Token exchange response contains invalid JSON")}}function Sy(r){return typeof globalThis.Bun?.version=="string"?/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(r):/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(r)}var nu=class r{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl="https://auth.openai.com/oauth/token";let{identityProviderId:n,serviceAccountId:s,clientId:i,refreshBufferSeconds:o,provider:a}=e;this.config={identityProviderId:n,serviceAccountId:s,...i===void 0?{}:{clientId:i},...o===void 0?{}:{refreshBufferSeconds:o},provider:{tokenType:a.tokenType,getToken:a.getToken.bind(a)}},this.fetch=t??pi()}async getToken(){if(!this.cachedToken||r.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(r.needsRefresh(this.cachedToken)&&!this.refreshPromise){let e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){let t=await this.config.provider.getToken(),n={grant_type:by,subject_token:t,subject_token_type:gy[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(n.client_id=this.config.clientId);let s=performance.now(),i=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),redirect:"manual"});if(!i.ok){let p=await i.text(),y;try{y=JSON.parse(p)}catch{}throw i.status===400||i.status===401||i.status===403?new Ve(i.status,y,i.headers):J.generate(i.status,y,`Token exchange failed with status ${i.status}`,i.headers)}let o=await Iy(i),a=typeof o=="object"&&o!==null&&"access_token"in o?o.access_token:void 0;if(typeof a!="string"||a.trim().length===0||Sy(a))throw new f("Token exchange response missing 'access_token' field");let c=o.expires_in??3600,d=Ay(c,s);return this.tokenGeneration===e&&(this.cachedToken={token:a,expiresAt:d,refreshAt:Ry(d,c,this.config.refreshBufferSeconds)}),a}static isTokenExpired(e){return Date.now()>=e.expiresAt}static needsRefresh(e){return Date.now()>=e.refreshAt}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}};var bf="https://mtls.api.openai.com/v1";function Gn(r){let e;try{e=new URL(r)}catch{throw new f("X.509 workload identity requires the approved global mTLS API origin.")}if(e.origin!=="https://mtls.api.openai.com"||e.username||e.password)throw new f("X.509 workload identity requires the approved global mTLS API origin.");for(let t of e.searchParams.keys())if(yi(t))throw new f("X.509 workload identity cannot send conflicting query authentication credentials.");return e}var wf=Symbol("brand.privateNullableHeaders"),Ey=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*Cy(r){if(!r)return;if(wf in r){let{values:s,nulls:i}=r;yield*s.entries();for(let o of i)yield[o,null];return}let e=!1,t,n=Symbol.iterator in r?r[Symbol.iterator]:void 0;typeof n=="function"?t={[Symbol.iterator]:()=>n.call(r)}:(e=!0,t=Object.entries(r??{}));for(let s of t){let i=s[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let o=Ld(s[1])?s[1]:[s[1]],a=!1;for(let c of o)c!==void 0&&(e&&!a&&(a=!0,yield[i,null]),yield[i,c])}}var g=r=>{let e=new Headers,t=new Set;for(let n of r){let s=new Set;for(let[i,o]of Cy(n)){if(!Ey.test(i))throw new TypeError(`Header name must be a valid HTTP token ["${i}"]`);let a=i.toLowerCase();s.has(a)||(e.delete(a),s.add(a)),o===null?(e.delete(a),t.add(a)):(e.append(a,o),t.delete(a))}}return{[wf]:!0,values:e,nulls:t}};var ol={};H_(ol,{findRegisteredX509Transport:()=>Ty,findX509Credential:()=>Ky,findX509OAuthError:()=>Ly,isApprovedX509Client:()=>zy,isRetryableX509IssuerError:()=>Dy,isTransientX509ConnectionError:()=>qy,markApprovedX509Client:()=>Fy,markRetryableX509IssuerError:()=>$y,markTransientX509ConnectionError:()=>jy,rememberRegisteredX509Transport:()=>ky,rememberX509Credential:()=>By,rememberX509OAuthError:()=>My});var Af=new WeakMap,Rf=new WeakSet,Of=new WeakSet,Pf=new WeakSet,xf=new WeakMap,vf=new WeakMap,Ty=WeakMap.prototype.get.bind(Af),ky=WeakMap.prototype.set.bind(Af),jy=WeakSet.prototype.add.bind(Rf),qy=WeakSet.prototype.has.bind(Rf),$y=WeakSet.prototype.add.bind(Of),Dy=WeakSet.prototype.has.bind(Of),Fy=WeakSet.prototype.add.bind(Pf),zy=WeakSet.prototype.has.bind(Pf),My=WeakMap.prototype.set.bind(xf),Ly=WeakMap.prototype.get.bind(xf),By=WeakMap.prototype.set.bind(vf),Ky=WeakMap.prototype.get.bind(vf);var il=X_(If(),1),Ny=typeof il.findRegisteredX509Transport=="function"?il:ol,{findRegisteredX509Transport:Sf,rememberRegisteredX509Transport:Rx,markTransientX509ConnectionError:Ox,isTransientX509ConnectionError:ou,markRetryableX509IssuerError:Px,isRetryableX509IssuerError:al,markApprovedX509Client:Ef,isApprovedX509Client:Wy,rememberX509OAuthError:xx,findX509OAuthError:Cf,rememberX509Credential:vx,findX509Credential:Tf}=Ny;function kf(r){if(!r||typeof r!="object")throw new f("X.509 workload identity requires an approved X.509 transport capability.");let e=Sf(r);if(!e)throw new f("X.509 workload identity requires an approved X.509 transport capability.");return e}var X,Ee,Wr,Ur,Rt,Ge,Ft,zt,we,Qr,Dt,Ze,Ye,Df,au,Ff,jf,zf,Mf,qf,Lf,Z,cl,Uy=["dispatcher","agent","client","tls","proxy"],Yn=(r,e)=>Headers.prototype.get.call(r,e),Qy=1200*1e3,$f=1e3,iu=r=>{let e=new Y;return Object.defineProperty(e,"cause",{value:r.reason,writable:!0,configurable:!0}),e};function ul(r){for(let e of Headers.prototype.keys.call(r)){let t=e.toLowerCase().split("_").join("-");if(t!=="authorization"&&Va(t)||t==="host")throw new f("X.509 workload identity cannot send conflicting authentication credentials.")}}function Hy(r,e){let t=new AbortController,n=r===void 0?void 0:setTimeout(()=>t.abort(new se),r),s=n;typeof s=="object"&&s!==null&&"unref"in s&&typeof s.unref=="function"&&s.unref();let i=()=>t.abort(e?.reason);return e?.addEventListener("abort",i,{once:!0}),e?.aborted&&i(),{signal:t.signal,dispose:()=>{e?.removeEventListener("abort",i),n&&clearTimeout(n)}}}function Xy(r,e){let t,n=new Promise((s,i)=>{t=()=>i(e.reason),e.addEventListener("abort",t,{once:!0}),e.aborted&&t()});return{result:Promise.race([r.promise,n]),dispose:()=>{t&&e.removeEventListener("abort",t)}}}function uu(r){if(!r||typeof r!="object")return!1;let e=r;for(;e!==null&&e!==Object.prototype;){let n=Object.getOwnPropertyDescriptor(e,"provider");if(n){if(!("value"in n)||n.value!==void 0)return!1;break}e=Object.getPrototypeOf(e)}let t=r;for(;t!==null&&t!==Object.prototype;){let n=Object.getOwnPropertyDescriptor(t,"type");if(n){if(!("value"in n))throw new f("X.509 workload identity type must be a plain data property.");return n.value==="x509"}t=Object.getPrototypeOf(t)}return!1}function ll(r){if(!r)return;for(let t of Uy)if(P(r,t))throw new f("X.509 workload identity cannot override its approved transport capability.");let e=Object.getOwnPropertyDescriptor(r,"redirect")?.value;if(e!==void 0&&e!=="manual")throw new f("X.509 workload identity requests require manual redirects.")}function Ri(r){if(ll(r),r&&["body","headers","method","signal"].some(e=>P(r,e)))throw new f("X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.")}function dl(r){Ri(r);let e={...r};return Ri(e),e}var Pe=class{constructor(e,t,n,s){if(X.add(this),Wr.set(this,void 0),Ur.set(this,void 0),Rt.set(this,void 0),Ge.set(this,void 0),Ft.set(this,void 0),zt.set(this,void 0),we.set(this,void 0),Qr.set(this,void 0),Dt.set(this,void 0),Ze.set(this,void 0),Ye.set(this,0),w(this,we,kf(t),"f"),w(this,Wr,e.identityProviderId,"f"),w(this,Ur,e.serviceAccountId,"f"),w(this,Rt,e.refreshBufferMs,"f"),w(this,Ge,e.refreshBufferSeconds,"f"),w(this,Ft,n,"f"),w(this,zt,s,"f"),u(this,Rt,"f")!==void 0&&u(this,Ge,"f")!==void 0)throw new f("X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.");if(u(this,Rt,"f")!==void 0&&(!Number.isSafeInteger(u(this,Rt,"f"))||u(this,Rt,"f")<0))throw new f("X.509 workload identity requires a nonnegative integer refreshBufferMs.");if(u(this,Ge,"f")!==void 0&&(!Number.isSafeInteger(u(this,Ge,"f"))||u(this,Ge,"f")<0||!Number.isSafeInteger(u(this,Ge,"f")*1e3)))throw new f("X.509 workload identity requires a nonnegative integer refreshBufferSeconds.");w(this,Qr,u(this,Ge,"f")===void 0?u(this,Rt,"f")??Qy:u(this,Ge,"f")*1e3,"f")}identitySnapshot(){return{type:"x509",identityProviderId:u(this,Wr,"f"),serviceAccountId:u(this,Ur,"f"),...u(this,Rt,"f")===void 0?{}:{refreshBufferMs:u(this,Rt,"f")},...u(this,Ge,"f")===void 0?{}:{refreshBufferSeconds:u(this,Ge,"f")}}}static shouldAuthenticate(e,t,n=e.headers){return!g([t,n]).nulls.has("authorization")}snapshotHeaders(e,t){let n=u(this,X,"m",Z).call(this);return n.defaultHeaders??(n.defaultHeaders=g([e])),n.requestHeaders??(n.requestHeaders=g([t])),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:t}=u(this,X,"m",Z).call(this);if(!e||!t)throw new f("X.509 workload identity requires snapshotted request headers.");return{defaultHeaders:e,requestHeaders:t}}snapshotTenant(e,t){if(e!==u(this,Ft,"f")||t!==u(this,zt,"f"))throw new f("X.509 workload identity cannot override its enrolled organization or project.");let n=u(this,X,"m",Z).call(this);return n.tenant={organization:e,project:t},n.tenant}tenantSnapshot(){let{tenant:e}=u(this,X,"m",Z).call(this);if(!e)throw new f("X.509 workload identity requires snapshotted tenant selectors.");return e}snapshotAPIURL(e){Gn(e),u(this,X,"m",Z).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=u(this,X,"m",Z).call(this);if(e===void 0)throw new f("X.509 workload identity requires a snapshotted API destination.");return e}snapshotRequest(e,t,n){var s;(s=u(this,X,"m",Z).call(this)).request??(s.request={signal:e,timeout:t,fetchOptions:n})}requestSnapshot(){let{request:e}=u(this,X,"m",Z).call(this);if(!e)throw new f("X.509 workload identity requires snapshotted request settings.");return e}beginRequestPreparation(){let e=u(this,X,"m",Z).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){u(this,X,"m",Z).call(this).phase="planning"}beginRequestNetwork(){let e=u(this,X,"m",Z).call(this);e.deadlineArmed?e.preparationStartedAt!==void 0&&(e.monotonicStartedAt+=performance.now()-e.preparationStartedAt,e.wallStartedAt+=Date.now()-(e.preparationWallStartedAt??Date.now()),delete e.preparationStartedAt,delete e.preparationWallStartedAt):(e.wallStartedAt=Date.now(),e.monotonicStartedAt=performance.now(),e.deadlineArmed=!0)}isPlanningRequest(){return u(this,X,"m",Z).call(this).phase==="planning"}authorizePlannedRequest(e,t,n,s=!1){let i=u(this,X,"m",Z).call(this),o=Object.getOwnPropertyDescriptor(t,"headers"),a=Object.getOwnPropertyDescriptor(t,"body"),c=Object.getOwnPropertyDescriptor(t,"signal"),d=Object.getOwnPropertyDescriptor(t,"redirect");if(i.phase!=="planning"||!o||!(o.value instanceof Headers)||!a&&"body"in t||[a,c,d].some(y=>y&&!("value"in y)))throw new f("X.509 workload identity requires an approved final request.");this.snapshotAPIURL(e),ll(t);try{ul(o.value)}catch{throw new f("X.509 workload identity cannot use caller-supplied authentication credentials.")}if(Yn(o.value,"Authorization")!==null)throw new f("X.509 workload identity cannot use caller-supplied authorization credentials.");if(u(this,X,"m",cl).call(this,o.value),!s&&(c?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new f("X.509 workload identity must preserve its approved request signal.");let p=this.requestSnapshot();i.request={...p,timeout:Math.min(p.timeout,n)},i.phase="authorizing"}ownRequestBody(e,t){e instanceof ReadableStream&&e!==t&&(u(this,X,"m",Z).call(this).materializedBody=e)}static isStreamingRequestBody(e){return globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream||typeof e=="object"&&e!==null&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")}retireRequestBody(){let e=u(this,X,"m",Z).call(this),t=e.materializedBody;delete e.materializedBody,t&&u(Ee,Ee,"m",Df).call(Ee,t)}releaseRequestBody(e){let t=u(this,X,"m",Z).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?u(this,X,"m",Z).call(this).effectiveSignal=e:delete u(this,X,"m",Z).call(this).effectiveSignal}effectiveSignal(){let e=u(this,X,"m",Z).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,t){return u(this,we,"f").run(async()=>{let n=u(this,we,"f").current();if(!n)throw new f("X.509 workload identity requires an active certificate request scope.");n.owner=this,n.requestOwner=t;try{return await e()}finally{this.retireRequestBody(),this.releaseRequestCredentials(),delete n.requestOwner,delete n.owner}})}inRequest(e){let t=u(this,we,"f").current();return t?.owner===this&&t.requestOwner===e&&t.phase!=="authorizing"}matches(e){return u(this,we,"f")===u(e,we,"f")&&u(this,Wr,"f")===u(e,Wr,"f")&&u(this,Ur,"f")===u(e,Ur,"f")&&u(this,Ft,"f")===u(e,Ft,"f")&&u(this,zt,"f")===u(e,zt,"f")&&u(this,Qr,"f")===u(e,Qr,"f")}continuation(){let{wallStartedAt:e,monotonicStartedAt:t,deadlineArmed:n,request:s,requestOwner:i,effectiveSignal:o}=u(this,X,"m",Z).call(this),a={wallStartedAt:e,monotonicStartedAt:t,owner:this,...n?{deadlineArmed:n}:{},...s?{request:s}:{},...o?{effectiveSignal:o}:{},...i?{requestOwner:i}:{}};return c=>u(this,we,"f").resume(a,async()=>{try{return await c()}finally{this.releaseRequestCredentials(),delete a.requestOwner,delete a.owner}})}releaseRequestCredentials(){let e=u(this,X,"m",Z).call(this);delete e.request,delete e.phase,delete e.deadlineArmed,delete e.preparationStartedAt,delete e.preparationWallStartedAt,delete e.effectiveSignal,delete e.materializedBody,delete e.apiURL,delete e.tenant,delete e.token,delete e.defaultHeaders,delete e.requestHeaders,delete e.tokenGeneration,delete e.headers,delete e.authorization}requestStartedAt(e){return u(this,we,"f").current()?.wallStartedAt}usedWorkloadToken(e){return u(this,we,"f").current()?.token!==void 0}remainingTimeout(e,t){let n=u(this,we,"f").current();if(n===void 0)return t;let s=t-(performance.now()-n.monotonicStartedAt);if(s<=0)throw new se;return s}async waitForRetry(e,t){try{await u(this,we,"f").sleep(e,t)}catch(n){throw t?.aborted?iu(t):n}}static isRetryableFailure(e){return typeof e=="object"&&e!==null&&(ou(e)||al(e))}static retryHeaders(e){if(!e||typeof e!="object"||!al(e))return;let t=Object.getOwnPropertyDescriptor(e,"headers")?.value;return t instanceof Headers?t:void 0}async getToken(e,t){let n=t?t.signal:e?.signal;if(n?.aborted)throw iu(n);e&&Ri(t?t.fetchOptions:e.fetchOptions),u(this,X,"m",Lf).call(this,t);let s=e?u(this,X,"m",Z).call(this):void 0,i=u(this,Dt,"f");if(i&&performance.now()<i.refreshAt&&Date.now()<i.wallRefreshAt)return u(Ee,Ee,"m",au).call(Ee,s,i);let o=t&&e?this.remainingTimeout(e,t.timeout):t?.timeout,{signal:a,dispose:c}=Hy(o,n);if(n?.aborted)throw c(),iu(n);let d=u(this,Ze,"f")??u(this,X,"m",Mf).call(this);d.waiters+=1;let p=Xy(d,a);try{let y=await p.result,_=u(this,Dt,"f");if(!_||_.accessToken!==y.accessToken)throw new Y;return u(Ee,Ee,"m",au).call(Ee,s,_)}catch(y){return await u(this,X,"m",Ff).call(this,y,d,i,s,e,t)}finally{p.dispose(),c(),d.waiters-=1,u(this,X,"m",zf).call(this,d)}}invalidateToken(){let e=u(this,we,"f").current();if(!e?.token||u(this,Dt,"f")?.accessToken!==e.token||u(this,Dt,"f").generation!==e.tokenGeneration)return;w(this,Ye,u(this,Ye,"f")+1,"f"),w(this,Dt,void 0,"f");let t=u(this,Ze,"f");w(this,Ze,void 0,"f"),t?.controller.abort(new Y)}bindRequest(e,t,n){if(!(t.headers instanceof Headers))throw new f("X.509 workload identity requires the original workload authorization headers.");let s=u(this,X,"m",Z).call(this),{token:i}=s,o=e.__security??{bearerAuth:!0},a=i?`Bearer ${i}`:null;!i&&o.adminAPIKeyAuth&&n!==null&&Yn(t.headers,"Authorization")!==null&&(a=new Headers({Authorization:`Bearer ${n}`}).get("Authorization")),s.headers=t.headers,s.authorization=a,this.assertRequest(t)}adoptRequestHeaders(e){let t=u(this,X,"m",Z).call(this),n=t.headers;if(!(n instanceof Headers)||!(e.headers instanceof Headers))throw new f("X.509 workload identity must preserve its issued workload authorization.");t.headers=e.headers;try{this.assertRequest(e)}catch(s){throw t.headers=n,s}}assertRequest(e){let{headers:t}=e;if(!(t instanceof Headers))throw new f("X.509 workload identity must preserve its issued workload authorization.");let n=u(this,we,"f").current();if(!n||n.headers!==t||n.authorization===void 0||Yn(t,"Authorization")!==n.authorization)throw new f("X.509 workload identity must preserve its issued workload authorization.");u(this,X,"m",cl).call(this,t),ul(t)}fetch(){return async(e,t={})=>{let n=Gn(typeof e=="string"||e instanceof URL?e:e.url);ll(t),this.assertRequest(t);let s=t.headers;if(!(s instanceof Headers))throw new f("X.509 workload identity must preserve its issued workload authorization.");let i=new Headers([...Headers.prototype.entries.call(s)]);return ul(i),t.headers=i,t.redirect="manual",await u(this,we,"f").dispatch(n,t)}}};Ee=Pe,Wr=new WeakMap,Ur=new WeakMap,Rt=new WeakMap,Ge=new WeakMap,Ft=new WeakMap,zt=new WeakMap,we=new WeakMap,Qr=new WeakMap,Dt=new WeakMap,Ze=new WeakMap,Ye=new WeakMap,X=new WeakSet,Df=async function(e){try{await dt(e)}catch{}},au=function(e,t){return e&&(e.token=t.accessToken,e.tokenGeneration=t.generation),t.accessToken},Ff=async function(e,t,n,s,i,o){let a=o?o.signal:i?.signal;if(a?.aborted)throw iu(a);if(t.controller.signal.aborted&&t.generation!==u(this,Ye,"f"))return await this.getToken(i,o);let c=u(this,X,"m",jf).call(this,e,n,s);if(c!==void 0)return c;if(e&&typeof e=="object"&&!(e instanceof Ve)){let d=Cf(e);if(d)throw new Ve(d.status,d.error,d.headers)}throw e},jf=function(e,t,n){if(!t||t!==u(this,Dt,"f")||performance.now()>=t.expiresAt||Date.now()>=t.wallExpiresAt||!Ee.isRetryableFailure(e))return;let s=Ee.retryHeaders(e),i=s?.get("retry-after-ms"),o=i?Number(i):void 0,a=s?.get("retry-after");if(a&&(o===void 0||Number.isNaN(o))){let d=Number(a);o=Number.isNaN(d)?Date.parse(a)-Date.now():d*1e3}let c=o!==void 0&&Number.isFinite(o)&&o>=0&&o<=6e4?Math.max($f,o):$f;return t.refreshAt=Math.min(t.expiresAt,performance.now()+c),t.wallRefreshAt=Math.min(t.wallExpiresAt,Date.now()+c),u(Ee,Ee,"m",au).call(Ee,n,t)},zf=function(e){e.waiters!==0||u(this,Ze,"f")!==e||queueMicrotask(()=>{e.waiters===0&&u(this,Ze,"f")===e&&(w(this,Ze,void 0,"f"),w(this,Ye,u(this,Ye,"f")+1,"f"),e.controller.abort(new Y))})},Mf=function(){let e=new AbortController,t=u(this,Ye,"f"),n={controller:e,generation:t,waiters:0,promise:u(this,X,"m",qf).call(this,e,t)};return w(this,Ze,n,"f"),n},qf=async function(e,t){let n=performance.now(),s=Date.now();try{let i=await u(this,we,"f").exchange(u(this,Wr,"f"),u(this,Ur,"f"),e.signal),o=i.expiresIn*1e3,a=n+o,c=s+o;if(performance.now()>=a||Date.now()>=c)throw new f("X.509 workload identity token expired before its exchange completed.");if(u(this,Ye,"f")!==t||e.signal.aborted||u(this,Ze,"f")?.controller!==e)throw new Y;return w(this,Ye,u(this,Ye,"f")+1,"f"),w(this,Dt,{accessToken:i.accessToken,generation:u(this,Ye,"f"),expiresAt:a,refreshAt:a-Math.min(u(this,Qr,"f"),o/2),wallExpiresAt:c,wallRefreshAt:c-Math.min(u(this,Qr,"f"),o/2)},"f"),i}finally{u(this,Ze,"f")?.controller===e&&w(this,Ze,void 0,"f")}},Lf=function(e){if(!e)return;if(e.organization!==u(this,Ft,"f")||e.project!==u(this,zt,"f"))throw new f("X.509 workload identity cannot override its enrolled organization or project.");Gn(e.apiURL);let t=g([e.defaultHeaders,e.requestHeaders]);if(u(this,Ft,"f")!==null&&t.nulls.has("openai-organization")||u(this,zt,"f")!==null&&t.nulls.has("openai-project"))throw new f("X.509 workload identity cannot omit its enrolled organization or project.");for(let n of t.values.keys()){let s=n.toLowerCase().split("_").join("-");if((s==="openai-organization"||s==="openai-project")&&(n!==s||Yn(t.values,n)!==(s==="openai-organization"?e.organization:e.project)))throw new f("X.509 workload identity cannot override its enrolled organization or project.");if(Va(s)||s==="host")throw new f("X.509 workload identity cannot use caller-supplied authentication credentials.")}},Z=function(){let e=u(this,we,"f").current();if(!e||e.owner!==this)throw new f("X.509 workload identity requires an active certificate request scope.");return e},cl=function(e){if(Yn(e,"OpenAI-Organization")!==u(this,Ft,"f")||Yn(e,"OpenAI-Project")!==u(this,zt,"f"))throw new f("X.509 workload identity cannot override its enrolled organization or project.");for(let t of Headers.prototype.keys.call(e)){let n=t.toLowerCase().split("_").join("-");if((n==="openai-organization"||n==="openai-project")&&t!==n)throw new f("X.509 workload identity cannot override its enrolled organization or project.")}};function Bf(r){let{credential:e}=r;if(e===void 0)return{credential:e,options:r};let t=Tf(e);if(!t)throw new f("An X.509 credential must be created by the SDK authentication helper.");let n=["apiKey","adminAPIKey","workloadIdentity","x509Transport"].filter(s=>{let i=r[s];return i!=null});if(n.length>0)throw new f(`The \`credential\` option cannot be combined with ${n.map(s=>`\`${s}\``).join(", ")}.`);return{credential:e,options:{...r,apiKey:null,adminAPIKey:null,baseURL:r.baseURL??null,organization:r.organization??null,project:r.project??null,workloadIdentity:t.identity,x509Transport:t.transport}}}function Jy({apiKey:r,adminAPIKey:e}){return r!=null||e!=null}function Vy(r,e){let t=r.provider,n=e.credential??e.workloadIdentity,s=e.provider??(n?void 0:t);return s!==t&&(delete r.baseURL,delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions,delete r.fetch),s&&(delete r.apiKey,delete r.adminAPIKey,delete r.credential,delete r.workloadIdentity,delete r.x509Transport,delete r.baseURL),s}function Kf(r,e,t,n){let s=P(e,"workloadIdentity")?e.workloadIdentity:r.workloadIdentity,i=t!==void 0&&(Jy(e)&&e.workloadIdentity===void 0||e.provider!==void 0);t!==void 0&&P(e,"workloadIdentity")&&delete r.x509Transport;let o=t!==void 0&&!i&&e.credential===void 0&&!P(e,"workloadIdentity")&&!P(e,"x509Transport")?t:void 0,a=e.credential===void 0?o:e.credential,c=a!==void 0||!i&&uu(s);return n!==c&&(delete r.fetch,delete r.baseURL,delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions,c?r.apiKey=null:(delete r.x509Transport,i&&delete r.workloadIdentity)),a!==void 0&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.x509Transport,r.credential=a,e.credential!==void 0&&(delete r.organization,delete r.project,delete r.defaultHeaders,delete r.defaultQuery,delete r.fetchOptions)),{credential:a,provider:Vy(r,e)}}var Qf=Symbol("brand.privateStreamingFile");function lu(r,e,t){if(typeof e!="string"||!e)throw new TypeError("toStreamingFile requires a non-empty file name");let n=t?.type;return n&&Yf(n),{[Qf]:!0,data:r,name:e,...n?{type:n}:{}}}var _l=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&Number.parseInt(r.versions.node.split("."),10)<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Mt(r,e,t){return _l(),new File(r,e??"unknown_file",t)}function Hr(r,e){if(typeof r!="object"||r===null)return;let t="name"in r?r.name:void 0,n=t&&String(t)||"filename"in r&&r.filename&&String(r.filename);if(n)return e?.stripFilename===!1?Hf(n):Zn(n);let s="url"in r&&r.url&&String(r.url);if(s)try{let o=Zn(new URL(s).pathname);return o===void 0?void 0:Zn(Gy(o))}catch{return Zn(s)}let i="path"in r&&r.path&&String(r.path);return i?Zn(i):void 0}function Zn(r){return r.split(/[\\/]/).pop()||void 0}function Gy(r){try{let e=decodeURIComponent(r);return/%(?:0[AD]|22)/i.test(e)?r:e.replace(/[\u0000-\u001F\u007F]/gu,encodeURIComponent)}catch{return r}}function Hf(r){let e=r.replace(/\\/g,"/");if(e.startsWith("/")||/^[A-Za-z]:/.test(e)||e.split("/").includes(".."))throw new TypeError("Upload file name must be a safe relative path without parent directory segments");return e}var Yy=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get;function yl(r){try{return Yy?.call(r)!==void 0}catch{return!1}}var es=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Ot=async(r,e,t)=>{if(!Pi(r.body))return r.__metadata?.finalizeMultipart===!0&&t?.stripFilenames===!1?{...r,__metadata:{...r.__metadata,preserveMultipartFilenames:!0}}:r;let n=r.__metadata?.finalizeMultipart===!0?{...r,__metadata:{...r.__metadata,finalizeMultipart:!1}}:r;return cu(r.body)?Vf(n,t):{...n,body:await Xf(n.body,e,t)}},re=async(r,e,t)=>cu(r.body)?Vf(r,t):{...r,body:await Xf(r.body,e,t)},Nf=new WeakMap;function Zy(r){let e=typeof r=="function"?r:r.fetch,t=Nf.get(e);if(t)return t;let n=(async()=>{try{let s;if("Response"in e)s=e.Response;else{let o=await e("data:,");await o.arrayBuffer(),s=o.constructor}let i=new FormData;return i.toString()!==await new s(i).text()}catch{return!0}})();return Nf.set(e,n),n}var Xf=async(r,e,t={})=>{if(!await Zy(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let n=new FormData;return await Promise.all(Object.entries(r||{}).map(([s,i])=>ml(n,s,i,t))),n},du=r=>r instanceof Blob,gl=r=>typeof r=="object"&&r!==null&&"getReader"in r&&typeof r.getReader=="function",xi=r=>typeof r=="object"&&r!==null&&Qf in r,fu=r=>typeof r=="object"&&r!==null&&(r instanceof Response||es(r)||gl(r)||xi(r)||du(r)),cu=r=>{if(xi(r)||es(r)||gl(r))return!0;if(Array.isArray(r))return r.some(cu);if(r&&typeof r=="object"&&!du(r)&&!(r instanceof Response)){for(let e of Object.keys(r))if(cu(r[e]))return!0}return!1},Pi=r=>{if(fu(r))return!0;if(Array.isArray(r))return r.some(Pi);if(r&&typeof r=="object"){for(let e of Object.keys(r))if(Pi(r[e]))return!0}return!1},Wf=(r,e)=>{let t=[];for(let n of r)fu(n.value)&&!e.has(n.value)&&e.set(n.value,Gf(n.value,{stripFilenames:!1})),t.push(n);return t},pl=new WeakMap,Jf=r=>{if(typeof r.body!="object"||r.body===null)return;let e=pl.get(r.body);e&&(r.stream=e(),pl.delete(r.body))},Vf=(r,e={})=>{let t=Uf(r.body),n=e.stripFilenames===!1?new WeakMap:void 0,s=n?Wf(t,n):t,i=`openai-${Math.random().toString(36).slice(2)}`;async function*o(){yield*eg(s,i,e,n)}let a=hi(o(),r.__metadata?.streamFromBody===!0?{highWaterMark:0}:void 0),c=r.body;return r.__metadata?.streamFromBody===!0&&typeof c=="object"&&c!==null&&pl.set(a,()=>{let d={...c},p=Uf(d);s=n?Wf(p,n):p;let y=Object.getOwnPropertyDescriptor(d,"stream")?.value;return y===!0||y==="true"}),{...r,body:a,headers:g([{"content-type":`multipart/form-data; boundary=${i}`},r.headers])}};async function*eg(r,e,t,n){for await(let{key:s,value:i}of r){if(fu(i)){let o=n?.get(i)??Gf(i,t),a=tg(i);yield ge(`--${e}\r
6
- `),yield ge(`Content-Disposition: form-data; name="${fl(s)}"; filename="${fl(o)}"\r
7
- Content-Type: ${a}\r
8
- \r
9
- `),yield*Oi(rg(i))}else yield ge(`--${e}\r
10
- `),yield ge(`Content-Disposition: form-data; name="${fl(s)}"\r
11
- \r
12
- ${String(i)}`);yield ge(`\r
13
- `)}yield ge(`--${e}--\r
14
- `)}function*Uf(r){if(!(!r||typeof r!="object"))for(let[e,t]of Object.entries(r))yield*hl(e,t)}function*hl(r,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${r}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||fu(e))yield{key:r,value:e};else if(Array.isArray(e))for(let t of e)yield*hl(r+"[]",t);else if(typeof e=="object")for(let[t,n]of Object.entries(e))yield*hl(`${r}[${t}]`,n);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function Gf(r,e){if(xi(r)){let{name:t}=r;if(typeof t!="string"||!t)throw new TypeError("Streaming upload file name must be a non-empty string");return e.stripFilenames===!1?Hf(t):Zn(t)??"unknown_file"}return Hr(r,{stripFilename:e.stripFilenames})??"unknown_file"}function tg(r){let e;return xi(r)||du(r)?{type:e}=r:r instanceof Response&&(e=r.headers.get("content-type")??void 0),Yf(e||"application/octet-stream")}function Yf(r){if(typeof r!="string")throw new TypeError("Streaming upload content type must be a string");for(let e=0;e<r.length;e+=1){let t=r.codePointAt(e)??0;if(t<=31||t===127)throw new TypeError("Streaming upload content type must not contain control characters")}return r}function rg(r){return xi(r)?r.data:r}async function*Oi(r){if(typeof r=="string")yield ge(r);else if(ArrayBuffer.isView(r))yield new Uint8Array(r.buffer,r.byteOffset,r.byteLength);else if(yl(r))yield new Uint8Array(r);else if(r instanceof Response)yield*Oi(r.body||await r.blob());else if(r instanceof Blob)typeof r.stream=="function"?yield*Oi(r.stream()):yield new Uint8Array(await r.arrayBuffer());else if(gl(r))for await(let e of Qa(r))yield*Oi(e);else if(es(r))for await(let e of r)yield*Oi(e);else throw new TypeError(`Invalid streaming file chunk: ${String(r)}`)}function fl(r){return Array.from(r,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e==='"'||e==="\\"?encodeURIComponent(e):e}).join("")}var ml=async(r,e,t,n)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response){let s=await t.blob();r.append(e,Mt([s],Hr(t,{stripFilename:n.stripFilenames}),{type:s.type}))}else if(es(t))r.append(e,Mt([await new Response(hi(t)).blob()],Hr(t,{stripFilename:n.stripFilenames})));else if(du(t)){let s=Hr(t,{stripFilename:n.stripFilenames});s===void 0?r.append(e,t):r.append(e,t,s)}else if(Array.isArray(t)){let s=await Promise.all(t.map(async i=>{let o=new FormData;return await ml(o,e+"[]",i,n),o}));for(let i of s)if(i)for(let[o,a]of i.entries())r.append(o,a)}else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,i])=>ml(r,`${e}[${s}]`,i,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Zf=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",ng=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Zf(r),sg=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",og=(r,e)=>e?.type!=null&&e.type!==r.type||e?.lastModified!=null&&e.lastModified!==r.lastModified||e?.endings!=null,ig=(r,e,t)=>(e==null||e===r.name)&&!og(r,t);async function pu(r,e,t){if(_l(),r=await r,ng(r)){let s={...t,type:t?.type??r.type,lastModified:t?.lastModified??r.lastModified};return r instanceof File?ig(r,e,t)?r:Mt([r],e??r.name,s):Mt([await r.arrayBuffer()],e??r.name,s)}if(sg(r)){let s=await r.blob();e??(e=Hr(r));let i=t?.type===void 0&&s.type?{...t,type:s.type}:t;return Mt(await bl(s),e,i)}let n=await bl(r);if(e??(e=Hr(r)),t?.type===void 0){let s=n.find(i=>typeof i=="object"&&"type"in i&&!!i.type);s&&(t={...t,type:s.type})}return Mt(n,e,t)}async function bl(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||yl(r))e.push(r);else if(Zf(r))e.push(r instanceof Blob?r:new Blob([await r.arrayBuffer()],{type:r.type}));else if(es(r))for await(let t of r)e.push(...await bl(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${ag(r)}`)}return e}function ag(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var m=class{constructor(e){this._client=e}};function tp(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ep=Object.freeze(Object.create(null)),cg=(r=tp)=>function(t,...n){if(t.length===1)return t[0];let s=!1,i=[],o="";for(let p=0;p<t.length;p+=1)if(p in t){let y=t[p];/[?#]/.test(y)&&(s=!0);let _=n[p],b=(s?encodeURIComponent:r)(""+_);p!==n.length&&(_==null||typeof _=="object"&&_.toString===Object.getPrototypeOf(Object.getPrototypeOf(_.hasOwnProperty??ep)??ep)?.toString)&&(b=_+"",i.push({start:o.length+y.length,length:b.length,error:`Value of type ${Object.prototype.toString.call(_).slice(8,-1)} is not a valid path parameter`})),o+=y+(p===n.length?"":b)}let a=o.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=c.exec(a))!==null;)i.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(i.sort((p,y)=>p.start-y.start),i.length>0){let p=0,y="";for(let _ of i){let b=" ".repeat(_.start-p),h="^".repeat(_.length);p=_.start+_.length,y+=b+h}throw new f(`Path parameters result in path with invalid segments:
15
- ${i.map(_=>_.error).join(`
16
- `)}
17
- ${o}
18
- ${y}`)}return o},l=cg(tp);function lg(r,e){return Promise.resolve(r).then(e)}var rp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function dg(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>rp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!rp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Xr=class extends m{list(e,t={},n){let s=dg(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/chat/completions/${e}/messages`,I,lg(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}};function Pt(r){return r!==void 0&&"function"in r&&r.function!==void 0}function pg(r){return r?.$brand==="auto-parseable-response-format"}function xt(r){return pg(r)||r?.type==="json_schema"}function Lt(r,e){if(!xt(r))return null;if(typeof r=="object"&&r!==null&&"$parseRaw"in r&&typeof r.$parseRaw=="function")return r.$parseRaw(e);try{return JSON.parse(e)}catch(t){throw t instanceof SyntaxError?new SyntaxError("Error reading response: invalid structured output JSON."):t}}function ft(r){return r?.$brand==="auto-parseable-tool"}function np(r,e){return!e||!Al(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:vi(r,e)}function vi(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new ur;if(n.finish_reason==="content_filter")throw new cr;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(s=>mg(e,s))??void 0}:void 0,parsed:n.message.content!==null&&n.message.content!==void 0&&!n.message.refusal&&(n.message.content!==""||!n.message.tool_calls?.length&&!n.message.function_call)?hg(e,n.message.content):null}}});return{...r,choices:t}}function hg(r,e){return Lt(r.response_format,e)}function mg(r,e){if(e.type==="custom")return e;if(e.type!=="function"){let s=e.type;throw new f(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${s}\``)}let t=r.tools?.find(s=>Pt(s)&&s.function?.name===e.function.name),n=null;return ft(t)?n=t.$parseRaw(e.function.arguments):t?.function.strict&&(n=Lt({type:"json_schema",$parseRaw:void 0},e.function.arguments)),{...e,function:{...e.function,parsed_arguments:n}}}function hu(r,e){if(!r||!("tools"in r)||!r.tools||e.type!=="function")return!1;let t=r.tools?.find(n=>Pt(n)&&n.function?.name===e.function?.name);return Pt(t)&&(ft(t)||t?.function.strict||!1)}function Al(r){return xt(r.response_format)?!0:r.tools?.some(e=>ft(e)||e.type==="function"&&e.function.strict===!0)??!1}function sp(r){for(let e of r??[])if(e.type!=="custom"){if(e.type!=="function"){let t=e.type;throw new f(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${t}\``)}if(e.function.strict!==!0)throw new f(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Bt=r=>r?.role==="assistant",Ii=r=>r?.role==="tool";var Me,yu,gu,ki,Ei,bu,ji,et,qi,$i,Ci,ts,dr,Jr,Au,Ru,rs,Vr,Il,dp,Sl,fp,El,wu,pp,op=4096,Ti=8*1024*1024,_g=4096,Di=256,yg=JSON.stringify,gg=JSON.parse,Rl=new WeakSet,bg=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer")?.get,wg=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length")?.get,Ag=Object.getOwnPropertyDescriptor(DataView.prototype,"buffer")?.get,ip=Object.getOwnPropertyDescriptor(Symbol.prototype,"description")?.get,Rg=Date.prototype.getTime,Og=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength")?.get,Pg=typeof SharedArrayBuffer=="function"?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength")?.get:void 0,Si=Object.getOwnPropertyDescriptor(new Error("native stack descriptor"),"stack"),vt=Function.prototype.toString,xg=Object.prototype.toString,mu=Object.getOwnPropertyDescriptor(Error,"isError"),ap=mu&&"value"in mu&&typeof mu.value=="function"?mu.value:void 0,vg=vt.call(Error),Ig=vt.call(Date),Sg=vt.call(Function),Ou=new Set([Je.prototype,se.prototype,J.prototype,f.prototype,Y.prototype,tr.prototype,bt.prototype,sr.prototype,cr.prototype,ar.prototype,Fe.prototype,ur.prototype,nr.prototype,Ve.prototype,rr.prototype,ir.prototype,Mr.prototype,or.prototype]),hp=new Set,mp=new Map,up=new WeakMap;function Eg(){if(!(typeof process>"u"))try{let r=Object.getOwnPropertyDescriptor(process,"getBuiltinModule");if(!r||!("value"in r)||typeof r.value!="function")return;let e=Reflect.apply(r.value,process,["node:util"]);if(typeof e!="object"||e===null)return;let t=Object.getOwnPropertyDescriptor(e,"types");if(!t||!("value"in t)||typeof t.value!="object"||t.value===null)return;let n=Object.getOwnPropertyDescriptor(t.value,"isProxy");return!n||!("value"in n)||typeof n.value!="function"?void 0:n.value}catch{return}}var Cg=Eg();function Pu(r){if(typeof r!="function")return;let e=Object.getOwnPropertyDescriptor(r,"prototype");if(!e||!("value"in e)||typeof e.value!="object"&&typeof e.value!="function")return;Ou.add(e.value);let t=vt.call(r);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(t)&&e.configurable===!1&&e.writable===!1){hp.add(t);let n=new Map;for(let s of Reflect.ownKeys(e.value)){let i=Object.getOwnPropertyDescriptor(e.value,s);i&&n.set(s,i)}mp.set(t,n)}}for(let r 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])Pu(r);for(let r of["SharedArrayBuffer","AggregateError","Float16Array","BigInt64Array","BigUint64Array","Blob","File","Headers"]){let e=Object.getOwnPropertyDescriptor(globalThis,r);e&&"value"in e&&Pu(e.value)}var Ol=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"constructor");Ol&&"value"in Ol&&Pu(Ol.value);typeof Buffer=="function"&&Pu(Buffer);var Tg=(()=>{if(typeof Blob=="function")try{let r=new Blob([]);for(let e of Object.getOwnPropertySymbols(r)){let t=Object.getOwnPropertyDescriptor(r,e);if(t&&"value"in t&&typeof t.value=="object"&&t.value)return Object.getPrototypeOf(t.value)}}catch{return}})(),kg=Map.prototype.entries,jg=Set.prototype.values,_u=typeof Headers=="function"?Object.getOwnPropertyDescriptor(Headers.prototype,"entries"):void 0,cp=_u&&"value"in _u&&typeof _u.value=="function"?_u.value:void 0,qg=new Set(["ArrayBuffer","SharedArrayBuffer","Blob","File","Map","Date","Set","Headers"]);function xu(r){let e=Object.getOwnPropertyDescriptor(r,"constructor");if(!e||!("value"in e)||typeof e.value!="function")return;let t=e.value,n=vt.call(t),s=mp.get(n);if(!hp.has(n)||!s)return;let i=Object.getOwnPropertyDescriptor(t,"prototype");if(!(!i||!("value"in i)||i.value!==r||i.configurable!==!1||i.writable!==!1))return{constructor:t,descriptors:s,functionPrototype:Object.getPrototypeOf(t)}}function $g(r){return Ou.has(r)||xu(r)!==void 0}function Pl(r,e,t){if(e===void 0)return r===void 0;if(typeof r!="function"||typeof e!="function")return!1;let n=vt.call(e);if(vt.call(r)!==n)return!1;let s=Object.getPrototypeOf(r);if(s===t)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n))return!1;let i=xu(s);return i!==void 0&&vt.call(i.constructor)===Sg}function Dg(r,e,t){return!e||r.configurable!==e.configurable||r.enumerable!==e.enumerable||"value"in r!="value"in e?!1:"value"in r&&"value"in e?r.writable!==e.writable?!1:typeof e.value=="function"?Pl(r.value,e.value,t):e.value!==null&&typeof e.value=="object"?!1:Object.is(r.value,e.value):Pl(r.get,e.get,t)&&Pl(r.set,e.set,t)}function lp(r){if(ap)return ap.call(Error,r);let e=r;for(let t=0;e!==null&&t<Di;t+=1){if(Object.getOwnPropertyDescriptor(e,Symbol.toStringTag))return!1;e=Object.getPrototypeOf(e)}return e===null&&xg.call(r)==="[object Error]"}function Fg(r,e){if(typeof e.get!="function"||typeof e.set!="function")return;let t=Object.getPrototypeOf(r);for(let n=0;t!==null&&n<Di;n+=1){let s=Object.getOwnPropertyDescriptor(t,"constructor");if(s&&"value"in s&&typeof s.value=="function"){let i=s.value;if(vt.call(i)===vg&&$g(t)){let o=Object.getPrototypeOf(i);return Object.getPrototypeOf(e.get)===o&&Object.getPrototypeOf(e.set)===o?{constructor:i,prototype:t}:void 0}}t=Object.getPrototypeOf(t)}}function zg(r,e){if(!lp(r))return!1;if(Si&&!("value"in Si)&&typeof Si.get=="function"&&Object.prototype.isPrototypeOf.call(Error.prototype,r)&&e.get===Si.get&&e.set===Si.set)return!0;let t=Fg(r,e);if(!t)return!1;let n=up.get(t.prototype);if(!n){let s=Reflect.construct(t.constructor,[]);if(typeof s!="object"||s===null||!lp(s)||Object.getPrototypeOf(s)!==t.prototype||(n=Object.getOwnPropertyDescriptor(s,"stack"),!n||"value"in n||typeof n.get!="function"||typeof n.set!="function"))return!1;up.set(t.prototype,n)}return e.get===n.get&&e.set===n.set}function xl(){let r=[],e=0;return{get length(){return r.length-e},enqueue(t){r.push(t)},dequeue(){if(e===r.length)return;let t=r[e];return r[e]=void 0,e+=1,e===r.length?(r=[],e=0):e>=1024&&e*2>=r.length&&(r=r.slice(e),e=0),t},clear(){r=[],e=0}}}function Mg(r){let e=Object.getPrototypeOf(r);for(let t=0;e!==null&&t<Di;t+=1){if(e===Date.prototype)return"Date";if(!Ou.has(e)){let s=Object.getOwnPropertyDescriptor(e,"constructor");if(s&&"value"in s&&typeof s.value=="function"&&vt.call(s.value)===Ig&&xu(e))return"Date"}let n=Object.getOwnPropertyDescriptor(e,Symbol.toStringTag);if(n&&"value"in n&&typeof n.value=="string"&&qg.has(n.value))return n.value;e=Object.getPrototypeOf(e)}}function Lg(r,e,t){if(ArrayBuffer.isView(r)){let a,c="typed-array";try{a=bg?.call(r)}catch{c="data-view",a=Ag?.call(r)}return typeof a!="object"||a===null?{bytes:Number.POSITIVE_INFINITY,kind:c}:(e(a,t+1),{bytes:0,kind:c})}let n=Mg(r);if(!n)return;let s,i="buffer";switch(n){case"ArrayBuffer":{s=Og;break}case"SharedArrayBuffer":{s=Pg;break}case"Blob":case"File":return{bytes:Number.POSITIVE_INFINITY,kind:"blob"};case"Map":return{bytes:0,kind:"map"};case"Date":return Reflect.apply(Rg,r,[]),{bytes:8,kind:"date"};case"Set":return{bytes:0,kind:"set"};case"Headers":return{bytes:0,kind:"headers"};default:return}let o=s?.call(r);return{bytes:typeof o=="number"&&Number.isSafeInteger(o)&&o>=0?o:Number.POSITIVE_INFINITY,kind:i}}function Bg(r,e,t){if(e==="map"){for(let[n,s]of kg.call(r))if(!t(n,8)||!t(s,8))return!1}if(e==="set"){for(let n of jg.call(r))if(!t(n,8))return!1}if(e==="headers"){if(!cp)return!1;for(let[n,s]of cp.call(r))if(!t(n,8)||!t(s,8))return!1}return!0}function Kg(r,e,t){if(Array.isArray(r)){let s=Object.getOwnPropertyDescriptor(r,"length"),i=s&&"value"in s?s.value:void 0;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>Math.floor(t/16))return}if(e!=="typed-array")return Reflect.ownKeys(r);let n=wg?.call(r);if(!(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>_g))return Reflect.ownKeys(r).filter(s=>{if(typeof s!="string")return!0;let i=Number(s);return!Number.isInteger(i)||i<0||i>=n||String(i)!==s})}function _p(r,e,t,n,s,i){let o=Kg(r,e,n());if(o===void 0)return!1;for(let a of o){if(!s(typeof a=="string"?a.length*2+8:8))return!1;typeof a=="symbol"&&i(a,t+1);let c=Object.getOwnPropertyDescriptor(r,a);if(!c)return!1;if(!("value"in c)){if(a==="stack"&&zg(r,c))continue;return!1}i(c.value,t+1,e==="blob")}return!0}function Ng(r,e,t,n,s,i,o,a){let c=Object.getPrototypeOf(r);for(let d=e+1;c!==null;d+=1){if(d>=Di)return!1;if(Ou.has(c)||t&&c===Tg)return!0;if(n.has(c))return o(c,d),s()>=0;n.add(c);let p=c;if(!a(p,()=>{if(!i(16))return!1;let _=xu(p);if(!_)return _p(p,void 0,d,s,i,o);for(let b of Reflect.ownKeys(p)){let h=Object.getOwnPropertyDescriptor(p,b);if(!h)return!1;if(!Dg(h,_.descriptors.get(b),_.functionPrototype)){if(!i(typeof b=="string"?b.length*2+8:8)||!("value"in h))return!1;typeof b=="symbol"&&o(b,d+1),o(h.value,d+1)}}return s()>=0}))return!1;c=Object.getPrototypeOf(p)}return!0}var Wg=32,Ug=32,yp=8,gp=16,Qg=128*1024;function vl(r,e){let t=0,n=0,s=new WeakSet,i=new Set,o=new Set,a=new Map,c,d=()=>e-t,p=A=>!Number.isSafeInteger(A)||A<0?(t=e+1,!1):(t+=A,c?c.bytes+=A:n+=A,t<=e),y=A=>{c?c.edges.add(A):o.add(A)},_=(A,O)=>{y(A);let E={bytes:0,edges:new Set};a.set(A,E);let x=c;c=E;try{return O()}finally{c=x}},b=A=>{if(i.has(A)){y(A),p(8);return}i.add(A),_(A,()=>{if(!ip)return!1;let O=Reflect.apply(ip,A,[]);return p(8+(O?.length??0)*2)})||(t=e+1)},h=(A,O,E=!1)=>{if(!(t>e)){if(typeof A=="string"){p(A.length*2);return}if(typeof A=="symbol"){b(A);return}if(typeof A=="function"){t=e+1;return}if(A===null||typeof A!="object"){p(8);return}if(Cg?.(A)){t=e+1;return}if(O>=Di){t=e+1;return}if(s.has(A)){y(A),p(8);return}s.add(A),_(A,()=>{if(!p(16))return!1;let x=Lg(A,h,O);return!Ng(A,O,E,s,d,p,h,_)||x!==void 0&&!p(x.bytes)||!Bg(A,x?.kind,(q,C)=>p(C)?(h(q,O+1),t<=e):!1)?!1:_p(A,x?.kind,O,d,p,h)})||(t=e+1)}};try{h(r,0)}catch{return}return t<=e?{scalarBytes:n,roots:o,nodes:a}:void 0}function Hg(r,e){if(r.size!==e.size)return!1;for(let t of r)if(!e.has(t))return!1;return!0}function Cl(r,e){return r.bytes+Ug+r.edges.size*yp+e*gp}function Tl(r){return Wg+r.scalarBytes+r.roots.size*yp}function Xg(r,e,t,n){let s=new Set,i=[...r];for(;i.length;){if(n.remaining-=1,n.remaining<0)return;let o=i.pop();if(s.has(o))continue;let a=e.get(o)??t.get(o);if(!a)return;s.add(o);for(let c of a.edges)i.push(c)}return s}function kl(r,e,t,n,s){let i=n.get(r);if(i)return s&&(i.node=s),i;let o=s??e.nodes.get(r)??t.get(r);if(!o)return;let a={node:o,ownerDelta:0};return n.set(r,a),a}function Jg(r,e,t,n,s){let i=new Set([r]);for(let[o,a]of e.nodes){if(s.remaining-=1,s.remaining<0)return;let c=t.get(o);if(!c)continue;let d=!Hg(c.edges,a.edges);if((c.bytes!==a.bytes||d)&&kl(o,e,t,n,a),!!d)for(let p of c.owners){if(s.remaining-=1,s.remaining<0)return;i.add(p)}}return i}function Vg(r,e,t,n,s,i){for(let o of r.identities){if(i.remaining-=1,i.remaining<0)return!1;if(!e.has(o)){let a=kl(o,t,n,s);if(!a)return!1;a.ownerDelta-=1}}for(let o of e){if(i.remaining-=1,i.remaining<0)return!1;if(!r.identities.has(o)){let a=kl(o,t,n,s);if(!a)return!1;a.ownerDelta+=1}}return!0}function Gg(r,e,t,n,s,i){let o=new Map;for(let a of t){let c=a===r?e.roots:a.roots,d=Xg(c,e.nodes,n,i);if(!d||!Vg(a,d,e,n,s,i))return;o.set(a,d)}return o}function Yg(r,e,t,n,s,i){let o=r-(n?0:Tl(e))+Tl(t);for(let[a,c]of s){let d=i.get(a),p=(d?.owners.size??0)+c.ownerDelta;if(p<0)return;d&&(o-=Cl(d,d.owners.size)),p&&(o+=Cl(c.node,p))}return Number.isSafeInteger(o)&&o>=0&&o<=Ti?o:void 0}function Zg(r,e,t){for(let[n,s]of e){let i=r.get(n);(i?.owners.size??0)+s.ownerDelta&&(i?(i.bytes=s.node.bytes,i.edges=s.node.edges):r.set(n,{bytes:s.node.bytes,edges:s.node.edges,owners:new Set}))}for(let[n,s]of t){for(let i of n.identities)s.has(i)||r.get(i)?.owners.delete(n);for(let i of s)n.identities.has(i)||r.get(i).owners.add(n);n.identities=s}for(let n of e.keys())r.get(n)?.owners.size===0&&r.delete(n)}function eb(){let r=new Map,e=0,t=(s,i,o)=>{let a={remaining:Qg},c=new Map,d=Jg(s,i,r,c,a);if(!d)return!1;let p=Gg(s,i,d,r,c,a);if(!p)return!1;let y=Yg(e,s,i,o,c,r);return y===void 0?!1:(Zg(r,c,p),s.scalarBytes=i.scalarBytes,s.roots=i.roots,e=y,!0)};return{retain(s){let i={scalarBytes:0,roots:new Set,identities:new Set};return t(i,s,!0)?i:void 0},refresh(s,i){return t(s,i,!1)},release:s=>{e-=Tl(s);for(let i of s.identities){let o=r.get(i);o?.owners.delete(s)&&(e-=gp,o.owners.size===0&&(e-=Cl(o,0),r.delete(i)))}s.identities.clear()},clear(){r.clear(),e=0}}}var fr=class{constructor(){Me.add(this),this.controller=new AbortController,yu.set(this,void 0),gu.set(this,()=>{}),ki.set(this,()=>{}),Ei.set(this,void 0),bu.set(this,()=>{}),ji.set(this,()=>{}),et.set(this,Object.create(null)),qi.set(this,[]),$i.set(this,new WeakMap),Ci.set(this,new Set),ts.set(this,new Set),dr.set(this,0),Jr.set(this,!1),Au.set(this,!1),Ru.set(this,!1),rs.set(this,!1),Vr.set(this,void 0),w(this,yu,new Promise((e,t)=>{w(this,gu,e,"f"),w(this,ki,t,"f")}),"f"),w(this,Ei,new Promise((e,t)=>{w(this,bu,e,"f"),w(this,ji,t,"f")}),"f"),u(this,yu,"f").catch(()=>{}),u(this,Ei,"f").catch(()=>{})}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(n=>{t=!0,u(this,Me,"m",wu).call(this,n)}).then(()=>{if(!t){try{this._emitFinal()}catch(n){u(this,Me,"m",wu).call(this,n);return}this._emit("end")}})},0)}_connected(){this.ended||(u(this,gu,"f").call(this),this._emit("connect"))}get ended(){return u(this,Jr,"f")}get errored(){return u(this,Au,"f")}get aborted(){return u(this,Ru,"f")}abort(){this.controller.abort()}_userAbortError(){let e=new Y;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){u(this,Me,"m",Il).call(this,e);return}if(u(this,qi,"f").some(n=>n.signal===e))return;let t=()=>u(this,Me,"m",Il).call(this,e);e.addEventListener("abort",t,{once:!0}),u(this,qi,"f").push({signal:e,listener:t})}on(e,t){var n;return((n=u(this,et,"f"))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=u(this,et,"f")[e];if(!n)return this;let s=u(this,$i,"f").get(t);if(s?.event===e&&!s.registration.removed&&!s.registration.detached)return u(this,Me,"m",fp).call(this,e,s.registration),this;let i=n.findIndex(o=>!o.removed&&o.listener===t);return i!==-1&&n.splice(i,1),this}once(e,t){var n;return((n=u(this,et,"f"))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{w(this,rs,!0,"f");let s=o=>{this.off(e,i),n(o)},i=(...o)=>{e!=="error"&&this.off("error",s),t(o.length>1?o:o[0])};e!=="error"&&u(this,Me,"m",Sl).call(this,"error",s),u(this,Me,"m",Sl).call(this,e,i)})}events(e){return this._createIterator(t=>{let n=(...s)=>{Rl.add(s);try{t(s)}finally{Rl.delete(s)}};return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!=="error",rejectOnAbort:e!=="abort"})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:n=!0,onReturn:s}={}){let i=xl(),o=xl(),a=xl(),c=eb(),d=this.ended,p,y=!1,_=()=>{},b=()=>({value:void 0,done:!0}),h=()=>{for(;a.length;)a.dequeue().resolve(b())},A=()=>{!p||y||!a.length||(y=!0,a.dequeue().reject(p))},O=()=>{_(),this.off("end",v),t&&this.off("error",D),n&&this.off("abort",D)},E=S=>{S.active=!1,S.check&&(u(this,ts,"f").delete(S.check),S.check=void 0)},x=(S=!1)=>{if(S){for(;o.length;)E(o.dequeue());i.clear(),c.clear()}let j=new f(`Event stream iterator buffer limit exceeded (${op} events or ${Ti} bytes); consume events as they arrive.`);try{u(this,Me,"m",wu).call(this,j)}finally{this.controller.abort()}return j},q=(S,j)=>{if(!j.active||u(this,Jr,"f"))return;let T=vl(S,Ti);(!T||!c.refresh(j.retention,T))&&x(!0)},C=S=>{if(d)return;let j=a.dequeue();if(j)j.resolve({value:S,done:!1});else{if(i.length>=op){x();return}let T=vl(S,Ti),$=T&&c.retain(T);if(!$){x();return}if(typeof S=="object"&&S!==null&&Rl.has(S)){let N=S;for(let H=0;H<N.length;H+=1){let M=N[H];typeof M=="string"&&(N[H]=gg(yg(M)))}}let k={retention:$,active:!0,check:void 0};i.enqueue(S),o.enqueue(k);let z=()=>{k.check=void 0,q(S,k)};k.check=z,u(this,ts,"f").add(z)}},D=S=>{p=S,i.length||A()},R=()=>{if(p)return;let S=u(this,Vr,"f");S&&(S.kind==="error"?t:n)&&(p=S.error)},v=()=>{d=!0,R(),O(),i.length||(A(),h())};return d||(_=e(C),this.on("end",v),t&&this.on("error",D),n&&this.on("abort",D)),{next:()=>{if(i.length){let S=i.dequeue(),j=o.dequeue();E(j);let T=vl(S,Ti);if(!T||!c.refresh(j.retention,T)){let $=x(!0);return y=!0,Promise.reject($)}return c.release(j.retention),Promise.resolve({value:S,done:!1})}return(d||this.ended)&&R(),p&&!y?(y=!0,Promise.reject(p)):d?Promise.resolve(b()):new Promise((S,j)=>{a.enqueue({resolve:S,reject:j})})},return:()=>{for(d=!0,y=!0;o.length;)E(o.dequeue());return i.clear(),c.clear(),O(),h(),s&&(this.done().catch(()=>{}),s()),Promise.resolve(b())},[Symbol.asyncIterator](){return this}}}async done(){w(this,rs,!0,"f"),await u(this,Ei,"f")}_hasListeners(e){return!!u(this,et,"f")[e]?.some(t=>!t.removed)}_emit(e,...t){if(u(this,Jr,"f"))return;e==="end"&&(u(this,Me,"m",dp).call(this),w(this,Jr,!0,"f"),u(this,bu,"f").call(this));let n=u(this,et,"f")[e],s,i=!1;try{if(n){u(this,et,"f")[e]=n.filter(o=>(o.once&&(o.detached=!0),!o.once&&!o.removed)),w(this,dr,u(this,dr,"f")+1,"f");try{for(let o of n)if(!o.removed){let{listener:a}=o;a(...t)}}finally{if(w(this,dr,u(this,dr,"f")-1,"f"),u(this,dr,"f")===0){u(this,Me,"m",El).call(this);for(let o of u(this,ts,"f"))u(this,ts,"f").delete(o),u(this,Jr,"f")||o()}}}}catch(o){s=o,i=!0}try{u(this,Me,"m",pp).call(this,e,t,!!n?.length)}catch(o){i||(s=o,i=!0)}if(i)throw s}_emitFinal(){}};yu=new WeakMap,gu=new WeakMap,ki=new WeakMap,Ei=new WeakMap,bu=new WeakMap,ji=new WeakMap,et=new WeakMap,qi=new WeakMap,$i=new WeakMap,Ci=new WeakMap,ts=new WeakMap,dr=new WeakMap,Jr=new WeakMap,Au=new WeakMap,Ru=new WeakMap,rs=new WeakMap,Vr=new WeakMap,Me=new WeakSet,Il=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},dp=function(){for(let{signal:e,listener:t}of u(this,qi,"f").splice(0))e.removeEventListener("abort",t)},Sl=function(e,t){let n=u(this,et,"f")[e],s=n?.length??0;this.once(e,t);let i=u(this,et,"f")[e],[o]=i?.slice(-1)??[];(n===void 0||i===n)&&i?.length===s+1&&o?.listener===t&&o.once&&u(this,$i,"f").set(t,{event:e,registration:o})},fp=function(e,t){t.removed||(t.removed=!0,u(this,$i,"f").delete(t.listener),u(this,Ci,"f").add(e),u(this,dr,"f")===0&&u(this,Me,"m",El).call(this))},El=function(){for(let e of u(this,Ci,"f")){let t=e,n=u(this,et,"f")[t];n&&(u(this,et,"f")[t]=n.filter(s=>!s.removed))}u(this,Ci,"f").clear()},wu=function(e){if(w(this,Au,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=this._userAbortError()),e instanceof Y)return w(this,Ru,!0,"f"),this._emit("abort",e);if(e instanceof f)return this._emit("error",e);if(e instanceof Error){let t=new f(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new f(String(e)))},pp=function(e,t,n){if(e==="abort"){let s=t[0];w(this,Vr,u(this,Vr,"f")??{kind:"abort",error:s},"f"),!u(this,rs,"f")&&!n&&Promise.reject(s),u(this,ki,"f").call(this,s),u(this,ji,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];w(this,Vr,u(this,Vr,"f")??{kind:"error",error:s},"f"),!u(this,rs,"f")&&!n&&Promise.reject(s),u(this,ki,"f").call(this,s),u(this,ji,"f").call(this,s),this._emit("end")}};function bp(r){return typeof r.parse=="function"}var Ce,Gr,vu,Iu,jl,Su,ql,$l,Dl,Fl,wp,Ap,tb=10;function rb(r){for(let e of r.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${De()}`)}function nb(r){if(!Bt(r))return r;let e={role:"assistant"};return r.audio!=null&&(e.audio={id:r.audio.id}),r.content!==void 0&&(e.content=r.content),r.function_call!=null&&(e.function_call=r.function_call),r.name!==void 0&&(e.name=r.name),r.refusal!=null&&(e.refusal=r.refusal),r.tool_calls!==void 0&&(e.tool_calls=r.tool_calls.map(t=>t.type==="custom"?{id:t.id,type:t.type,custom:{input:t.custom.input,name:t.custom.name}}:{id:t.id,type:t.type,function:{arguments:t.function.arguments,name:t.function.name}})),e}var Yr=class extends fr{constructor(){super(...arguments),Ce.add(this),this._chatCompletions=[],vu.set(this,!1),Iu.set(this,!1),this.messages=[]}_addChatCompletion(e){w(this,vu,!this.controller.signal.aborted,"f"),rb(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0,n=!0){if(n&&!("content"in e)&&(e.content=null),this.messages.push(e),t){if(this._emit("message",e),Ii(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Bt(e)&&e.tool_calls)for(let s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new f("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),u(this,Ce,"m",jl).call(this)}async finalMessage(){return await this.done(),u(this,Ce,"m",Su).call(this)}async finalFunctionToolCall(){return await this.done(),u(this,Ce,"m",ql).call(this)}async finalFunctionToolCallResult(){return await this.done(),u(this,Ce,"m",$l).call(this)}async totalUsage(){return await this.done(),u(this,Ce,"m",Dl).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){u(this,Iu,"f")&&u(this,Ce,"m",Fl).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=u(this,Ce,"m",Su).call(this);t&&this._emit("finalMessage",t);let n=u(this,Ce,"m",jl).call(this);n&&this._emit("finalContent",n);let s=u(this,Ce,"m",ql).call(this);s&&this._emit("finalFunctionToolCall",s);let i=u(this,Ce,"m",$l).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",u(this,Ce,"m",Dl).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),u(Gr,Gr,"m",wp).call(Gr,t);let s=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(vi(s,t))}async _runChatCompletion(e,t,n){for(let s of t.messages)this._addMessage(s,!1,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,s){let i="tool",{tool_choice:o="auto",stream:a,toolContext:c,...d}=t,p=c,y=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:_=tb,afterCompletion:b}=s||{},h=async C=>{b!=null&&(w(this,Iu,!0,"f"),await b(C,n),u(this,Ce,"m",Fl).call(this))},A=t.tools.map(C=>{if(ft(C)){if(!C.$callback)throw new f("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:C.$callback,name:C.function.name,description:C.function.description||"",parameters:C.function.parameters,parse:C.$parseRaw,strict:!0}}}return C}),O=Object.create(null);for(let C of A)C.type==="function"&&(O[C.function.name||C.function.function.name]=C.function);let E="tools"in t?A.map(C=>C.type==="function"?{type:"function",function:{name:C.function.name||C.function.function.name,parameters:C.function.parameters,description:C.function.description,strict:C.function.strict}}:C):void 0;for(let C of t.messages)this._addMessage(C,!1,!1);let x=!1,q=async C=>{let D=x;if(x=!1,C.type!=="function")return{message:void 0,functionCalled:!1};let R=C.id,{name:v,arguments:S}=C.function,j=O[v];if(!j){let k=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(O).map(z=>JSON.stringify(z)).join(", ")}. Please try again`;return{message:{role:i,tool_call_id:R,content:k},functionCalled:!1}}if(y&&y!==v){let k=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(y)} requested. Please try again`;return{message:{role:i,tool_call_id:R,content:k},functionCalled:!1}}let T;if(bp(j)){let k;try{k=await j.parse(S)}catch(z){if(this.controller.signal.aborted)throw this._userAbortError();let N=z instanceof Error?z.message:String(z);return{message:{role:i,tool_call_id:R,content:N},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{T=await j.function(k,n,p)}catch(z){throw this.controller.signal.aborted&&Object.is(z,this.controller.signal.reason)?this._userAbortError():z}}else{if(this.controller.signal.aborted&&!D)throw this._userAbortError();try{T=await j.function(S,n,p)}catch(k){throw this.controller.signal.aborted&&Object.is(k,this.controller.signal.reason)?this._userAbortError():k}}let $=u(Gr,Gr,"m",Ap).call(Gr,T);return{message:{role:i,tool_call_id:R,content:$},functionCalled:!0}};for(let C=0;C<_;++C){let D=await this._createChatCompletion(e,{...d,tool_choice:o,tools:E,messages:this.messages.map(nb)},s);x=this.controller.signal.aborted&&u(this,vu,"f");let R=D.choices[0]?.message;if(!R)throw new f("missing message in ChatCompletion response");if(!R.tool_calls?.length){await h(D);return}if(y||t.parallel_tool_calls===!1)for(let v of R.tool_calls){let S=await q(v);if(S.message&&this._addMessage(S.message),this.controller.signal.aborted)throw this._userAbortError();if(y&&S.functionCalled){await h(D);return}}else{let v=await Promise.allSettled(R.tool_calls.map(q));if(!this.controller.signal.aborted){for(let S of v)if(S.status==="rejected")throw S.reason}for(let S of v)S.status==="fulfilled"&&S.value.message&&this._addMessage(S.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await h(D)}}};Gr=Yr,vu=new WeakMap,Iu=new WeakMap,Ce=new WeakSet,jl=function(){return u(this,Ce,"m",Su).call(this).content??null},Su=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Bt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new f("stream ended without producing a ChatCompletionMessage with role=assistant")},ql=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Bt(t)&&t?.tool_calls?.length)for(let n=t.tool_calls.length-1;n>=0;n--){let s=t.tool_calls[n];if(s?.type==="function")return s.function}}},$l=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ii(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},Dl=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)if(t){e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens;for(let n of["completion_tokens_details","prompt_tokens_details"]){let s=t[n];if(L(s)){let i=e[n]??(e[n]={});for(let o in s){if(!P(s,o))continue;let a=s[o];typeof a=="number"&&Object.defineProperty(i,o,{value:(P(i,o)?i[o]??0:0)+a,enumerable:!0,configurable:!0,writable:!0})}}}}return e},Fl=function(){if(this.controller.signal.aborted)throw this._userAbortError()},wp=function(e){if(e.n!=null&&e.n>1)throw new f("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ap=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Fi=class r extends Yr{static runTools(e,t,n){let s=new r,i={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,i)),s}_addMessage(e,t=!0,n=!0){super._addMessage(e,t,n),t&&Bt(e)&&e.content&&this._emit("content",e.content)}};var Ae={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},zl=class extends Error{},zi=class extends Error{};function sb(r,e=Ae.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return ob(r.trim(),e)}var ob=(r,e)=>{let t=r.length,n=0,s=_=>{throw new zl(`${_} at position ${n}`)},i=_=>{throw new zi(`${_} at position ${n}`)},o=()=>(y(),n>=t&&s("Unexpected end of input"),r[n]==='"'?a():r[n]==="{"?c():r[n]==="["?d():r.substring(n,n+4)==="null"||Ae.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||Ae.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||Ae.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||Ae.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||Ae.MINUS_INFINITY&e&&t-n>1&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||Ae.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,Number.NaN):p()),a=()=>{let _=n,b=!1;for(n++;n<t&&(r[n]!=='"'||b&&r[n-1]==="\\");)b=r[n]==="\\"?!b:!1,n++;if(r.charAt(n)==='"')try{return JSON.parse(r.substring(_,++n-Number(b)))}catch(h){i(String(h))}else if(Ae.STR&e)try{return JSON.parse(r.substring(_,n-Number(b))+'"')}catch{return JSON.parse(r.substring(_,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{n++,y();let _={};try{for(;r[n]!=="}";){if(y(),n>=t&&Ae.OBJ&e)return _;let b=a();y(),n++;try{let h=o();Object.defineProperty(_,b,{value:h,writable:!0,enumerable:!0,configurable:!0})}catch(h){if(Ae.OBJ&e)return _;throw h}y(),r[n]===","&&n++}}catch{if(Ae.OBJ&e)return _;s("Expected '}' at end of object")}return n++,_},d=()=>{n++;let _=[];try{for(;r[n]!=="]";)_.push(o()),y(),r[n]===","&&n++}catch{if(Ae.ARR&e)return _;s("Expected ']' at end of array")}return n++,_},p=()=>{if(n===0){r==="-"&&Ae.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(h){if(Ae.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}i(String(h))}}let _=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n===t&&!(Ae.NUM&e)&&s("Unterminated number literal");let b=r.substring(_,n);try{return JSON.parse(b)}catch{b==="-"&&Ae.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(b.substring(0,b.lastIndexOf("e")))}catch(h){i(String(h))}}},y=()=>{for(;n<t&&`
19
- \r `.includes(r[n]);)n++};return o()},Rp=r=>sb(r,Ae.ALL^Ae.NUM);function Ml(r){return Array.isArray(r?.choices)?{...r,choices:r.choices.map(e=>({...e,finish_reason:e.finish_reason??null}))}:r}function Op(r){let e=r[Symbol.asyncIterator].bind(r);return r[Symbol.asyncIterator]=async function*(){let n={[Symbol.asyncIterator]:e};for await(let s of n)yield Ml(s)},r}var ee,de,Eu,pr,Zr,Te,tt,Ke,Ll,ns,Bl,Kl,Nl,ss,Mi,Pp;function xp(r){try{return Rp(r)}catch(e){if(e instanceof zi||e instanceof SyntaxError)return Lt({type:"json_schema",$parseRaw:void 0},r);throw e}}var ed="chat.completion.chunk.message:";function Tp(r,e,t){let n={type:"message",message:e,...t?{tool_call_ids:t}:{}};return{id:r.id,choices:[],created:r.created,model:r.model,object:`${ed}${JSON.stringify(n)}`}}function ib(r){return"type"in r&&r.type==="message"&&"message"in r||"object"in r&&typeof r.object=="string"&&r.object.startsWith(ed)}function ab(r){return"type"in r?r:JSON.parse(r.object.slice(ed.length))}var Cu=128,hr=128,ub=16*1024*1024,cb=65536,td=128,kp=64*1024*1024,vp=1024;function Vl(){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 Gl(r,e,t,n){if(e.fragments>=cb)throw new f("Chat completion stream exceeded its structured JSON fragment limit");let s=0,{depth:i,escaped:o,has_non_whitespace:a,in_string:c}=r,d=!1,p=!0;for(let _ of t){let b=s,h=_.codePointAt(0);if(p&&r.pending_high_surrogate&&h>=56320&&h<=57343||h<=127?s+=1:h<=2047?s+=2:h<=65535?s+=3:s+=4,p=!1,e.bytes+s>ub)throw new f("Chat completion stream exceeded its structured JSON byte limit");if(n&&n.work+s>kp)throw n.work+=b,new f("Chat completion stream exceeded its structured JSON parse-work limit");if(_!==" "&&_!==`
20
- `&&_!=="\r"&&_!==" "&&(a=!0),c){o?o=!1:_==="\\"?o=!0:_==='"'&&(c=!1,d||(d=i===0));continue}if(_==='"')c=!0;else if(_==="{"||_==="["){if(i+=1,i>td)throw new f("Chat completion stream exceeded its structured JSON nesting depth limit")}else(_==="}"||_==="]")&&i>0&&(i-=1,d||(d=i===0))}if(r.bytes+=s,r.fragments+=1,r.depth=i,r.escaped=o,r.has_non_whitespace=a,r.in_string=c,t.length>0){let _=t.codePointAt(t.length-1)??0;r.pending_high_surrogate=_>=55296&&_<=56319}if(e.bytes+=s,e.fragments+=1,n&&(n.work+=s),!a||s===0)return!1;let y=Math.max(vp,Math.floor(r.last_parsed_bytes/2));return!(r.bytes>vp&&!d&&r.bytes-r.last_parsed_bytes<y)}function Yl(r,e){return e.work+r.bytes>kp?!1:(e.work+=r.bytes,r.work+=r.bytes,r.last_parsed_bytes=r.bytes,!0)}function rt(r,e){let t=Object.getOwnPropertyDescriptor(r,e);if(!t){let n=Object.getPrototypeOf(r);for(let s=0;n!==null;s+=1){if(s>=td||Object.getOwnPropertyDescriptor(n,e))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");n=Object.getPrototypeOf(n)}return}if(!("value"in t)||typeof t.value!="string"&&t.value!==null&&t.value!==void 0)throw new f("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}function Li(r){let e=Object.getOwnPropertyDescriptor(r,"message");if(!e||!("value"in e)||typeof e.value!="object"||e.value===null)throw new f("Chat completion stream contains an unsafe structured JSON snapshot");return e.value}function Ip(r,e,t,n){let s=Object.getOwnPropertyDescriptor(r,e);if(!s){let o=Object.getPrototypeOf(r);for(let a=0;o!==null;a+=1){if(a>=td||Object.getOwnPropertyDescriptor(o,e))throw new f(`Chat completion stream contains an unsafe snapshot ${n} collection`);o=Object.getPrototypeOf(o)}return}if(!("value"in s)||!Array.isArray(s.value))throw new f(`Chat completion stream contains an unsafe snapshot ${n} collection`);let i=Object.getOwnPropertyDescriptor(s.value,"length");if(!i||!("value"in i)||!Number.isSafeInteger(i.value)||i.value>t)throw new f(`Chat completion stream exceeded its snapshot ${n} limit`);return s.value}function Wl(r,e){let t=Object.getOwnPropertyDescriptor(r,e);if(t){if(!("value"in t))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");return t.value}}function Sp(r,e,t,n){let s=Object.getOwnPropertyDescriptor(r,"length"),i=s&&"value"in s?s.value:void 0;if(typeof i!="number"||!Number.isSafeInteger(i)||i<0||i>e)throw new f(`Chat completion stream exceeded its snapshot ${t} limit`);let o=[];o.length=i;for(let a=0;a<i;a+=1){let c=Object.getOwnPropertyDescriptor(r,a);if(c){if(!("value"in c))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");o[a]=n(c.value,a)}}return o}function en(r,e,t){let n=Vl(),s=e??{bytes:0,fragments:0,work:0};if(Gl(n,s,r,t),!Yl(n,s))throw new f("Chat completion stream exceeded its structured JSON parse-work limit");return r}function Tu(r){let e=Object.getOwnPropertyDescriptor(r,"type"),t=Object.getOwnPropertyDescriptor(r,"function");if(!e||!("value"in e)||e.value!=="function"||!t||!("value"in t)||typeof t.value!="object"||t.value===null)return;let n=Object.getOwnPropertyDescriptor(t.value,"name");if(!(!n||!("value"in n)||typeof n.value!="string"||n.value.length===0))return{type:"function",name:n.value}}function Ul(r,e){let t=Tu(r);if(!t||t.name!==e.name||t.type!==e.type)throw new f("Chat completion stream contains a changed tool call identity")}function Bi(r,e){return Object.prototype.propertyIsEnumerable.call(e,"__proto__")&&!P(r,"__proto__")&&Object.defineProperty(r,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(r,e)}function Ki(r,e=[]){let t=Object.getOwnPropertyDescriptors(r);for(let n of e){let s=t[n];!s&&!(n in r)||(t[n]={value:s&&"value"in s?s.value:Reflect.get(r,n,r),enumerable:s?.enumerable??!1,configurable:s?.configurable??!0,writable:s&&"writable"in s?s.writable:!1})}return Object.create(Object.getPrototypeOf(r),t)}function lb(r){let e=Ki(r);if(r.tools){let t=[],n=Object.getOwnPropertyDescriptor(r.tools,"length"),s=n&&"value"in n?n.value:void 0,i=typeof s=="number"&&Number.isSafeInteger(s)&&s>=0?Math.min(s,hr):0;for(let o=0;o<i;o+=1){let a=Object.getOwnPropertyDescriptor(r.tools,String(o));if(!a||!("value"in a)){t.length=o+1;continue}let c=a.value,d=Ki(c,["type","$brand","$parseRaw","$callback","function"]),p=Object.getOwnPropertyDescriptors(d);if(Pt(d)){let y=p.function;p.function={...y&&"value"in y?y:{configurable:!0,enumerable:!0,writable:!0},value:Ki(d.function,["name","strict"])}}t[o]=Object.create(Object.getPrototypeOf(c),p)}e.tools=t}return r.response_format&&(e.response_format=Ki(r.response_format,["type","$brand","$parseRaw"])),e}var Ql=4096,Hl=JSON.stringify,db=1024*1024,fb=64,Xl=Symbol("omitted serialized parser value"),Re=Symbol("unsafe serialized parser value");function jp(r,e){let t=new WeakSet,n=i=>!Number.isSafeInteger(i)||i<0||e.bytes+i>db?!1:(e.bytes+=i,!0),s=(i,o)=>{if(o>fb||e.nodes>=Ql)return Re;if(e.nodes+=1,i===void 0||typeof i=="function"||typeof i=="symbol")return Xl;if(typeof i=="bigint")return Re;if(i===null||typeof i=="boolean"||typeof i=="number"){let d=Hl(i);return typeof d=="string"&&n(d.length)?d:Re}if(typeof i=="string")return n(i.length*6+2)?Hl(i):Re;if(typeof i!="object"||t.has(i))return Re;let a=Array.isArray(i),c=Object.getPrototypeOf(i);if(a&&c!==Array.prototype||!a&&c!==null&&c!==Object.prototype)return Re;for(let d=i;d!==null;d=Object.getPrototypeOf(d)){let p=Object.getOwnPropertyDescriptor(d,"toJSON");if(p){if(!("value"in p)||typeof p.value=="function")return Re;break}}t.add(i);try{if(!n(2))return Re;if(a){let _=Object.getOwnPropertyDescriptor(i,"length"),b=_&&"value"in _?_.value:void 0;if(typeof b!="number"||!Number.isSafeInteger(b)||b<0||b>Ql-e.nodes)return Re;let h=[];for(let A=0;A<b;A+=1){let O=String(A),E=Object.getOwnPropertyDescriptor(i,O);if(!E){if(Object.getOwnPropertyDescriptor(Array.prototype,O)||Object.getOwnPropertyDescriptor(Object.prototype,O)||(e.nodes+=1,!n(4)))return Re;h.push("null");continue}if(!("value"in E))return Re;let x=s(E.value,o+1);if(x===Re)return x;h.push(x===Xl?"null":x)}return`[${h.join(",")}]`}let d=Reflect.ownKeys(i);if(d.length>Ql-e.nodes)return Re;let p=[];for(let _ of d){if(typeof _!="string")continue;let b=Object.getOwnPropertyDescriptor(i,_);if(!b)return Re;if(b.enumerable){if(!("value"in b))return Re;p.push([_,b.value])}}p.sort(([_],[b])=>_===b?0:_<b?-1:1);let y=[];for(let[_,b]of p){let h=s(b,o+1);if(h===Re)return h;if(h!==Xl){if(!n(_.length*6+3))return Re;y.push(`${Hl(_)}:${h}`)}}return`{${y.join(",")}}`}finally{t.delete(i)}};try{let i=s(r,0);return typeof i=="string"?i:void 0}catch{return}}function Ep(r,e,t,n){let s=Object.getOwnPropertyDescriptor(e,"$parseRaw"),i=Object.getOwnPropertyDescriptor(t,n);if(!s||!("value"in s)||typeof s.value!="function"||!i||!("value"in i))return;let o=jp(i.value,{nodes:0,bytes:0});o!==void 0&&r.set(e,o)}function Cp(r,e,t,n,s){let i=e&&r.get(e),o=Object.getOwnPropertyDescriptor(t,n);return i!==void 0&&o!==void 0&&"value"in o&&jp(s,{nodes:0,bytes:0})===i}function os(r,e){return r&&"value"in r?{...r,value:e}:{configurable:!0,enumerable:!0,writable:!0,value:e}}function Zl(r,e,t){for(let n of t){let s=r[n];!s&&!(n in e)||(r[n]=s&&"value"in s?{...s,value:void 0}:{configurable:s?.configurable??!0,enumerable:s?.enumerable??!1,writable:!1,value:void 0})}}function pb(r){let e=r.source??{type:r.type,...r.type==="function"?{function:{}}:{}},t=Object.getOwnPropertyDescriptors(e);if(t.type=os(t.type,r.type),r.type!=="function"||!r.function)return t.function&&(t.function=os(t.function,void 0)),Zl(t,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),t);let n=t.function,s=n&&"value"in n&&typeof n.value=="object"&&n.value!==null?n.value:{},i=Object.getOwnPropertyDescriptors(s);return i.name=os(i.name,r.function.name),i.strict=os(i.strict,r.function.strict),t.function=os(n,Object.create(Object.getPrototypeOf(s),i)),r.function.schemaMatches||Zl(t,e,["$brand","$parseRaw","$callback"]),Object.create(Object.getPrototypeOf(e),t)}function hb(r){let e=r.source??{type:r.type},t=Object.getOwnPropertyDescriptors(e);return t.type=os(t.type,r.type),(r.type!=="json_schema"||!r.source||!r.schemaMatches)&&Zl(t,e,["$brand","$parseRaw"]),Object.create(Object.getPrototypeOf(e),t)}function Jl(r,e){let t=Object.getOwnPropertyDescriptor(r,e);if(!t||!("value"in t))return;let{value:n}=t;return typeof n=="object"&&n!==null?n:void 0}function mb(r,e,t){let n=new WeakMap,s=new WeakMap;if(r.tools)for(let b=0;b<r.tools.length&&b<hr;b+=1){let h=Jl(r.tools,String(b)),A=e.tools?.[b];if(h&&A){n.set(h,A);let O=Jl(A,"function");O&&Ep(s,A,O,"parameters")}}e.response_format&&Ep(s,e.response_format,e.response_format,"json_schema");let i,o,a,c,d=[],p=new WeakMap,y=new Map,_=new WeakMap;return eu(r,{value(b,h,A){if(!i&&h===""&&typeof A=="object"&&A!==null){i=A,o=void 0,a=void 0,c=void 0,d=[],p=new WeakMap,y=new Map,_=new WeakMap;return}if(b===i&&h==="response_format"){typeof A=="object"&&A!==null&&(a=A,c={source:Jl(b,h)===r.response_format?e.response_format:void 0,schemaMatches:!1});return}if(b===i&&h==="tools")return Array.isArray(A)?(o=new Proxy(A,{get(x,q){let C=Reflect.get(x,q,x);if(typeof q=="string"){let D=Number(q);Number.isSafeInteger(D)&&D>=0&&D<hr&&String(D)===q&&y.set(D,typeof C=="object"&&C!==null?C:void 0)}return C}}),o):void 0;if(b===o){let x=Number(h);if(!Number.isSafeInteger(x)||x<0||x>=hr||typeof A!="object"||A===null)return;let q=y.get(x),D={source:q?n.get(q):void 0};d[x]=D,p.set(A,D);return}let O=p.get(b);if(O){if(h==="type"&&typeof A=="string")O.type=A;else if(h==="function"&&typeof A=="object"&&A!==null){let x={source:O.source,schemaMatches:!1};O.function=x,_.set(A,x)}return}if(b===a&&c){h==="type"&&typeof A=="string"?c.type=A:h==="json_schema"&&(c.schemaMatches=Cp(s,c.source,b,h,A));return}let E=_.get(b);E&&(h==="name"&&typeof A=="string"?E.name=A:h==="strict"&&typeof A=="boolean"?E.strict=A:h==="parameters"&&(E.schemaMatches=Cp(s,E.source,b,h,A)))},complete(){if(!i)return;let b=Ki(e);if(o){let h=[];for(let A=0;A<d.length;A+=1){let O=d[A];O&&(h[A]=pb(O))}b.tools=h}else delete b.tools;c?b.response_format=hb(c):delete b.response_format,t(b),i=void 0,o=void 0,a=void 0,c=void 0,d=[],p=new WeakMap,y=new Map,_=new WeakMap}})}var tn=class r extends Yr{constructor(e){super(),ee.add(this),de.set(this,void 0),Eu.set(this,!1),pr.set(this,void 0),Zr.set(this,void 0),Te.set(this,void 0),tt.set(this,void 0),Ke.set(this,void 0),w(this,de,e,"f"),w(this,pr,new Set,"f"),w(this,Zr,[],"f"),w(this,tt,!1,"f");let t=e?.tools,n=t&&Object.getOwnPropertyDescriptor(t,"length"),s=n&&"value"in n?n.value:void 0;if(t&&typeof s=="number"&&Number.isSafeInteger(s)&&s>=0)for(let i=0;i<Math.min(s,hr);i+=1){let o=Object.getOwnPropertyDescriptor(t,String(i));if(!o||!("value"in o))continue;let a=o.value;if(Pt(a)&&(ft(a)||a.function.strict===!0)){w(this,tt,!0,"f");break}}w(this,Ke,{bytes:0,fragments:0,work:0},"f")}get currentChatCompletionSnapshot(){return u(this,Te,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let s=new r(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}_runTools(e,t,n,s){return w(this,Eu,!0,"f"),super._runTools(e,t,n,s)}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0};w(this,de,s,"f"),u(this,ee,"m",Ll).call(this);let i=lb(s);w(this,de,i,"f"),w(this,tt,i.tools?.some(c=>Pt(c)&&(ft(c)||c.function.strict===!0))??!1,"f");let o=s.tools||s.response_format?mb(s,i,c=>{w(this,de,c,"f"),w(this,tt,c.tools?.some(d=>Pt(d)&&(ft(d)||d.function.strict===!0))??!1,"f")}):void 0,a=await e.chat.completions.create(s,{...n,signal:this.controller.signal}).finally(o);this._connected();for await(let c of a)u(this,ee,"m",Bl).call(this,c);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(u(this,ee,"m",Mi).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,ee,"m",Ll).call(this),this._connected();let n=ze.fromReadableStream(e,this.controller),s;for await(let o of n){if("error"in o&&P(o,"error")&&typeof o.error=="object"&&o.error!==null)throw new J(void 0,o.error,void 0,void 0);if(ib(o)){let c=ab(o);if(u(this,Te,"f")){let d=u(this,Te,"f").choices[0]?.message.tool_calls;for(let[p,y]of c.tool_call_ids?.entries()??[]){let _=d?.[p];_&&y&&(_.id=y)}this._addChatCompletion(u(this,ee,"m",Mi).call(this)),s=void 0}this._addMessage(c.message);continue}let a=Ml(o);s&&a.id&&s!==a.id&&this._addChatCompletion(u(this,ee,"m",Mi).call(this)),u(this,ee,"m",Bl).call(this,a),a.id&&(s=a.id)}if(n.controller.signal?.aborted)throw this._userAbortError();if(u(this,Te,"f"))return this._addChatCompletion(u(this,ee,"m",Mi).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new f("request ended without sending any chunks")}[(de=new WeakMap,Eu=new WeakMap,pr=new WeakMap,Zr=new WeakMap,Te=new WeakMap,tt=new WeakMap,Ke=new WeakMap,ee=new WeakSet,Ll=function(){this.ended||(w(this,pr,new Set,"f"),w(this,Te,void 0,"f"),w(this,Ke,{bytes:0,fragments:0,work:0},"f"))},ns=function(t){let n=u(this,Zr,"f")[t.index];return n||(n={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},u(this,Zr,"f")[t.index]=n,n)},Bl=function(t){if(this.ended)return;let n=new WeakMap,s=u(this,ee,"m",Pp).call(this,t,n);this._emit("chunk",t,s);for(let i of t.choices){let o=n.get(i),a=s.choices[o?.index??i.index],c=o?.tool_calls??[],{delta:d}=i,p=xt(u(this,de,"f")?.response_format),y=p||u(this,tt,"f"),_=y?Li(a):a.message,b=y?rt(_,"refusal"):_.refusal,A=!b&&p?rt(_,"content"):_.content;d?.content!=null&&_.role==="assistant"&&A&&(this._emit("content",d.content,A),this._emit("content.delta",{delta:d.content,snapshot:A,parsed:_.parsed})),d?.refusal!=null&&_.role==="assistant"&&b&&this._emit("refusal.delta",{delta:d.refusal,snapshot:b}),i.logprobs?.content!=null&&_.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:a.logprobs?.content??[]}),i.logprobs?.refusal!=null&&_.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});let O=u(this,ee,"m",ns).call(this,a);a.finish_reason&&(u(this,ee,"m",Nl).call(this,a),O.current_tool_call_index!=null&&u(this,ee,"m",Kl).call(this,a,O.current_tool_call_index));for(let E of c)O.current_tool_call_index!==E.index&&(u(this,ee,"m",Nl).call(this,a),O.current_tool_call_index!=null&&u(this,ee,"m",Kl).call(this,a,O.current_tool_call_index)),O.current_tool_call_index=E.index;for(let E of c){let x=_.tool_calls?.[E.index];if(x?.type)if(x.type==="function"){let q=O.tool_call_identities.get(E.index),C;if(q?.parseable){let D=rt(x.function,"arguments");if(typeof D!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");C=D}else C=x.function.arguments;this._emit("tool_calls.function.arguments.delta",{name:x.function.name,index:E.index,arguments:C,parsed_arguments:x.function.parsed_arguments,arguments_delta:E.arguments_delta})}else x.type!=="custom"&&x}}},Kl=function(t,n){let s=u(this,ee,"m",ns).call(this,t);if(s.done_tool_calls.has(n))return;let o=(u(this,tt,"f")?Li(t):t.message).tool_calls?.[n];if(!o)throw new Error("no tool call snapshot");let a=s.tool_call_identities.get(n);if(a&&Ul(o,a),!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let c=u(this,de,"f")?.tools?.find(_=>Pt(_)&&_.function.name===o.function.name),d=null,p=ft(c)||c?.function.strict===!0,y;if(p){u(this,Te,"f")&&u(this,ee,"m",ss).call(this,u(this,Te,"f"));let _=rt(o.function,"arguments");if(typeof _!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");y=_}else y=o.function.arguments;ft(c)?d=c.$parseRaw(en(y)):c?.function.strict&&(d=Lt({type:"json_schema",$parseRaw:void 0},en(y))),t.finish_reason&&s.done_tool_calls.add(n),this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:y,parsed_arguments:d})}else o.type!=="custom"&&o},Nl=function(t){let n=u(this,ee,"m",ns).call(this,t),s=xt(u(this,de,"f")?.response_format),i=s||u(this,tt,"f"),o=i?Li(t):t.message,a=i?rt(o,"refusal"):o.refusal,c=!a&&s,d=c?rt(o,"content"):o.content;d!=null&&(d!==""||!a&&!o.tool_calls?.length&&!o.function_call)&&!n.content_done&&(c&&u(this,Te,"f")&&u(this,ee,"m",ss).call(this,u(this,Te,"f")),n.content_done=!0,this._emit("content.done",{content:d,parsed:a?null:Lt(u(this,de,"f")?.response_format,c?en(d):d)})),a&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:a})),t.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},ss=function(t){let n={bytes:0,fragments:0,work:0},s=xt(u(this,de,"f")?.response_format),i=new WeakMap,o=Ip(t,"choices",Cu,"choice");if(!o)throw new f("Chat completion stream contains an unsafe snapshot choice collection");for(let a=0;a<o.length;a+=1){let c=Wl(o,a);if(!c)continue;let d=Li(c),p=rt(d,"refusal"),y=rt(d,"content"),_=new Map,b=Ip(d,"tool_calls",hr,"tool-call");i.set(c,Object.freeze({message:d,content:y,refusal:p,toolCallCollection:b,toolCalls:_}));let h=u(this,Zr,"f")[c.index];s&&!p&&typeof y=="string"&&en(y,n,u(this,Ke,"f"));for(let[A,O]of h?.tool_call_identities??[]){let E=b&&Wl(b,A);if(!E)throw new f("Chat completion stream contains a changed tool call identity");Ul(E,O)}if(u(this,tt,"f"))for(let A=0;A<(b?.length??0);A+=1){let O=Wl(b,A);if(!O)continue;let E=Tu(O);if(!E){let D=Object.getOwnPropertyDescriptor(O,"type");if(D&&!("value"in D))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");if(D?.value!=="function")continue;let R=Object.getOwnPropertyDescriptor(O,"function");if(R&&!("value"in R))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");if(R&&typeof R.value=="object"&&R.value!==null){let v=Object.getOwnPropertyDescriptor(R.value,"name");if(v&&!("value"in v))throw new f("Chat completion stream contains an unsafe structured JSON snapshot")}continue}if(!hu(u(this,de,"f"),{type:E.type,function:{name:E.name}}))continue;let x=Object.getOwnPropertyDescriptor(O,"function");if(!x||!("value"in x))throw new f("Chat completion stream contains an unsafe structured JSON snapshot");let q=x.value,C=rt(q,"arguments");if(typeof C!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");en(C,n,u(this,Ke,"f")),_.set(A,Object.freeze({tool:O,function:q,type:E.type,name:E.name,arguments:C}))}}return i},Mi=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");let t=u(this,Te,"f");if(!t)throw new f("request ended without sending any chunks");let n=u(this,ee,"m",ss).call(this,t),s=u(this,pr,"f");return w(this,pr,new Set,"f"),w(this,Te,void 0,"f"),w(this,Zr,[],"f"),_b(t,u(this,de,"f"),s,n)},Pp=function(t,n){var s,i,o,a,c;let d=u(this,Te,"f"),{choices:p,obfuscation:y,..._}=t;if(d)t.id&&Bi(d,_);else{let A={..._,choices:[]};w(this,Te,A,"f"),d=A}let b=u(this,de,"f")?.n,h=typeof b=="number"&&Number.isSafeInteger(b)&&b>0?Math.min(b,Cu):Cu;for(let A of t.choices){let{delta:O,finish_reason:E,index:x,logprobs:q=null,...C}=A,D=[];if(n.set(A,Object.freeze({index:x,tool_calls:D})),!Number.isSafeInteger(x)||x<0||x>=h)throw new f(`Chat completion stream contains an invalid choice index: ${x}`);let R=d.choices[x];if(!R){let M={finish_reason:E??null,index:x,message:{},logprobs:null,...C};d.choices[x]=M,R=M}if((xt(u(this,de,"f")?.response_format)||u(this,tt,"f"))&&rt(Li(R),"refusal"),q)if(R.logprobs){let{content:M,refusal:ne,...V}=q;Bi(R.logprobs,V),M&&((s=R.logprobs).content??(s.content=[]),R.logprobs.content.push(...M)),ne&&((i=R.logprobs).refusal??(i.refusal=[]),R.logprobs.refusal.push(...ne))}else R.logprobs={...q},q.content&&(R.logprobs.content=[...q.content]),q.refusal&&(R.logprobs.refusal=[...q.refusal]);if(E&&(R.finish_reason=E,u(this,de,"f")&&(u(this,Eu,"f")||Al(u(this,de,"f"))))){if(E==="length")throw new ur;if(E==="content_filter")throw new cr}if(Bi(R,C),!O){Object.freeze(D);continue}u(this,pr,"f").delete(x);let{audio:v,content:S,refusal:j,function_call:T,role:$,...k}=O,{tool_calls:z,...N}=k,H=P(k,"tool_calls")?z:O.tool_calls;if(Bi(R.message,N),v?.expires_at!=null&&v.id==null&&v.data==null&&v.transcript==null&&S==null&&j==null&&T==null&&$==null&&H==null&&Object.keys(N).length===0&&u(this,pr,"f").add(x),j&&(R.message.refusal=(R.message.refusal||"")+j),$&&(R.message.role=$),v){let M=(o=R.message).audio??(o.audio={});v.id!=null&&(M.id=v.id),v.data!=null&&(M.data=(M.data??"")+v.data),v.transcript!=null&&(M.transcript=(M.transcript??"")+v.transcript),v.expires_at!=null&&(M.expires_at=v.expires_at)}if(T&&(R.message.function_call?(T.name&&(R.message.function_call.name=T.name),T.arguments&&((a=R.message.function_call).arguments??(a.arguments=""),R.message.function_call.arguments+=T.arguments)):R.message.function_call=T),S!=null)if(!R.message.refusal&&xt(u(this,de,"f")?.response_format)){let M=u(this,ee,"m",ns).call(this,R),ne=M.content_parse_state??(M.content_parse_state=Vl()),V=Gl(ne,u(this,Ke,"f"),S);R.message.content=(rt(R.message,"content")||"")+S,ne.has_non_whitespace?V&&Yl(ne,u(this,Ke,"f"))?(u(this,ee,"m",ss).call(this,d),R.message.parsed=xp(en(R.message.content))):S.length>0&&(R.message.parsed=null):R.message.parsed=null}else R.message.content=(R.message.content||"")+S;if(H){let M=(c=R.message).tool_calls??(c.tool_calls=[]);for(let ne of H){let{index:V,id:Na,type:Qn,function:Hn,custom:kt,...Nc}=ne;if(!Number.isSafeInteger(V)||V<0||V>=hr)throw new f(`Chat completion stream contains an invalid tool call index: ${V}`);let Qe="",pe=M[V]??(M[V]={}),lt=Hn?.name,yt=u(this,tt,"f")?u(this,ee,"m",ns).call(this,R):void 0,He=yt?.tool_call_identities.get(V);if(He&&(Ul(pe,He),Qn!==void 0&&Qn!==He.type||lt!==void 0&&lt!==He.name))throw new f("Chat completion stream contains a changed tool call identity");if(Bi(pe,Nc),Na&&(pe.id=Na),Qn&&(pe.type=Qn),kt){let $e=pe.custom??(pe.custom={name:kt.name??"",input:""});kt.name&&($e.name=kt.name),kt.input&&($e.input+=kt.input)}if(Hn){let $e=pe.function??(pe.function={name:lt??"",arguments:""});if(lt&&($e.name=lt),yt&&!He){let Xe=Tu(pe),Wc=Xe&&u(this,de,"f")?.tools?.find(gt=>Pt(gt)&&gt.function.name===Xe.name);if(Xe&&(He={...Xe,parseable:Wc!==void 0&&hu(u(this,de,"f"),{type:Xe.type,function:{name:Xe.name}})},yt.tool_call_identities.set(V,He),!He.parseable)){let gt=yt.tool_call_parse_states.get(V);gt&&(u(this,Ke,"f").bytes-=gt.bytes,u(this,Ke,"f").fragments-=gt.fragments,u(this,Ke,"f").work-=gt.work,yt.tool_call_parse_states.delete(V))}}let er=Hn.arguments;if(er!=null)if(Qe=er,yt&&He?.parseable!==!1){let Xe=yt.tool_call_parse_states.get(V);Xe||(Xe=Vl(),yt.tool_call_parse_states.set(V,Xe));let Wc=Gl(Xe,u(this,Ke,"f"),er),gt=rt($e,"arguments");if(typeof gt!="string")throw new f("Chat completion stream contains an unsafe structured JSON snapshot");$e.arguments=gt+er,Wc&&He?.parseable===!0&&Yl(Xe,u(this,Ke,"f"))?(u(this,ee,"m",ss).call(this,d),$e.parsed_arguments=xp(en($e.arguments))):er.length>0&&P($e,"parsed_arguments")&&($e.parsed_arguments=void 0)}else $e.arguments+=er}D.push(Object.freeze({index:V,arguments_delta:Qe}))}}Object.freeze(D)}return d},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=n=>e(n);return this.on("chunk",t),()=>this.off("chunk",t)},{onReturn:()=>this.abort()})}toReadableStream(){return new ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function _b(r,e,t,n){let{id:s,choices:i,created:o,model:a,system_fingerprint:c,...d}=r,p={...d,id:s,choices:Sp(i,Cu,"choice",y=>{let _=n.get(y);if(!_)throw new f("Chat completion stream contains an unsafe structured JSON snapshot");let b=new Proxy(y,{get(k,z,N){return z==="message"?_.message:Reflect.get(k,z,N)}}),{message:h,finish_reason:A,index:O,logprobs:E,...x}=b,q=new Proxy(h,{get(k,z,N){return z==="content"?_.content:z==="refusal"?_.refusal:z==="tool_calls"?_.toolCallCollection:Reflect.get(k,z,N)}}),{content:C=null,function_call:D,tool_calls:R,audio:v,...S}=q,j=A??(t.has(O)&&yb(v)?"stop":null);if(!j)throw new f(`missing finish_reason for choice ${O}`);let T=v?{audio:v}:{},$=q.role;if(!$)throw new f(`missing role for choice ${O}`);if(D){let{arguments:k,name:z}=D;if(k==null)throw new f(`missing function_call.arguments for choice ${O}`);if(!z)throw new f(`missing function_call.name for choice ${O}`);return{...x,message:{...T,content:C,function_call:{arguments:k,name:z},role:$,refusal:q.refusal??null},finish_reason:j,index:O,logprobs:E}}return R?{...x,index:O,finish_reason:j,logprobs:E,message:{...S,...T,role:$,content:C,refusal:q.refusal??null,tool_calls:Sp(R,hr,"tool-call",(k,z)=>{let N=_.toolCalls.get(z);if(!N){let Qe=Tu(k);if(Qe&&hu(e,{type:Qe.type,function:{name:Qe.name}}))throw new f("Chat completion stream contains an unsafe structured JSON snapshot")}if(N&&N.tool!==k)throw new f("Chat completion stream contains a changed tool call identity");let H=N&&new Proxy(N.function,{get(Qe,pe,lt){return pe==="arguments"?N.arguments:pe==="name"?N.name:Reflect.get(Qe,pe,lt)}}),M=N&&H?new Proxy(k,{get(Qe,pe,lt){return pe==="type"?N.type:pe==="function"?H:Reflect.get(Qe,pe,lt)}}):k;if(M.type==null)throw new f(`missing choices[${O}].tool_calls[${z}].type`);if(M.type==="custom"){let{custom:Qe,type:pe,id:lt,...yt}=M,{input:He="",name:$e,...er}=Qe||{};if($e==null)throw new f(`missing choices[${O}].tool_calls[${z}].custom.name`);return{...yt,id:lt||`call_${De()}`,type:pe,custom:{...er,name:$e,input:He}}}let{function:ne,type:V,id:Na,...Qn}=M,{arguments:Hn,name:kt,...Nc}=ne||{};if(kt==null)throw new f(`missing choices[${O}].tool_calls[${z}].function.name`);if(Hn==null)throw new f(`missing choices[${O}].tool_calls[${z}].function.arguments`);return{...Qn,id:Na||`call_${De()}`,type:V,function:{...Nc,name:kt,arguments:Hn}}})}}:{...x,message:{...S,...T,content:C,role:$,refusal:q.refusal??null},finish_reason:j,index:O,logprobs:E}}),created:o,model:a,object:"chat.completion",...c?{system_fingerprint:c}:{}};return np(p,e)}function yb(r){return r?.id!=null&&r.data!=null&&r.transcript!=null&&r.expires_at!=null}var Ni=class r extends tn{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e,t,n=this._createIterator(i=>{let o=c=>{e=c,i(c)},a=c=>{if(Bt(c)){t=c.tool_calls?.map(d=>d.id);return}if(Ii(c)){if(!e)throw new f("cannot serialize a tool message before receiving any chunks");i(Tp(e,c,t)),t=void 0}};return this.on("chunk",o),this.on("message",a),()=>{this.off("chunk",o),this.off("message",a)}},{onReturn:()=>this.abort()});return new ze(()=>n,this.controller).toReadableStream()}static runTools(e,t,n){let s=new r(t),i={...n,__metadata:{...n?.__metadata,helperMethod:"runTools"}};return s._run(()=>s._runTools(e,t,s,i)),s}};function Wi(r,e){return Promise.resolve(r).then(e)}function gb(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var qp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function bb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>qp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!qp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var mr=class extends m{constructor(){super(...arguments),this.messages=new Xr(this._client)}create(e,t){return this._client.post("/chat/completions",Wi(t,n=>gb({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))._thenUnwrap((n,s)=>s.options.stream?Op(n):n)}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,Wi(t,n=>({...n,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/chat/completions/${e}`,Wi(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}list(e={},t){let n=bb(e,["after","limit","metadata","model","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/chat/completions",I,Wi(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,Wi(t,n=>({...n,__security:{bearerAuth:!0}})))}parse(e,t){return sp(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:"chat.completions.parse"}})._thenUnwrap(n=>vi(n,e))}runTools(e,t){return e.stream?Ni.runTools(this._client,e,t):Fi.runTools(this._client,e,t)}stream(e,t){return tn.createChatCompletion(this._client,e,t)}};mr.Messages=Xr;var _r=class extends m{constructor(){super(...arguments),this.completions=new mr(this._client)}};_r.Completions=mr;function ku(r,e){return Promise.resolve(r).then(e)}var $p=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Ab(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>$p.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!$p.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var is=class extends m{create(e,t){return this._client.post("/organization/admin_api_keys",ku(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/admin_api_keys/${e}`,ku(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Ab(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/admin_api_keys",I,ku(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/admin_api_keys/${e}`,ku(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function Ob(r,e){return Promise.resolve(r).then(e)}var Dp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Pb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Dp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Dp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var as=class extends m{list(e={},t){let n=Pb(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",Q,Ob(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}};function rn(r,e){return Promise.resolve(r).then(e)}var Fp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function zp(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Fp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Fp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var us=class extends m{create(e,t){return this._client.post("/organization/certificates",rn(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t={},n){let s=zp(t,["include"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.get(l`/organization/certificates/${e}`,rn(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/certificates/${e}`,rn(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=zp(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/certificates",Q,rn(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/certificates/${e}`,rn(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",be,rn(t,n=>({body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})))}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",be,rn(t,n=>({body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})))}};function Mp(r,e){return Promise.resolve(r).then(e)}var cs=class extends m{retrieve(e){return this._client.get("/organization/data_retention",Mp(e,t=>({...t,__security:{adminAPIKeyAuth:!0}})))}update(e,t){return this._client.post("/organization/data_retention",Mp(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}};function Ui(r,e){return Promise.resolve(r).then(e)}var Lp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Sb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Lp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Lp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ls=class extends m{create(e,t){return this._client.post("/organization/external_keys",Ui(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/external_keys/${e}`,Ui(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Sb(e,["after","limit","order","purpose"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/external_keys",I,Ui(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/external_keys/${e}`,Ui(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}validate(e,t){return this._client.post(l`/organization/external_keys/${e}/validate`,Ui(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function Qi(r,e){return Promise.resolve(r).then(e)}var Bp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Cb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Bp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Bp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ds=class extends m{create(e,t){return this._client.post("/organization/external_storage",Qi(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/external_storage/${e}`,Qi(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Cb(e,["after","limit","order","project_id"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/external_storage",I,Qi(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/external_storage/${e}`,Qi(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}validate(e,t){return this._client.post(l`/organization/external_storage/${e}/validate`,Qi(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function ju(r,e){return Promise.resolve(r).then(e)}var Kp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function kb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Kp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Kp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var fs=class extends m{create(e,t){return this._client.post("/organization/invites",ju(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/invites/${e}`,ju(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=kb(e,["after","limit"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/invites",Q,ju(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/invites/${e}`,ju(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function Hi(r,e){return Promise.resolve(r).then(e)}var Np=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function qb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Np.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Np.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ps=class extends m{create(e,t){return this._client.post("/organization/roles",Hi(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/roles/${e}`,Hi(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/roles/${e}`,Hi(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=qb(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/roles",ie,Hi(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/roles/${e}`,Hi(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function Xi(r,e){return Promise.resolve(r).then(e)}var Wp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Db(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Wp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Wp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var hs=class extends m{create(e,t){return this._client.post("/organization/spend_alerts",Xi(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/spend_alerts/${e}`,Xi(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/spend_alerts/${e}`,Xi(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Db(e,["after","before","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/spend_alerts",Q,Xi(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/spend_alerts/${e}`,Xi(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function rd(r,e){return Promise.resolve(r).then(e)}var ms=class extends m{retrieve(e){return this._client.get("/organization/spend_limit",rd(e,t=>({...t,__security:{adminAPIKeyAuth:!0}})))}update(e,t){return this._client.post("/organization/spend_limit",rd(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}delete(e){return this._client.delete("/organization/spend_limit",rd(e,t=>({...t,__security:{adminAPIKeyAuth:!0}})))}};function nt(r,e){return Promise.resolve(r).then(e)}var _s=class extends m{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}completions(e,t){return this._client.get("/organization/usage/completions",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}costs(e,t){return this._client.get("/organization/costs",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}decisions(e,t){return this._client.get("/organization/usage/decisions",nt(t,n=>({query:Object.fromEntries(Object.entries(e).filter(([,s])=>s!==null)),...n,__security:{adminAPIKeyAuth:!0}})))}embeddings(e,t){return this._client.get("/organization/usage/embeddings",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}images(e,t){return this._client.get("/organization/usage/images",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}moderations(e,t){return this._client.get("/organization/usage/moderations",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",nt(t,n=>({query:e,...n,__security:{adminAPIKeyAuth:!0}})))}};function qu(r,e){return Promise.resolve(r).then(e)}var Up=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Lb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Up.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Up.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ys=class extends m{create(e,t,n){return this._client.post(l`/organization/groups/${e}/roles`,qu(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(l`/organization/groups/${s}/roles/${e}`,qu(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=Lb(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/groups/${e}/roles`,ie,qu(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{group_id:s}=t;return this._client.delete(l`/organization/groups/${s}/roles/${e}`,qu(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function $u(r,e){return Promise.resolve(r).then(e)}var Qp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Kb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Qp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Qp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var gs=class extends m{create(e,t,n){return this._client.post(l`/organization/groups/${e}/users`,$u(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{group_id:s}=t;return this._client.get(l`/organization/groups/${s}/users/${e}`,$u(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=Kb(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/groups/${e}/users`,ie,$u(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{group_id:s}=t;return this._client.delete(l`/organization/groups/${s}/users/${e}`,$u(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function Ji(r,e){return Promise.resolve(r).then(e)}var Hp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Wb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Hp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Hp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var yr=class extends m{constructor(){super(...arguments),this.users=new gs(this._client),this.roles=new ys(this._client)}create(e,t){return this._client.post("/organization/groups",Ji(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/groups/${e}`,Ji(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/groups/${e}`,Ji(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Wb(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/groups",ie,Ji(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/groups/${e}`,Ji(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};yr.Users=gs;yr.Roles=ys;function Du(r,e){return Promise.resolve(r).then(e)}var Xp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Qb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Xp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Xp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var bs=class extends m{retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/api_keys/${e}`,Du(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/organization/projects/${s}/api_keys/${e}`,Du(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=Qb(t,["after","limit","owner_project_access"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/api_keys`,Q,Du(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/api_keys/${e}`,Du(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function nd(r,e){return Promise.resolve(r).then(e)}var Jp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Xb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Jp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Jp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ws=class extends m{list(e,t={},n){let s=Xb(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/certificates`,Q,nd(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}activate(e,t,n){return this._client.getAPIList(l`/organization/projects/${e}/certificates/activate`,be,nd(n,s=>({body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})))}deactivate(e,t,n){return this._client.getAPIList(l`/organization/projects/${e}/certificates/deactivate`,be,nd(n,s=>({body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})))}};function Vp(r,e){return Promise.resolve(r).then(e)}var As=class extends m{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/data_retention`,Vp(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/projects/${e}/data_retention`,Vp(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}};function Gp(r,e){return Promise.resolve(r).then(e)}var Rs=class extends m{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/hosted_tool_permissions`,Gp(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/projects/${e}/hosted_tool_permissions`,Gp(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}};function sd(r,e){return Promise.resolve(r).then(e)}var Os=class extends m{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/model_permissions`,sd(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/projects/${e}/model_permissions`,sd(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/projects/${e}/model_permissions`,sd(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function Yp(r,e){return Promise.resolve(r).then(e)}var Zp=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Zb(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Zp.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Zp.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Ps=class extends m{listRateLimits(e,t={},n){let s=Zb(t,["after","before","limit"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/rate_limits`,Q,Yp(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}updateRateLimit(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/organization/projects/${s}/rate_limits/${e}`,Yp(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}};function Vi(r,e){return Promise.resolve(r).then(e)}var eh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function tw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>eh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!eh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var xs=class extends m{create(e,t,n){return this._client.post(l`/projects/${e}/roles`,Vi(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/projects/${s}/roles/${e}`,Vi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/projects/${s}/roles/${e}`,Vi(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=tw(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/projects/${e}/roles`,ie,Vi(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/projects/${s}/roles/${e}`,Vi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function th(r,e){return Promise.resolve(r).then(e)}var vs=class extends m{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/service_tier_settings`,th(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/projects/${e}/service_tier_settings`,th(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}};function Gi(r,e){return Promise.resolve(r).then(e)}var rh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function sw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>rh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!rh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Is=class extends m{create(e,t,n){return this._client.post(l`/organization/projects/${e}/spend_alerts`,Gi(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/spend_alerts/${e}`,Gi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/organization/projects/${s}/spend_alerts/${e}`,Gi(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=sw(t,["after","before","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/spend_alerts`,Q,Gi(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/spend_alerts/${e}`,Gi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function od(r,e){return Promise.resolve(r).then(e)}var Ss=class extends m{retrieve(e,t){return this._client.get(l`/organization/projects/${e}/spend_limit`,od(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/projects/${e}/spend_limit`,od(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/projects/${e}/spend_limit`,od(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};function Fu(r,e){return Promise.resolve(r).then(e)}var Es=class extends m{create(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/projects/${s}/groups/${e}/roles`,Fu(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:s,group_id:i}=t;return this._client.get(l`/projects/${s}/groups/${i}/roles/${e}`,Fu(n,o=>({...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t,n){let{project_id:s,...i}=t;return this._client.getAPIList(l`/projects/${s}/groups/${e}/roles`,ie,Fu(n,o=>({query:i,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s,group_id:i}=t;return this._client.delete(l`/projects/${s}/groups/${i}/roles/${e}`,Fu(n,o=>({...o,__security:{adminAPIKeyAuth:!0}})))}};function zu(r,e){return Promise.resolve(r).then(e)}var nh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function uw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>nh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!nh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var nn=class extends m{constructor(){super(...arguments),this.roles=new Es(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/groups`,zu(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:s,...i}=t;return this._client.get(l`/organization/projects/${s}/groups/${e}`,zu(n,o=>({query:i,...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=uw(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/groups`,ie,zu(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/groups/${e}`,zu(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};nn.Roles=Es;function lw(r,e){return Promise.resolve(r).then(e)}var Cs=class extends m{create(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/organization/projects/${s}/service_accounts/${e}/api_keys`,lw(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}};function Yi(r,e){return Promise.resolve(r).then(e)}var sh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function fw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>sh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!sh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var sn=class extends m{constructor(){super(...arguments),this.apiKeys=new Cs(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/service_accounts`,Yi(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/service_accounts/${e}`,Yi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/organization/projects/${s}/service_accounts/${e}`,Yi(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=fw(t,["after","limit"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/service_accounts`,Q,Yi(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/service_accounts/${e}`,Yi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};sn.APIKeys=Cs;function Mu(r,e){return Promise.resolve(r).then(e)}var Ts=class extends m{create(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/projects/${s}/users/${e}/roles`,Mu(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:s,user_id:i}=t;return this._client.get(l`/projects/${s}/users/${i}/roles/${e}`,Mu(n,o=>({...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t,n){let{project_id:s,...i}=t;return this._client.getAPIList(l`/projects/${s}/users/${e}/roles`,ie,Mu(n,o=>({query:i,...o,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s,user_id:i}=t;return this._client.delete(l`/projects/${s}/users/${i}/roles/${e}`,Mu(n,o=>({...o,__security:{adminAPIKeyAuth:!0}})))}};function Zi(r,e){return Promise.resolve(r).then(e)}var oh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function mw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>oh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!oh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var on=class extends m{constructor(){super(...arguments),this.roles=new Ts(this._client)}create(e,t,n){return this._client.post(l`/organization/projects/${e}/users`,Zi(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{project_id:s}=t;return this._client.get(l`/organization/projects/${s}/users/${e}`,Zi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{project_id:s,...i}=t;return this._client.post(l`/organization/projects/${s}/users/${e}`,Zi(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=mw(t,["after","limit"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/projects/${e}/users`,Q,Zi(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{project_id:s}=t;return this._client.delete(l`/organization/projects/${s}/users/${e}`,Zi(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};on.Roles=Ts;function ea(r,e){return Promise.resolve(r).then(e)}var ih=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function yw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>ih.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!ih.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var me=class extends m{constructor(){super(...arguments),this.users=new on(this._client),this.serviceAccounts=new sn(this._client),this.apiKeys=new bs(this._client),this.rateLimits=new Ps(this._client),this.modelPermissions=new Os(this._client),this.serviceTierSettings=new vs(this._client),this.hostedToolPermissions=new Rs(this._client),this.groups=new nn(this._client),this.roles=new xs(this._client),this.dataRetention=new As(this._client),this.spendLimit=new Ss(this._client),this.spendAlerts=new Is(this._client),this.certificates=new ws(this._client)}create(e,t){return this._client.post("/organization/projects",ea(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/projects/${e}`,ea(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/projects/${e}`,ea(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=yw(e,["after","include_archived","limit"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/projects",Q,ea(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}archive(e,t){return this._client.post(l`/organization/projects/${e}/archive`,ea(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};me.Users=on;me.ServiceAccounts=sn;me.APIKeys=bs;me.RateLimits=Ps;me.ModelPermissions=Os;me.ServiceTierSettings=vs;me.HostedToolPermissions=Rs;me.Groups=nn;me.Roles=xs;me.DataRetention=As;me.SpendLimit=Ss;me.SpendAlerts=Is;me.Certificates=ws;function Lu(r,e){return Promise.resolve(r).then(e)}var ah=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function bw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>ah.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!ah.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ks=class extends m{create(e,t,n){return this._client.post(l`/organization/users/${e}/roles`,Lu(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{user_id:s}=t;return this._client.get(l`/organization/users/${s}/roles/${e}`,Lu(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=bw(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/users/${e}/roles`,ie,Lu(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{user_id:s}=t;return this._client.delete(l`/organization/users/${s}/roles/${e}`,Lu(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function Bu(r,e){return Promise.resolve(r).then(e)}var uh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Aw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>uh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!uh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var an=class extends m{constructor(){super(...arguments),this.roles=new ks(this._client)}retrieve(e,t){return this._client.get(l`/organization/users/${e}`,Bu(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){return this._client.post(l`/organization/users/${e}`,Bu(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=Aw(e,["after","emails","limit"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/users",Q,Bu(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/users/${e}`,Bu(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};an.Roles=ks;function ta(r,e){return Promise.resolve(r).then(e)}var ch=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Ow(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>ch.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!ch.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var js=class extends m{create(e,t,n){return this._client.post(l`/organization/workload_identity_providers/${e}/federation_rules`,ta(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t,n){let{workload_identity_provider_id:s}=t;return this._client.get(l`/organization/workload_identity_providers/${s}/federation_rules/${e}`,ta(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}update(e,t,n){let{workload_identity_provider_id:s,...i}=t;return this._client.post(l`/organization/workload_identity_providers/${s}/federation_rules/${e}`,ta(n,o=>({body:i,...o,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=Ow(t,["after","limit","order","service_account_id"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/organization/workload_identity_providers/${e}/federation_rules`,I,ta(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{workload_identity_provider_id:s}=t;return this._client.delete(l`/organization/workload_identity_providers/${s}/federation_rules/${e}`,ta(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};function ra(r,e){return Promise.resolve(r).then(e)}var lh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function xw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>lh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!lh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var un=class extends m{constructor(){super(...arguments),this.federationRules=new js(this._client)}create(e,t){return this._client.post("/organization/workload_identity_providers",ra(t,n=>({body:e,...n,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t){return this._client.get(l`/organization/workload_identity_providers/${e}`,ra(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}update(e,t={},n){return this._client.post(l`/organization/workload_identity_providers/${e}`,ra(n,s=>({body:t,...s,__security:{adminAPIKeyAuth:!0}})))}list(e={},t){let n=xw(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/organization/workload_identity_providers",I,ra(t,s=>({query:e,...s,__security:{adminAPIKeyAuth:!0}})))}delete(e,t){return this._client.delete(l`/organization/workload_identity_providers/${e}`,ra(t,n=>({...n,__security:{adminAPIKeyAuth:!0}})))}};un.FederationRules=js;var ce=class extends m{constructor(){super(...arguments),this.auditLogs=new as(this._client),this.adminAPIKeys=new is(this._client),this.usage=new _s(this._client),this.invites=new fs(this._client),this.users=new an(this._client),this.groups=new yr(this._client),this.roles=new ps(this._client),this.dataRetention=new cs(this._client),this.externalKeys=new ls(this._client),this.workloadIdentityProviders=new un(this._client),this.externalStorage=new ds(this._client),this.spendLimit=new ms(this._client),this.spendAlerts=new hs(this._client),this.certificates=new us(this._client),this.projects=new me(this._client)}};ce.AuditLogs=as;ce.AdminAPIKeys=is;ce.Usage=_s;ce.Invites=fs;ce.Users=an;ce.Groups=yr;ce.Roles=ps;ce.DataRetention=cs;ce.ExternalKeys=ls;ce.WorkloadIdentityProviders=un;ce.ExternalStorage=ds;ce.SpendLimit=ms;ce.SpendAlerts=hs;ce.Certificates=us;ce.Projects=me;var gr=class extends m{constructor(){super(...arguments),this.organization=new ce(this._client)}};gr.Organization=ce;function Sw(r,e){return Promise.resolve(r).then(e)}var qs=class extends m{create(e,t){return this._client.post("/audio/speech",Sw(t,n=>({body:e,...n,headers:g([{Accept:"application/octet-stream"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function Cw(r,e){return Promise.resolve(r).then(e)}function Tw(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var $s=class extends m{create(e,t){return this._client.post("/audio/transcriptions",Cw(t,n=>re(Tw((s=>({...s,__metadata:{model:e.model}}))({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}}),{streamFromBody:!0}),this._client)))}};function jw(r,e){return Promise.resolve(r).then(e)}var Ds=class extends m{create(e,t){return this._client.post("/audio/translations",jw(t,n=>re((s=>({...s,__metadata:{model:e.model}}))({body:e,...n,__security:{bearerAuth:!0}}),this._client)))}};function na(r,e){return Promise.resolve(r).then(e)}var dh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function $w(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>dh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!dh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Fs=class extends m{create(e,t){return this._client.post("/audio/voice_consents",na(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(l`/audio/voice_consents/${e}`,na(t,n=>({...n,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/audio/voice_consents/${e}`,na(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}list(e={},t){let n=$w(e,["after","limit"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/audio/voice_consents",I,na(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/audio/voice_consents/${e}`,na(t,n=>({...n,__security:{bearerAuth:!0}})))}};function fh(r,e){return Promise.resolve(r).then(e)}var zs=class extends m{create(e,t){return this._client.post("/audio/voices",fh(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}delete(e,t){return this._client.delete(l`/audio/voices/${e}`,fh(t,n=>({...n,__security:{bearerAuth:!0}})))}};var st=class extends m{constructor(){super(...arguments),this.transcriptions=new $s(this._client),this.translations=new Ds(this._client),this.speech=new qs(this._client),this.voices=new zs(this._client),this.voiceConsents=new Fs(this._client)}};st.Transcriptions=$s;st.Translations=Ds;st.Speech=qs;st.Voices=zs;st.VoiceConsents=Fs;function Ku(r,e){return Promise.resolve(r).then(e)}var ph=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function zw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>ph.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!ph.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var cn=class extends m{create(e,t){return this._client.post("/batches",Ku(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/batches/${e}`,Ku(t,n=>({...n,__security:{bearerAuth:!0}})))}list(e={},t){let n=zw(e,["after","limit"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/batches",I,Ku(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,Ku(t,n=>({...n,__security:{bearerAuth:!0}})))}};function sa(r,e){return Promise.resolve(r).then(e)}var hh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Mw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>hh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!hh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Ms=class extends m{create(e,t){return this._client.post("/assistants",sa(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/assistants/${e}`,sa(t,n=>({...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/assistants/${e}`,sa(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Mw(e,["after","before","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/assistants",I,sa(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/assistants/${e}`,sa(t,n=>({...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}};function id(r,e){return Promise.resolve(r).then(e)}var mh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Bw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>mh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!mh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Ls=class extends m{create(e,t){return this._client.post(l`/agents/automations/${e}/invocations`,id(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{automation_id:s}=t;return this._client.get(l`/agents/automations/${s}/invocations/${e}`,id(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=Bw(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/agents/automations/${e}/invocations`,I,id(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function ln(r,e){return Promise.resolve(r).then(e)}var _h=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Nw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>_h.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!_h.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var dn=class extends m{constructor(){super(...arguments),this.invocations=new Ls(this._client)}create(e,t){return this._client.post("/agents/automations",ln(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/automations/${e}`,ln(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/agents/automations/${e}`,ln(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Nw(e,["after","limit","order","session_id"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/agents/automations",I,ln(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/automations/${e}`,ln(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}pause(e,t){return this._client.post(l`/agents/automations/${e}/pause`,ln(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}resume(e,t){return this._client.post(l`/agents/automations/${e}/resume`,ln(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}};dn.Invocations=Ls;var Nu=class extends f{constructor(e,t){super("Agent file preparation or staging failed; uploaded files remain caller-owned."),this.name="AgentFileUploadError",this.uploadedFiles=e,Object.defineProperty(this,"cause",{value:t,configurable:!0})}};function Uw(r){let e=r.split("/"),t=e[2]??"";if(!r.startsWith("/workspace/")||r.includes("\\")||r.includes("\0")||e.slice(1).some(n=>n===""||n==="."||n==="..")||t===".codex"||t===".managed-agents"||t.startsWith(".managed-agents-")||r==="/workspace/outputs")throw new f("Agent files require a non-reserved absolute file path inside /workspace")}function Qw(r,e){let t=Object.entries(r),n=g([e.headers]);if(t.length>1&&(n.values.has("idempotency-key")||!n.nulls.has("idempotency-key")&&e?.idempotencyKey!==void 0))throw new f("Do not reuse an Idempotency-Key across multiple file uploads");let s={children:new Map};for(let[i]of t){Uw(i);let o=s;for(let a of i.split("/")){if(o.file)throw new f("Agent file destinations conflict");let c=o.children.get(a);c||(c={children:new Map},o.children.set(a,c)),o=c}if(o.children.size>0)throw new f("Agent file destinations conflict");o.file=!0}return t}async function ad(r,e,t){let n={...t},s=g([r._options.defaultHeaders,n.headers]);n.headers=s;let i=Qw(e,n);i.length>1&&s.nulls.add("idempotency-key");let o={files:[],uploadedFiles:[]};try{for(let[a,c]of i){let d=await r.files.create({file:c,purpose:"user_data"},n);o.uploadedFiles.push(d),o.files.push({type:"file_id",file_id:d.id,path:a})}return o}catch(a){throw new Nu(o.uploadedFiles,a)}}async function yh(r,e,t,n,s){let i=await ad(r,{[n.path]:n.file},s),[o]=i.files,[a]=i.uploadedFiles;if(!o||!a)throw new f("Missing prepared agent file");try{return{uploadedFile:a,environmentFile:await e.create(t,o,s)}}catch(c){throw new Nu(i.uploadedFiles,c)}}function gh(r,e){return Promise.resolve(r).then(e)}var Bs=class extends m{create(e,t,n){return this._client.post(l`/agents/environments/${e}/files`,gh(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){return this._client.getAPIList(l`/agents/environments/${e}/files`,Vn,gh(n,s=>({query:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}prepare(e,t){return ad(this._client,e,t)}upload(e,t,n){return yh(this._client,this,e,t,n)}};function oa(r,e){return Promise.resolve(r).then(e)}var bh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Xw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>bh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!bh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Ks=class extends m{create(e={},t){return this._client.post("/agents/environments/templates",oa(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/environments/templates/${e}`,oa(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(l`/agents/environments/templates/${e}`,oa(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Xw(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/agents/environments/templates",I,oa(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/environments/templates/${e}`,oa(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}};function ud(r,e){return Promise.resolve(r).then(e)}var wh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Vw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>wh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!wh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var br=class extends m{constructor(){super(...arguments),this.files=new Bs(this._client),this.templates=new Ks(this._client)}create(e,t){let{"Idempotency-Key":n,...s}=e;return this._client.post("/agents/environments",ud(t,i=>({body:s,...i,headers:g([{"OpenAI-Beta":"agents=v1",...n!=null?{"Idempotency-Key":n}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/environments/${e}`,ud(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Vw(e,["after","limit","order","type"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/agents/environments",cd,ud(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}},cd=class extends I{constructor(e,t,n,s){super(e,t,n,s),this.object=n.object,this.first_id=n.first_id,this.last_id=n.last_id}};br.Files=Bs;br.Templates=Ks;async function*Ah(r){let e;for(;;){let t=await r(e);if(yield*t.data,!t.has_more)return;let n=t.body,s=t.data[t.data.length-1],i=L(n)&&typeof n.last_id=="string"?n.last_id:s?.id;if(!i||i===e)throw new f("Agent pagination cannot advance to the next page");e=i}}var Ns,fn,Wu,Uu=class{constructor(e,t){Ns.set(this,void 0),fn.set(this,void 0),Wu.set(this,void 0),w(this,Ns,e,"f"),w(this,fn,t.session_id,"f"),w(this,Wu,t.turn_id,"f")}async retrieve(e,t){let n;for await(let s of Ah(i=>u(this,Ns,"f").list(u(this,fn,"f"),{},{...t,query:{...t?.query,after:i,environment_id:void 0}})))if(s.session_id===u(this,fn,"f")&&s.turn_id===u(this,Wu,"f")&&s.path===e){if(n)throw new f("Multiple artifacts match this result and path");n=s}if(!n)throw new f("No artifact matches this result and path");return n}async content(e,t){let n=await this.retrieve(e,t);return u(this,Ns,"f").content(n.id,{session_id:u(this,fn,"f")},t)}async download(e,t){let{path:n,to:s}=e,i=await this.retrieve(n,t),o=await u(this,Ns,"f").content(i.id,{session_id:u(this,fn,"f")},t);if(!o.body)throw new f("Artifact response has no content stream");try{await o.body.pipeTo(s,t?.signal?{signal:t.signal}:{})}catch(a){try{await o.body.cancel()}catch{}throw a}return i}};Ns=new WeakMap,fn=new WeakMap,Wu=new WeakMap;function Qu(r,e){return Promise.resolve(r).then(e)}var Rh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Yw(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Rh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Rh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Ws=class extends m{retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/artifacts/${e}`,Qu(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=Yw(t,["after","environment_id","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/artifacts`,I,Qu(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{session_id:s}=t;return this._client.delete(l`/agents/sessions/${s}/artifacts/${e}`,Qu(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}content(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/artifacts/${e}/content`,Qu(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1",Accept:"application/octet-stream"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}forResult(e){return new Uu(this,e)}};function Oh(r,e){return Promise.resolve(r).then(e)}var Us=class extends m{create(e,t,n){let{"Idempotency-Key":s,...i}=t;return this._client.post(l`/agents/sessions/${e}/events`,Oh(n,o=>({body:i,...o,headers:g([{"OpenAI-Beta":"agents=v1",Accept:"*/*",...s!=null?{"Idempotency-Key":s}:void 0},o?.headers]),__security:{bearerAuth:!0}})))}stream(e,t){return this._client.get(l`/agents/sessions/${e}/events`,Oh(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1",Accept:"text/event-stream"},n?.headers]),stream:!0,__streamMode:"events",__security:{bearerAuth:!0}})))}};function tA(r,e){return Promise.resolve(r).then(e)}var Ph=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function rA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Ph.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Ph.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Qs=class extends m{list(e,t={},n){let s=rA(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/items`,I,tA(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function sA(r,e){return Promise.resolve(r).then(e)}var xh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function oA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>xh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!xh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Hs=class extends m{list(e,t={},n){let s=oA(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/traces`,I,sA(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function aA(r,e){return Promise.resolve(r).then(e)}var Xs=class extends m{list(e,t,n){let{session_id:s,...i}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${e}/items`,I,aA(n,o=>({query:i,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}};function cA(r,e){return Promise.resolve(r).then(e)}var Js=class extends m{list(e,t,n){let{session_id:s,subagent_id:i,...o}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${i}/turns/${e}/items`,I,cA(n,a=>({query:o,...a,headers:g([{"OpenAI-Beta":"agents=v1"},a?.headers]),__security:{bearerAuth:!0}})))}};function vh(r,e){return Promise.resolve(r).then(e)}var pn=class extends m{constructor(){super(...arguments),this.items=new Js(this._client)}retrieve(e,t,n){let{session_id:s,subagent_id:i}=t;return this._client.get(l`/agents/sessions/${s}/subagents/${i}/turns/${e}`,vh(n,o=>({...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e,t,n){let{session_id:s,...i}=t;return this._client.getAPIList(l`/agents/sessions/${s}/subagents/${e}/turns`,I,vh(n,o=>({query:i,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}};pn.Items=Js;function Ih(r,e){return Promise.resolve(r).then(e)}var Sh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function fA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Sh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Sh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var wr=class extends m{constructor(){super(...arguments),this.items=new Xs(this._client),this.turns=new pn(this._client)}retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/subagents/${e}`,Ih(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=fA(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/subagents`,I,Ih(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};wr.Items=Xs;wr.Turns=pn;function hA(r,e){return Promise.resolve(r).then(e)}var Vs=class extends m{list(e,t,n){let{session_id:s,...i}=t;return this._client.getAPIList(l`/agents/sessions/${s}/turns/${e}/items`,Q,hA(n,o=>({query:i,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}};function Eh(r,e){return Promise.resolve(r).then(e)}var Ch=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function _A(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Ch.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Ch.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var hn=class extends m{constructor(){super(...arguments),this.items=new Vs(this._client)}retrieve(e,t,n){let{session_id:s}=t;return this._client.get(l`/agents/sessions/${s}/turns/${e}`,Eh(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=_A(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/agents/sessions/${e}/turns`,I,Eh(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};hn.Items=Vs;var Gs,Hu,mn,Xu,Ys=class{constructor(){Gs.set(this,void 0),Hu.set(this,!1),mn.set(this,new Set),Xu.set(this,new Set)}accept(e){if(u(this,mn,"f").has(e.event_id))return!1;if(u(this,mn,"f").size===1024){let t=u(this,mn,"f").values().next();t.done||u(this,mn,"f").delete(t.value)}return u(this,mn,"f").add(e.event_id),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&u(this,Gs,"f")===void 0&&w(this,Gs,e.turn_id,"f"),(e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled")&&u(this,Gs,"f")!==void 0&&e.turn_id===u(this,Gs,"f")&&w(this,Hu,!0,"f"),!0}terminal(e){return e.type==="agent.session.failed"||e.type==="agent.session.idle"&&u(this,Hu,"f")}call(e){if(e.type!=="agent.session.turn.item.added"||e.item.type!=="function_call")return;let t=e.item,n=JSON.stringify([t.turn_id,t.call_id]);if(!u(this,Xu,"f").has(n))return u(this,Xu,"f").add(n),t}};Gs=new WeakMap,Hu=new WeakMap,mn=new WeakMap,Xu=new WeakMap;function Th(r){if(!L(r))return!1;let e=r,t;if(e.type==="input_text")t="text";else if(e.type==="input_image")t="image_url";else return!1;return P(e,"type")&&P(e,t)&&typeof e[t]=="string"}var kh=Symbol.for("openai.beta.agents.toolStages");var xe,ia,Vu,Gu,_n,Zs,jh,yn,ld,Ju,qh;function gA(r){if(r===null)return null;if(typeof r=="string"||Array.isArray(r)&&r.every(Th))return r;throw new f("Tool output must be text, content, a JSON object, or null")}function bA(r,e){let t=L(e)?JSON.stringify(e):e,n=JSON.stringify(t);if(n===void 0)throw new f("Tool output must be JSON serializable");return{type:"agent.session.input.tool_result",turn_id:r.turn_id,call_id:r.call_id,success:!0,output:gA(typeof t=="string"?t:JSON.parse(n))}}var eo=class{constructor(e,t,n,s,i){xe.add(this),ia.set(this,void 0),Vu.set(this,void 0),Gu.set(this,void 0),_n.set(this,void 0),Zs.set(this,void 0),w(this,Gu,e,"f"),w(this,_n,n,"f"),w(this,Zs,i,"f"),w(this,ia,new Map(Object.entries(t)),"f");let o=g([s?.headers]);o.values.delete("idempotency-key"),o.nulls.delete("idempotency-key");let{idempotencyKey:a,...c}=s??{};w(this,Vu,{...c,headers:o,signal:n.signal},"f")}canHandle(e){return typeof u(this,ia,"f").get(e)=="function"}prepare(e,t){let n=e&&u(this,ia,"f").get(e.name);if(!e||typeof n!="function")return;if(!t)throw new f("Tool call received before the session creation event");let s=structuredClone(e);return async()=>{u(this,xe,"m",yn).call(this);let i=await u(this,xe,"m",jh).call(this,s,n,t);u(this,xe,"m",yn).call(this),await u(this,xe,"m",qh).call(this,t,i)}}};ia=new WeakMap,Vu=new WeakMap,Gu=new WeakMap,_n=new WeakMap,Zs=new WeakMap,xe=new WeakSet,jh=async function(e,t,n){let s="arguments";try{let i=typeof e.arguments=="string"?JSON.parse(e.arguments):e.arguments;if(!L(i))throw new f("Function arguments must be a JSON object");s="execution";let o=i,a=await u(this,xe,"m",Ju).call(this,()=>u(this,Zs,"f")&&t[kh]?t(o,c=>{s=c}):t(o));return s="output",bA(e,a)}catch(i){if(u(this,xe,"m",yn).call(this),u(this,Zs,"f")){let o=Object.freeze({error:i,stage:s,tool_name:e.name,session_id:n,turn_id:e.turn_id,call_id:e.call_id});try{await u(this,xe,"m",Ju).call(this,()=>u(this,Zs,"f")?.call(this,o))}catch{u(this,xe,"m",yn).call(this)}}return{type:"agent.session.input.tool_result",turn_id:e.turn_id,call_id:e.call_id,success:!1,error:"Tool handler failed."}}},yn=function(){if(u(this,_n,"f").signal.aborted)throw u(this,xe,"m",ld).call(this)},ld=function(){let e=new Y;return Object.defineProperty(e,"cause",{value:u(this,_n,"f").signal.reason,writable:!0,configurable:!0}),e},Ju=async function(e){let t,n=new Promise((s,i)=>{t=()=>i(u(this,xe,"m",ld).call(this)),u(this,_n,"f").signal.addEventListener("abort",t,{once:!0})});try{u(this,xe,"m",yn).call(this);let s=async()=>await e();return await Promise.race([s(),n])}finally{t&&u(this,_n,"f").signal.removeEventListener("abort",t)}},qh=async function r(e,t,n=De(),s=0){u(this,xe,"m",yn).call(this);try{await u(this,Gu,"f").events.create(e,{events:[t],"Idempotency-Key":n},u(this,Vu,"f"))}catch(i){let o=[100,300,600][s];if(o===void 0||!(i instanceof bt)||i.code!=="invalid_request_error"||!i.error||!("message"in i.error)||i.error.message!==`Unknown pending tool call: ${t.call_id}`)throw i;let a;try{await u(this,xe,"m",Ju).call(this,()=>new Promise(c=>{a=setTimeout(c,o)}))}finally{a!==void 0&&clearTimeout(a)}await u(this,xe,"m",r).call(this,e,t,n,s+1)}};function $h(r){return r.content.map(e=>e.type==="output_text"?e.text:"").join("")}var to=class{constructor(e,t){this.turn=e,this.messages=t}get session_id(){return this.turn.session_id}get turn_id(){return this.turn.id}get output_text(){return this.messages.map($h).join("")}};var Yu=class extends to{constructor(e,t){super(e.turn,e.messages),this.raw_result=e,this.output_parsed=t}};var Zu,aa=class extends f{constructor(e){super("The completed agent output could not be parsed"),this.name="AgentOutputParseError",Zu.set(this,void 0),w(this,Zu,e,"f")}get raw_result(){return u(this,Zu,"f")}};Zu=new WeakMap;function wA(r,e){try{if(!e)return r;let t;for(let n of r.messages)for(let s of n.content)if(s.type==="output_text"){let i=e.$parseRaw(s.text);t??(t={value:i})}if(!t)throw new aa(r);return new Yu(r,t.value)}catch{throw new aa(r)}}function ro(r,e){let t=r&&Object.getOwnPropertyDescriptor(r,e);return t?.enumerable&&"value"in t?t.value:void 0}function fd(r){if(!r)return;let e=Object.getOwnPropertyDescriptor(r,"$parseRaw");if(!e||!("value"in e)||typeof e.value!="function")return;let t=ro(r,"schema");if(ro(r,"type")!=="json_schema"||!t)throw new f("Typed agent formats require own enumerable type and schema data properties");let n=e.value;return{type:"json_schema",schema:t,$parseRaw:s=>n.call(r,s)}}function dd(r,e,t=n=>n){let n=Object.getOwnPropertyDescriptor(r,e);if(!n?.enumerable)return r;let s=t(r[e]);return"value"in n&&s===n.value?r:Object.create(Object.getPrototypeOf(r),{...Object.getOwnPropertyDescriptors(r),[e]:{value:s,enumerable:!0,configurable:n.configurable,writable:!0}})}function Dh(r,e){let t=dd(r,"agent",c=>c&&dd(c,"text",d=>d&&dd(d,"format"))),n=ro(t,"agent"),s=ro(n,"text"),i=fd(ro(s,"format"));if(!i)return{body:t,options:e};let o=structuredClone(i.schema);for(let c of[t,n,s])if(c&&"toJSON"in c)throw new f("Typed agent requests cannot customize body, agent, or text serialization");let a={...e};if(ro(a,"body")!==void 0)throw new f("Typed agent requests cannot override the body in request options");return delete a.body,{options:a,body:{...t,agent:{...n,text:{...s,format:{type:"json_schema",schema:o}}}},format:i}}async function ec(r,e){return wA(await r,e)}var no=class extends f{constructor(e,t,n,s,i=[],o){super(`Could not collect the agent turn result: ${e}`),this.name="AgentTurnResultError",this.reason=e,this.session_id=t,this.turn=n,this.messages=s,this.required_actions=i,this.cause=o}get turn_id(){return this.turn?.id}};var ao,gn,ot,uo,so,oo,ua,bn,io,zh,Fh,pd,tc=class{constructor(e){ao.add(this),gn.set(this,void 0),ot.set(this,void 0),uo.set(this,new Map),so.set(this,[]),oo.set(this,void 0),ua.set(this,!1),bn.set(this,!1),io.set(this,!1),w(this,gn,e,"f")}accept(e){if(this.ready)return;"session"in e&&(w(this,gn,u(this,gn,"f")??e.session.id,"f"),w(this,so,structuredClone(e.session.required_actions??[]),"f"),w(this,oo,void 0,"f"),w(this,ua,u(this,ua,"f")||e.type==="agent.session.failed","f"),w(this,io,u(this,io,"f")||e.type==="agent.session.idle"&&u(this,bn,"f"),"f")),e.type==="agent.session.turn.created"&&e.turn.subagent_id===null&&!u(this,ot,"f")&&(w(this,ot,structuredClone(e.turn),"f"),w(this,gn,e.turn.session_id,"f"));let t="turn_id"in e?e.turn_id:void 0;"item"in e&&(t=e.item.turn_id),!(!u(this,ot,"f")||t!==u(this,ot,"f").id)&&u(this,ao,"m",zh).call(this,e)}error(e,t){return new no(e,u(this,gn,"f"),u(this,ot,"f"),u(this,ao,"m",pd).call(this),u(this,so,"f"),t)}checkAction(e){if(u(this,ua,"f")||u(this,ot,"f")?.status==="failed")throw this.error("failed");if(u(this,ot,"f")?.status==="cancelled")throw this.error("cancelled");if(u(this,oo,"f")!==e){if(u(this,so,"f").some(t=>t.type!=="function_call"||!e(t.name)))throw this.error("requires_action");w(this,oo,e,"f")}}get ready(){return u(this,bn,"f")&&u(this,io,"f")}release(){u(this,uo,"f").clear(),w(this,so,[],"f"),w(this,oo,void 0,"f")}finish(){if(this.checkAction(()=>this.ready),!u(this,bn,"f")||u(this,ot,"f")?.status!=="completed"||!u(this,io,"f"))throw this.error("observation");return new to(u(this,ot,"f"),u(this,ao,"m",pd).call(this))}};gn=new WeakMap,ot=new WeakMap,uo=new WeakMap,so=new WeakMap,oo=new WeakMap,ua=new WeakMap,bn=new WeakMap,io=new WeakMap,ao=new WeakSet,zh=function(e){"turn"in e&&(w(this,ot,structuredClone(e.turn),"f"),w(this,bn,u(this,bn,"f")||e.type==="agent.session.turn.completed"||e.type==="agent.session.turn.failed"||e.type==="agent.session.turn.cancelled","f")),u(this,ao,"m",Fh).call(this,e)},Fh=function(e){e.type!=="agent.session.turn.item.done"||e.item.type!=="message"||e.item.status!=="completed"||e.item.phase==="commentary"||u(this,uo,"f").has(e.item.id)||u(this,uo,"f").set(e.item.id,{index:e.output_index,message:structuredClone(e.item)})},pd=function(){return[...u(this,uo,"f").values()].sort((e,t)=>e.index-t.index).map(({message:e})=>e)};var rc,co,nc,lo,oc,ca,sc,ic,la,ac,Mh,Lh,fo=class{constructor(e,t=()=>!1,n,s){rc.add(this),co.set(this,void 0),nc.set(this,!1),lo.set(this,!1),oc.set(this,!1),ca.set(this,void 0),sc.set(this,void 0),ic.set(this,void 0),la.set(this,void 0),ac.set(this,void 0),w(this,ic,e,"f"),w(this,la,s,"f"),w(this,ac,t,"f"),this.collector=new tc(n)}enable(){if(!u(this,lo,"f")&&u(this,oc,"f"))throw new f("Call withResultCollection() before consuming events, or call finalResult() on a fresh stream.");w(this,lo,!0,"f")}iterate(){if(u(this,co,"f"))throw new f("An agent result stream can only be consumed once");return w(this,co,u(this,rc,"m",Mh).call(this),"f")}finalResult(){return w(this,sc,u(this,sc,"f")??u(this,rc,"m",Lh).call(this),"f")}};co=new WeakMap,nc=new WeakMap,lo=new WeakMap,oc=new WeakMap,ca=new WeakMap,sc=new WeakMap,ic=new WeakMap,la=new WeakMap,ac=new WeakMap,rc=new WeakSet,Mh=async function*(){let e=u(this,ic,"f").call(this),t=!1;try{for(;;){let n=await e.next();if(n.done){t=!0;return}u(this,lo,"f")?this.collector.accept(n.value):w(this,oc,!0,"f"),yield n.value}}catch(n){throw u(this,lo,"f")&&w(this,ca,n,"f"),n}finally{w(this,nc,!0,"f"),t||await e.return?.()}},Lh=async function(){this.enable();try{let e=u(this,co,"f")??this.iterate();for(;!u(this,nc,"f")&&!this.collector.ready&&(this.collector.checkAction(u(this,ac,"f")),!(await e.next()).done););if(u(this,ca,"f")!==void 0&&!this.collector.ready)throw u(this,ca,"f");if(!this.collector.ready&&u(this,la,"f")?.aborted)throw this.collector.error("observation",u(this,la,"f").reason);return this.collector.finish()}catch(e){throw e instanceof no?e:this.collector.error("observation",e)}finally{try{await u(this,co,"f")?.return()}finally{this.collector.release()}}};var It,uc,da,cc,po,mo,lc,dc,_o,An,fc,fa,yo,ho,Kh,wn,Bh;async function AA(r){try{await r?.body?.cancel()}catch{}}var pc=class{constructor(e,t,n,s){It.add(this),this.controller=new AbortController,uc.set(this,!1),da.set(this,void 0),cc.set(this,void 0),po.set(this,void 0),mo.set(this,void 0),lc.set(this,void 0),dc.set(this,!1),_o.set(this,void 0),An.set(this,void 0),fc.set(this,void 0),fa.set(this,void 0),yo.set(this,void 0),ho.set(this,void 0);let i=typeof n.input=="string"?[{role:"user",content:[{type:"input_text",text:n.input}]}]:n.input;if(n.input.length===0)throw new f("input must not be empty");if(w(this,da,fd(n.outputFormat),"f"),n.outputFormat&&!u(this,da,"f"))throw new f("outputFormat must have its own parser function");w(this,_o,e,"f"),w(this,An,t,"f"),w(this,fc,{type:"agent.session.input.message",input:i},"f");let o=g([s?.headers]);w(this,yo,o.nulls.has("idempotency-key")?void 0:o.values.get("idempotency-key")??n.idempotencyKey??s?.idempotencyKey??De(),"f"),o.values.delete("idempotency-key"),o.nulls.delete("idempotency-key");let{idempotencyKey:a,...c}=s??{};w(this,ho,{...c,headers:o},"f"),w(this,fa,new eo(e,n.toolHandlers??{},this.controller,u(this,ho,"f"),n.onToolError),"f"),w(this,po,new fo(()=>u(this,It,"m",Kh).call(this),d=>u(this,fa,"f").canHandle(d),t),"f")}abort(e){this.controller.abort(e),u(this,mo,"f")?.controller.abort(this.controller.signal.reason),u(this,dc,"f")||AA(u(this,lc,"f"))}[(uc=new WeakMap,da=new WeakMap,cc=new WeakMap,po=new WeakMap,mo=new WeakMap,lc=new WeakMap,dc=new WeakMap,_o=new WeakMap,An=new WeakMap,fc=new WeakMap,fa=new WeakMap,yo=new WeakMap,ho=new WeakMap,It=new WeakSet,Symbol.asyncIterator)](){if(u(this,uc,"f"))throw new f("An AgentSessionStream can only be consumed once");return w(this,uc,!0,"f"),u(this,po,"f").iterate()}withResultCollection(){return u(this,po,"f").enable(),this}finalResult(){return w(this,cc,u(this,cc,"f")??ec(u(this,po,"f").finalResult(),u(this,da,"f")),"f")}};Kh=async function*(){let e=u(this,ho,"f").signal,t=()=>this.abort(e?.aborted?e.reason:this.controller.signal.reason);e?.addEventListener("abort",t,{once:!0}),this.controller.signal.addEventListener("abort",t,{once:!0});let n={...u(this,ho,"f"),signal:this.controller.signal},s=new Ys;try{if(e?.aborted&&this.abort(e.reason),u(this,It,"m",wn).call(this),(await u(this,_o,"f").retrieve(u(this,An,"f"),n)).status!=="idle")throw new f("sessions.stream requires an idle session; use sessions.events.stream for active sessions");let o=await u(this,_o,"f").events.stream(u(this,An,"f"),n).withResponse();w(this,mo,o.data,"f"),w(this,lc,o.response,"f"),u(this,It,"m",wn).call(this),await u(this,_o,"f").events.create(u(this,An,"f"),{events:[u(this,fc,"f")],...u(this,yo,"f")===void 0?{}:{"Idempotency-Key":u(this,yo,"f")}},{...n,headers:g([n.headers,{"Idempotency-Key":u(this,yo,"f")??null}])}),u(this,It,"m",wn).call(this),w(this,dc,!0,"f");for await(let a of u(this,mo,"f")){if(u(this,It,"m",wn).call(this),!s.accept(a))continue;let c=s.terminal(a),d=u(this,fa,"f").prepare(s.call(a),u(this,An,"f"));if(c&&u(this,mo,"f").controller.abort(),yield a,c)return;u(this,It,"m",wn).call(this),await d?.()}throw u(this,It,"m",wn).call(this),new f("Session event stream ended before the turn reached idle or failed")}finally{e?.removeEventListener("abort",t),this.controller.signal.removeEventListener("abort",t),this.abort()}},wn=function(){if(this.controller.signal.aborted)throw u(this,It,"m",Bh).call(this)},Bh=function(){let e=new Y;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e};async function*RA(r,e,t){let n=new Ys,s;for await(let i of{[Symbol.asyncIterator]:r}){i.type==="agent.session.created"&&(s??(s=i.session.id));let o=n.accept(i)?e.prepare(n.call(i),s):void 0;if(yield i,t.aborted)return;try{await o?.()}catch(a){if(t.aborted&&a instanceof Y)return;throw a}}}function Nh(r,e,t){let n;r.__betaTransformIterator(o=>{let{path:a,method:c,stream:d,...p}=t?.options??{},y=t&&new eo(t.sessions,t.handlers,r.controller,p);return n=new fo(y?()=>RA(o,y,r.controller.signal):o,y?_=>y.canHandle(_):void 0,void 0,r.controller.signal),()=>n.iterate()});let s,i=Object.assign(r,{finalResult:()=>s??(s=ec(n.finalResult(),e)),withResultCollection:()=>(n.enable(),i)});return i}function Wh(r,e){let t=Object.getOwnPropertyDescriptor(r,"toolHandlers");if(!t)return{body:r,options:e};let n=r.toolHandlers;if(n===void 0&&"value"in t)return{body:r,options:e};let s=Object.getOwnPropertyDescriptors(r);delete s.toolHandlers;let i={...e};if("toJSON"in r||i.body!==void 0)throw new f("Creation tool handlers cannot customize request body serialization");if(n===void 0)return{body:Object.create(Object.getPrototypeOf(r),s),options:i};let{stream:o}=r;if(o!==!0)throw new f("toolHandlers requires stream: true");return i.headers=g([i.headers]),s.stream={value:o,enumerable:!0,configurable:!0,writable:!0},{body:Object.create(Object.getPrototypeOf(r),s),options:i,handlers:n&&Object.fromEntries(Object.entries(n))}}function pa(r,e){return Promise.resolve(r).then(e)}function OA(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var Uh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function PA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Uh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Uh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var it=class extends m{constructor(){super(...arguments),this.subagents=new wr(this._client),this.artifacts=new Ws(this._client),this.items=new Qs(this._client),this.events=new Us(this._client),this.traces=new Hs(this._client),this.turns=new hn(this._client)}create(e,t){let n=Wh(e,t),s=Dh(n.body,n.options);return((o,a)=>this._client.post("/agents/sessions",pa(a,c=>OA({body:o,...c,headers:g([{"OpenAI-Beta":"agents=v1"},c?.headers]),stream:o.stream??!1,__streamMode:"events",__security:{bearerAuth:!0}},{streamFromBody:!0}))))(s.body,s.options)._thenUnwrap((o,{options:a})=>a.stream?Nh(o,s.format,n.handlers?{sessions:this,handlers:n.handlers,options:s.options}:void 0):o)}retrieve(e,t){return this._client.get(l`/agents/sessions/${e}`,pa(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(l`/agents/sessions/${e}`,pa(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=PA(e,["after","agent_id","limit","metadata","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/agents/sessions",I,pa(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/sessions/${e}`,pa(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}stream(e,t,n){return new pc(this,e,t,n)}};it.Subagents=wr;it.Artifacts=Ws;it.Items=Qs;it.Events=Us;it.Traces=Hs;it.Turns=hn;function ha(r,e){return Promise.resolve(r).then(e)}var Qh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function vA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Qh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Qh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var go=class extends m{create(e,t,n){return this._client.post(l`/vaults/${e}/credentials`,ha(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{vault_id:s}=t;return this._client.get(l`/vaults/${s}/credentials/${e}`,ha(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{vault_id:s,...i}=t;return this._client.post(l`/vaults/${s}/credentials/${e}`,ha(n,o=>({body:i,...o,headers:g([{"OpenAI-Beta":"agents=v1"},o?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=vA(t,["after","limit","metadata","order","status"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/vaults/${e}/credentials`,I,ha(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{vault_id:s}=t;return this._client.delete(l`/vaults/${s}/credentials/${e}`,ha(n,i=>({...i,headers:g([{"OpenAI-Beta":"agents=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};function ma(r,e){return Promise.resolve(r).then(e)}var Hh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function SA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Hh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Hh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Rn=class extends m{constructor(){super(...arguments),this.credentials=new go(this._client)}create(e={},t){return this._client.post("/vaults",ma(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/vaults/${e}`,ma(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/vaults/${e}`,ma(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=SA(e,["after","limit","metadata","order","status"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/vaults",I,ma(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/vaults/${e}`,ma(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}};Rn.Credentials=go;function _a(r,e){return Promise.resolve(r).then(e)}var Xh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function CA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Xh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Xh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var St=class extends m{constructor(){super(...arguments),this.automations=new dn(this._client),this.environments=new br(this._client),this.vaults=new Rn(this._client),this.sessions=new it(this._client)}create(e,t){return this._client.post("/agents",_a(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/agents/${e}`,_a(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(l`/agents/${e}`,_a(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=CA(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/agents",I,_a(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"agents=v1"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/agents/${e}`,_a(t,n=>({...n,headers:g([{"OpenAI-Beta":"agents=v1"},n?.headers]),__security:{bearerAuth:!0}})))}};St.Automations=dn;St.Environments=br;St.Vaults=Rn;St.Sessions=it;function Jh(r,e){return Promise.resolve(r).then(e)}var bo=class extends m{create(e,t){return this._client.post("/chatkit/sessions",Jh(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,Jh(t,n=>({...n,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})))}};function hc(r,e){return Promise.resolve(r).then(e)}var Vh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Gh(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Vh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Vh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var wo=class extends m{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,hc(t,n=>({...n,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=Gh(e,["after","before","limit","order","user"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/chatkit/threads",Q,hc(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,hc(t,n=>({...n,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers]),__security:{bearerAuth:!0}})))}listItems(e,t={},n){let s=Gh(t,["after","before","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/chatkit/threads/${e}/items`,Q,hc(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},i?.headers]),__security:{bearerAuth:!0}})))}};var Ar=class extends m{constructor(){super(...arguments),this.sessions=new bo(this._client),this.threads=new wo(this._client)}};Ar.Sessions=bo;Ar.Threads=wo;function $A(r,e){return Promise.resolve(r).then(e)}var Yh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function DA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Yh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Yh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Ao=class extends m{list(e,t={},n){let s=DA(t,["after","betas","include","limit","order"],n);s!==void 0&&(n=s,t={}),t=t;let{betas:i,...o}=t??{};return this._client.getAPIList(l`/responses/${e}/input_items?beta=true`,I,$A(n,a=>({query:o,...a,headers:g([{...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},a?.headers]),__security:{bearerAuth:!0}})))}};function zA(r,e){return Promise.resolve(r).then(e)}var Ro=class extends m{count(e={},t){let{betas:n,...s}=e??{};return this._client.post("/responses/input_tokens?beta=true",zA(t,i=>({body:s,...i,headers:g([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}};function ya(r,e){return Promise.resolve(r).then(e)}function LA(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var Zh=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function BA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Zh.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Zh.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Rr=class extends m{constructor(){super(...arguments),this.inputItems=new Ao(this._client),this.inputTokens=new Ro(this._client)}create(e,t){let{betas:n,...s}=e;return this._client.post("/responses?beta=true",ya(t,i=>LA({body:s,...i,headers:g([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},i?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}retrieve(e,t={},n){let s=BA(t,["betas","include","include_obfuscation","starting_after","stream"],n);s!==void 0&&(n=s,t={}),t=t;let{betas:i,...o}=t??{};return this._client.get(l`/responses/${e}?beta=true`,ya(n,a=>({query:o,...a,headers:g([{...i?.toString()!=null?{"openai-beta":i?.toString()}:void 0},a?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})))}delete(e,t={},n){let{betas:s}=t??{};return this._client.delete(l`/responses/${e}?beta=true`,ya(n,i=>({...i,headers:g([{Accept:"*/*",...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t={},n){let{betas:s}=t??{};return this._client.post(l`/responses/${e}/cancel?beta=true`,ya(n,i=>({...i,headers:g([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}compact(e,t){let{betas:n,...s}=e;return this._client.post("/responses/compact?beta=true",ya(t,i=>({body:s,...i,headers:g([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},i?.headers]),__security:{bearerAuth:!0}})))}};Rr.InputItems=Ao;Rr.InputTokens=Ro;function ga(r,e){return Promise.resolve(r).then(e)}var em=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function NA(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>em.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!em.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Oo=class extends m{create(e,t,n){return this._client.post(l`/threads/${e}/messages`,ga(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,ga(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{thread_id:s,...i}=t;return this._client.post(l`/threads/${s}/messages/${e}`,ga(n,o=>({body:i,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=NA(t,["after","before","limit","order","run_id"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/threads/${e}/messages`,I,ga(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,ga(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}};function tm(r,e){return Promise.resolve(r).then(e)}var Po=class extends m{retrieve(e,t,n){let{thread_id:s,run_id:i,...o}=t;return this._client.get(l`/threads/${s}/runs/${i}/steps/${e}`,tm(n,a=>({query:o,...a,headers:g([{"OpenAI-Beta":"assistants=v2"},a?.headers]),__security:{bearerAuth:!0}})))}list(e,t,n){let{thread_id:s,...i}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,I,tm(n,o=>({query:i,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}};function QA(r,e){return new Promise((t,n)=>{let s,i,o=!1,a=p=>{try{e.removeEventListener("abort",p)}catch{}},c=()=>{if(s!==void 0&&(clearTimeout(s),s=void 0),i){let p=i;i=void 0,a(p)}},d=()=>{if(!o){o=!0,c();try{let p=new Y;Object.defineProperty(p,"cause",{value:e.reason,writable:!0,configurable:!0}),n(p)}catch(p){n(p)}}};if(e.aborted){d();return}s=setTimeout(()=>{o||(o=!0,c(),t())},r),i=d;try{e.addEventListener("abort",d,{once:!0}),o?a(d):e.aborted&&d()}catch(p){o?a(d):(o=!0,c(),n(p))}})}async function ba(r,e,t,n){let s=g([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:o}=await r(s).withResponse(),{status:a}=i;if(e.includes(a)){let c=5e3,d=n?.pollIntervalMs;if(d||d===0)c=d;else{let y=o.headers.get("openai-poll-after-ms");if(y){let _=Number.parseInt(y);Number.isNaN(_)||(c=_)}}let p=n&&Object.prototype.propertyIsEnumerable.call(n,"signal")?n.signal:void 0;await(p?QA(c,p):Xn(c))}else if(t.includes(a))return i}}function rm(r,e,t,n){return ba(s=>r.retrieve(e,t,{...n,headers:{...n?.headers,...s}}),["queued","in_progress","cancelling"],["requires_action","incomplete","cancelled","completed","failed","expired"],n)}var mc=r=>{if(typeof globalThis.Buffer<"u"){let e=globalThis.Buffer.from(r,"base64");return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}if(typeof atob<"u"){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}throw new f("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},nm=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");if(e.length%Float32Array.BYTES_PER_ELEMENT!==0)throw new RangeError("Invalid base64-encoded float32 array: byte length must be a multiple of 4");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};var _e=r=>{try{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0}catch{return}};var om=1024,HA=65536;function XA(r){switch(r){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 r;default:return"unknown"}}var wa=new WeakMap,Or=new WeakSet;function im(r){return{arrays:new Map,cacheArrays:r,records:new WeakMap}}function am(r){for(let[e,t]of r.arrays)t.cacheable&&!Or.has(e)?wa.set(e,{length:t.length,ownEntryCount:t.ownEntryCount}):wa.delete(e)}function sm(r){return typeof r=="string"||typeof r=="number"}function um(r,e){return e.every(sm)&&r.every(sm)}function JA(r){let e=0;for(let t of Object.keys(r)){let n=Number(t);Number.isSafeInteger(n)&&n>=0&&n<r.length&&String(n)===t&&(e+=1)}return e}function VA(r,e,t){return e?t?.length===r.length?t.ownEntryCount:JA(r):0}function GA(r,e,t){let{index:n}=r;if(e==="array"&&n==null)throw new Error("Expected array delta entry to have an `index` property");if(e==="array"&&typeof n!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(n)||n<0||n>=t+om||n>=HA){let s=typeof n=="number"?n:"unknown";throw new f(`Assistant stream delta contains an invalid ${e} index: ${s}`)}return n}function cm(r,e,t,n,s){let i=n.arrays.get(r);if(!i){let o=n.cacheArrays&&!Or.has(r),a=o?wa.get(r):void 0;i={baselineLength:r.length,cacheable:o,enforceSparseHoleBudget:o,entries:new Map,length:r.length,ownEntryCount:VA(r,o,a)},n.arrays.set(r,i)}for(let o of e){if(!L(o))throw new Error("Expected array delta entry to be an object but got an invalid value");let a=GA(o,t,i.baselineLength),c;i.entries.has(a)?c=i.entries.get(a):P(r,a)?(c=r[a],c==null&&i.entries.set(a,o)):(i.entries.set(a,o),i.ownEntryCount+=1);let d=Math.max(i.length,a+1);if(i.enforceSparseHoleBudget&&d-i.ownEntryCount>om)throw new f(`Assistant stream delta contains an invalid ${t} index: ${a}`);L(c)&&s(c,o,n),i.length=d}}function _c(r,e,t){let n=t.records.get(r);for(let[s,i]of Object.entries(e)){if(s==="index"||s==="type")continue;let o;if(n?.has(s)?o=n.get(s):P(r,s)&&(o=r[s]),o==null){n||(n=new Map,t.records.set(r,n)),n.set(s,i);continue}L(o)&&L(i)?_c(o,i,t):Array.isArray(o)&&Array.isArray(i)&&!um(o,i)&&cm(o,i,"array",t,_c)}}function yc(r){return(L(r)||Array.isArray(r))&&Or.has(r)}function pt(r){if(!(!L(r)&&!Array.isArray(r)||Or.has(r))){Or.add(r),Array.isArray(r)&&wa.delete(r);for(let e of Reflect.ownKeys(r)){let t=Object.getOwnPropertyDescriptor(r,e);t&&"value"in t&&pt(t.value)}}}function md(r,e,t){Or.has(r)&&pt(t),Object.defineProperty(r,e,{configurable:!0,enumerable:!0,value:t,writable:!0})}function YA(r){let{index:e}=r;if(e==null)throw new Error("Expected array delta entry to have an `index` property");if(typeof e!="number")throw new TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return e}function ZA(r,e,t){if(um(r,e)){r.push(...e),wa.delete(r);return}for(let n of e){if(!L(n))throw new Error("Expected array delta entry to be an object but got an invalid value");let s=YA(n);if(P(r,s)){let i=r[s];i==null?(Or.has(r)&&pt(n),r[s]=n):r[s]=t(i,n)}else md(r,s,n)}}function hd(r,e){let t=Or.has(r);for(let[n,s]of Object.entries(e)){if(n==="__proto__"||n==="constructor"||n==="prototype")throw new f(`Assistant stream delta contains an unsafe property: ${n}`);if(!P(r,n)){t&&pt(s),r[n]=s;continue}let i=r[n];if(i==null){t&&pt(s),r[n]=s;continue}if(n==="index"||n==="type"){r[n]=s;continue}if(typeof i=="string"&&typeof s=="string")i+=s;else if(typeof i=="number"&&typeof s=="number")i+=s;else if(L(i)&&L(s))i=hd(i,s);else if(Array.isArray(i)&&Array.isArray(s)){ZA(i,s,hd);continue}else throw new TypeError(`Unhandled record type: ${XA(n)}`);r[n]=i}return r}function Aa(r){if(!(!L(r)&&!Array.isArray(r)))for(let[e,t]of Object.entries(r)){if(e==="__proto__"||e==="constructor"||e==="prototype")throw new f(`Assistant stream delta contains an unsafe property: ${e}`);Aa(t)}}function gc(r,e,t=!1){Aa(e);let n=r,s=e,i=im(t&&!yc(r));return _c(n,s,i),hd(n,s),am(i),r}function lm(r,e,t,n=!0){Aa(e);let s=im(n&&!yc(r));return cm(r,e,t,s,_c),()=>am(s)}var B,ke,Pr,at,Io,vo,ve,Kt,Pn,xr,Nt,On,Le,Oa,Pa,vr,xa,va,dm,xo,fm,Ra,pm,hm,fe,mm,_m,ym,gm,bm;function eR(r){let e=Object.getOwnPropertyDescriptor(r,"event"),t=Object.getOwnPropertyDescriptor(r,"data"),n=Reflect.get(r,"event",r),s=Reflect.get(r,"data",r),i=s;if(n==="thread.message.created"||n==="thread.message.in_progress"||n==="thread.message.delta"||n==="thread.message.completed"||n==="thread.message.incomplete"||n==="thread.run.step.created"||n==="thread.run.step.in_progress"||n==="thread.run.step.delta"||n==="thread.run.step.completed"||n==="thread.run.step.failed"||n==="thread.run.step.cancelled"||n==="thread.run.step.expired"){let c=Object.getOwnPropertyDescriptor(s,"id");if(c&&"value"in c&&s.id!==c.value){let d=c.value;i=new Proxy(s,{get(p,y){return y==="id"?d:Reflect.get(p,y,p)}})}}let o=Object.freeze({event:n,data:i}),a=e!==void 0&&"value"in e&&e.value===n&&t!==void 0&&"value"in t&&t.value===s&&i===s;return{event:o,exposedEvent:a?r:{event:n,data:i}}}var Ir=class r extends fr{constructor(){super(...arguments),B.add(this),ke.set(this,Object.create(null)),Pr.set(this,new Map),at.set(this,void 0),Io.set(this,Object.create(null)),vo.set(this,new Map),ve.set(this,void 0),Kt.set(this,void 0),Pn.set(this,void 0),xr.set(this,void 0),Nt.set(this,void 0),On.set(this,void 0),Le.set(this,void 0),Oa.set(this,void 0),Pa.set(this,void 0),vr.set(this,void 0)}[(ke=new WeakMap,Pr=new WeakMap,at=new WeakMap,Io=new WeakMap,vo=new WeakMap,ve=new WeakMap,Kt=new WeakMap,Pn=new WeakMap,xr=new WeakMap,Nt=new WeakMap,On=new WeakMap,Le=new WeakMap,Oa=new WeakMap,Pa=new WeakMap,vr=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=n=>e(structuredClone(n));return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=ze.fromReadableStream(e,this.controller);for await(let s of n)u(this,B,"m",xa).call(this,s);if(n.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,B,"m",va).call(this))}toReadableStream(){return new ze(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){let i=new r;return i._run(()=>i._runToolAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),i}async _createToolAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let i={...n,stream:!0},o=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(let a of o)u(this,B,"m",xa).call(this,a);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,B,"m",va).call(this))}static createThreadAssistantStream(e,t,n){let s=new r;return s._run(()=>s._threadAssistantStream(e,t,{...n,__metadata:{...n?.__metadata,helperMethod:"stream"}})),s}static createAssistantStream(e,t,n,s){let i=new r;return i._run(()=>i._runAssistantStream(e,t,n,{...s,__metadata:{...s?.__metadata,helperMethod:"stream"}})),i}currentEvent(){return pt(u(this,Oa,"f")),u(this,Oa,"f")}currentRun(){return pt(u(this,Pa,"f")),u(this,Pa,"f")}currentMessageSnapshot(){return pt(u(this,ve,"f")),u(this,ve,"f")}currentRunStepSnapshot(){return pt(u(this,vr,"f")),u(this,vr,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,ke,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,Io,"f"))}async finalRun(){if(await this.done(),!u(this,Pn,"f"))throw new Error("Final run was not received.");return u(this,Pn,"f")}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let s={...t,stream:!0},i=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let o of i)u(this,B,"m",xa).call(this,o);if(i.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,B,"m",va).call(this))}async _createAssistantStream(e,t,n,s){this._listenForAbort(s?.signal);let i={...n,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(let a of o)u(this,B,"m",xa).call(this,a);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(u(this,B,"m",va).call(this))}static accumulateDelta(e,t){return gc(e,t)}_addRun(e){return u(this,B,"m",fe).call(this,"run",e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}};xa=function(e){if(this.ended)return;let{event:t,exposedEvent:n}=eR(e),s,i,o,a;switch(t.event){case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{s=u(this,B,"m",fm).call(this,t),i=t.data;break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{o=u(this,B,"m",dm).call(this,t),a=t.data;break}}switch(w(this,Oa,n,"f"),u(this,B,"m",mm).call(this,n),s!==void 0&&i!==void 0&&u(this,B,"m",Ra).call(this,i,s),o!==void 0&&a!==void 0&&u(this,B,"m",xo).call(this,a,o),o===void 0&&u(this,at,"f")!==void 0&&u(this,vr,"f")&&u(this,B,"m",xo).call(this,u(this,vr,"f"),u(this,at,"f")),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":{u(this,B,"m",bm).call(this,t);break}case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{if(o===void 0)throw new f("Received assistant run-step event without a canonical run-step ID");let c=u(this,ke,"f")[o];c&&u(this,B,"m",xo).call(this,c,o),u(this,B,"m",hm).call(this,t,o),u(this,B,"m",xo).call(this,t.data,o);let d=u(this,ke,"f")[o];d&&u(this,B,"m",xo).call(this,d,o);break}case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":{if(s!==void 0&&u(this,ve,"f")&&u(this,B,"m",Ra).call(this,u(this,ve,"f"),s),u(this,B,"m",pm).call(this,t),s!==void 0){u(this,B,"m",Ra).call(this,t.data,s);let c=u(this,Io,"f")[s];c&&u(this,B,"m",Ra).call(this,c,s)}break}case"error":throw new J(void 0,t.data,void 0,void 0);default:}},va=function(){if(this.ended)throw new f("stream has ended, this shouldn't happen");if(!u(this,Pn,"f"))throw new Error("Final run has not been received");return u(this,Pn,"f")},dm=function(e){let t=Object.getOwnPropertyDescriptor(e.data,"id"),n=t&&"value"in t?t.value:void 0;if(typeof n!="string"||n.length===0)throw new f("Received assistant run-step event with an invalid run-step ID");if(e.event==="thread.run.step.delta"){let s=e.data.delta;if(s&&P(s,"id"))throw new f("Run-step deltas must not contain an id field")}if(e.event==="thread.run.step.created"){if(u(this,at,"f")!==void 0)throw new f(`Received run-step creation for "${n}" before the active run step "${u(this,at,"f")}" reached a terminal state`);if(P(u(this,ke,"f"),n)||u(this,Pr,"f").has(n))throw new f(`Received run-step creation for run step "${n}", which has already been created`);return w(this,at,n,"f"),u(this,Pr,"f").set(n,n),n}if(u(this,at,"f")!==void 0){if(n!==u(this,at,"f"))throw new f(`Received ${e.event} for run step "${n}", which does not match the active run step "${u(this,at,"f")}"`);return n}if(e.event==="thread.run.step.delta")throw P(u(this,ke,"f"),n)?new f(`Received run-step delta for "${n}" with no active run step`):new f("Received a RunStepDelta before creation of a snapshot");if(P(u(this,ke,"f"),n)||u(this,Pr,"f").has(n))throw new f(`Received run-step event for run step "${n}", which has already been created`);return u(this,Pr,"f").set(n,n),e.event==="thread.run.step.in_progress"&&w(this,at,n,"f"),n},xo=function(e,t){let n=Object.getOwnPropertyDescriptor(e,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!="string"||s.length===0)throw new f("Received assistant run-step event with an invalid run-step ID");let i=u(this,Pr,"f").get(s);if(i!==void 0&&i!==t)throw new f(`Received run-step creation for run step "${s}", which has already been created`);u(this,Pr,"f").set(s,t)},fm=function(e){let t=Object.getOwnPropertyDescriptor(e.data,"id"),n=t&&"value"in t?t.value:void 0;if(typeof n!="string"||n.length===0)throw new f("Received assistant message event with an invalid message ID");if(e.event==="thread.message.created"){if(u(this,ve,"f"))throw new f(`Received message creation for "${n}" before the active message "${u(this,Kt,"f")}" reached a terminal state`);if(P(u(this,Io,"f"),n)||u(this,vo,"f").has(n))throw new f(`Received message creation for message "${n}", which has already been created`);return w(this,Kt,n,"f"),u(this,vo,"f").set(n,n),n}if(!u(this,ve,"f"))throw e.event==="thread.message.delta"?new f("Received a delta with no existing snapshot (there should be one from message creation)"):new f("Received thread message event with no existing snapshot");if(n!==u(this,Kt,"f"))throw new f(`Received ${e.event} for message "${n}", which does not match the active message "${u(this,Kt,"f")}"`);return n},Ra=function(e,t){let n=Object.getOwnPropertyDescriptor(e,"id"),s=n&&"value"in n?n.value:void 0;if(typeof s!="string"||s.length===0)throw new f("Received assistant message event with an invalid message ID");let i=u(this,vo,"f").get(s);if(i!==void 0&&i!==t)throw new f(`Received message creation for message "${s}", which has already been created`);u(this,vo,"f").set(s,t)},pm=function(e){let[t,n]=u(this,B,"m",ym).call(this,e,u(this,ve,"f"));if(w(this,ve,t,"f"),!u(this,Kt,"f"))throw new f("Received thread message event with no active message ID");u(this,Io,"f")[u(this,Kt,"f")]=t;for(let s of n){let i=t.content[s.index];i?.type==="text"&&u(this,B,"m",fe).call(this,"textCreated",i.text)}switch(e.event){case"thread.message.created":{w(this,xr,void 0,"f"),w(this,Nt,void 0,"f"),u(this,B,"m",fe).call(this,"messageCreated",e.data);break}case"thread.message.in_progress":break;case"thread.message.delta":{if(u(this,B,"m",fe).call(this,"messageDelta",e.data.delta,t),e.data.delta.content)for(let s of e.data.delta.content){if(s.type==="text"&&s.text){let i=s.text,o=t.content[s.index];if(o&&o.type==="text")u(this,B,"m",fe).call(this,"textDelta",i,o.text);else throw new Error("The snapshot associated with this text delta is not text or missing")}if(s.index!==u(this,xr,"f")){if(u(this,Nt,"f"))switch(u(this,Nt,"f").type){case"text":{u(this,B,"m",fe).call(this,"textDone",u(this,Nt,"f").text,u(this,ve,"f"));break}case"image_file":{u(this,B,"m",fe).call(this,"imageFileDone",u(this,Nt,"f").image_file,u(this,ve,"f"));break}}w(this,xr,s.index,"f")}w(this,Nt,t.content[s.index],"f")}break}case"thread.message.completed":case"thread.message.incomplete":{if(u(this,xr,"f")!==void 0){let s=e.data.content[u(this,xr,"f")];if(s)switch(s.type){case"image_file":{u(this,B,"m",fe).call(this,"imageFileDone",s.image_file,u(this,ve,"f"));break}case"text":{u(this,B,"m",fe).call(this,"textDone",s.text,u(this,ve,"f"));break}}}u(this,ve,"f")&&u(this,B,"m",fe).call(this,"messageDone",e.data),w(this,xr,void 0,"f"),w(this,Nt,void 0,"f"),w(this,ve,void 0,"f"),w(this,Kt,void 0,"f")}}},hm=function(e,t){let n=u(this,B,"m",_m).call(this,e,t);switch(w(this,vr,n,"f"),e.event){case"thread.run.step.created":{w(this,On,void 0,"f"),w(this,Le,void 0,"f"),u(this,B,"m",fe).call(this,"runStepCreated",e.data);break}case"thread.run.step.delta":{let s=e.data.delta;if(s.step_details&&s.step_details.type==="tool_calls"&&s.step_details.tool_calls&&n.step_details.type==="tool_calls")for(let i of s.step_details.tool_calls)i.index===u(this,On,"f")?u(this,B,"m",fe).call(this,"toolCallDelta",i,n.step_details.tool_calls[i.index]):(u(this,Le,"f")&&u(this,B,"m",fe).call(this,"toolCallDone",u(this,Le,"f")),w(this,On,i.index,"f"),w(this,Le,n.step_details.tool_calls[i.index],"f"),u(this,Le,"f")&&u(this,B,"m",fe).call(this,"toolCallCreated",u(this,Le,"f")));u(this,B,"m",fe).call(this,"runStepDelta",e.data.delta,n);break}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":{w(this,vr,void 0,"f"),w(this,at,void 0,"f"),e.data.step_details.type==="tool_calls"&&u(this,Le,"f")&&u(this,B,"m",fe).call(this,"toolCallDone",u(this,Le,"f")),u(this,B,"m",fe).call(this,"runStepDone",e.data,n),w(this,On,void 0,"f"),w(this,Le,void 0,"f");break}case"thread.run.step.in_progress":break}},fe=function(e,...t){if(this._hasListeners(e))for(let n of t)pt(n);this._emit(e,...t)},mm=function(e){u(this,B,"m",fe).call(this,"event",e)},_m=function(e,t){switch(e.event){case"thread.run.step.created":return u(this,ke,"f")[t]=e.data,e.data;case"thread.run.step.delta":{let n=u(this,ke,"f")[t];if(!n)throw new Error("Received a RunStepDelta before creation of a snapshot");let s=e.data.delta;if(s){if(P(s,"id"))throw new f("Run-step deltas must not contain an id field");let i=gc(n,s,!0);u(this,ke,"f")[t]=i}return u(this,ke,"f")[t]}case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":{u(this,ke,"f")[t]=e.data;break}}if(u(this,ke,"f")[t])return u(this,ke,"f")[t];throw new Error("No snapshot available")},ym=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":{if(!t)throw new Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content){Aa(s.delta);let i=!yc(t),o=lm(t.content,s.delta.content,"content",i);for(let a of s.delta.content)if(P(t.content,a.index)){let c=t.content[a.index];t.content[a.index]=u(this,B,"m",gm).call(this,a,c,i)}else md(t.content,a.index,a),n.push(a);o()}return[t,n]}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,n];throw new Error("Received thread message event with no existing snapshot")}}throw new Error("Tried to accumulate a non-message event")},gm=function(e,t,n){return gc(t,e,n)},bm=function(e){switch(w(this,Pa,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":{w(this,Pn,e.data,"f"),u(this,Le,"f")&&u(this,B,"m",fe).call(this,"toolCallDone",u(this,Le,"f")),w(this,On,void 0,"f"),w(this,Le,void 0,"f");break}case"thread.run.cancelling":break}};function So(r,e){return Promise.resolve(r).then(e)}function wm(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var Am=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function tR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Am.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Am.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var xn=class extends m{constructor(){super(...arguments),this.steps=new Po(this._client)}create(e,t,n){let{include:s,...i}=t;return this._client.post(l`/threads/${e}/runs`,So(n,o=>wm({query:{include:s},body:i,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return Ir.createAssistantStream(e,this._client.beta.threads.runs,t,n)}retrieve(e,t,n){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,So(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{thread_id:s,...i}=t;return this._client.post(l`/threads/${s}/runs/${e}`,So(n,o=>({body:i,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=tR(t,["after","before","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/threads/${e}/runs`,I,So(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t,n){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,So(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}async poll(e,t,n){return await rm(this,e,t,n)}stream(e,t,n){return Ir.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:s,...i}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,So(n,o=>wm({body:i,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!0})))}async submitToolOutputsAndPoll(e,t,n){let s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return Ir.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};xn.Steps=Po;function Ia(r,e){return Promise.resolve(r).then(e)}function nR(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var Sr=class extends m{constructor(){super(...arguments),this.runs=new xn(this._client),this.messages=new Oo(this._client)}create(e={},t){return this._client.post("/threads",Ia(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/threads/${e}`,Ia(t,n=>({...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/threads/${e}`,Ia(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/threads/${e}`,Ia(t,n=>({...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}createAndRun(e,t){return this._client.post("/threads/runs",Ia(t,n=>nR({body:e,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}},{streamFromBody:!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 Ir.createThreadAssistantStream(e,this._client.beta.threads,t)}};Sr.Runs=xn;Sr.Messages=Oo;var Eo=class extends m{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Co=class extends m{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Er=class extends m{constructor(){super(...arguments),this.sessions=new Eo(this._client),this.transcriptionSessions=new Co(this._client)}};Er.Sessions=Eo;Er.TranscriptionSessions=Co;var Ne=class extends m{constructor(){super(...arguments),this.realtime=new Er(this._client),this.agents=new St(this._client),this.responses=new Rr(this._client),this.chatkit=new Ar(this._client),this.assistants=new Ms(this._client),this.threads=new Sr(this._client)}};Ne.Realtime=Er;Ne.Agents=St;Ne.Responses=Rr;Ne.ChatKit=Ar;Ne.Assistants=Ms;Ne.Threads=Sr;function uR(r,e){return Promise.resolve(r).then(e)}function cR(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var vn=class extends m{create(e,t){return this._client.post("/completions",uR(t,n=>cR({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}};function lR(r,e){return Promise.resolve(r).then(e)}var To=class extends m{retrieve(e,t,n){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,lR(n,i=>({...i,headers:g([{Accept:"application/binary"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function bc(r,e){return Promise.resolve(r).then(e)}function fR(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var Rm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function pR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Rm.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Rm.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var In=class extends m{constructor(){super(...arguments),this.content=new To(this._client)}create(e,t,n){return this._client.post(l`/containers/${e}/files`,bc(n,s=>Ot(fR({body:t,...s,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client)))}retrieve(e,t,n){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,bc(n,i=>({...i,__security:{bearerAuth:!0}})))}list(e,t={},n){let s=pR(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/containers/${e}/files`,I,bc(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,n){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,bc(n,i=>({...i,headers:g([{Accept:"*/*"},i?.headers]),__security:{bearerAuth:!0}})))}};In.Content=To;function wc(r,e){return Promise.resolve(r).then(e)}var Om=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function mR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Om.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Om.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Cr=class extends m{constructor(){super(...arguments),this.files=new In(this._client)}create(e,t){return this._client.post("/containers",wc(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/containers/${e}`,wc(t,n=>({...n,__security:{bearerAuth:!0}})))}list(e={},t){let n=mR(e,["after","limit","name","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/containers",I,wc(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/containers/${e}`,wc(t,n=>({...n,headers:g([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})))}};Cr.Files=In;function _R(r,e){return Promise.resolve(r).then(e)}var Sn=class extends m{create(e,t){return this._client.post("/content_provenance_checks",_R(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}};function Ac(r,e){return Promise.resolve(r).then(e)}var Pm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function yR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Pm.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Pm.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ko=class extends m{create(e,t,n){let{include:s,...i}=t;return this._client.post(l`/conversations/${e}/items`,Ac(n,o=>({query:{include:s},body:i,...o,__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{conversation_id:s,...i}=t;return this._client.get(l`/conversations/${s}/items/${e}`,Ac(n,o=>({query:i,...o,__security:{bearerAuth:!0}})))}list(e,t={},n){let s=yR(t,["after","include","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/conversations/${e}/items`,Q,Ac(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,n){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,Ac(n,i=>({...i,__security:{bearerAuth:!0}})))}};function Rc(r,e){return Promise.resolve(r).then(e)}var Tr=class extends m{constructor(){super(...arguments),this.items=new ko(this._client)}create(e={},t){return this._client.post("/conversations",Rc(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/conversations/${e}`,Rc(t,n=>({...n,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/conversations/${e}`,Rc(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/conversations/${e}`,Rc(t,n=>({...n,__security:{bearerAuth:!0}})))}};Tr.Items=ko;function bR(r,e){return Promise.resolve(r).then(e)}var En=class extends m{create(e,t){return this._client.post("/decisions",bR(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}};function xm(r,e,t){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&ue(r).debug("embeddings/user defined encoding_format:",e.encoding_format);let o={body:{...e,encoding_format:s},...t,__security:{bearerAuth:!0}},a=r.post("/embeddings",o);return n?a:(ue(r).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(c=>{let d=c?.data;if(d!==void 0){if(!Array.isArray(d))throw new TypeError("Expected embeddings response data to be an array");let{length:p}=d;for(let y=0;y<p;y+=1)if(y in d){let _=d[y],{embedding:b}=_;if(Array.isArray(b))continue;_.embedding=nm(b)}}return c}))}var Cn=class extends m{create(e,t){return xm(this._client,e,t)}};function vm(r,e){return Promise.resolve(r).then(e)}var jo=class extends m{retrieve(e,t,n){let{eval_id:s,run_id:i}=t;return this._client.get(l`/evals/${s}/runs/${i}/output_items/${e}`,vm(n,o=>({...o,__security:{bearerAuth:!0}})))}list(e,t,n){let{eval_id:s,...i}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,I,vm(n,o=>({query:i,...o,__security:{bearerAuth:!0}})))}};function Sa(r,e){return Promise.resolve(r).then(e)}var Im=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function AR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Im.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Im.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Tn=class extends m{constructor(){super(...arguments),this.outputItems=new jo(this._client)}create(e,t,n){return this._client.post(l`/evals/${e}/runs`,Sa(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,Sa(n,i=>({...i,__security:{bearerAuth:!0}})))}list(e,t={},n){let s=AR(t,["after","limit","order","status"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/evals/${e}/runs`,I,Sa(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,n){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,Sa(n,i=>({...i,__security:{bearerAuth:!0}})))}cancel(e,t,n){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}/cancel`,Sa(n,i=>({...i,__security:{bearerAuth:!0}})))}};Tn.OutputItems=jo;function Ea(r,e){return Promise.resolve(r).then(e)}var Sm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function OR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Sm.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Sm.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var kr=class extends m{constructor(){super(...arguments),this.runs=new Tn(this._client)}create(e,t){return this._client.post("/evals",Ea(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/evals/${e}`,Ea(t,n=>({...n,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/evals/${e}`,Ea(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}list(e={},t){let n=OR(e,["after","limit","order","order_by"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/evals",I,Ea(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/evals/${e}`,Ea(t,n=>({...n,__security:{bearerAuth:!0}})))}};kr.Runs=Tn;async function Em(r,e,t,n){let s=new Set(["processed","error","deleted"]),i=performance.now(),o=await r.retrieve(e);for(;!o.status||!s.has(o.status);)if(await Xn(t),o=await r.retrieve(e),performance.now()-i>n)throw new se({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}function Ca(r,e){return Promise.resolve(r).then(e)}var Cm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function PR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Cm.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Cm.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var kn=class extends m{create(e,t){return this._client.post("/files",Ca(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(l`/files/${e}`,Ca(t,n=>({...n,__security:{bearerAuth:!0}})))}list(e={},t){let n=PR(e,["after","limit","order","purpose"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/files",I,Ca(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/files/${e}`,Ca(t,n=>({...n,__security:{bearerAuth:!0}})))}content(e,t){return this._client.get(l`/files/${e}/content`,Ca(t,n=>({...n,headers:g([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){return await Em(this,e,t,n)}};var qo=class extends m{};function Tm(r,e){return Promise.resolve(r).then(e)}var $o=class extends m{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",Tm(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",Tm(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}};var jn=class extends m{constructor(){super(...arguments),this.graders=new $o(this._client)}};jn.Graders=$o;function Oc(r,e){return Promise.resolve(r).then(e)}var km=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function jm(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>km.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!km.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Do=class extends m{create(e,t,n){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,be,Oc(n,s=>({body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})))}retrieve(e,t={},n){let s=jm(t,["after","limit","order","project_id"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,Oc(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}list(e,t={},n){let s=jm(t,["after","limit","order","project_id"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Q,Oc(n,i=>({query:t,...i,__security:{adminAPIKeyAuth:!0}})))}delete(e,t,n){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,Oc(n,i=>({...i,__security:{adminAPIKeyAuth:!0}})))}};var qn=class extends m{constructor(){super(...arguments),this.permissions=new Do(this._client)}};qn.Permissions=Do;function CR(r,e){return Promise.resolve(r).then(e)}var qm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function TR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>qm.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!qm.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Fo=class extends m{list(e,t={},n){let s=TR(t,["after","limit"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,I,CR(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}};function $n(r,e){return Promise.resolve(r).then(e)}var $m=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function Dm(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>$m.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!$m.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Dn=class extends m{constructor(){super(...arguments),this.checkpoints=new Fo(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",$n(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,$n(t,n=>({...n,__security:{bearerAuth:!0}})))}list(e={},t){let n=Dm(e,["after","limit","metadata"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/fine_tuning/jobs",I,$n(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,$n(t,n=>({...n,__security:{bearerAuth:!0}})))}listEvents(e,t={},n){let s=Dm(t,["after","limit"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,I,$n(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,$n(t,n=>({...n,__security:{bearerAuth:!0}})))}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,$n(t,n=>({...n,__security:{bearerAuth:!0}})))}};Dn.Checkpoints=Fo;var ht=class extends m{constructor(){super(...arguments),this.methods=new qo(this._client),this.jobs=new Dn(this._client),this.checkpoints=new qn(this._client),this.alpha=new jn(this._client)}};ht.Methods=qo;ht.Jobs=Dn;ht.Checkpoints=qn;ht.Alpha=jn;var zo=class extends m{};var jr=class extends m{constructor(){super(...arguments),this.graderModels=new zo(this._client)}};jr.GraderModels=zo;function _d(r,e){return Promise.resolve(r).then(e)}function Fm(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var Fn=class extends m{createVariation(e,t){return this._client.post("/images/variations",_d(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}edit(e,t){return this._client.post("/images/edits",_d(t,n=>re(Fm((s=>({...s,body:Object.fromEntries(Object.entries(s.body??{}).map(([i,o])=>[i,i==="safety_identifier"&&o===null?void 0:o]))}))({body:e,...n,stream:e.stream??!1,__metadata:{...n?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}}),{streamFromBody:!0}),this._client)))}generate(e,t){return this._client.post("/images/generations",_d(t,n=>Fm({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))}};function Mo(r,e){return Promise.resolve(r).then(e)}var Lo=class extends m{accept(e,t,n){return this._client.post(l`/live/sessions/${e}/accept`,Mo(n,s=>({body:t,...s,headers:g([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})))}downloadRecording(e,t){return this._client.get(l`/live/sessions/${e}/content`,Mo(t,n=>({...n,headers:g([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}fork(e,t,n){return this._client.post(l`/live/sessions/${e}/fork`,Mo(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}hangup(e,t){return this._client.post(l`/live/sessions/${e}/hangup`,Mo(t,n=>({...n,headers:g([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})))}refer(e,t,n){return this._client.post(l`/live/sessions/${e}/refer`,Mo(n,s=>({body:t,...s,headers:g([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})))}reject(e,t,n){return this._client.post(l`/live/sessions/${e}/reject`,Mo(n,s=>({body:t,...s,headers:g([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})))}};var Bo=class extends m{};var Ko=class extends m{};function zR(r,e){return Promise.resolve(r).then(e)}var Et=class extends m{constructor(){super(...arguments),this.sideband=new Ko(this._client),this.forks=new Bo(this._client),this.sessions=new Lo(this._client)}create(e,t){return this._client.post("/live/sessions",zR(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}};Et.Sideband=Ko;Et.Forks=Bo;Et.Sessions=Lo;function yd(r,e){return Promise.resolve(r).then(e)}var zn=class extends m{retrieve(e,t){return this._client.get(l`/models/${e}`,yd(t,n=>({...n,__security:{bearerAuth:!0}})))}list(e){return this._client.getAPIList("/models",be,yd(e,t=>({...t,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/models/${e}`,yd(t,n=>({...n,__security:{bearerAuth:!0}})))}};function MR(r,e){return Promise.resolve(r).then(e)}var Mn=class extends m{create(e,t){return this._client.post("/moderations",MR(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}};async function zm(r,e,t,n=null){if(r.body===null||typeof r.body!="object"||Array.isArray(r.body))throw new TypeError("Multipart request body must be an object");let s=Object.fromEntries(Object.entries(r.body).filter(([,c])=>c!==void 0));if(n!==null&&Object.keys(s).length===1&&Object.prototype.hasOwnProperty.call(s,n)){let c=s[n];if(typeof c!="string")throw new TypeError("Raw multipart alternative must be a string");return{...r,body:c,headers:g([r.headers,{"content-type":t[n].content_type}])}}let i=[];for(let[c,d]of Object.entries(t)){if(!Object.prototype.hasOwnProperty.call(s,c))continue;let p=s[c],y=d.json?JSON.stringify(p):p;if(typeof y!="string")throw new TypeError(`Multipart field ${c} must encode as a string`);i.push([c,Mt([y],"",{type:d.content_type})]),delete s[c]}let a=(await re({...r,body:s},e)).body;if(!(a instanceof FormData))throw await a.cancel(),new TypeError("Unexpected streaming upload in typed multipart request body");for(let[c,d]of i)a.append(c,d,"");return{...r,body:a,headers:g([r.headers,{"content-type":null}])}}function Ta(r,e){return Promise.resolve(r).then(e)}var No=class extends m{create(e,t){return this._client.post("/realtime/calls",Ta(t,n=>zm({body:e,...n,headers:g([{Accept:"application/sdp"},n?.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(l`/realtime/calls/${e}/accept`,Ta(n,s=>({body:t,...s,headers:g([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})))}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,Ta(t,n=>({...n,headers:g([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})))}refer(e,t,n){return this._client.post(l`/realtime/calls/${e}/refer`,Ta(n,s=>({body:t,...s,headers:g([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})))}reject(e,t={},n){return this._client.post(l`/realtime/calls/${e}/reject`,Ta(n,s=>({body:t,...s,headers:g([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})))}};function BR(r,e){return Promise.resolve(r).then(e)}var Wo=class extends m{create(e,t){return this._client.post("/realtime/client_secrets",BR(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}};function NR(r,e){return Promise.resolve(r).then(e)}var Uo=class extends m{create(e,t){return this._client.post("/realtime/translations/client_secrets",NR(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}};var Ln=class extends m{constructor(){super(...arguments),this.clientSecrets=new Uo(this._client)}};Ln.ClientSecrets=Uo;var Ct=class extends m{constructor(){super(...arguments),this.clientSecrets=new Wo(this._client),this.calls=new No(this._client),this.translations=new Ln(this._client)}};Ct.ClientSecrets=Wo;Ct.Calls=No;Ct.Translations=Ln;function QR(r,e){return Promise.resolve(r).then(e)}var Mm=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function HR(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>Mm.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!Mm.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Qo=class extends m{list(e,t={},n){let s=HR(t,["after","include","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/responses/${e}/input_items`,I,QR(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}};function JR(r,e){return Promise.resolve(r).then(e)}var Ho=class extends m{count(e={},t){return this._client.post("/responses/input_tokens",JR(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}};function Lm(r){return L(r)&&typeof r.type=="string"}function Xo({body:r},e){if(e===null||!L(r))return e??null;let{input:t}=r;if(Array.isArray(t))for(let i=t.length-1;i>=0;i-=1){let o=t[i];if(!L(o)||o.type!=="configuration_update")continue;let{text:a}=o;if(!L(a))continue;let{format:c}=a;if(Lm(c)){if(c.type==="text"&&e!==void 0)throw new f("Cannot use parseAs with a plain-text format update.");return e??c}}let{text:n}=r,s=L(n)?n.format:null;return e??(Lm(s)?s:null)}function ka(r,e){let t=e&&P(e,"parseAs")?e.parseAs:void 0;t!=null&&Xo({body:r},t);let n={...e};delete n.parseAs;let s;return n.__metadata={...e?.__metadata,captureResponseParser(i){let o=Xo(i,t);s=o===null?null:{type:o.type,$brand:"$brand"in o?o.$brand:void 0,$parseRaw:"$parseRaw"in o?o.$parseRaw:void 0}}},{getTextFormat:i=>s===void 0?Xo(i,t):s,requestOptions:n}}function Bm(r,e,t=e&&Xo({body:e})){if(!e||!GR(e,t)){let n={...r,output_parsed:null,output:r.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(i=>({...i,parsed:null}))}:s)};return Km(r,n)&&Wt(n),n}return bd(r,e,t)}function bd(r,e,t=Xo({body:e})){let n=!r.status||r.status==="completed",s=r.output.map(o=>{if(o.type==="function_call")return n?ZR(e,o):{...o,parsed_arguments:null};if(o.type==="message"){let a=o.content.map(c=>c.type==="output_text"?{...c,parsed:n&&(o.phase==null||o.phase==="final_answer")?Lt(t,c.text):null}:c);return{...o,content:a}}return o}),i={...r,output:s};return Km(r,i)&&Wt(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let o of i.output)if(o.type==="message"){for(let a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),i}function GR(r,e=Xo({body:r})){return xt(e)?!0:Array.isArray(r.tools)&&r.tools.some(t=>gd(t)||t.type==="function"&&t.strict===!0||t.type==="namespace"&&t.tools.some(n=>n.type==="function"&&(gd(n)||n.strict===!0)))}function gd(r){return r?.$brand==="auto-parseable-tool"}function YR(r,e,t){for(let n of r)if(t==null){if(n.type==="function"&&n.name===e)return n}else if(n.type==="namespace"&&n.name===t)return n.tools.find(s=>s.type==="function"&&s.name===e);if(t===e)return r.find(n=>n.type==="function"&&n.name===e&&n.defer_loading===!0)}function ZR(r,e){let t=YR(r.tools??[],e.name,e.namespace),n=null;return gd(t)?n=t.$parseRaw(e.arguments):t?.strict&&(n=Lt({type:"json_schema",$parseRaw:void 0},e.arguments)),{...e,parsed_arguments:n}}function Km(r,e){return!Object.getOwnPropertyDescriptor(r,"output_text")||e.output_text==null}function Wt(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var Jo=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw new RangeError(`missing output at index ${e}`);let n=this.capacity+e,s=t-(this.values[n]??0);if(s!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+s,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw new RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,s=0;for(;t<n;)t%2===1&&(s+=this.values[t]??0,t+=1),n%2===1&&(n-=1,s+=this.values[n]??0),t=Math.floor(t/2),n=Math.floor(n/2);return s}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 n=this.capacity-1;n>0;n-=1)t[n]=(t[n*2]??0)+(t[n*2+1]??0);this.values=t}};function wd(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Jo}}function Vo(r,e){if(e.type!=="message")return"";let t="";for(let n of e.content)n.type==="output_text"&&(t+=n.text);return r.outputTextLengths.set(e,t.length),t}function mt(r,e){if(r.deferOutputText){r.canonicalSnapshot=void 0;return}if(r.canonicalSnapshot===e)return;let t=new Jo,n="";for(let s of e.output){let i=Vo(r,s);n+=i,t.append(i.length)}e.output_text=n,r.outputTextIndex=t,r.canonicalSnapshot=e}function Wm(r,e){r.canonicalSnapshot=void 0,r.outputTextLengths=new WeakMap,r.outputTextIndex=new Jo;let t=structuredClone(e);return!Object.getOwnPropertyDescriptor(t,"output_text")||t.output_text===null||t.output_text===void 0?mt(r,t):t.output.length===0&&t.output_text===""&&(r.canonicalSnapshot=t),t}function ja(r,e,t,n,s){if(r.deferOutputText)return;let i=r.outputTextLengths.get(e);if(i!==void 0){let o=i-n.length+s.length;r.outputTextLengths.set(e,o),r.outputTextIndex.update(t,o)}}function Nm(r,e,t){if(e.length===0){r.output_text+=t;return}r.output_text=r.output_text.slice(0,r.output_text.length-e.length)+t}function eO(r,e,t,n){if(t===void 0||e?.type!=="message")return 0;if(t<e.content.length-t-1){let o=0;for(let a=0;a<t;a+=1){let c=e.content[a];c?.type==="output_text"&&(o+=c.text.length)}return o}let s=0;for(let o=t+1;o<e.content.length;o+=1){let a=e.content[o];a?.type==="output_text"&&(s+=a.text.length)}return(r.outputTextLengths.get(e)??Vo(r,e).length)-s-n.length}function Go(r,e,t,n,s,i){if(n===s)return;if(r.deferOutputText){r.outputTextDirty=!0;return}let o=e.output[t];if(t===e.output.length-1&&(i===void 0||o?.type==="message"&&i===o.content.length-1)){Nm(e,n,s);return}let a=eO(r,o,i,s),c=r.outputTextIndex.prefixSum(t)+a;if(c+n.length===e.output_text.length){Nm(e,n,s);return}e.output_text=e.output_text.slice(0,c)+s+e.output_text.slice(c+n.length)}var Ad=new WeakMap;function qr(r,e,t,n=!1){if(!Array.isArray(r)||!Number.isSafeInteger(e)||e<0||e>r.length||(e===r.length?!n||e in r:!P(r,e)))throw new f(`missing ${t} at index ${e}`)}function xc(r,e,t){if(e!==r.length)throw new f(`missing ${t} at index ${e}`);qr(r,e,t,!0)}function K(r,e){qr(r.output,e,"output");let t=r.output[e];if(!t)throw new f(`missing output at index ${e}`);return t}function qa(r){return r.type==="function_call"||r.type==="custom_tool_call"||r.type==="shell_call"||r.type==="shell_call_output"}function vc(r,e){if(!P(r,"type")||typeof r.type!="string")throw new f(`expected an own output item type for ${e}`);let t=r.type==="function_call"||r.type==="custom_tool_call",n=[];if(P(r,"id")){if(typeof r.id!="string"||r.id.length===0&&r.type!=="computer_call")throw new f(`expected a non-empty output item id for ${e}`);n.push(`id:${r.id}`)}else if(!t)throw new f(`expected a non-empty output item id for ${e}`);if(qa(r)){if(!P(r,"call_id")||typeof r.call_id!="string"||r.call_id.length===0&&r.type!=="function_call")throw new f(`expected a non-empty output item call_id for ${e}`);n.push(`call:${r.type}:${r.call_id}`)}return n}function Xm(r,e){for(let t of e)if(r.has(t))throw new f(`duplicate output item identity '${t}'`)}function Rd(r,e){Xm(r,e);for(let t of e)r.add(t)}function Jm(r){let e={snapshot:r,output:r.output,length:r.output.length,identities:new Set};for(let t=0;t<r.output.length;t+=1){let n=K(r,t);Rd(e.identities,vc(n,"response snapshot"))}return e}function Vm(r,e){let t=Ad.get(r);if(t&&t.snapshot===e&&t.output===e.output&&t.length===e.output.length)return t;let n=Jm(e);return Ad.set(r,n),n}function Ic(r,e){let t=wd(),n=Wm(t,e),s=Jm(n);return r.canonicalSnapshot=t.canonicalSnapshot,r.outputTextLengths=t.outputTextLengths,r.outputTextIndex=t.outputTextIndex,Ad.set(r,s),n}var Od={"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 tO(r){return r.type==="response.content_part.added"||r.type==="response.content_part.done"?r.part.type==="reasoning_text"?"reasoning":"message":Od[r.type]}function $a(r,e,t){if(vc(r,t),vc(e,t),!P(e,"type")||r.type!==e.type)throw new f(`expected output item type '${r.type}', got '${e.type}'`);let n=P(r,"id")?r.id:void 0,s=P(e,"id")?e.id:void 0,i=n===void 0&&(r.type==="function_call"||r.type==="custom_tool_call");if(n!==s&&!i)throw new f(`expected output item id '${n}', got '${s}'`);if(qa(r)&&qa(e)&&r.call_id!==e.call_id)throw new f(`expected output item call_id '${r.call_id}', got '${e.call_id}'`)}function rO(r,e,t){if(r.type==="response.output_item.done")return;if(t&&(r.type==="response.shell_call_command.added"||r.type==="response.shell_call_command.delta"||r.type==="response.shell_call_command.done")){let a=K(e,r.output_index);if(!P(a,"type")||a.type!=="shell_call")throw new f(`expected output item type 'shell_call', got '${a.type}'`);return}if(r.type!=="response.content_part.added"&&r.type!=="response.content_part.done"&&!P(Od,r.type))return;let n=r;if(!P(r,"item_id")||typeof n.item_id!="string"||n.item_id.length===0)throw new f(`expected a non-empty item_id for ${r.type}`);let s=K(e,n.output_index),i=P(s,"id")?s.id:void 0;if(i!==n.item_id)throw new f(`expected item_id '${i}', got '${n.item_id}'`);let o=tO(n);if(s.type!==o)throw new f(`expected output item type '${o}', got '${s.type}'`)}function Be(r,e){qr(r,e,"content");let t=r[e];if(!t)throw new f(`missing content at index ${e}`);return t}function Um(r,e,t){let n=r.output.find(s=>s.type==="shell_call"&&s.call_id===e.call_id);for(n?qr(n.action.commands,t,"command"):qr(e.output,t,"content",!0);e.output.length<=t;)e.output.push({stdout:"",stderr:"",outcome:{type:"exit",exit_code:0}});return Be(e.output,t)}function nO(r){return new Set(r)}var sO=nO(["response.output_item.added","response.output_item.done","response.content_part.added","response.content_part.done","response.output_text.delta","response.output_text.done","response.output_text.annotation.added","response.refusal.delta","response.refusal.done","response.function_call_arguments.delta","response.function_call_arguments.done","response.custom_tool_call_input.delta","response.custom_tool_call_input.done","response.mcp_call_arguments.delta","response.mcp_call_arguments.done","response.shell_call_command.added","response.shell_call_command.done","response.shell_call_command.delta","response.shell_call_output_content.delta","response.shell_call_output_content.done","response.reasoning_text.delta","response.reasoning_text.done","response.reasoning_summary_part.added","response.reasoning_summary_part.done","response.reasoning_summary_text.delta","response.reasoning_summary_text.done","response.code_interpreter_call_code.delta","response.code_interpreter_call_code.done","response.code_interpreter_call.in_progress","response.code_interpreter_call.interpreting","response.code_interpreter_call.completed","response.file_search_call.in_progress","response.file_search_call.searching","response.file_search_call.completed","response.web_search_call.in_progress","response.web_search_call.searching","response.web_search_call.completed","response.image_generation_call.in_progress","response.image_generation_call.generating","response.image_generation_call.completed","response.mcp_call.in_progress","response.mcp_call.completed","response.mcp_call.failed","response.created","response.queued","response.in_progress","response.completed","response.failed","response.incomplete","response.audio.delta","response.audio.done","response.audio.transcript.delta","response.audio.transcript.done","response.compaction.compacting","response.image_generation_call.partial_image","response.mcp_list_tools.in_progress","response.mcp_list_tools.completed","response.mcp_list_tools.failed","keepalive","error"]);function Pc(r){throw new f("Unhandled response stream event: unknown")}var oO=["item_id","output_index","content_index","annotation_index","command_index","summary_index"];function iO(r){let e;try{e=Object.getOwnPropertyDescriptor(r,"type")}catch{return Pc(r)}let t=e?.value;if(typeof t!="string"||!sO.has(t))return Pc(r);let n=new Map([["type",t]]);if(t==="response.output_item.added"||t==="response.output_item.done"||t==="response.content_part.added"||t==="response.content_part.done"||t==="response.shell_call_command.added"||t==="response.shell_call_command.delta"||t==="response.shell_call_command.done"||P(Od,t))try{for(let i of oO){let o=Object.getOwnPropertyDescriptor(r,i);n.set(i,o?r[i]:void 0)}t==="response.output_item.added"||t==="response.output_item.done"?n.set("item",structuredClone(r.item)):(t==="response.content_part.added"||t==="response.content_part.done")&&n.set("part",structuredClone(r.part))}catch{return Pc(r)}return new Proxy(r,{get(i,o){return n.has(o)?n.get(o):Reflect.get(i,o,i)}})}function Pd(r,e,t,n,s=!0){let i=K(e,t);if($a(i,n,"response.output_item.done"),!P(i,"id")&&P(n,"id")){let{identities:c}=Vm(r,e);Rd(c,[`id:${n.id}`])}if(!s){e.output[t]=n;return}let o=Vo(r,i);(i.type==="message"||n.type==="message")&&mt(r,e),e.output[t]=n;let a=Vo(r,n);r.canonicalSnapshot===e&&r.outputTextIndex.update(t,a.length),Go(r,e,t,o,a)}function aO(r,e,t){switch(r.type){case"response.output_item.added":{xc(e.output,r.output_index,"output");let n=Vm(t,e),s=r.item,i=vc(s,r.type);Xm(n.identities,i),s.type==="message"&&mt(t,e),e.output.push(s),Rd(n.identities,i),n.length=e.output.length;let o=Vo(t,s);return t.canonicalSnapshot===e&&t.outputTextIndex.append(o.length),o&&(t.deferOutputText?t.outputTextDirty=!0:e.output_text+=o),!0}case"response.output_item.done":return Pd(t,e,r.output_index,r.item),!0;default:return!1}}function uO(r,e,t){switch(r.type){case"response.content_part.added":{let n=K(e,r.output_index),{type:s}=n,{part:i}=r;if(s==="message"&&i.type!=="reasoning_text"){xc(n.content,r.content_index,"content");let o=i;o.type==="output_text"&&mt(t,e),n.content.push(o),o.type==="output_text"&&(ja(t,n,r.output_index,"",o.text),Go(t,e,r.output_index,"",o.text,r.content_index))}else if(s==="reasoning"&&i.type==="reasoning_text"){let o=n.content??[];xc(o,r.content_index,"content"),n.content||(n.content=o),o.push(i)}return!0}default:return!1}}function cO(r,e,t){switch(r.type){case"response.content_part.done":{let n=K(e,r.output_index),{part:s}=r;if(n.type==="message"&&s.type!=="reasoning_text"){let i=Be(n.content,r.content_index),o=i.type==="output_text"?i.text:"",a=s;(i.type==="output_text"||a.type==="output_text")&&mt(t,e),n.content[r.content_index]=a;let c=a.type==="output_text"?a.text:"";ja(t,n,r.output_index,o,c),Go(t,e,r.output_index,o,c,r.content_index)}else if(n.type==="reasoning"&&s.type==="reasoning_text"){let{content:i}=n;if(!i)throw new f(`missing content at index ${r.content_index}`);Be(i,r.content_index),i[r.content_index]=s}return!0}default:return!1}}function Qm(r){return L(r)&&typeof r.token=="string"&&typeof r.logprob=="number"&&Array.isArray(r.bytes)&&r.bytes.every(e=>typeof e=="number")}function lO(r){return Array.isArray(r)&&r.every(e=>Qm(e)&&"top_logprobs"in e&&Array.isArray(e.top_logprobs)&&e.top_logprobs.every(Qm))}function Hm(r,e){let t=structuredClone(e.logprobs);if(lO(t)){if(e.type==="response.output_text.done")(t.length>0||Array.isArray(r.logprobs)&&r.logprobs.length>0)&&(r.logprobs=t);else if(t.length>0){Array.isArray(r.logprobs)||(r.logprobs=[]);for(let n of t)r.logprobs.push(n)}}}function dO(r,e,t){switch(r.type){case"response.output_text.delta":{let n=K(e,r.output_index);if(n.type==="message"){let s=Be(n.content,r.content_index);if(s.type!=="output_text")throw new f(`expected content to be 'output_text', got ${s.type}`);Hm(s,r);let i=s.text;mt(t,e),s.text=i+r.delta,ja(t,n,r.output_index,i,s.text),r.output_index===e.output.length-1&&r.content_index===n.content.length-1?t.deferOutputText?r.delta!==""&&(t.outputTextDirty=!0):e.output_text+=r.delta:Go(t,e,r.output_index,i,s.text,r.content_index)}return!0}case"response.output_text.done":{let n=K(e,r.output_index);if(n.type==="message"){let s=Be(n.content,r.content_index);if(s.type!=="output_text")throw new f(`expected content to be 'output_text', got ${s.type}`);Hm(s,r);let i=s.text;mt(t,e),s.text=r.text,ja(t,n,r.output_index,i,r.text),Go(t,e,r.output_index,i,r.text,r.content_index)}return!0}case"response.output_text.annotation.added":{let n=K(e,r.output_index);if(n.type==="message"){let s=Be(n.content,r.content_index);if(s.type!=="output_text")throw new f(`expected content to be 'output_text', got ${s.type}`);qr(s.annotations,r.annotation_index,"annotation",!0),s.annotations[r.annotation_index]=structuredClone(r.annotation)}return!0}default:return!1}}function fO(r,e){switch(r.type){case"response.refusal.delta":{let t=K(e,r.output_index);if(t.type==="message"){let n=Be(t.content,r.content_index);if(n.type!=="refusal")throw new f(`expected content to be 'refusal', got ${n.type}`);n.refusal+=r.delta}return!0}case"response.refusal.done":{let t=K(e,r.output_index);if(t.type==="message"){let n=Be(t.content,r.content_index);if(n.type!=="refusal")throw new f(`expected content to be 'refusal', got ${n.type}`);n.refusal=r.refusal}return!0}case"response.function_call_arguments.delta":{let t=K(e,r.output_index);return t.type==="function_call"&&(t.arguments+=r.delta),!0}case"response.function_call_arguments.done":{let t=K(e,r.output_index);return t.type==="function_call"&&(t.arguments=r.arguments),!0}case"response.custom_tool_call_input.delta":{let t=K(e,r.output_index);return t.type==="custom_tool_call"&&(t.input+=r.delta),!0}case"response.custom_tool_call_input.done":{let t=K(e,r.output_index);return t.type==="custom_tool_call"&&(t.input=r.input),!0}case"response.mcp_call_arguments.delta":{let t=K(e,r.output_index);return t.type==="mcp_call"&&(t.arguments+=r.delta),!0}case"response.mcp_call_arguments.done":{let t=K(e,r.output_index);return t.type==="mcp_call"&&(t.arguments=r.arguments),!0}default:return!1}}function pO(r,e){switch(r.type){case"response.shell_call_command.added":case"response.shell_call_command.done":{let t=K(e,r.output_index);if(t.type==="shell_call"){let n=r.type==="response.shell_call_command.added";qr(t.action.commands,r.command_index,"command",n),t.action.commands[r.command_index]=r.command}return!0}case"response.shell_call_command.delta":{let t=K(e,r.output_index);return t.type==="shell_call"&&(qr(t.action.commands,r.command_index,"command"),t.action.commands[r.command_index]+=r.delta),!0}case"response.shell_call_output_content.delta":{let t=K(e,r.output_index);if(t.type==="shell_call_output"){let n=Um(e,t,r.command_index);n.stdout+=r.delta.stdout??"",n.stderr+=r.delta.stderr??""}return!0}case"response.shell_call_output_content.done":{let t=K(e,r.output_index);if(t.type==="shell_call_output"){let n=Be(r.output,0);Um(e,t,r.command_index),t.output[r.command_index]=structuredClone(n)}return!0}default:return!1}}function hO(r,e){switch(r.type){case"response.reasoning_text.delta":{let t=K(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new f(`missing content at index ${r.content_index}`);let n=Be(t.content,r.content_index);if(n.type!=="reasoning_text")throw new f(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=r.delta}return!0}case"response.reasoning_text.done":{let t=K(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new f(`missing content at index ${r.content_index}`);let n=Be(t.content,r.content_index);if(n.type!=="reasoning_text")throw new f(`expected content to be 'reasoning_text', got ${n.type}`);n.text=r.text}return!0}case"response.reasoning_summary_part.added":{let t=K(e,r.output_index);return t.type==="reasoning"&&(xc(t.summary,r.summary_index,"content"),t.summary.push(structuredClone(r.part))),!0}case"response.reasoning_summary_part.done":{let t=K(e,r.output_index);return t.type==="reasoning"&&(Be(t.summary,r.summary_index),t.summary[r.summary_index]=structuredClone(r.part)),!0}case"response.reasoning_summary_text.delta":{let t=K(e,r.output_index);if(t.type==="reasoning"){let n=Be(t.summary,r.summary_index);n.text+=r.delta}return!0}case"response.reasoning_summary_text.done":{let t=K(e,r.output_index);if(t.type==="reasoning"){let n=Be(t.summary,r.summary_index);n.text=r.text}return!0}default:return!1}}function mO(r,e){switch(r.type){case"response.code_interpreter_call_code.delta":{let t=K(e,r.output_index);return t.type==="code_interpreter_call"&&(t.code=(t.code??"")+r.delta),!0}case"response.code_interpreter_call_code.done":{let t=K(e,r.output_index);return t.type==="code_interpreter_call"&&(t.code=r.code),!0}case"response.code_interpreter_call.in_progress":{let t=K(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="in_progress"),!0}case"response.code_interpreter_call.interpreting":{let t=K(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="interpreting"),!0}case"response.code_interpreter_call.completed":{let t=K(e,r.output_index);return t.type==="code_interpreter_call"&&(t.status="completed"),!0}default:return!1}}function _O(r,e){switch(r.type){case"response.file_search_call.in_progress":{let t=K(e,r.output_index);return t.type==="file_search_call"&&(t.status="in_progress"),!0}case"response.file_search_call.searching":{let t=K(e,r.output_index);return t.type==="file_search_call"&&(t.status="searching"),!0}case"response.file_search_call.completed":{let t=K(e,r.output_index);return t.type==="file_search_call"&&(t.status="completed"),!0}case"response.web_search_call.in_progress":{let t=K(e,r.output_index);return t.type==="web_search_call"&&(t.status="in_progress"),!0}case"response.web_search_call.searching":{let t=K(e,r.output_index);return t.type==="web_search_call"&&(t.status="searching"),!0}case"response.web_search_call.completed":{let t=K(e,r.output_index);return t.type==="web_search_call"&&(t.status="completed"),!0}default:return!1}}function yO(r,e){switch(r.type){case"response.image_generation_call.in_progress":{let t=K(e,r.output_index);return t.type==="image_generation_call"&&(t.status="in_progress"),!0}case"response.image_generation_call.generating":{let t=K(e,r.output_index);return t.type==="image_generation_call"&&(t.status="generating"),!0}case"response.image_generation_call.completed":{let t=K(e,r.output_index);return t.type==="image_generation_call"&&(t.status="completed"),!0}case"response.mcp_call.in_progress":{let t=K(e,r.output_index);return t.type==="mcp_call"&&(t.status="in_progress"),!0}case"response.mcp_call.completed":{let t=K(e,r.output_index);return t.type==="mcp_call"&&(t.status="completed"),!0}case"response.mcp_call.failed":{let t=K(e,r.output_index);return t.type==="mcp_call"&&(t.status="failed"),!0}default:return!1}}function gO(r){switch(r.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 bO(r){switch(r.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 Yo(){return wd()}function wO(r,e,t,n){return rO(r,e,n),!!(aO(r,e,t)||uO(r,e,t)||cO(r,e,t)||dO(r,e,t)||fO(r,e)||pO(r,e)||hO(r,e)||mO(r,e)||_O(r,e)||yO(r,e)||bO(r))}function Gm(r,e,t,n=!1,s){let i=iO(r);if(s&&i.type!=="keepalive"){let o=s(i);if(o===null){if(!e)throw new f("Cannot ignore a response event before response.created.");return e}i=o}if(!e){if(i.type!=="response.created")throw new f(`When snapshot hasn't been set yet, expected 'response.created' event, got ${i.type}`);return Ic(t,i.response)}return wO(i,e,t,n)?e:gO(i)?Ic(t,i.response):Pc(i)}var ye,Sc,Ie,Ec,ut,We,Ut,Qt,Se,Ue,xd,Ym,Zm,Cc,e_,t_,Tc,r_,vd,Id,AO={annotation:!0,annotation_index:!0,arguments:!0,background:!0,code:!0,command:!0,command_index:!0,content_index:!0,delta:!0,input:!0,item:!0,item_id:!0,logprobs:!0,message:!0,obfuscation:!0,output:!0,output_format:!0,output_index:!0,param:!0,part:!0,partial_image_b64:!0,partial_image_index:!0,quality:!0,refusal:!0,response:!0,sequence_number:!0,size:!0,status:!0,summary_index:!0,text:!0,type:!0},kc=class r extends fr{constructor(e){super(),ye.add(this),Sc.set(this,void 0),Ie.set(this,void 0),Ec.set(this,void 0),ut.set(this,Yo()),We.set(this,new Map),Ut.set(this,new Map),Qt.set(this,!1),Se.set(this,new Map),Ue.set(this,new Map),w(this,Sc,e,"f"),this.once("end",()=>{u(this,We,"f").clear(),u(this,Ut,"f").clear(),u(this,Se,"f").clear(),u(this,Ue,"f").clear()})}static createResponse(e,t,n){let{getTextFormat:s,requestOptions:i}=ka(t,n),o=new r(Array.isArray(t.tools)?{tools:t.tools}:{});return o._run(()=>o._createOrRetrieveResponse(e,t,{...i,__metadata:{...i?.__metadata,helperMethod:"stream"}},s)),o}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,n,s=ka(t).getTextFormat){this._listenForAbort(n?.signal),u(this,ye,"m",xd).call(this);let i,o,a=null;if("response_id"in t)o=s({body:t}),i=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null;else{let c={...t,stream:!0},d={body:c},p=null,y=e.responses.create(c,{...n,signal:this.controller.signal});y instanceof $t&&(y=y._thenUnwrap((_,b)=>(d=b.options,p=b.response.body,_))),i=await y;try{o=s(d)}catch(_){throw this.abort(),i.controller.abort(),RO(p),_}}this._connected();for await(let c of i)u(this,ye,"m",vd).call(this,c,a);if(i.controller.signal?.aborted)throw this._userAbortError();return u(this,ye,"m",Id).call(this,o)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),u(this,ye,"m",xd).call(this),this._connected();let n=ze.fromReadableStream(e,this.controller);for await(let s of n)u(this,ye,"m",vd).call(this,s,null);if(n.controller.signal?.aborted)throw this._userAbortError();return u(this,ye,"m",Id).call(this)}[(Sc=new WeakMap,Ie=new WeakMap,Ec=new WeakMap,ut=new WeakMap,We=new WeakMap,Ut=new WeakMap,Qt=new WeakMap,Se=new WeakMap,Ue=new WeakMap,ye=new WeakSet,xd=function(){this.ended||(w(this,Ie,void 0,"f"),w(this,ut,Yo(),"f"),u(this,We,"f").clear(),u(this,Ut,"f").clear(),w(this,Qt,!1,"f"),u(this,Se,"f").clear(),u(this,Ue,"f").clear())},Ym=function(t){if(t.type==="response.created"||t.type==="response.queued"||t.type==="response.in_progress"||t.type==="response.completed"||t.type==="response.failed"||t.type==="response.incomplete"){if(!P(t,"response"))throw new f("Lifecycle events require their own response field.");let{response:n,...s}=t;if(!L(n))throw new f("Lifecycle events require a response object.");let i=structuredClone(n);if(u(this,Ie,"f")&&i.id!==u(this,Ie,"f").id)throw new f("Lifecycle response identity changed.");if(!P(i,"output")||i.output==null){let o;t.type==="response.completed"?o=[...u(this,Se,"f")].sort(([a],[c])=>a-c).map(([,a])=>structuredClone(a)):t.type==="response.failed"||t.type==="response.incomplete"?o=[...u(this,We,"f").keys()].sort((a,c)=>a-c).map(a=>structuredClone(u(this,ye,"m",Cc).call(this,a))):o=[],i={...i,output:o},(t.type==="response.completed"||t.type==="response.failed"||t.type==="response.incomplete")&&Wt(i)}return t.type==="response.completed"&&u(this,ye,"m",e_).call(this,i),{...s,type:t.type,sequence_number:t.sequence_number,response:i}}return u(this,ye,"m",Zm).call(this,t)},Zm=function(t){if(!u(this,Ie,"f")||!P(t,"output_index")||!("output_index"in t))return t;let n=t.output_index;if(!Number.isSafeInteger(n)||n<0)throw new f("Invalid response output index.");let s;if(t.type==="response.output_item.added"){if(t.item==null)return null;if(u(this,Se,"f").has(n)||u(this,Ue,"f").has(n))throw new f(`Duplicate response output index ${n}.`);s=u(this,Ie,"f").output.length}else{let i=u(this,We,"f").get(n);if(i===void 0)throw new f(`missing output at index ${n}`);s=i}return new Proxy(t,{get(i,o){return o==="output_index"?s:Reflect.get(i,o,i)}})},Cc=function(t){let n=u(this,We,"f").get(t);return u(this,Se,"f").get(t)??(n===void 0?void 0:u(this,Ie,"f")?.output[n])},e_=function(t){if(u(this,Ue,"f").size===0&&u(this,Se,"f").size===0)return;let n=new Map((t.output??[]).map(s=>[Ht(s),s]));for(let s of u(this,Se,"f").values()){let i=n.get(Ht(s));i&&$a(s,i,"response.completed")}for(let[s,i]of u(this,Ue,"f")){let o=n.get(i);if(!o)throw new f("Cannot complete response with unfinished output items.");let a=u(this,ye,"m",Cc).call(this,s);if(!a)throw new f("Cannot complete response with a missing output identity.");$a(a,o,"response.completed")}},t_=function(t,n,s){if(t.type==="response.completed"){w(this,Qt,!1,"f");return}if(n!==u(this,Ie,"f")){let i=new Map;for(let[a,c]of u(this,Se,"f"))i.set(Ht(c),a);for(let[a,c]of u(this,Ue,"f"))i.set(c,a);let o=new Map;u(this,Ut,"f").clear();for(let[a,c]of n.output.entries()){let d=Ht(c),y=i.get(d)??a,_=u(this,Se,"f").get(y),b=u(this,Ue,"f").get(y);if(o.has(y)||_&&Ht(_)!==d||b!==void 0&&b!==d)throw new f("Response snapshot has conflicting output positions.");let h=u(this,ye,"m",Cc).call(this,y);h&&$a(h,c,t.type),o.set(y,a),u(this,Ut,"f").set(d,y),_?u(this,Se,"f").set(y,structuredClone(c)):u(this,Ue,"f").set(y,d)}w(this,We,o,"f"),w(this,Qt,!["response.failed","response.incomplete"].includes(t.type),"f"),["response.created","response.queued","response.in_progress"].includes(t.type)&&u(this,ye,"m",Tc).call(this,n);return}if(s!==void 0){if(t.type==="response.output_item.added"&&t.item!=null){u(this,We,"f").set(t.output_index,s);let i=Ht(t.item);u(this,Ue,"f").set(t.output_index,i),u(this,Ut,"f").set(i,t.output_index),w(this,Qt,!0,"f")}else if(t.type==="response.output_item.done"){let i=n.output[s];if(!i)throw new f(`missing output at index ${t.output_index}`);u(this,Se,"f").set(t.output_index,structuredClone(i)),u(this,Ue,"f").delete(t.output_index)}}},Tc=function(t){if(!u(this,Qt,"f"))return;let n=[...u(this,We,"f")];if(n.sort(([s],[i])=>s-i),n.some(([,s],i)=>s!==i)){let s=u(this,ut,"f").canonicalSnapshot===t;t.output=n.map(([,i])=>t.output[i]),w(this,We,new Map(n.map(([i],o)=>[i,o])),"f"),w(this,ut,Yo(),"f"),s&&mt(u(this,ut,"f"),t)}w(this,Qt,!1,"f")},r_=function(t,n){if(!Array.isArray(t.output))return!1;let s=P(t,"output_text")?t.output_text:void 0;if(t.output.length!==0){let a=Ic(Yo(),t),c=[];for(let p of a.output){let y=u(this,Ut,"f").get(Ht(p)),_=y===void 0?void 0:u(this,We,"f").get(y);if(y===void 0||_===void 0)return!1;c.push({wire:y,position:_,item:p})}let d=s==null;d||(u(this,ut,"f").canonicalSnapshot=void 0);for(let{wire:p,position:y,item:_}of c)Pd(u(this,ut,"f"),n,y,_,d),u(this,Se,"f").has(p)&&u(this,Se,"f").set(p,structuredClone(_));u(this,ye,"m",Tc).call(this,n)}let{output:i}=n,o=s;o==null?(mt(u(this,ut,"f"),n),o=n.output_text):u(this,ut,"f").canonicalSnapshot=void 0;for(let a of Object.keys(n))P(t,a)||Reflect.deleteProperty(n,a);return Object.defineProperties(n,Object.getOwnPropertyDescriptors({...t,output:i,output_text:o})),!0},vd=function(t,n){if(this.ended)return;let s=(p,y)=>{(n==null||y.sequence_number>n)&&this._emit(p,y)};if(t.type==="error"){let p="error"in t&&typeof t.error=="object"&&t.error!==null?t.error:t;throw new J(void 0,p,t.message,void 0)}let i=t,o,a=Gm(t,u(this,Ie,"f"),u(this,ut,"f"),!0,p=>{i=p;let y=u(this,ye,"m",Ym).call(this,p);if(y){if(P(y,"output_index")&&"output_index"in y)o=y.output_index;else if(P(y,"response")&&"response"in y&&(i=y,(y.type==="response.created"||y.type==="response.queued"||y.type==="response.in_progress")&&u(this,Ie,"f"))){if(u(this,ye,"m",r_).call(this,y.response,u(this,Ie,"f")))return null;let _=new Set(y.response.output.map(Ht)),b=u(this,Ie,"f").output.filter(h=>!_.has(Ht(h)));if(b.length)return{...y,response:{...y.response,output:[...y.response.output,...b]}}}}return y});if(u(this,ye,"m",t_).call(this,i,a,o),w(this,Ie,a,"f"),i.type==="response.output_item.added"&&i.item==null)return;let c={...i};for(let p of Object.keys(AO)){let y=Object.getOwnPropertyDescriptor(i,p);y&&!y.enumerable&&Object.defineProperty(c,p,{value:Reflect.get(i,p,i),enumerable:!0})}let d=structuredClone(c);switch(s("event",d),c.type){case"response.output_text.delta":{let p=a.output[o??c.output_index];if(!p)throw new f(`missing output at index ${c.output_index}`);if(p.type==="message"){let y=p.content[c.content_index];if(!y)throw new f(`missing content at index ${c.content_index}`);if(y.type!=="output_text")throw new f(`expected content to be 'output_text', got ${y.type}`);s("response.output_text.delta",{...structuredClone(c),snapshot:y.text})}break}case"response.function_call_arguments.delta":{let p=a.output[o??c.output_index];if(!p)throw new f(`missing output at index ${c.output_index}`);p.type==="function_call"&&s("response.function_call_arguments.delta",{...structuredClone(c),snapshot:p.arguments});break}default:{s(c.type,d);break}}},Id=function(t){if(this.ended)throw new f("stream has ended, this shouldn't happen");let n=u(this,Ie,"f");if(!n)throw new f("request ended without sending any events");u(this,ye,"m",Tc).call(this,n),w(this,Ie,void 0,"f"),w(this,ut,Yo(),"f"),u(this,We,"f").clear(),u(this,Ut,"f").clear(),w(this,Qt,!1,"f"),u(this,Se,"f").clear(),u(this,Ue,"f").clear();let s=OO(n,u(this,Sc,"f"),t);return w(this,Ec,s,"f"),s},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=n=>e(n);return this.on("event",t),()=>this.off("event",t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=u(this,Ec,"f");if(!e)throw new f("stream ended without producing a Response");return e}};async function RO(r){try{await dt(r)}catch{}}function Ht(r){return JSON.stringify([r.type,!qa(r)&&P(r,"id")?r.id:null,P(r,"call_id")&&"call_id"in r?r.call_id:null])}function OO(r,e,t){return Bm(r,e,t)}function Da(r,e){return Promise.resolve(r).then(e)}function PO(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var n_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function xO(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>n_.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!n_.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var _t=class extends m{constructor(){super(...arguments),this.inputItems=new Qo(this._client),this.inputTokens=new Ho(this._client)}create(e,t){return this._client.post("/responses",Da(t,n=>PO({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},{streamFromBody:!0})))._thenUnwrap(n=>("object"in n&&n.object==="response"&&Wt(n),n))}retrieve(e,t={},n){let s=xO(t,["include","include_obfuscation","starting_after","stream"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.get(l`/responses/${e}`,Da(n,i=>({query:t,...i,stream:t?.stream??!1,__security:{bearerAuth:!0}})))._thenUnwrap(i=>("object"in i&&i.object==="response"&&Wt(i),i))}delete(e,t){return this._client.delete(l`/responses/${e}`,Da(t,n=>({...n,headers:g([{Accept:"*/*"},n?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,Da(t,n=>({...n,__security:{bearerAuth:!0}})))}compact(e,t){return this._client.post("/responses/compact",Da(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}parse(e,t){let{getTextFormat:n,requestOptions:s}=ka(e,t);return this._client.responses.create(e,s)._thenUnwrap((i,{options:o})=>bd(i,e,n(o)))}stream(e,t){return kc.createResponse(this._client,e,t)}};_t.InputItems=Qo;_t.InputTokens=Ho;function vO(r,e){return Promise.resolve(r).then(e)}var Zo=class extends m{retrieve(e,t){return this._client.get(l`/safety/alerts/${e}`,vO(t,n=>({...n,__security:{bearerAuth:!0}})))}};function SO(r,e){return Promise.resolve(r).then(e)}var ei=class extends m{retrieve(e,t){return this._client.get(l`/safety/cases/${e}`,SO(t,n=>({...n,__security:{bearerAuth:!0}})))}};var Xt=class extends m{constructor(){super(...arguments),this.cases=new ei(this._client),this.alerts=new Zo(this._client)}};Xt.Cases=ei;Xt.Alerts=Zo;function CO(r,e){return Promise.resolve(r).then(e)}var ti=class extends m{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,CO(t,n=>({...n,headers:g([{Accept:"application/binary"},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function kO(r,e){return Promise.resolve(r).then(e)}var ri=class extends m{retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,kO(n,i=>({...i,headers:g([{Accept:"application/binary"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}};function Sd(r,e){return Promise.resolve(r).then(e)}function qO(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var s_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function $O(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>s_.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!s_.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Bn=class extends m{constructor(){super(...arguments),this.content=new ri(this._client)}create(e,t={},n){return this._client.post(l`/skills/${e}/versions`,Ot(qO({body:t,...n,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,Sd(n,i=>({...i,__security:{bearerAuth:!0}})))}list(e,t={},n){let s=$O(t,["after","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/skills/${e}/versions`,I,Sd(n,i=>({query:t,...i,__security:{bearerAuth:!0}})))}delete(e,t,n){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,Sd(n,i=>({...i,__security:{bearerAuth:!0}})))}};Bn.Content=ri;function jc(r,e){return Promise.resolve(r).then(e)}function FO(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var o_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function zO(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>o_.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!o_.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Jt=class extends m{constructor(){super(...arguments),this.content=new ti(this._client),this.versions=new Bn(this._client)}create(e={},t){return this._client.post("/skills",Ot(FO({body:e,...t,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(l`/skills/${e}`,jc(t,n=>({...n,__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/skills/${e}`,jc(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}list(e={},t){let n=zO(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/skills",I,jc(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/skills/${e}`,jc(t,n=>({...n,__security:{bearerAuth:!0}})))}};Jt.Content=ti;Jt.Versions=Bn;function MO(r,e){return Promise.resolve(r).then(e)}var ni=class extends m{create(e,t,n){return this._client.post(l`/uploads/${e}/parts`,MO(n,s=>re({body:t,...s,__security:{bearerAuth:!0}},this._client)))}};function Ed(r,e){return Promise.resolve(r).then(e)}var $r=class extends m{constructor(){super(...arguments),this.parts=new ni(this._client)}create(e,t){return this._client.post("/uploads",Ed(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,Ed(t,n=>({...n,__security:{bearerAuth:!0}})))}complete(e,t,n){return this._client.post(l`/uploads/${e}/complete`,Ed(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}};$r.Parts=ni;function i_(r,e,t,n){return ba(s=>r.retrieve(t,{vector_store_id:e},{...n,headers:s}),["in_progress"],["failed","cancelled","completed"],n)}function a_(r,e,t,n){return ba(s=>r.retrieve(t,{vector_store_id:e},{...n,headers:s}),["in_progress"],["failed","cancelled","completed"],n)}var u_=async r=>{let e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length)throw Object.defineProperty(new Error(`${t.length} promise(s) failed`),"rejections",{configurable:!0,value:t.map(({reason:s})=>s),writable:!0});let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};async function c_(r,e,t,n,s,i){if(n==null||n.length===0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=i?.maxConcurrency??5,a=Math.min(o,n.length);if(a===0)throw new RangeError("maxConcurrency must be greater than 0");let c=n.values(),d=[...s];async function p(_){for(let b of _){let h=await e.files.create({file:b,purpose:"assistants"},i);d.push(h.id)}}let y=[];y.length=a;for(let _=0;_<y.length;_+=1)y[_]=p(c);return await u_(y),await r.createAndPoll(t,{file_ids:d},i)}function qc(r,e){return Promise.resolve(r).then(e)}var si=class extends m{create(e,t,n){return this._client.post(l`/vector_stores/${e}/file_batches`,qc(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,qc(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}cancel(e,t,n){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,qc(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}listFiles(e,t,n){let{vector_store_id:s,...i}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,I,qc(n,o=>({query:i,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}async poll(e,t,n){return await a_(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){return await c_(this,this._client,e,t,n,s)}};function oi(r,e){return Promise.resolve(r).then(e)}var l_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function KO(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>l_.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!l_.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var ii=class extends m{create(e,t,n){return this._client.post(l`/vector_stores/${e}/files`,oi(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t,n){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,oi(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){let{vector_store_id:s,...i}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,oi(n,o=>({body:i,...o,headers:g([{"OpenAI-Beta":"assistants=v2"},o?.headers]),__security:{bearerAuth:!0}})))}list(e,t={},n){let s=KO(t,["after","before","filter","limit","order"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.getAPIList(l`/vector_stores/${e}/files`,I,oi(n,i=>({query:t,...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}delete(e,t,n){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,oi(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}async createAndPoll(e,t,n){let s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){return await i_(this,e,t,n)}async upload(e,t,n){let s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){let s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,be,oi(n,i=>({...i,headers:g([{"OpenAI-Beta":"assistants=v2"},i?.headers]),__security:{bearerAuth:!0}})))}};function ai(r,e){return Promise.resolve(r).then(e)}var d_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function WO(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>d_.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!d_.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Vt=class extends m{constructor(){super(...arguments),this.files=new ii(this._client),this.fileBatches=new si(this._client)}create(e,t){return this._client.post("/vector_stores",ai(t,n=>({body:e,...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,ai(t,n=>({...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}update(e,t,n){return this._client.post(l`/vector_stores/${e}`,ai(n,s=>({body:t,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}list(e={},t){let n=WO(e,["after","before","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/vector_stores",I,ai(t,s=>({query:e,...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,ai(t,n=>({...n,headers:g([{"OpenAI-Beta":"assistants=v2"},n?.headers]),__security:{bearerAuth:!0}})))}search(e,t,n){return this._client.getAPIList(l`/vector_stores/${e}/search`,be,ai(n,s=>({body:t,method:"post",...s,headers:g([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})))}};Vt.Files=ii;Vt.FileBatches=si;function Tt(r,e){return Promise.resolve(r).then(e)}function UO(r,e){return{...r,__metadata:{...r.__metadata,...e}}}var f_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function p_(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>f_.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!f_.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Kn=class extends m{create(e,t){return this._client.post("/videos",Tt(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}retrieve(e,t){return this._client.get(l`/videos/${e}`,Tt(t,n=>({...n,__security:{bearerAuth:!0}})))}list(e={},t){let n=p_(e,["after","limit","order"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/videos",Q,Tt(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/videos/${e}`,Tt(t,n=>({...n,__security:{bearerAuth:!0}})))}createCharacter(e,t){return this._client.post("/videos/characters",Tt(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}downloadContent(e,t={},n){let s=p_(t,["variant"],n);return s!==void 0&&(n=s,t={}),t=t,this._client.get(l`/videos/${e}/content`,Tt(n,i=>({query:t,...i,headers:g([{Accept:"application/binary"},i?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})))}edit(e,t){return this._client.post("/videos/edits",Tt(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}extend(e,t){return this._client.post("/videos/extensions",Tt(t,n=>re({body:e,...n,__security:{bearerAuth:!0}},this._client)))}getCharacter(e,t){return this._client.get(l`/videos/characters/${e}`,Tt(t,n=>({...n,__security:{bearerAuth:!0}})))}remix(e,t,n){return this._client.post(l`/videos/${e}/remix`,Tt(n,s=>Ot(UO({body:t,...s,__security:{bearerAuth:!0}},{finalizeMultipart:!0}),this._client)))}};function QO(r,e){return Promise.resolve(r).then(e)}var ui=class extends m{list(e){return this._client.get("/webhook_event_types",QO(e,t=>({...t,__security:{bearerAuth:!0}})))}};var h_=32,XO=32;function Cd(r){return r.split(" ",h_+1).length>h_}function*Td(r){let e=0;for(;e<=r.length;){let t=r.indexOf(" ",e),n=r.slice(e,t===-1?void 0:t);if(yield n.startsWith("v1,")?n.slice(3):n,t===-1)break;e=t+1}}function m_(r){try{let e=mc(r);return e.byteLength===XO?e:void 0}catch{return}}function JO(r){for(let e of Td(r)){let t=m_(e);if(t)return t}}function VO(r,e,t){let n=t;for(let s of Td(r)){let i=m_(s);if(!i)continue;let o=0;for(let[a,c]of i.entries())o|=c^(e[a]??0);o===0&&(n=i)}return n}async function __(r,e,t,n,s,i){let o=Number.parseInt(t,10);if(Number.isNaN(o))throw new Fe("Invalid webhook timestamp format");let a=Math.floor(Date.now()/1e3);if(a-o>i)throw new Fe("Webhook timestamp is too old");if(o>a+i)throw new Fe("Webhook timestamp is too new");let c=Cd(e),d=c?JO(e):void 0;if(c&&!d)throw new Fe("The given webhook signature does not match the expected signature");let p=Uint8Array.from(s.startsWith("whsec_")?mc(s.slice(6)):ge(s)),y=n?`${n}.${t}.${r}`:`${t}.${r}`,_=Uint8Array.from(ge(y)),b=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,c?["sign","verify"]:["verify"]);if(c&&d){let h=new Uint8Array(await crypto.subtle.sign("HMAC",b,_)),A=VO(e,h,d);try{if(await crypto.subtle.verify("HMAC",b,Uint8Array.from(A),_))return}catch{}throw new Fe("The given webhook signature does not match the expected signature")}for(let h of Td(e))try{let A=Uint8Array.from(mc(h));if(await crypto.subtle.verify("HMAC",b,A,_))return}catch{}throw new Fe("The given webhook signature does not match the expected signature")}var ci,g_,$c;function Nn(r,e){return Promise.resolve(r).then(e)}var y_=new Set(["method","path","query","body","headers","maxRetries","stream","timeout","httpAgent","fetchOptions","signal","idempotencyKey","defaultBaseURL","__metadata","__binaryRequest","__binaryResponse","__streamClass","__streamMode","__security","__synthesizeEventData"]);function GO(r,e,t){if(typeof r!="object"||r===null)return;let n=Object.entries(Object.getOwnPropertyDescriptors(r)).filter(([,o])=>o.enumerable&&(!("value"in o)||o.value!==void 0)),s=n.map(([o])=>o);if(s.some(o=>y_.has(o)&&!e.includes(o))){if(t!==void 0||s.some(o=>!y_.has(o)||e.includes(o)))throw new TypeError("Query parameters and request options must be passed as separate arguments.");if(s.some(o=>!["headers","maxRetries","timeout","signal","idempotencyKey","query"].includes(o)))throw new TypeError("Pass transport overrides in the explicit request options argument.");return Object.fromEntries(n.map(([o,a])=>"value"in a?[o,a.value]:[o,a.get?Reflect.apply(a.get,r,[]):void 0]))}}var Dr=class extends m{constructor(){super(...arguments),ci.add(this),this.eventTypes=new ui(this._client)}create(e,t){return this._client.post("/webhook_endpoints",Nn(t,n=>({body:e,...n,__security:{bearerAuth:!0}})))}retrieve(e,t){return this._client.get(l`/webhook_endpoints/${e}`,Nn(t,n=>({...n,__security:{bearerAuth:!0}})))}update(e,t={},n){return this._client.post(l`/webhook_endpoints/${e}`,Nn(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}list(e={},t){let n=GO(e,["after","limit"],t);return n!==void 0&&(t=n,e={}),e=e,this._client.getAPIList("/webhook_endpoints",I,Nn(t,s=>({query:e,...s,__security:{bearerAuth:!0}})))}delete(e,t){return this._client.delete(l`/webhook_endpoints/${e}`,Nn(t,n=>({...n,__security:{bearerAuth:!0}})))}rotateSecret(e,t={},n){return this._client.post(l`/webhook_endpoints/${e}/rotate_secret`,Nn(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}test(e,t,n){return this._client.post(l`/webhook_endpoints/${e}/test`,Nn(n,s=>({body:t,...s,__security:{bearerAuth:!0}})))}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle?.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");u(this,ci,"m",g_).call(this,n);let i=g([t]).values,o=u(this,ci,"m",$c).call(this,i,"webhook-signature"),a=u(this,ci,"m",$c).call(this,i,"webhook-timestamp"),c=u(this,ci,"m",$c).call(this,i,"webhook-id");if(Cd(o)&&typeof crypto.subtle.sign!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");return await __(e,o,a,c,n,s)}};ci=new WeakSet,g_=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},$c=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};Dr.EventTypes=ui;var Dc=Symbol.for("openai.privateBedrockClient");function Fr(r,e){let t=new URL(r),n=new URL(e),s=t.origin,i=n.origin;if(t.protocol!=="http:"&&t.protocol!=="https:"||n.protocol!=="http:"&&n.protocol!=="https:"||i!==s)throw new f(`Bedrock request origin \`${i}\` does not match the configured base URL origin \`${s}\`.`)}function Fa(r){if(/^[\t ]|[\t ]$/.test(r))throw new TypeError("Bedrock bearer credential contains an invalid HTTP header value.");for(let e of r){let t=e.codePointAt(0)??0;if(t<32&&t!==9||t===127||t>255)throw new TypeError("Bedrock bearer credential contains an invalid HTTP header value.")}}function w_(r,e,t){let n=new Map(Object.entries(e).map(([s,i])=>[s.toLowerCase(),i]));for(let s of t)n.delete(s);for(let[s,i]of Object.entries(r.headers??{}))n.set(s,i);return{...r,headers:Object.fromEntries(n)}}var A_=new WeakMap;var Fc=Symbol.for("openai.realtimeAPIKeyCacheContext"),YO;function R_(r){let e=r[Fc]?.getStore();return e?.client===r?e:void 0}function za(r,e){return e!==null&&Dc in r&&Fa(e),e}async function zc(r,e=!1){let t,n={client:r,commit:()=>t===void 0?r.apiKey:t},s=c=>{t=c},i=()=>r._callApiKey(s),o=r[Fc]??YO;e&&o&&!r[Fc]&&Object.defineProperty(r,Fc,{value:o});let a=await(o?o.run(e?n:void 0,i):i());return{apiKey:t===void 0?r.apiKey:t,isProvider:a,commit:()=>{let c=n.providerKey!==void 0&&t!==void 0&&t!==n.providerKey?za(r,t):void 0,d=n.commit();return c===void 0?za(r,d):c}}}var O_=Symbol.for("openai.node.providerTimeout.v1");function P_(r){return r instanceof se||r instanceof Error&&O_ in r&&r[O_]===!0}var x_=Symbol.for("openai.node.providerDefinitions.v1"),v_=globalThis,I_=v_[x_],S_=I_??new WeakMap;I_||Object.defineProperty(v_,x_,{value:S_});function E_(r){let e=S_.get(r);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var qe,je,Ma,te,Mc,Gt,Ka,La,kd,q_,Ba,Wn,C_,$_;function T_(){if(nf())return!0;let r=globalThis;return typeof r.WorkerGlobalScope=="function"&&r instanceof r.WorkerGlobalScope&&typeof r.WorkerNavigator=="function"&&r.navigator instanceof r.WorkerNavigator&&typeof r.navigator?.userAgent=="string"&&r.navigator.userAgent!=="Cloudflare-Workers"&&r.process?.versions?.node===void 0&&r.Deno===void 0&&r.Bun===void 0&&r.EdgeRuntime===void 0&&r.WebSocketPair===void 0}var ZO="workload-identity-auth",k_=Symbol("inheritedDataResidencySelection"),F=class{constructor(e={}){qe.add(this),Ma.set(this,void 0),te.set(this,void 0),Mc.set(this,void 0),Gt.set(this,void 0),Ka.set(this,!1),La.set(this,new WeakMap),this._apiKeyInvocation=0,this._lastCachedAPIKeyInvocation=0,this.decisions=new En(this),this.completions=new vn(this),this.chat=new _r(this),this.embeddings=new Cn(this),this.files=new kn(this),this.images=new Fn(this),this.contentProvenanceChecks=new Sn(this),this.audio=new st(this),this.moderations=new Mn(this),this.models=new zn(this),this.fineTuning=new ht(this),this.graders=new jr(this),this.vectorStores=new Vt(this),this.safety=new Xt(this),this.webhooks=new Dr(this),this.beta=new Ne(this),this.batches=new cn(this),this.uploads=new $r(this),this.admin=new gr(this),this.responses=new _t(this),this.live=new Et(this),this.realtime=new Ct(this),this.conversations=new Tr(this),this.evals=new kr(this),this.containers=new Cr(this),this.skills=new Jt(this),this.videos=new Kn(this);let{credential:t,options:n}=Bf(e);e=n;let s=sl(e),i=e.provider,{baseURL:o=i?null:_e("OPENAI_BASE_URL"),dataResidency:a,[k_]:c=!1,apiKey:d=i?null:_e("OPENAI_API_KEY")??null,adminAPIKey:p=i?null:_e("OPENAI_ADMIN_KEY")??null,organization:y=i?null:_e("OPENAI_ORG_ID")??null,project:_=i?null:_e("OPENAI_PROJECT_ID")??null,webhookSecret:b=_e("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:h,x509Transport:A,credential:O,...E}=e;if(i){let j=["apiKey","adminAPIKey","workloadIdentity","x509Transport","baseURL","dataResidency"].filter(T=>(T==="workloadIdentity"?h:e[T])!=null);if(j.length)throw new f(`The \`provider\` option cannot be used with ${j.map(T=>`\`${T}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let x=uu(h)?{x509:h,legacy:void 0}:{x509:void 0,legacy:h},q=x.x509,C=q!==void 0,D=i?E_(i):void 0,R={apiKey:d,adminAPIKey:p,organization:y,project:_,webhookSecret:b,workloadIdentity:h,x509Transport:A,provider:i,...E,baseURL:D?.baseURL??s??(o||(C?bf:"https://api.openai.com/v1"))};if(A&&!C)throw new f("An X.509 transport requires an X.509 workload identity.");if(C){if(s!==void 0||c)throw new f("X.509 workload identity does not support data residency selection.");if(e.fetch!==void 0)throw new f("X.509 workload identity does not support a custom fetch implementation.");if(Gn(R.baseURL),Ri(R.fetchOptions),this.fetchWithAuth!==je.prototype.fetchWithAuth||this.fetchWithTimeout!==je.prototype.fetchWithTimeout)throw new f("X.509 workload identity does not support overridden fetch dispatch hooks.")}if(d&&h)throw new f("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!D&&!d&&!p&&!h)throw new f("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!R.dangerouslyAllowBrowser&&T_())throw new f(`It looks like you're running in a browser-like environment.
21
-
22
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
23
- If you understand the risks and have appropriate mitigations in place,
24
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
25
-
26
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
27
-
28
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
29
- `);this.baseURL=R.baseURL,w(this,Ka,s!==void 0||c,"f"),this.timeout=R.timeout??je.DEFAULT_TIMEOUT,this.logger=u(this,qe,"m",$_).call(this,R.logger??console);let v="warn";this.logLevel=v,this.logLevel=Jc(R.logLevel,"ClientOptions.logLevel",this)??Jc(_e("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??v,this.fetchOptions=R.fetchOptions,this.maxRetries=u(this,qe,"m",Ba).call(this,R.maxRetries),this.fetch=R.fetch??pi(),w(this,Ma,of,"f");let S=i||t?void 0:_e("OPENAI_CUSTOM_HEADERS");if(S){let j={};for(let T of S.split(`
30
- `)){let $=T.indexOf(":");$>=0&&(j[T.substring(0,$).trim()]=T.substring($+1).trim())}R.defaultHeaders=g([j,R.defaultHeaders])}if(this._options=R,this._provider=D,q){let j=new Pe(q,A,y,_);this._workloadIdentityAuth=j,w(this,te,j,"f"),w(this,Mc,t,"f"),w(this,Gt,j.fetch(),"f"),this.fetch=u(this,Gt,"f"),Ef(this)}else x.legacy&&(this._workloadIdentityAuth=new nu(x.legacy,this.fetch));this.apiKey=typeof d=="string"?d:null,this.adminAPIKey=p,this.organization=y,this.project=_,this.webhookSecret=b}withOptions(e){let t=sl(e),n=u(this,te,"f"),s={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:u(this,te,"f")?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:n?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:i,provider:o}=Kf(s,e,u(this,Mc,"f"),n!==void 0);t!==void 0&&delete s.baseURL;let a={...s,...e,credential:i,provider:o,[k_]:u(this,Ka,"f")&&t===void 0&&!P(e,"baseURL")&&e.credential===void 0&&!o},c=new this.constructor(a);return o&&new URL(c.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(c._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),c.fetchOptions=e.fetchOptions,c.fetch=e.fetch??pi(),c.organization=e.organization??null,c.project=e.project??null),u(this,te,"f")&&u(c,te,"f")&&this.baseURL===c.baseURL&&u(this,te,"f").matches(u(c,te,"f"))&&(c._workloadIdentityAuth=u(this,te,"f"),w(c,te,u(this,te,"f"),"f"),w(c,Gt,u(this,Gt,"f"),"f")),c}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e,t){let n=A_.get(this);if(n?.baseHeaders)return w_({headers:n.baseHeaders},e,n.removedHeaders??new Set).headers;let s=g([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]);s.nulls.forEach(o=>(t??n?.removedHeaders)?.add(o));let i=Object.fromEntries(s.values);return n&&(n.baseHeaders={...i}),i}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return(u(this,te,"f")??this._workloadIdentityAuth)instanceof Pe&&t.adminAPIKeyAuth&&this.adminAPIKey!==null?await this.adminAPIKeyAuth(e):g([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=u(this,te,"f")??this._workloadIdentityAuth;if(t){if(t instanceof Pe){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==je.prototype.fetchWithAuth||this.fetchWithTimeout!==je.prototype.fetchWithTimeout))throw new f("X.509 workload identity does not support overridden fetch dispatch hooks.");let i=t.headerSnapshots();if(!Pe.shouldAuthenticate(e,i.defaultHeaders,i.requestHeaders))return}let s=t instanceof Pe?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken();return g([{Authorization:`Bearer ${s}`}])}let{apiKey:n}=await zc(this);if(n!=null)return g([{Authorization:`Bearer ${n}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return g([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return yf(e)}getUserAgent(){return`${this.constructor.name}/JS ${lr}`}defaultIdempotencyKey(){return`stainless-node-retry-${De()}`}makeStatusError(e,t,n,s){let i=t&&typeof t=="object"&&t.error==null?{error:t}:t;return J.generate(e,i,n,s)}_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=R_(this),s=++this._apiKeyInvocation,i;try{i=await t()}catch(d){throw d instanceof f?d:new f(`Failed to get token from 'apiKey' function: ${d.message}`,{cause:d})}if(typeof i!="string"||!i)throw new f(`Expected 'apiKey' function argument to return a string but it returned ${i}`);let o=i,a=()=>{if(e&&za(this,o),s<this._lastCachedAPIKeyInvocation)return o;this.apiKey=o;let d=e?this.apiKey:o;return this._lastCachedAPIKeyInvocation=s,d};n&&(n.providerKey=o,n.commit=a);let c=n?za(this,o):a();return e?.(c),!0}buildURL(e,t,n){let s=!u(this,qe,"m",q_).call(this)&&n||this.baseURL,i,o={},a;if(Md(e))i=new URL(e);else if(s.includes("?")){let y=new URL(s);a=new URLSearchParams(y.search),o=Object.fromEntries(a),y.search="",y.hash="",i=new URL(y.toString()+(y.pathname.endsWith("/")&&e.startsWith("/")?e.slice(1):e))}else i=new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e));let c=this.defaultQuery(),d=Object.fromEntries(i.searchParams),p;if((!Wa(o)||!Wa(c)||!Wa(d))&&(p={...d,...c,...t},t={...o,...p}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t),a&&p)){let y=new Set,_=new Set;for(let b of a.keys())y.has(b)&&!P(p,b)&&_.add(b),y.add(b);if(_.size){let b=new URLSearchParams;for(let[h,A]of i.searchParams)_.has(h)||b.append(h,A);for(let[h,A]of a)_.has(h)&&b.append(h,A);i.search=b.toString()}}return i.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(s=>({method:e,path:t,...s})))}request(e,t=null){let n=u(this,te,"f")??this._workloadIdentityAuth,s=n instanceof Pe?Promise.resolve(e).then(i=>n.runRequest(()=>this.makeRequest(i,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(s)}responsePromise(e,t=(n,s)=>this.parseResponseWithTimeout(n,s)){let n=new $t(this,e,(s,i)=>{let o=u(this,La,"f").get(i.controller)?.continueRequest;return o?o(()=>t(s,i)):t(s,i)});return n.withResponse=async()=>{let s=await n,{response:i}=await e;return{data:s,response:i,request_id:i.headers.get("x-request-id")}},n._thenUnwrap=s=>this.responsePromise(e,async(i,o)=>gi(s(await t(i,o),o),o.response)),n}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||t.response.status===204||t.response.headers.get("content-length")==="0")return Kr(e,t);for(;;){let n=u(this,La,"f").get(t.controller),s=n?.timeout??t.options.timeout??this.timeout,i=n?.authentication,o=i?t.controller.signal:t.options.signal,a=()=>i&&o?this._makeUserAbortError(o):new Y,c;try{c=i?.remainingTimeout(t.options,s)??Math.max(0,t.startTime+s-Date.now())}catch(_){let b=o?.aborted?a():void 0;throw t.controller.abort(),dt(t.response.body).catch(()=>{}),b??_}let d,p,y=!1;try{if(o?.aborted&&n?.helperMethod!=="runTools")throw a();let _=new Promise((b,h)=>{d=setTimeout(()=>{y=!0,t.controller.abort(),h(new se)},c),o&&(p=()=>{y||h(a())},o.addEventListener("abort",p,{once:!0}))});return await Promise.race([Kr(e,t),_])}catch(_){if(o?.aborted&&!y)throw a();if(!y)throw i&&_ instanceof SyntaxError?new SyntaxError("X.509 workload identity API response contains invalid JSON."):i&&!(_ instanceof f)?new Je({message:"X.509 workload identity API response body could not be read."}):_;let b=n?.retriesRemaining??0;if(!b||n?.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 se;d!==void 0&&clearTimeout(d),p&&o?.removeEventListener("abort",p),p=void 0;let h=await this.retryRequest(t.options,b,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,h)}finally{d!==void 0&&clearTimeout(d),p&&o?.removeEventListener("abort",p)}}}async readX509ResponseError(e,t,n,s,i){let o=new AbortController,a=s.signal,c=!1,d=()=>o.abort(a.reason);a.addEventListener("abort",d,{once:!0}),a.aborted&&d();try{let p=i.remainingTimeout(t,n),y=i.waitForRetry(p,o.signal).then(()=>{throw new se}),_=await Promise.race([e.text().catch(()=>"X.509 workload identity API response body could not be read."),y]);if(a.aborted)throw this._makeUserAbortError(a);return _}catch(p){throw p instanceof se&&(c=!a.aborted,s.abort(),dt(e.body).catch(()=>{})),a.aborted&&!c?this._makeUserAbortError(a):p}finally{a.removeEventListener("abort",d),o.abort()}}async makeRequest(e,t,n){let s=await e,i=u(this,qe,"m",Ba).call(this,s.maxRetries??this.maxRetries);t==null?t=i:t=Math.min(u(this,qe,"m",Ba).call(this,t),i);let o=u(this,te,"f");o?.beginRequestPreparation(),await this.prepareOptions(s),o?.beginRequestPlanning();let a;try{let $=await this.buildRequest(s,{retryCount:i-t});if(a={req:$.req,url:$.url,timeout:$.timeout},o){Uc("timeout",a.timeout),o.authorizePlannedRequest(a.url,a.req,a.timeout),Pe.isStreamingRequestBody(a.req.body)&&(s.__metadata={...s.__metadata,hasStreamingBody:!0}),await this.prepareRequest(a.req,{url:a.url,options:s}),await this._provider?.prepareRequest?.(a.req,{url:a.url,options:s,timeout:a.timeout}),o.beginRequestPlanning(),o.authorizePlannedRequest(a.url,a.req,a.timeout,!0),Pe.isStreamingRequestBody(a.req.body)&&(s.__metadata={...s.__metadata,hasStreamingBody:!0});let k=o.requestSnapshot().signal;if(k?.aborted||a.req.signal?.aborted)throw this._makeUserAbortError(k?.aborted?k:a.req.signal);o.setEffectiveSignal(a.req.signal||k?j_(a.req.signal??k,k).signal:void 0),o.beginRequestNetwork();let z=s.__security??{bearerAuth:!0},N=await this.authHeaders(s,z),H=o.headerSnapshots(),M=g([H.defaultHeaders,H.requestHeaders]);for(let[ne,V]of N?.values??[])!M.nulls.has(ne)&&!a.req.headers.has(ne)&&a.req.headers.set(ne,V);this.validateHeaders(g([M,a.req.headers]),z)}}catch($){if(o?.retireRequestBody(),o&&t&&!s.__metadata?.hasStreamingBody&&Pe.isRetryableFailure($))return await this.retryRequest(s,t,n??"x509-token-exchange",Pe.retryHeaders($));throw $}let{req:c,url:d}=a,p=o?Math.min(a.timeout,o.requestSnapshot().timeout):a.timeout;o?.bindRequest(s,c,this.adminAPIKey);let y=s.__metadata?.hasStreamingBody===!0,_,b;if(!o){await this.prepareRequest(c,{url:d,options:s}),this._provider?.timeoutIncludesAuth&&(_={wallTime:Date.now(),monotonicTime:performance.now()});try{await this._provider?.prepareRequest?.(c,{url:d,options:s,timeout:p})}catch($){if(!_||!P_($))throw $;b=$}}o?.adoptRequestHeaders(c),o&&Pe.isStreamingRequestBody(c.body)&&(y=!0);let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),A=n===void 0?"":`, retryOf: ${n}`,O=o?.requestStartedAt(s)??_?.wallTime??Date.now();if(this.logLevel==="debug"){let $=typeof c.body=="string"?{type:"string",length:c.body.length}:c.body;ue(this).debug(`[${h}] sending request`,qt({retryOfRequestLogID:n,method:s.method,url:d,options:o?{body:$,...o.requestSnapshot()}:{...s,body:$},headers:c.headers}))}let E=o?o.requestSnapshot().signal:s.signal;if(E?.aborted||c.signal?.aborted)throw this._makeUserAbortError(E?.aborted?E:c.signal);let x=s.__security??{bearerAuth:!0},q=o||this.fetchWithTimeout===je.prototype.fetchWithTimeout?j_(c.signal??(o?E:void 0),o?E:void 0):new AbortController,C=o?.remainingTimeout(s,p)??(_?p-(performance.now()-_.monotonicTime):p);_&&C<=0&&(b??(b=new se));let D=o?je.prototype.fetchWithAuth:this.fetchWithAuth;o?.releaseRequestBody(c.body);let R=b??await D.call(this,d,c,C,q,x).catch(li),v=Date.now();if(R instanceof globalThis.Error){let $=`retrying, ${t} attempts remaining`;if(E?.aborted||c.signal?.aborted)throw this._makeUserAbortError(E?.aborted?E:c.signal);let k=jt(R)||/timed? ?out/i.test(String(R)+("cause"in R?String(R.cause):""));if(t&&!y&&(!o||ou(R)))return ue(this).info(`[${h}] connection ${k?"timed out":"failed"} - ${$}`),ue(this).debug(`[${h}] connection ${k?"timed out":"failed"} (${$})`,qt({retryOfRequestLogID:n,url:d,durationMs:v-O,message:o?"X.509 workload identity API connection failed.":R.message})),this.retryRequest(s,t,n??h,void 0,c.signal);let z=y?"error; streaming body cannot be retried":"error; no more retries left";if(ue(this).info(`[${h}] connection ${k?"timed out":"failed"} - ${z}`),ue(this).debug(`[${h}] connection ${k?"timed out":"failed"} (${z})`,qt({retryOfRequestLogID:n,url:d,durationMs:v-O,message:o?"X.509 workload identity API connection failed.":R.message})),R instanceof Ve||R instanceof Mr)throw R;if(k){let N="cause"in R?R.cause:void 0,M=typeof N=="object"&&N!==null&&"code"in N&&N.code==="UND_ERR_HEADERS_TIMEOUT"?new se({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 se;throw o?new se:Object.assign(M,{cause:R})}throw o?new Je({message:"X.509 workload identity API connection failed."}):new Je({message:eP(R),cause:R})}let S=[...R.headers.entries()].filter(([$])=>$==="x-request-id").map(([$,k])=>", "+$+": "+JSON.stringify(k)).join(""),j=`[${h}${A}${S}] ${c.method} ${Ja(d)} ${R.ok?"succeeded":"failed"} with status ${R.status} in ${v-O}ms`;if(!R.ok){let $=R.status===401&&o&&x.bearerAuth&&o.usedWorkloadToken(s);if($&&o.invalidateToken(),R.status===401&&(o||this._workloadIdentityAuth)&&x.bearerAuth&&(!o||o.usedWorkloadToken(s))&&(!o||t>0)&&!y&&!s.__metadata?.workloadIdentityTokenRefreshed){o?dt(R.body).catch(()=>{}):(await dt(R.body),this._workloadIdentityAuth?.invalidateToken());let V={...s,__metadata:{...s.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(V,o?t-1:t,n??h)}let k=$&&s.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(R);if(t&&k&&!y){let V=`retrying, ${t} attempts remaining`;return o?dt(R.body).catch(()=>{}):await dt(R.body),ue(this).info(`${j} - ${V}`),ue(this).debug(`[${h}] response error (${V})`,qt({retryOfRequestLogID:n,url:R.url,status:R.status,headers:R.headers,durationMs:v-O})),this.retryRequest(s,t,n??h,R.headers,c.signal)}let z=k?y?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";ue(this).info(`${j} - ${z}`);let N=o?await this.readX509ResponseError(R,s,p,q,o):await R.text().catch(V=>li(V).message),H=Bd(N),M=H?void 0:N;throw ue(this).debug(`[${h}] response error (${z})`,qt({retryOfRequestLogID:n,url:R.url,status:R.status,headers:R.headers,message:M,durationMs:Date.now()-O})),this.makeStatusError(R.status,H,M,R.headers)}ue(this).info(j),ue(this).debug(`[${h}] response start`,qt({retryOfRequestLogID:n,url:R.url,status:R.status,headers:R.headers,durationMs:v-O}));let T=o?.continuation();return o?.releaseRequestCredentials(),u(this,La,"f").set(q,{timeout:p,retriesRemaining:t,hasStreamingBody:y,...o?{authentication:o}:{},helperMethod:s.__metadata?.helperMethod,...T?{continueRequest:T}:{}}),{response:R,options:s,controller:q,requestSignal:c.signal,requestLogID:h,retryOfRequestLogID:n,startTime:O}}getAPIList(e,t,n){return this.requestAPIList(t,n&&"then"in n?n.then(s=>({method:"get",path:e,...s})):{method:"get",path:e,...n})}requestAPIList(e,t){let n=u(this,te,"f")??this._workloadIdentityAuth,s=n instanceof Pe?Promise.resolve(t).then(a=>n.runRequest(()=>this.makeRequest(a,null,void 0),this)):this.makeRequest(t,null,void 0),i=new Ai(this,s,e),o=this.responsePromise(s,async(a,c)=>{let d=await this.parseResponseWithTimeout(a,c);return new e(a,c.response,d,c.options)});return i.then=o.then.bind(o),i.catch=o.catch.bind(o),i.finally=o.finally.bind(o),i.withResponse=o.withResponse.bind(o),i._thenUnwrap=o._thenUnwrap.bind(o),i}async fetchWithAuth(e,t,n,s,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!u(this,Gt,"f")&&i.bearerAuth){let c=t.headers;if(c.get("Authorization")===`Bearer ${ZO}`){let p=await this._workloadIdentityAuth.getToken();c.set("Authorization",`Bearer ${p}`)}}return await(u(this,Gt,"f")?je.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,n,s)}async fetchWithTimeout(e,t,n,s){let{signal:i,method:o,...a}=t||{},c=this._makeAbort(s),d=!!i&&D_.get(s)===i,p=i&&!d?Nd(i,c,s.signal):void 0,y=setTimeout(c,n),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,b={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};o&&(b.method=o.toUpperCase());try{let h=await(u(this,Gt,"f")??this.fetch).call(void 0,e,b);return p&&Qc(h.body??h,c,s.signal),h}catch(h){throw p?.(),h}finally{clearTimeout(y)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,s,i=e.signal){let o,a=s?.get("retry-after-ms");if(a){let p=parseFloat(a);Number.isNaN(p)||(o=p)}let c=s?.get("retry-after");if(c&&o===void 0){let p=parseFloat(c);Number.isNaN(p)?o=Date.parse(c)-Date.now():o=p*1e3}if(o===void 0||!Number.isFinite(o)||o<0||o>60*1e3){let p=u(this,qe,"m",Ba).call(this,e.maxRetries??this.maxRetries);o=this.calculateDefaultRetryTimeoutMillis(t,p)}let d=u(this,te,"f");if(d){let p=d.remainingTimeout(e,d.requestSnapshot().timeout);if(o>=p)throw new se}if(d)await d.waitForRetry(o,d.effectiveSignal());else{let p=i===e.signal?[i]:[i,e.signal];try{await Xn(o,...p)}catch(y){let _=p.find(b=>b?.aborted);throw _?this._makeUserAbortError(_):y}}return this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}async buildRequest(e,{retryCount:t=0}={}){if(u(this,te,"f")&&!u(this,te,"f").inRequest(this)){let H=u(this,te,"f");return await H.runRequest(async()=>{let M=await je.prototype.buildRequest.call(this,e,{retryCount:t});return H.releaseRequestBody(M.req.body),M},this)}let n={...e},s=u(this,te,"f"),i=s?.snapshotTenant(this.organization,this.project),o=s?.snapshotHeaders(this._options.defaultHeaders,n.headers);o&&(n.headers=o.requestHeaders);let a=s?dl(this.fetchOptions):void 0,c=s?dl(n.fetchOptions):void 0,{method:d,path:p,query:y,defaultBaseURL:_}=n,b=this.buildURL(p,y,_);s?.snapshotAPIURL(b);let h="timeout"in n;if(h&&Uc("timeout",n.timeout),n.timeout=n.timeout??this.timeout,s&&c&&s.snapshotRequest(n.signal,n.timeout,c),s){let H=s.requestSnapshot();n.timeout=H.timeout,H.signal===void 0?delete n.signal:n.signal=H.signal}let A=this._provider||s?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0});if(n.__metadata?.finalizeMultipart===!0&&Pi(n.body)){let H=g([n.headers]);H.values.delete("content-type"),H.nulls.delete("content-type");let M=await Ot({...n,headers:H},this,n.__metadata?.preserveMultipartFilenames===!0?{stripFilenames:!1}:void 0);e.body=n.body=M.body,n.headers=M.headers,e.__metadata=n.__metadata={...M.__metadata,finalizedMultipart:{body:M.body,contentType:g([M.headers]).values.get("content-type")}}}n.__metadata?.streamFromBody===!0&&(Jf(n),e.stream=n.stream);let O=JSON.isRawJSON,E,x=!1,q=!1,C=!1,D=n.__metadata?.streamFromBody===!0&&typeof n.body=="object"&&n.body!==null?eu(n.body,{value(H,M,ne){if(!x)x=!0,E=ne;else if(H===E&&M==="stream"){if(q=ne===!0,O?.(ne))q=ne.rawJSON==="true";else if(ne!==null&&typeof ne=="object")try{q=Boolean.prototype.valueOf.call(ne)}catch{}}},complete(){C=!0}}):void 0,R;try{R=this.buildBody({options:n})}finally{D?.()}let{bodyHeaders:v,body:S,isStreamingBody:j}=R,T=n.__metadata?.captureResponseParser;typeof T=="function"&&T(n),n.__metadata?.streamFromBody===!0&&(S instanceof FormData?e.stream=n.stream=S.get("stream")==="true":C&&E!==null&&typeof E=="object"&&!Array.isArray(E)&&!O?.(E)&&(e.stream=n.stream=q)),j&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},s?.ownRequestBody(S,n.body));let $,k=n.__metadata?.finalizedMultipart;if(typeof k=="object"&&k!==null&&"body"in k&&"contentType"in k){let{body:H,contentType:M}=k;H===S&&(typeof M=="string"?$=M:M===null&&($=null))}let z=await this.buildHeaders({options:e,method:d,bodyHeaders:v,authenticationHeaders:A,retryCount:t,x509Headers:o,x509Timeout:h?n.timeout:void 0,x509Tenant:i});return $===null?z.delete("content-type"):$!==void 0&&z.set("content-type",$),{req:{method:d,headers:z,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&S instanceof globalThis.ReadableStream&&{duplex:"half"},...S&&{body:S},...(s?a:this.fetchOptions)??{},...(s?c:n.fetchOptions)??{}},url:b,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,authenticationHeaders:s,retryCount:i,x509Headers:o,x509Timeout:a,x509Tenant:c}){let d={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),d[this.idempotencyHeader]=e.idempotencyKey);let p=e.__metadata?.helperMethod,y=o?a:e.timeout,_=g([d,{Accept:"application/json",...T_()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(i),...y?{"X-Stainless-Timeout":String(Math.trunc(y/1e3))}:{},...sf(),...typeof p=="string"?{"X-Stainless-Helper-Method":p}:{},"OpenAI-Organization":c?c.organization:this.organization,"OpenAI-Project":c?c.project:this.project},u(this,te,"f")&&!u(this,te,"f").isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):s,o?.defaultHeaders??this._options.defaultHeaders,n,o?.requestHeaders??e.headers]);return!this._provider&&!u(this,te,"f")?.isPlanningRequest()&&this.validateHeaders(_,e.__security??{bearerAuth:!0}),_.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new Y;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&"body"in e?{...u(this,Ma,"f").call(this,{body:t,headers:g([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let s=g([n]),i=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,o=!i&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&s.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!o}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:hi(t),isStreamingBody:!0}:typeof t=="object"&&s.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...u(this,Ma,"f").call(this,{body:t,headers:s}),isStreamingBody:!1}}};je=F,Ma=new WeakMap,te=new WeakMap,Mc=new WeakMap,Gt=new WeakMap,Ka=new WeakMap,La=new WeakMap,qe=new WeakSet,q_=function(){return u(this,Ka,"f")||this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"},Ba=function(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:2},Wn=function(e){let t=e.replace(/[^a-z0-9]/gi,"").toLowerCase();if(/authorization|authentication|cookie|session|signature|assertion|connectionstring|devicecode|codeverifier|accountkey|mtlskey|proxyauth|^(?:auth|key|sig|sas|jwt|bearer|pfx|p12)$|(?:sid|token|secret|password|passwd|pwd|credential|passphrase|apikey|accesskey|privatekey|username)s?$/.test(t))return!0;let n=/api|access|secret|private|security|refresh|id|bearer|aws|azure|openai|admin|client|proxy|auth/.exec(t);return n!==null&&/key|token|secret|password|passwd|pwd|credential|auth/.test(t.slice(n.index+n[0].length))},C_=function(e,t){let i=b=>b.replace(/(\/\/)([^/\s?#]*@)(?=[^/\s?#]+)/g,"$1[REDACTED]@").replace(/(^|[\s/])([^/\s]+)/g,(h,A,O)=>{let E=A==="/"?O.search(/[=(]/)+1:0;if(A==="/"&&E===0)return h;let x=O.indexOf(":",E+1),q=O.length-2;for(;q>=0&&(O[q]!=="@"||O[q+1]==="@");)q--;return x>=0&&q>x?`${A}${O.slice(0,E)}[REDACTED]${O.slice(q)}`:h}).replace(/(^|[\s,;])([a-z][a-z0-9_-]*)(\s*:\s*)([^\r\n,;]+)/gi,(h,A,O,E)=>u(this,qe,"m",Wn).call(this,O)?`${A}${O}${E}[REDACTED]`:h).replace(/(^|[?&#;])([^=&;\s?#/]+)=([^&;\s#]+)/g,(h,A,O)=>{let E=O;try{E=globalThis.decodeURIComponent(O)}catch{}return u(this,qe,"m",Wn).call(this,E)?`${A}${O}=[REDACTED]`:h}),o=b=>{try{return globalThis.String.prototype.valueOf.call(b)}catch{return}},a=b=>{let h=o(b);if(h!==void 0)return u(this,qe,"m",Wn).call(this,h);try{return b instanceof globalThis.String}catch{return!0}},c=[],d=[],p,y=(b,h)=>{try{return{descriptor:globalThis.Object.getOwnPropertyDescriptor(b,h),failed:!1}}catch{return{descriptor:void 0,failed:!0}}},_=(b,h,A)=>{if(h>64||c.length>=4096){A("[REDACTED]");return}c.push({value:b,depth:h,assign:A})};_(e,0,b=>{p=b});for(let b=0;b<c.length;b+=1){let{value:h,depth:A,assign:O}=c[b];if(typeof h=="string"){O(i(h));continue}if(typeof h=="function"||typeof h=="symbol"){O("[REDACTED]");continue}if(typeof h!="object"||h===null){O(h);continue}let E=t.get(h);if(E!==void 0){O(E);continue}try{let x=o(h);if(x!==void 0){let v=new globalThis.String(i(x));t.set(h,v),O(v);continue}if(h instanceof globalThis.String){t.set(h,"[REDACTED]"),O("[REDACTED]");continue}let q=globalThis.Headers;if(typeof q=="function"&&h instanceof q){let v=new q;t.set(h,v),O(v),q.prototype.forEach.call(h,(S,j)=>{v.set(j,u(this,qe,"m",Wn).call(this,j)?"[REDACTED]":i(S))});continue}if(h instanceof URL){let v=new URL(URL.prototype.toString.call(h));t.set(h,v),O(v),v.username&&(v.username="[REDACTED]"),v.password&&(v.password="[REDACTED]");for(let[S]of v.searchParams)u(this,qe,"m",Wn).call(this,S)&&v.searchParams.set(S,"[REDACTED]");v.hash&&(v.hash=i(v.hash));continue}if(Array.isArray(h)){let v=y(h,"length");if(v.failed||!v.descriptor||!("value"in v.descriptor)||typeof v.descriptor.value!="number"){t.set(h,"[REDACTED]"),O("[REDACTED]");continue}let S=[];t.set(h,S),O(S);let j=Math.min(v.descriptor.value,4096),T=y(h,"0"),$=!T.failed&&T.descriptor&&"value"in T.descriptor?T.descriptor.value:void 0;for(let k=0;k<j;k+=1){let z=k===0?T:y(h,`${k}`);if(z.failed){S[k]="[REDACTED]";continue}let N=z.descriptor;if(N?.enumerable){if(k===1&&(T.failed||T.descriptor&&!("value"in T.descriptor)||a($))){S[k]="[REDACTED]";continue}if(!("value"in N)){S[k]="[REDACTED]";continue}_(N.value,A+1,H=>{S[k]=H})}}S.length=j,v.descriptor.value>j&&(S[j]="[REDACTED]");continue}if(h instanceof globalThis.Map){let v=new globalThis.Map,S=[];d.push({map:v,entries:S}),t.set(h,v),O(v),globalThis.Map.prototype.forEach.call(h,(j,T)=>{let $=["[REDACTED]","[REDACTED]"];S.push($),_(T,A+1,k=>{typeof k!="function"&&typeof k!="symbol"&&!(typeof T=="object"&&T!==null&&k===T)&&($[0]=k)}),!a(T)&&_(j,A+1,k=>{$[1]=k})});continue}if(h instanceof globalThis.Set){let v=new globalThis.Set;t.set(h,v),O(v),globalThis.Set.prototype.forEach.call(h,S=>{_(S,A+1,j=>{v.add(j)})});continue}if(h instanceof globalThis.Date){O(new globalThis.Date(globalThis.Date.prototype.getTime.call(h)));continue}let C=globalThis.ReadableStream;if(typeof C=="function"&&h instanceof C||h instanceof globalThis.ArrayBuffer||globalThis.ArrayBuffer.isView(h)){t.set(h,"[REDACTED]"),O("[REDACTED]");continue}let D;try{D=globalThis.Reflect.ownKeys(h)}catch{t.set(h,"[REDACTED]"),O("[REDACTED]");continue}let R={};t.set(h,R),O(R);for(let v of D){if(typeof v!="string")continue;let S=y(h,v);if(S.failed){R[v]="[REDACTED]";continue}let j=S.descriptor;if(j?.enumerable){if(u(this,qe,"m",Wn).call(this,v)){R[v]="[REDACTED]";continue}if(!("value"in j)){R[v]="[REDACTED]";continue}_(j.value,A+1,T=>{R[v]=T})}}}catch{t.set(h,"[REDACTED]"),O("[REDACTED]")}}for(let{map:b,entries:h}of d)for(let[A,O]of h)b.set(A,O);return p},$_=function(e){if(u(je,je,"f",kd).has(e))return e;let t=new globalThis.Proxy(Object.create(null),{get:(n,s)=>{let i=globalThis.Reflect.get(e,s,e);return typeof i!="function"?i:typeof s!="string"||!["debug","info","warn","error","trace","log"].includes(s)?i.bind(e):(...o)=>{let a=new WeakMap;return globalThis.Reflect.apply(i,e,o.map(c=>u(this,qe,"m",C_).call(this,c,a)))}},set:(n,s,i)=>globalThis.Reflect.set(e,s,i,e)});return u(je,je,"f",kd).add(t),t};kd={value:new globalThis.WeakSet};F.OpenAI=je;F.DEFAULT_TIMEOUT=6e5;F.OpenAIError=f;F.APIError=J;F.APIConnectionError=Je;F.APIConnectionTimeoutError=se;F.APIUserAbortError=Y;F.NotFoundError=nr;F.ConflictError=sr;F.RateLimitError=ir;F.BadRequestError=bt;F.AuthenticationError=tr;F.InternalServerError=ar;F.PermissionDeniedError=rr;F.UnprocessableEntityError=or;F.InvalidWebhookSignatureError=Fe;F.toFile=pu;F.toStreamingFile=lu;F.Decisions=En;F.Completions=vn;F.Chat=_r;F.Embeddings=Cn;F.Files=kn;F.Images=Fn;F.ContentProvenanceChecks=Sn;F.Audio=st;F.Moderations=Mn;F.Models=zn;F.FineTuning=ht;F.Graders=jr;F.VectorStores=Vt;F.Safety=Xt;F.Webhooks=Dr;F.Beta=Ne;F.Batches=cn;F.Uploads=$r;F.Admin=gr;F.Responses=_t;F.Live=Et;F.Realtime=Ct;F.Conversations=Tr;F.Evals=kr;F.Containers=Cr;F.Skills=Jt;F.Videos=Kn;F.ConversationCursorPage=Q;F.CursorPage=I;F.NextCursorPage=ie;F.Page=be;F.TokenPage=Vn;var D_=new WeakMap;function j_(r,e){let t=new AbortController;if(!r)return t;let n=globalThis.AbortSignal;if(typeof n?.any!="function"||!(r instanceof n))return t;try{let s=[t.signal,r];e&&e!==r&&s.push(e);let i=n.any(s);Object.defineProperty(t,"signal",{value:i,configurable:!0}),D_.set(t,r)}catch{}return t}function eP(r){if(tP(r))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 tP(r){let e=r;for(let t=0;t<8&&e&&typeof e=="object";t++){let n=e;if(n.code==="UND_ERR_INVALID_ARG"&&typeof n.message=="string"&&n.message.includes("invalid onRequestStart method"))return!0;e=n.cause}return!1}function jd(r){let e=[];for(let t of r){let n=rP(t);n&&e.push(n)}return e}function rP(r){switch(r.type){case"message":{if(r.role!=="assistant"||!("id"in r)||!Array.isArray(r.content))return zr(r);let e=r.content.map(t=>{if((t.type==="output_text"||t.type==="refusal")&&"parsed"in t){let{parsed:n,...s}=t;return s}return t});return e.every((t,n)=>t===r.content[n])?zr(r):{...zr(r),content:e}}case"function_call":{let e=zr(r);if(!("parsed_arguments"in e))return e;let{parsed_arguments:t,...n}=e;return n}case"additional_tools":return r.role!=="developer"?null:zr(r);case"shell_call_output":{let e=r.output.map(t=>zr(t));return{...zr(r),output:e}}case"computer_call_output":{let{created_by:e,...t}=r;return t.status==="failed"?null:t}case"custom_tool_call_output":{if("status"in r&&r.status!=="completed")return null;let{created_by:e,status:t,...n}=r;return n}case"apply_patch_call":case"apply_patch_call_output":case"code_interpreter_call":case"compaction":case"compaction_trigger":case"computer_call":case"configuration_update":case"custom_tool_call":case"file_search_call":case"function_call_output":case"image_generation_call":case"item_reference":case"local_shell_call":case"local_shell_call_output":case"mcp_approval_request":case"mcp_approval_response":case"mcp_call":case"mcp_list_tools":case"program":case"program_output":case"reasoning":case"shell_call":case"tool_search_call":case"tool_search_output":case"web_search_call":case null:case void 0:return zr(r);default:return nP(r)}}function zr(r){if(!("created_by"in r))return r;let{created_by:e,...t}=r;return t}function nP(r){let e=r.type;throw new TypeError(`Unsupported response item type: ${String(e)}`)}async function sP(r){try{await r}catch{}}function Yt(r,e,t,n){if(r)try{let s=null;if(n){let{input_tokens:o,output_tokens:a,total_tokens:c}=n;Number.isSafeInteger(o)&&o>=0&&Number.isSafeInteger(a)&&a>=0&&Number.isSafeInteger(c)&&c>=0&&(s={input_tokens:o,output_tokens:a,total_tokens:c})}let i=r({...e,call_id:e.call_id??null,member:e.member??null,duration_ms:Math.max(0,performance.now()-t),usage:s});sP(i)}catch{}}function Lc(r,e){if(!r)return e;let t=Object.create(Object.getPrototypeOf(r)),n=new Set;return new Proxy(t,{ownKeys(s){if(!Reflect.isExtensible(s))return Reflect.ownKeys(s);let i=[...Reflect.ownKeys(r),...Reflect.ownKeys(e)].filter(o=>!n.has(o));return[...new Set([...i,...Reflect.ownKeys(s)])]},getOwnPropertyDescriptor(s,i){let o=Object.getOwnPropertyDescriptor(s,i);if(o||n.has(i)||!Reflect.isExtensible(s))return o;let a=Object.getOwnPropertyDescriptor(P(e,i)?e:r,i);return a?{...a,configurable:!0}:void 0},get(s,i,o){return P(s,i)?Reflect.get(s,i,o):n.has(i)||!Reflect.isExtensible(s)?Reflect.get(s,i,r):P(e,i)?Reflect.get(e,i,e):Reflect.get(r,i,r)},set(s,i,o,a){return P(s,i)?Reflect.set(s,i,o,a):Reflect.defineProperty(s,i,{value:o,writable:!0,enumerable:!0,configurable:!0})},deleteProperty(s,i){return Reflect.deleteProperty(s,i)?(n.add(i),!0):!1},has(s,i){return Reflect.has(s,i)||Reflect.isExtensible(s)&&!n.has(i)&&(P(e,i)||Reflect.has(r,i))},preventExtensions(s){if(!Reflect.isExtensible(s))return!0;let i=new Set([...Reflect.ownKeys(r),...Reflect.ownKeys(e)]);for(let o of i){if(n.has(o)||P(s,o))continue;let a=P(e,o)?e:r,c=Object.getOwnPropertyDescriptor(a,o);if(c)if("value"in c)Object.defineProperty(s,o,{...c,configurable:!0});else{let d=c.get,p=!1,y,_={...c,configurable:!0};d&&(_.get=()=>p?y:d.call(a)),c.set&&(_.set=b=>{p=!0,y=b}),Object.defineProperty(s,o,_)}}return Reflect.preventExtensions(s)}})}var Bc=class{constructor(){this.state="open"}enter(){if(this.state!=="open")throw new TypeError(this.state==="busy"?"Helper is busy.":"Helper is closed.");this.state="busy"}leave(){this.state=this.state==="draining"?"closed":"open"}close(){return this.state=this.state==="busy"||this.state==="draining"?"draining":"closed",{status:this.state}}};function qd(r){if(r===Object.prototype)return!0;if(Object.getPrototypeOf(r)!==null)return!1;let e=Object.getOwnPropertyDescriptor(r,"constructor");if(!e||!P(e,"value"))return!1;let t=e.value;if(typeof t!="function")return!1;let n=Object.getOwnPropertyDescriptor(t,"prototype");return n!==void 0&&P(n,"value")&&n.value===r&&Function.prototype.toString.call(t)===Function.prototype.toString.call(Object)}function U(r,e,t){let n=r;for(;n!==null&&!qd(n);){let s=Object.getOwnPropertyDescriptor(n,e);if(s)return n===r&&s.enumerable&&t?t[e]:r[e];n=Object.getPrototypeOf(n)}}function F_(r,e,t){let n=g([e&&Object.getOwnPropertyDescriptor(e,"headers")?.enumerable?e.headers:void 0]),s=g([r._options.defaultHeaders,n]),i=e&&Object.getOwnPropertyDescriptor(e,"idempotencyKey")?.enumerable?e.idempotencyKey:void 0;if(!i&&!s.values.has("idempotency-key")){if(e===void 0&&t===void 0)return;let a={signal:t};for(let[c,d]of[["headers",n],["idempotencyKey",i]])Object.defineProperty(a,c,{value:d,writable:!0,configurable:!0,enumerable:e?!!Object.getOwnPropertyDescriptor(e,c)?.enumerable:!1});return Lc(e,a)}let o=`stainless-node-retry-${De()}`;return Lc(e,{signal:t,idempotencyKey:o,headers:g([n,...s.values.has("idempotency-key")?[{"idempotency-key":o}]:[]])})}function ct(r){let e=[r],t=new WeakSet;for(let n of e){let s=Object.getPrototypeOf(n);if(t.has(n)||!Array.isArray(n)&&s!==Object.prototype&&s!==null)continue;t.add(n),P(n,"toJSON")||Object.defineProperty(n,"toJSON",{value:void 0,writable:!0,configurable:!0});let i=Object.values(n);for(let o of i)o!==null&&typeof o=="object"&&e.push(o)}}function W(r,e){return P(r,e)?r[e]:void 0}function Un(r,e){if(!Array.isArray(r))return!1;for(let t=0;t<r.length;t+=1){let n=Object.getOwnPropertyDescriptor(r,t);if(!n?.enumerable||!("value"in n)||!e(n.value))return!1}return!0}function oP(r){if(!L(r))return!1;switch(W(r,"type")){case"file_citation":return typeof W(r,"file_id")=="string"&&typeof W(r,"filename")=="string"&&Number.isInteger(W(r,"index"));case"url_citation":return typeof W(r,"url")=="string"&&typeof W(r,"title")=="string"&&Number.isInteger(W(r,"start_index"))&&Number.isInteger(W(r,"end_index"));case"container_file_citation":return typeof W(r,"container_id")=="string"&&typeof W(r,"file_id")=="string"&&typeof W(r,"filename")=="string"&&Number.isInteger(W(r,"start_index"))&&Number.isInteger(W(r,"end_index"));case"file_path":return typeof W(r,"file_id")=="string"&&Number.isInteger(W(r,"index"));default:return!1}}function z_(r){return L(r)&&typeof W(r,"token")=="string"&&typeof W(r,"logprob")=="number"&&Number.isFinite(W(r,"logprob"))&&Un(W(r,"bytes"),Number.isInteger)}function iP(r){return L(r)&&z_(r)&&Un(W(r,"top_logprobs"),z_)}function aP(r){if(!L(r))return!1;if(W(r,"type")==="refusal")return typeof W(r,"refusal")=="string";let e=W(r,"logprobs");return W(r,"type")==="output_text"&&typeof W(r,"text")=="string"&&Un(W(r,"annotations"),oP)&&(e==null||Un(e,iP))}function M_(r){if(!L(r))return!1;let e=W(r,"status"),t=W(r,"phase");return W(r,"type")==="message"&&typeof W(r,"id")=="string"&&W(r,"role")==="assistant"&&(e==="completed"||e==="incomplete"||e==="in_progress")&&(t==null||t==="commentary"||t==="final_answer")&&Un(W(r,"content"),aP)}function L_(r){if(!L(r))return!1;let e=W(r,"status"),t=W(r,"content"),n=W(r,"encrypted_content");return W(r,"type")==="reasoning"&&typeof W(r,"id")=="string"&&Un(W(r,"summary"),s=>L(s)&&W(s,"type")==="summary_text"&&typeof W(s,"text")=="string")&&(t===void 0||Un(t,s=>L(s)&&W(s,"type")==="reasoning_text"&&typeof W(s,"text")=="string"))&&(n==null||typeof n=="string")&&(e===void 0||e==="completed"||e==="incomplete"||e==="in_progress")}function uP(r){let e=U(r,"pending_safety_checks");if(!U(r,"actions")||e!==void 0){if(!Array.isArray(e))throw new f("ComputerToolset requires valid pending safety checks before execution.");for(let t=0;t<e.length;t+=1){let n=P(e,t)?e[t]:void 0,s=n?U(n,"code"):void 0,i=n?U(n,"message"):void 0;if(!n||!P(n,"id")||typeof n.id!="string"||s!=null&&typeof s!="string"||i!=null&&typeof i!="string")throw new f("ComputerToolset requires valid pending safety checks before execution.")}}}function Kc(r){return L(r)&&P(r,"x")&&P(r,"y")&&Number.isInteger(r.x)&&Number.isInteger(r.y)}function Dd(r){if(!Array.isArray(r))return!1;for(let e=0;e<r.length;e+=1)if(!P(r,e))return!1;return!0}function B_(r){return Dd(r)&&r.every(e=>typeof e=="string")}function cP(r){if(!r||!P(r,"type"))return!1;let e="keys"in r?U(r,"keys"):void 0;if(e!=null&&!B_(e))return!1;switch(r.type){case"click":{let t=U(r,"button");return Kc(r)&&["left","right","wheel","back","forward"].some(n=>n===t)}case"double_click":case"move":return Kc(r);case"scroll":return Kc(r)&&Number.isInteger(U(r,"scroll_x"))&&Number.isInteger(U(r,"scroll_y"));case"drag":{let t=U(r,"path");return Dd(t)&&t.every(Kc)}case"keypress":return B_(U(r,"keys"));case"type":return typeof U(r,"text")=="string";case"screenshot":case"wait":return!0;default:return!1}}function N_(r){let e=U(r,"action"),t=U(r,"actions");if(!P(r,"type")||!P(r,"status")||!P(r,"id")||!P(r,"call_id")||r.type!=="computer_call"||r.status!=="completed"||typeof r.id!="string"||typeof r.call_id!="string"||e===null||t===null||e!==void 0==(t!==void 0))throw new f("ComputerToolset requires a completed call with exactly one of action or actions.");uP(r);let n=t??[e];if(!Array.isArray(n)||n.length===0)throw new f("ComputerToolset requires at least one computer action.");if(!Dd(n))throw new f("ComputerToolset received an invalid computer action.");for(let s of n)if(Array.isArray(s)||!cP(s))throw new f("ComputerToolset received an invalid computer action.");return n}function K_(r){return{signal:U(r,"signal"),approveSafetyChecks:U(r,"approveSafetyChecks")?.bind(r),beforeAction:U(r,"beforeAction")?.bind(r),onDiagnostic:U(r,"onDiagnostic")?.bind(r)}}function lP(r,e){if(!Number.isSafeInteger(e)||e<1)throw new TypeError("ComputerToolset maxSteps must be a positive safe integer.");let t=U(r,"tools"),n=t===void 0?[{type:"computer"}]:t,s=U(r,"conversation"),i=U(r,"previous_response_id");if(U(r,"stream")||U(r,"background")||s!=null||i!=null||!Array.isArray(n)||n.length!==1||n.some(o=>{let a=o&&U(o,"type");return a!=="computer"&&a!=="computer_use_preview"}))throw new TypeError("ComputerToolset.run requires non-streaming, foreground, one computer tool and explicit input history.");return n}function dP(r){return r==="required"||typeof r=="object"&&P(r,"type")&&["computer","computer_use_preview","computer_use"].includes(r.type)?"auto":typeof r=="object"&&P(r,"type")&&r.type==="allowed_tools"&&P(r,"mode")&&r.mode==="required"?{...r,mode:"auto"}:r}function fP(r){let e=r;for(;e!==null&&!qd(e);){let t=Object.getOwnPropertyDescriptor(e,"pending_safety_checks");if(t){if(e!==r||!t.enumerable||!("value"in t))throw new f("ComputerToolset requires own enumerable data for safety checks.");break}e=Object.getPrototypeOf(e)}}function W_(r){if(Array.isArray(r))throw new f("ComputerToolset requires a call object.");fP(r);let e=structuredClone(r);for(let t of N_(e))t.type==="double_click"&&U(t,"keys")===void 0&&(t.keys=null);return e}function pP(r){let e=U(r,"pending_safety_checks")??[],t=U(r,"actions");if(!Array.isArray(t)){let i=structuredClone({...r,pending_safety_checks:e});return ct(i),i}let n={actions:t,pending_safety_checks:e},s=structuredClone({...r,actions:[],pending_safety_checks:[]});ct(s);for(let i of["actions","pending_safety_checks"]){let o=n[i],a=!1,c,d=p=>(c=p,a=!0,Object.getOwnPropertyDescriptor(s,i)?.configurable&&Object.defineProperty(s,i,{value:c,writable:!0,enumerable:!0,configurable:!0}),c);Object.defineProperty(s,i,{configurable:!0,enumerable:!0,get(){if(a)return c;let p=structuredClone(o);return ct(p),d(p)},set(p){if(Object.isFrozen(s))throw new TypeError("Cannot assign to frozen computer approval call.");d(p)}})}return s}function hP(r,e,t){if(U(r,"status")!=="completed")throw new f("ComputerToolset.run received a response that is not completed.");let n=[],s=[],i=U(r,"output");if(!Array.isArray(i))throw new f("ComputerToolset.run received an invalid output array.");let{length:o}=i;if(!Number.isSafeInteger(o)||o<0)throw new f("ComputerToolset.run received an invalid output array.");let a=!1,c=new Set,d=new Set;for(let p=0;p<o;p+=1){let y=P(i,p)?i[p]:void 0;if(!y)throw new f("ComputerToolset.run received an absent output item.");let _=Object.getOwnPropertyDescriptors(y);for(let[A,O]of Object.entries(_))O.get&&(A==="type"?_.type={value:O.get.call(y),enumerable:!!O.enumerable,configurable:!!O.configurable}:O.get=O.get.bind(y));let b=Object.create(Object.getPrototypeOf(y),_),h=P(b,"type")&&b.type==="computer_call"?W_(b):structuredClone(b);if(!P(h,"type")||!P(h,"id")||typeof h.id!="string")throw new f("ComputerToolset.run requires emitted output type and id fields.");if(h.type==="computer_call"){if(d.has(h.call_id)||t.has(h.call_id))throw new f("ComputerToolset.run received a duplicate computer call identity.");d.add(h.call_id),n.push(h)}else if(h.type==="message"){if(!M_(h))throw new f("ComputerToolset.run requires native assistant content before replay.");a||(a=h.status==="completed"&&(!P(h,"phase")||h.phase!=="commentary"))}else if(h.type==="reasoning"){if(!L_(h))throw new f("ComputerToolset.run requires native reasoning content before replay.")}else if(h.type==="compaction"){if(!P(h,"encrypted_content")||typeof h.encrypted_content!="string")throw new f("ComputerToolset.run requires native compaction content before replay.")}else throw new f("ComputerToolset.run cannot handle a non-computer output item.");if(s.push(h),c.has(h.id)||h.id!==""&&e.has(h.id))throw new f("ComputerToolset.run received a duplicate output item identity.");c.add(h.id)}if(n.length===0&&!a)throw new f("ComputerToolset.run received no completed final message.");for(let p of c)p!==""&&e.add(p);for(let p of d)t.add(p);return{calls:n,output:s}}function Zt(r,e){let t=U(r,e);if(typeof t!="function")throw new f("ComputerToolset requires callable computer driver methods.");return t}var $d=class r{constructor(e){this.lifecycle=new Bc;let t={click:Zt(e,"click"),double_click:Zt(e,"double_click"),drag:Zt(e,"drag"),keypress:Zt(e,"keypress"),move:Zt(e,"move"),screenshot:Zt(e,"screenshot"),scroll:Zt(e,"scroll"),type:Zt(e,"type"),wait:Zt(e,"wait")};this.driver={click:t.click.bind(e),double_click:t.double_click.bind(e),drag:t.drag.bind(e),keypress:t.keypress.bind(e),move:t.move.bind(e),screenshot:t.screenshot.bind(e),scroll:t.scroll.bind(e),type:t.type.bind(e),wait:t.wait.bind(e)}}close(){return this.lifecycle.close()}static validate(e){return W_(e)}async run(e,t,n={}){this.lifecycle.enter();try{return await this.runOwned(e,t,n)}finally{this.lifecycle.leave()}}async runOwned(e,t,n){let s=U(n,"maxSteps"),i=s===void 0?20:s,o=JSON.stringify(t),a=JSON.parse(o);if(!L(a))throw new TypeError("ComputerToolset request must be an object.");let c=a,d=lP(c,i),p=U(c,"input"),y=typeof p=="string"?[{role:"user",content:p}]:[...p===void 0?[]:p],_=[...U(c,"include")??[]];_.includes("reasoning.encrypted_content")||_.push("reasoning.encrypted_content");let b={...c,tools:d,include:_,input:y};ct(b);let h=K_(n),A=U(n,"requestOptions"),O=A&&Object.getOwnPropertyDescriptor(A,"signal"),E=h.signal??(A&&U(A,"signal"))??void 0;(h.signal||O&&!("value"in O)||E&&!O?.enumerable)&&(A=Lc(A,{signal:E}));let x={...h,signal:E},q=new Set,C=new Set;for(let D of y){if(!L(D))continue;let R=P(D,"id")?D.id:void 0,v=P(D,"call_id")?D.call_id:void 0;typeof R=="string"&&R!==""&&q.add(R),typeof v=="string"&&C.add(v)}for(let D=0;;D+=1){E?.throwIfAborted();let R=D===0?A:F_(e,A,E);if(R&&Object.getOwnPropertyDescriptor(R,"body")?.enumerable)throw new TypeError("ComputerToolset.run requestOptions.body is not supported.");let v;try{v=await e.responses.create(b,R)}catch(z){throw E?.throwIfAborted(),z}E?.throwIfAborted();let{calls:S,output:j}=hP(v,q,C);if(S.length===0)return v;if(D>=i-1)throw new f("ComputerToolset.run reached maxSteps before executing another computer call.");let T=jd(j);ct(T);let $=JSON.parse(JSON.stringify(T));ct($);for(let z of $)b.input.push(z);for(let z of S){let N=await this.executeOwned(z,x);b.input.push(N)}let k=U(b,"tool_choice");k!=null&&(b.tool_choice=dP(k),typeof b.tool_choice=="object"&&ct(b.tool_choice))}}async execute(e,t={}){this.lifecycle.enter();try{return await this.executeOwned(e,K_(t))}finally{this.lifecycle.leave()}}async executeOwned(e,t){let n=r.validate(e),s=jd([n]);ct(s);let i=JSON.parse(JSON.stringify(s)),o=N_(n);for(let h of o)(h.type==="click"||h.type==="drag"||h.type==="move"||h.type==="scroll")&&U(h,"keys")===void 0&&Object.defineProperty(h,"keys",{value:void 0,enumerable:!0,writable:!0,configurable:!0});let a=o[o.length-1]?.type!=="screenshot";t.signal?.throwIfAborted();let c=U(n,"pending_safety_checks")??[],d=c.map(h=>({id:h.id,code:P(h,"code")?h.code:void 0,message:P(h,"message")?h.message:void 0})),p=i[0]?.pending_safety_checks??[];if(!Array.isArray(p)||p.length!==d.length||!p.every((h,A)=>L(h)&&P(h,"id")&&h.id===d[A]?.id&&(P(h,"code")?h.code:void 0)===d[A]?.code&&(P(h,"message")?h.message:void 0)===d[A]?.message))throw new f("ComputerToolset serialization changed the pending safety checks.");let y=p;if(c.length>0){for(let A of c)for(let O of["code","message"])P(A,O)||Object.defineProperty(A,O,{value:void 0,enumerable:!0,writable:!0,configurable:!0});let h=performance.now();try{let A=structuredClone({...n,pending_safety_checks:c});ct(A);let O=await t.approveSafetyChecks?.(A,{signal:t.signal});if(t.signal?.throwIfAborted(),O!==!0)throw new f("ComputerToolset requires explicit approval of pending safety checks.");Yt(t.onDiagnostic,{api:"computer",stage:"approval",reason:"completed",call_id:n.call_id},h)}catch(A){throw Yt(t.onDiagnostic,{api:"computer",stage:"approval",reason:t.signal?.aborted?"cancelled":"policy_failed",call_id:n.call_id},h),t.signal?.throwIfAborted(),A}}for(let h of o)await this.perform(h,n,t);a&&await this.perform({type:"screenshot"},n,t),t.signal?.throwIfAborted();let _=await this.captureScreenshot(n,t),b={type:"computer_call_output",call_id:n.call_id,output:_,...c.length>0?{acknowledged_safety_checks:y}:{}};return ct(b),b}async captureScreenshot(e,t){let n=performance.now(),s;try{let i=await this.driver.screenshot({signal:t.signal});if(t.signal?.throwIfAborted(),!L(i))throw new f("ComputerToolset screenshot must return a computer_screenshot with image_url or file_id.");let o=U(i,"type"),a=U(i,"image_url"),c=U(i,"file_id");if(o!=="computer_screenshot"||a!==void 0&&(typeof a!="string"||!a.trim())||c!==void 0&&(typeof c!="string"||!c.trim())||a===void 0&&c===void 0)throw new f("ComputerToolset screenshot must return a computer_screenshot with image_url or file_id.");s={type:o,...a===void 0?{}:{image_url:a},...c===void 0?{}:{file_id:c}},Yt(t.onDiagnostic,{api:"computer",stage:"action",reason:"completed",call_id:e.call_id,member:"screenshot"},n)}catch(i){throw Yt(t.onDiagnostic,{api:"computer",stage:"action",reason:t.signal?.aborted?"cancelled":"driver_failed",call_id:e.call_id,member:"screenshot"},n),t.signal?.throwIfAborted(),i}return t.signal?.throwIfAborted(),s}async perform(e,t,n){n.signal?.throwIfAborted(),n.beforeAction&&await r.approveAction(e,t,n.beforeAction,n),n.signal?.throwIfAborted();let s=performance.now();try{let i=structuredClone(e);switch(i.type){case"click":{await this.driver.click(i,{signal:n.signal});break}case"double_click":{await this.driver.double_click(i,{signal:n.signal});break}case"drag":{await this.driver.drag(i,{signal:n.signal});break}case"keypress":{await this.driver.keypress(i,{signal:n.signal});break}case"move":{await this.driver.move(i,{signal:n.signal});break}case"screenshot":break;case"scroll":{await this.driver.scroll(i,{signal:n.signal});break}case"type":{await this.driver.type(i,{signal:n.signal});break}case"wait":{await this.driver.wait(i,{signal:n.signal});break}default:throw new f("ComputerToolset received an unsupported computer action.")}n.signal?.throwIfAborted(),e.type!=="screenshot"&&Yt(n.onDiagnostic,{api:"computer",stage:"action",reason:"completed",call_id:t.call_id,member:e.type},s)}catch(i){throw Yt(n.onDiagnostic,{api:"computer",stage:"action",reason:n.signal?.aborted?"cancelled":"driver_failed",call_id:t.call_id,member:e.type},s),n.signal?.throwIfAborted(),i}n.signal?.throwIfAborted()}static async approveAction(e,t,n,s){let i=performance.now();try{let o=structuredClone(e);ct(o);let a=await n(o,pP(t),{signal:s.signal});if(s.signal?.throwIfAborted(),a!==!0)throw new f("ComputerToolset action declined by beforeAction.");Yt(s.onDiagnostic,{api:"computer",stage:"approval",reason:"completed",call_id:t.call_id,member:e.type},i)}catch(o){throw Yt(s.onDiagnostic,{api:"computer",stage:"approval",reason:s.signal?.aborted?"cancelled":"policy_failed",call_id:t.call_id,member:e.type},i),s.signal?.throwIfAborted(),o}}};var Fd=class extends F{constructor({baseURL:e=_e("OPENAI_BASE_URL"),apiKey:t=_e("AZURE_OPENAI_API_KEY"),apiVersion:n=_e("OPENAI_API_VERSION"),endpoint:s,deployment:i,azureADTokenProvider:o,dangerouslyAllowBrowser:a,dataResidency:c,...d}={}){if(tu(c,"AzureOpenAI"),!n)throw new f("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof o=="function"&&(a??(a=!0)),!o&&!t)throw new f("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new f("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(d.defaultQuery={...d.defaultQuery,"api-version":n},e){if(s)throw new f("baseURL and endpoint are mutually exclusive")}else{if(s||(s=process.env.AZURE_OPENAI_ENDPOINT),!s)throw new f("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let p=s.length;for(;p>0&&s[p-1]==="/";)p--;e=`${s.slice(0,p)}/openai`}super({apiKey:o??t,baseURL:e,...d,...a===void 0?{}:{dangerouslyAllowBrowser:a}}),this.apiVersion="",this.apiVersion=n,this.deploymentName=i}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};return P(e,"endpoint")&&e.endpoint!==void 0&&!P(e,"baseURL")&&(t.baseURL=void 0),super.withOptions(t)}async buildRequest(e,t={}){if(_P.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!L(e.body))throw new Error("Expected request body to be an object");let s=this.deploymentName||e.body.model||e.__metadata?.model;s!==void 0&&!mP(this.baseURL)&&(e.path=l`/deployments/${s}`+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,s,i){return new Headers(t.headers).has("api-key")&&(t.redirect="manual"),super.fetchWithAuth(e,t,n,s,i)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey=="string"?g([{"api-key":this.apiKey}]):super.authHeaders(e,n)}};function mP(r){try{return new URL(r).pathname.split("/").includes("deployments")}catch{return!1}}var _P=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);var U_;function yP(r){let e=r?.trim();if(!e)throw new f("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(e))throw new f("The Bedrock AWS `region` is invalid. Use a standard AWS region such as `us-east-1`.");return`https://bedrock-mantle.${e}.api.aws/openai/v1`}function gP(r){let e=new URL(r),t=e.pathname.match(/\/responses(?:\/.*)?$/);return t?.index!==void 0&&(e.pathname=e.pathname.slice(0,t.index)||"/"),e.toString().replace(/\/$/,"")}function bP(r){return Object.getOwnPropertyDescriptor(r,"output_text")||Wt(r),r}function wP(r){let e=r.stream.bind(r);return r.stream=((t,n)=>{let s=e(t,n),i=s.finalResponse.bind(s);return s.finalResponse=async()=>bP(await i()),s}),r}var zd=class extends F{constructor({baseURL:e=_e("AWS_BEDROCK_BASE_URL"),apiKey:t,awsRegion:n=_e("AWS_REGION")??_e("AWS_DEFAULT_REGION"),bedrockTokenProvider:s,adminAPIKey:i,workloadIdentity:o,x509Transport:a,dataResidency:c,...d}={}){if(tu(c,"BedrockOpenAI"),i||o||a)throw new f("BedrockOpenAI only supports Bedrock bearer token authentication.");if(t===void 0&&!s&&(t=_e("AWS_BEARER_TOKEN_BEDROCK")??null),typeof t=="function")throw new f("Pass refreshable Bedrock credentials via `bedrockTokenProvider`, not `apiKey`.");if(t&&s)throw new f("The `apiKey` and `bedrockTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(!t&&!s)throw new f("Missing credentials. Please pass an `apiKey` or `bedrockTokenProvider`, or set the `AWS_BEARER_TOKEN_BEDROCK` environment variable.");let p=e?.trim()?e:yP(n);super({apiKey:s??t,adminAPIKey:null,baseURL:gP(p),...d}),this[U_]=!0;let y=this.apiKey;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,get(){return y!==null&&Fa(y),y},set(h){y=h}});let _=this.baseURL,b=_;Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!1,get(){return b},set(h){Fr(_,h),b=h}}),this.bedrockTokenProvider=s,this.responses=wP(new _t(this))}async prepareOptions(e){let t=this._options.baseURL??this.baseURL;Fr(t,this.buildURL(e.path,null,e.defaultBaseURL)),await super.prepareOptions(e),Fr(t,this.buildURL(e.path,null,e.defaultBaseURL))}async prepareRequest(e,t){Fr(this._options.baseURL??this.baseURL,t.url),await super.prepareRequest(e,t),Fr(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){Fr(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL));let{apiKey:s}=await zc(this);if(Fr(this._options.baseURL??this.baseURL,this.buildURL(e.path,null,e.defaultBaseURL)),s===null)return;Fa(s);try{return g([{Authorization:`Bearer ${s}`}])}catch(i){throw i instanceof TypeError?new TypeError("Bedrock bearer credential contains an invalid HTTP header value."):i}}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}:{}})}};U_=Dc;export{Je as APIConnectionError,se as APIConnectionTimeoutError,J as APIError,$t as APIPromise,Y as APIUserAbortError,tr as AuthenticationError,Fd as AzureOpenAI,bt as BadRequestError,zd as BedrockOpenAI,$d as ComputerToolset,sr as ConflictError,ar as InternalServerError,Fe as InvalidWebhookSignatureError,nr as NotFoundError,Ve as OAuthError,F as OpenAI,f as OpenAIError,Ai as PagePromise,rr as PermissionDeniedError,ir as RateLimitError,Mr as SubjectTokenProviderError,or as UnprocessableEntityError,F as default,pu as toFile,lu as toStreamingFile};